xref: /llvm-project/llvm/lib/MC/MachObjectWriter.cpp (revision 009082aa4b20462d46c885d5abc9320a887f1932)
1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ADT/DenseMap.h"
10 #include "llvm/ADT/Twine.h"
11 #include "llvm/ADT/iterator_range.h"
12 #include "llvm/BinaryFormat/MachO.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAsmInfoDarwin.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCDirectives.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCFixupKindInfo.h"
20 #include "llvm/MC/MCFragment.h"
21 #include "llvm/MC/MCMachObjectWriter.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCSymbolMachO.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/Support/Alignment.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 #include <string>
40 #include <utility>
41 #include <vector>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "mc"
46 
47 void MachObjectWriter::reset() {
48   Relocations.clear();
49   IndirectSymBase.clear();
50   IndirectSymbols.clear();
51   DataRegions.clear();
52   SectionAddress.clear();
53   SectionOrder.clear();
54   StringTable.clear();
55   LocalSymbolData.clear();
56   ExternalSymbolData.clear();
57   UndefinedSymbolData.clear();
58   MCObjectWriter::reset();
59 }
60 
61 bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
62   // Undefined symbols are always extern.
63   if (S.isUndefined())
64     return true;
65 
66   // References to weak definitions require external relocation entries; the
67   // definition may not always be the one in the same object file.
68   if (cast<MCSymbolMachO>(S).isWeakDefinition())
69     return true;
70 
71   // Otherwise, we can use an internal relocation.
72   return false;
73 }
74 
75 bool MachObjectWriter::
76 MachSymbolData::operator<(const MachSymbolData &RHS) const {
77   return Symbol->getName() < RHS.Symbol->getName();
78 }
79 
80 bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
81   const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
82     (MCFixupKind) Kind);
83 
84   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
85 }
86 
87 uint64_t
88 MachObjectWriter::getFragmentAddress(const MCAssembler &Asm,
89                                      const MCFragment *Fragment) const {
90   return getSectionAddress(Fragment->getParent()) +
91          Asm.getFragmentOffset(*Fragment);
92 }
93 
94 uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
95                                             const MCAssembler &Asm) const {
96   // If this is a variable, then recursively evaluate now.
97   if (S.isVariable()) {
98     if (const MCConstantExpr *C =
99           dyn_cast<const MCConstantExpr>(S.getVariableValue()))
100       return C->getValue();
101 
102     MCValue Target;
103     if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Asm, nullptr))
104       report_fatal_error("unable to evaluate offset for variable '" +
105                          S.getName() + "'");
106 
107     // Verify that any used symbols are defined.
108     if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
109       report_fatal_error("unable to evaluate offset to undefined symbol '" +
110                          Target.getSymA()->getSymbol().getName() + "'");
111     if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
112       report_fatal_error("unable to evaluate offset to undefined symbol '" +
113                          Target.getSymB()->getSymbol().getName() + "'");
114 
115     uint64_t Address = Target.getConstant();
116     if (Target.getSymA())
117       Address += getSymbolAddress(Target.getSymA()->getSymbol(), Asm);
118     if (Target.getSymB())
119       Address += getSymbolAddress(Target.getSymB()->getSymbol(), Asm);
120     return Address;
121   }
122 
123   return getSectionAddress(S.getFragment()->getParent()) +
124          Asm.getSymbolOffset(S);
125 }
126 
127 uint64_t MachObjectWriter::getPaddingSize(const MCAssembler &Asm,
128                                           const MCSection *Sec) const {
129   uint64_t EndAddr = getSectionAddress(Sec) + Asm.getSectionAddressSize(*Sec);
130   unsigned Next = cast<MCSectionMachO>(Sec)->getLayoutOrder() + 1;
131   if (Next >= SectionOrder.size())
132     return 0;
133 
134   const MCSection &NextSec = *SectionOrder[Next];
135   if (NextSec.isVirtualSection())
136     return 0;
137   return offsetToAlignment(EndAddr, NextSec.getAlign());
138 }
139 
140 static bool isSymbolLinkerVisible(const MCSymbol &Symbol) {
141   // Non-temporary labels should always be visible to the linker.
142   if (!Symbol.isTemporary())
143     return true;
144 
145   if (Symbol.isUsedInReloc())
146     return true;
147 
148   return false;
149 }
150 
151 const MCSymbol *MachObjectWriter::getAtom(const MCSymbol &S) const {
152   // Linker visible symbols define atoms.
153   if (isSymbolLinkerVisible(S))
154     return &S;
155 
156   // Absolute and undefined symbols have no defining atom.
157   if (!S.isInSection())
158     return nullptr;
159 
160   // Non-linker visible symbols in sections which can't be atomized have no
161   // defining atom.
162   if (!MCAsmInfoDarwin::isSectionAtomizableBySymbols(
163           *S.getFragment()->getParent()))
164     return nullptr;
165 
166   // Otherwise, return the atom for the containing fragment.
167   return S.getFragment()->getAtom();
168 }
169 
170 void MachObjectWriter::writeHeader(MachO::HeaderFileType Type,
171                                    unsigned NumLoadCommands,
172                                    unsigned LoadCommandsSize,
173                                    bool SubsectionsViaSymbols) {
174   uint32_t Flags = 0;
175 
176   if (SubsectionsViaSymbols)
177     Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
178 
179   // struct mach_header (28 bytes) or
180   // struct mach_header_64 (32 bytes)
181 
182   uint64_t Start = W.OS.tell();
183   (void) Start;
184 
185   W.write<uint32_t>(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
186 
187   W.write<uint32_t>(TargetObjectWriter->getCPUType());
188   W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
189 
190   W.write<uint32_t>(Type);
191   W.write<uint32_t>(NumLoadCommands);
192   W.write<uint32_t>(LoadCommandsSize);
193   W.write<uint32_t>(Flags);
194   if (is64Bit())
195     W.write<uint32_t>(0); // reserved
196 
197   assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64)
198                                            : sizeof(MachO::mach_header)));
199 }
200 
201 void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) {
202   assert(Size >= Str.size());
203   W.OS << Str;
204   W.OS.write_zeros(Size - Str.size());
205 }
206 
207 /// writeSegmentLoadCommand - Write a segment load command.
208 ///
209 /// \param NumSections The number of sections in this segment.
210 /// \param SectionDataSize The total size of the sections.
211 void MachObjectWriter::writeSegmentLoadCommand(
212     StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
213     uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
214     uint32_t InitProt) {
215   // struct segment_command (56 bytes) or
216   // struct segment_command_64 (72 bytes)
217 
218   uint64_t Start = W.OS.tell();
219   (void) Start;
220 
221   unsigned SegmentLoadCommandSize =
222     is64Bit() ? sizeof(MachO::segment_command_64):
223     sizeof(MachO::segment_command);
224   W.write<uint32_t>(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
225   W.write<uint32_t>(SegmentLoadCommandSize +
226           NumSections * (is64Bit() ? sizeof(MachO::section_64) :
227                          sizeof(MachO::section)));
228 
229   writeWithPadding(Name, 16);
230   if (is64Bit()) {
231     W.write<uint64_t>(VMAddr);                 // vmaddr
232     W.write<uint64_t>(VMSize); // vmsize
233     W.write<uint64_t>(SectionDataStartOffset); // file offset
234     W.write<uint64_t>(SectionDataSize); // file size
235   } else {
236     W.write<uint32_t>(VMAddr);                 // vmaddr
237     W.write<uint32_t>(VMSize); // vmsize
238     W.write<uint32_t>(SectionDataStartOffset); // file offset
239     W.write<uint32_t>(SectionDataSize); // file size
240   }
241   // maxprot
242   W.write<uint32_t>(MaxProt);
243   // initprot
244   W.write<uint32_t>(InitProt);
245   W.write<uint32_t>(NumSections);
246   W.write<uint32_t>(0); // flags
247 
248   assert(W.OS.tell() - Start == SegmentLoadCommandSize);
249 }
250 
251 void MachObjectWriter::writeSection(const MCAssembler &Asm,
252                                     const MCSection &Sec, uint64_t VMAddr,
253                                     uint64_t FileOffset, unsigned Flags,
254                                     uint64_t RelocationsStart,
255                                     unsigned NumRelocations) {
256   uint64_t SectionSize = Asm.getSectionAddressSize(Sec);
257   const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
258 
259   // The offset is unused for virtual sections.
260   if (Section.isVirtualSection()) {
261     assert(Asm.getSectionFileSize(Sec) == 0 && "Invalid file size!");
262     FileOffset = 0;
263   }
264 
265   // struct section (68 bytes) or
266   // struct section_64 (80 bytes)
267 
268   uint64_t Start = W.OS.tell();
269   (void) Start;
270 
271   writeWithPadding(Section.getName(), 16);
272   writeWithPadding(Section.getSegmentName(), 16);
273   if (is64Bit()) {
274     W.write<uint64_t>(VMAddr);      // address
275     W.write<uint64_t>(SectionSize); // size
276   } else {
277     W.write<uint32_t>(VMAddr);      // address
278     W.write<uint32_t>(SectionSize); // size
279   }
280   W.write<uint32_t>(FileOffset);
281 
282   W.write<uint32_t>(Log2(Section.getAlign()));
283   W.write<uint32_t>(NumRelocations ? RelocationsStart : 0);
284   W.write<uint32_t>(NumRelocations);
285   W.write<uint32_t>(Flags);
286   W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1
287   W.write<uint32_t>(Section.getStubSize()); // reserved2
288   if (is64Bit())
289     W.write<uint32_t>(0); // reserved3
290 
291   assert(W.OS.tell() - Start ==
292          (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
293 }
294 
295 void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
296                                               uint32_t NumSymbols,
297                                               uint32_t StringTableOffset,
298                                               uint32_t StringTableSize) {
299   // struct symtab_command (24 bytes)
300 
301   uint64_t Start = W.OS.tell();
302   (void) Start;
303 
304   W.write<uint32_t>(MachO::LC_SYMTAB);
305   W.write<uint32_t>(sizeof(MachO::symtab_command));
306   W.write<uint32_t>(SymbolOffset);
307   W.write<uint32_t>(NumSymbols);
308   W.write<uint32_t>(StringTableOffset);
309   W.write<uint32_t>(StringTableSize);
310 
311   assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
312 }
313 
314 void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
315                                                 uint32_t NumLocalSymbols,
316                                                 uint32_t FirstExternalSymbol,
317                                                 uint32_t NumExternalSymbols,
318                                                 uint32_t FirstUndefinedSymbol,
319                                                 uint32_t NumUndefinedSymbols,
320                                                 uint32_t IndirectSymbolOffset,
321                                                 uint32_t NumIndirectSymbols) {
322   // struct dysymtab_command (80 bytes)
323 
324   uint64_t Start = W.OS.tell();
325   (void) Start;
326 
327   W.write<uint32_t>(MachO::LC_DYSYMTAB);
328   W.write<uint32_t>(sizeof(MachO::dysymtab_command));
329   W.write<uint32_t>(FirstLocalSymbol);
330   W.write<uint32_t>(NumLocalSymbols);
331   W.write<uint32_t>(FirstExternalSymbol);
332   W.write<uint32_t>(NumExternalSymbols);
333   W.write<uint32_t>(FirstUndefinedSymbol);
334   W.write<uint32_t>(NumUndefinedSymbols);
335   W.write<uint32_t>(0); // tocoff
336   W.write<uint32_t>(0); // ntoc
337   W.write<uint32_t>(0); // modtaboff
338   W.write<uint32_t>(0); // nmodtab
339   W.write<uint32_t>(0); // extrefsymoff
340   W.write<uint32_t>(0); // nextrefsyms
341   W.write<uint32_t>(IndirectSymbolOffset);
342   W.write<uint32_t>(NumIndirectSymbols);
343   W.write<uint32_t>(0); // extreloff
344   W.write<uint32_t>(0); // nextrel
345   W.write<uint32_t>(0); // locreloff
346   W.write<uint32_t>(0); // nlocrel
347 
348   assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
349 }
350 
351 MachObjectWriter::MachSymbolData *
352 MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
353   for (auto *SymbolData :
354        {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
355     for (MachSymbolData &Entry : *SymbolData)
356       if (Entry.Symbol == &Sym)
357         return &Entry;
358 
359   return nullptr;
360 }
361 
362 const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
363   const MCSymbol *S = &Sym;
364   while (S->isVariable()) {
365     const MCExpr *Value = S->getVariableValue();
366     const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
367     if (!Ref)
368       return *S;
369     S = &Ref->getSymbol();
370   }
371   return *S;
372 }
373 
374 void MachObjectWriter::writeNlist(MachSymbolData &MSD, const MCAssembler &Asm) {
375   const MCSymbol *Symbol = MSD.Symbol;
376   const MCSymbol &Data = *Symbol;
377   const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
378   uint8_t SectionIndex = MSD.SectionIndex;
379   uint8_t Type = 0;
380   uint64_t Address = 0;
381   bool IsAlias = Symbol != AliasedSymbol;
382 
383   const MCSymbol &OrigSymbol = *Symbol;
384   MachSymbolData *AliaseeInfo;
385   if (IsAlias) {
386     AliaseeInfo = findSymbolData(*AliasedSymbol);
387     if (AliaseeInfo)
388       SectionIndex = AliaseeInfo->SectionIndex;
389     Symbol = AliasedSymbol;
390     // FIXME: Should this update Data as well?
391   }
392 
393   // Set the N_TYPE bits. See <mach-o/nlist.h>.
394   //
395   // FIXME: Are the prebound or indirect fields possible here?
396   if (IsAlias && Symbol->isUndefined())
397     Type = MachO::N_INDR;
398   else if (Symbol->isUndefined())
399     Type = MachO::N_UNDF;
400   else if (Symbol->isAbsolute())
401     Type = MachO::N_ABS;
402   else
403     Type = MachO::N_SECT;
404 
405   // FIXME: Set STAB bits.
406 
407   if (Data.isPrivateExtern())
408     Type |= MachO::N_PEXT;
409 
410   // Set external bit.
411   if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
412     Type |= MachO::N_EXT;
413 
414   // Compute the symbol address.
415   if (IsAlias && Symbol->isUndefined())
416     Address = AliaseeInfo->StringIndex;
417   else if (Symbol->isDefined())
418     Address = getSymbolAddress(OrigSymbol, Asm);
419   else if (Symbol->isCommon()) {
420     // Common symbols are encoded with the size in the address
421     // field, and their alignment in the flags.
422     Address = Symbol->getCommonSize();
423   }
424 
425   // struct nlist (12 bytes)
426 
427   W.write<uint32_t>(MSD.StringIndex);
428   W.OS << char(Type);
429   W.OS << char(SectionIndex);
430 
431   // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
432   // value.
433   bool EncodeAsAltEntry =
434     IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
435   W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
436   if (is64Bit())
437     W.write<uint64_t>(Address);
438   else
439     W.write<uint32_t>(Address);
440 }
441 
442 void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
443                                                 uint32_t DataOffset,
444                                                 uint32_t DataSize) {
445   uint64_t Start = W.OS.tell();
446   (void) Start;
447 
448   W.write<uint32_t>(Type);
449   W.write<uint32_t>(sizeof(MachO::linkedit_data_command));
450   W.write<uint32_t>(DataOffset);
451   W.write<uint32_t>(DataSize);
452 
453   assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
454 }
455 
456 static unsigned ComputeLinkerOptionsLoadCommandSize(
457   const std::vector<std::string> &Options, bool is64Bit)
458 {
459   unsigned Size = sizeof(MachO::linker_option_command);
460   for (const std::string &Option : Options)
461     Size += Option.size() + 1;
462   return alignTo(Size, is64Bit ? 8 : 4);
463 }
464 
465 void MachObjectWriter::writeLinkerOptionsLoadCommand(
466   const std::vector<std::string> &Options)
467 {
468   unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
469   uint64_t Start = W.OS.tell();
470   (void) Start;
471 
472   W.write<uint32_t>(MachO::LC_LINKER_OPTION);
473   W.write<uint32_t>(Size);
474   W.write<uint32_t>(Options.size());
475   uint64_t BytesWritten = sizeof(MachO::linker_option_command);
476   for (const std::string &Option : Options) {
477     // Write each string, including the null byte.
478     W.OS << Option << '\0';
479     BytesWritten += Option.size() + 1;
480   }
481 
482   // Pad to a multiple of the pointer size.
483   W.OS.write_zeros(
484       offsetToAlignment(BytesWritten, is64Bit() ? Align(8) : Align(4)));
485 
486   assert(W.OS.tell() - Start == Size);
487 }
488 
489 static bool isFixupTargetValid(const MCValue &Target) {
490   // Target is (LHS - RHS + cst).
491   // We don't support the form where LHS is null: -RHS + cst
492   if (!Target.getSymA() && Target.getSymB())
493     return false;
494   return true;
495 }
496 
497 void MachObjectWriter::recordRelocation(MCAssembler &Asm,
498                                         const MCFragment *Fragment,
499                                         const MCFixup &Fixup, MCValue Target,
500                                         uint64_t &FixedValue) {
501   if (!isFixupTargetValid(Target)) {
502     Asm.getContext().reportError(Fixup.getLoc(),
503                                  "unsupported relocation expression");
504     return;
505   }
506 
507   TargetObjectWriter->recordRelocation(this, Asm, Fragment, Fixup, Target,
508                                        FixedValue);
509 }
510 
511 void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
512   // This is the point where 'as' creates actual symbols for indirect symbols
513   // (in the following two passes). It would be easier for us to do this sooner
514   // when we see the attribute, but that makes getting the order in the symbol
515   // table much more complicated than it is worth.
516   //
517   // FIXME: Revisit this when the dust settles.
518 
519   // Report errors for use of .indirect_symbol not in a symbol pointer section
520   // or stub section.
521   for (IndirectSymbolData &ISD : IndirectSymbols) {
522     const MCSectionMachO &Section = cast<MCSectionMachO>(*ISD.Section);
523 
524     if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
525         Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
526         Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS &&
527         Section.getType() != MachO::S_SYMBOL_STUBS) {
528       MCSymbol &Symbol = *ISD.Symbol;
529       report_fatal_error("indirect symbol '" + Symbol.getName() +
530                          "' not in a symbol pointer or stub section");
531     }
532   }
533 
534   // Bind non-lazy symbol pointers first.
535   for (auto [IndirectIndex, ISD] : enumerate(IndirectSymbols)) {
536     const auto &Section = cast<MCSectionMachO>(*ISD.Section);
537 
538     if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
539         Section.getType() !=  MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
540       continue;
541 
542     // Initialize the section indirect symbol base, if necessary.
543     IndirectSymBase.insert(std::make_pair(ISD.Section, IndirectIndex));
544 
545     Asm.registerSymbol(*ISD.Symbol);
546   }
547 
548   // Then lazy symbol pointers and symbol stubs.
549   for (auto [IndirectIndex, ISD] : enumerate(IndirectSymbols)) {
550     const auto &Section = cast<MCSectionMachO>(*ISD.Section);
551 
552     if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
553         Section.getType() != MachO::S_SYMBOL_STUBS)
554       continue;
555 
556     // Initialize the section indirect symbol base, if necessary.
557     IndirectSymBase.insert(std::make_pair(ISD.Section, IndirectIndex));
558 
559     // Set the symbol type to undefined lazy, but only on construction.
560     //
561     // FIXME: Do not hardcode.
562     if (Asm.registerSymbol(*ISD.Symbol))
563       cast<MCSymbolMachO>(ISD.Symbol)->setReferenceTypeUndefinedLazy(true);
564   }
565 }
566 
567 /// computeSymbolTable - Compute the symbol table data
568 void MachObjectWriter::computeSymbolTable(
569     MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
570     std::vector<MachSymbolData> &ExternalSymbolData,
571     std::vector<MachSymbolData> &UndefinedSymbolData) {
572   // Build section lookup table.
573   DenseMap<const MCSection*, uint8_t> SectionIndexMap;
574   unsigned Index = 1;
575   for (MCAssembler::iterator it = Asm.begin(),
576          ie = Asm.end(); it != ie; ++it, ++Index)
577     SectionIndexMap[&*it] = Index;
578   assert(Index <= 256 && "Too many sections!");
579 
580   // Build the string table.
581   for (const MCSymbol &Symbol : Asm.symbols()) {
582     if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
583       continue;
584 
585     StringTable.add(Symbol.getName());
586   }
587   StringTable.finalize();
588 
589   // Build the symbol arrays but only for non-local symbols.
590   //
591   // The particular order that we collect and then sort the symbols is chosen to
592   // match 'as'. Even though it doesn't matter for correctness, this is
593   // important for letting us diff .o files.
594   for (const MCSymbol &Symbol : Asm.symbols()) {
595     // Ignore non-linker visible symbols.
596     if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
597       continue;
598 
599     if (!Symbol.isExternal() && !Symbol.isUndefined())
600       continue;
601 
602     MachSymbolData MSD;
603     MSD.Symbol = &Symbol;
604     MSD.StringIndex = StringTable.getOffset(Symbol.getName());
605 
606     if (Symbol.isUndefined()) {
607       MSD.SectionIndex = 0;
608       UndefinedSymbolData.push_back(MSD);
609     } else if (Symbol.isAbsolute()) {
610       MSD.SectionIndex = 0;
611       ExternalSymbolData.push_back(MSD);
612     } else {
613       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
614       assert(MSD.SectionIndex && "Invalid section index!");
615       ExternalSymbolData.push_back(MSD);
616     }
617   }
618 
619   // Now add the data for local symbols.
620   for (const MCSymbol &Symbol : Asm.symbols()) {
621     // Ignore non-linker visible symbols.
622     if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
623       continue;
624 
625     if (Symbol.isExternal() || Symbol.isUndefined())
626       continue;
627 
628     MachSymbolData MSD;
629     MSD.Symbol = &Symbol;
630     MSD.StringIndex = StringTable.getOffset(Symbol.getName());
631 
632     if (Symbol.isAbsolute()) {
633       MSD.SectionIndex = 0;
634       LocalSymbolData.push_back(MSD);
635     } else {
636       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
637       assert(MSD.SectionIndex && "Invalid section index!");
638       LocalSymbolData.push_back(MSD);
639     }
640   }
641 
642   // External and undefined symbols are required to be in lexicographic order.
643   llvm::sort(ExternalSymbolData);
644   llvm::sort(UndefinedSymbolData);
645 
646   // Set the symbol indices.
647   Index = 0;
648   for (auto *SymbolData :
649        {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
650     for (MachSymbolData &Entry : *SymbolData)
651       Entry.Symbol->setIndex(Index++);
652 
653   for (const MCSection &Section : Asm) {
654     for (RelAndSymbol &Rel : Relocations[&Section]) {
655       if (!Rel.Sym)
656         continue;
657 
658       // Set the Index and the IsExtern bit.
659       unsigned Index = Rel.Sym->getIndex();
660       assert(isInt<24>(Index));
661       if (W.Endian == llvm::endianness::little)
662         Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
663       else
664         Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
665     }
666   }
667 }
668 
669 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm) {
670   // Assign layout order indices to sections.
671   unsigned i = 0;
672   // Compute the section layout order. Virtual sections must go last.
673   for (MCSection &Sec : Asm) {
674     if (!Sec.isVirtualSection()) {
675       SectionOrder.push_back(&Sec);
676       cast<MCSectionMachO>(Sec).setLayoutOrder(i++);
677     }
678   }
679   for (MCSection &Sec : Asm) {
680     if (Sec.isVirtualSection()) {
681       SectionOrder.push_back(&Sec);
682       cast<MCSectionMachO>(Sec).setLayoutOrder(i++);
683     }
684   }
685 
686   uint64_t StartAddress = 0;
687   for (const MCSection *Sec : SectionOrder) {
688     StartAddress = alignTo(StartAddress, Sec->getAlign());
689     SectionAddress[Sec] = StartAddress;
690     StartAddress += Asm.getSectionAddressSize(*Sec);
691 
692     // Explicitly pad the section to match the alignment requirements of the
693     // following one. This is for 'gas' compatibility, it shouldn't
694     /// strictly be necessary.
695     StartAddress += getPaddingSize(Asm, Sec);
696   }
697 }
698 
699 void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm) {
700   computeSectionAddresses(Asm);
701 
702   // Create symbol data for any indirect symbols.
703   bindIndirectSymbols(Asm);
704 }
705 
706 bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
707     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
708     bool InSet, bool IsPCRel) const {
709   if (InSet)
710     return true;
711 
712   // The effective address is
713   //     addr(atom(A)) + offset(A)
714   //   - addr(atom(B)) - offset(B)
715   // and the offsets are not relocatable, so the fixup is fully resolved when
716   //  addr(atom(A)) - addr(atom(B)) == 0.
717   const MCSymbol &SA = findAliasedSymbol(SymA);
718   const MCSection &SecA = SA.getSection();
719   const MCSection &SecB = *FB.getParent();
720 
721   if (IsPCRel) {
722     // The simple (Darwin, except on x86_64) way of dealing with this was to
723     // assume that any reference to a temporary symbol *must* be a temporary
724     // symbol in the same atom, unless the sections differ. Therefore, any PCrel
725     // relocation to a temporary symbol (in the same section) is fully
726     // resolved. This also works in conjunction with absolutized .set, which
727     // requires the compiler to use .set to absolutize the differences between
728     // symbols which the compiler knows to be assembly time constants, so we
729     // don't need to worry about considering symbol differences fully resolved.
730     //
731     // If the file isn't using sub-sections-via-symbols, we can make the
732     // same assumptions about any symbol that we normally make about
733     // assembler locals.
734 
735     bool hasReliableSymbolDifference = isX86_64();
736     if (!hasReliableSymbolDifference) {
737       if (!SA.isInSection() || &SecA != &SecB ||
738           (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
739            Asm.getSubsectionsViaSymbols()))
740         return false;
741       return true;
742     }
743   }
744 
745   // If they are not in the same section, we can't compute the diff.
746   if (&SecA != &SecB)
747     return false;
748 
749   // If the atoms are the same, they are guaranteed to have the same address.
750   return SA.getFragment()->getAtom() == FB.getAtom();
751 }
752 
753 static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) {
754   switch (Type) {
755   case MCVM_OSXVersionMin:     return MachO::LC_VERSION_MIN_MACOSX;
756   case MCVM_IOSVersionMin:     return MachO::LC_VERSION_MIN_IPHONEOS;
757   case MCVM_TvOSVersionMin:    return MachO::LC_VERSION_MIN_TVOS;
758   case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
759   }
760   llvm_unreachable("Invalid mc version min type");
761 }
762 
763 void MachObjectWriter::populateAddrSigSection(MCAssembler &Asm) {
764   MCSection *AddrSigSection =
765       Asm.getContext().getObjectFileInfo()->getAddrSigSection();
766   unsigned Log2Size = is64Bit() ? 3 : 2;
767   for (const MCSymbol *S : getAddrsigSyms()) {
768     if (!S->isRegistered())
769       continue;
770     MachO::any_relocation_info MRE;
771     MRE.r_word0 = 0;
772     MRE.r_word1 = (Log2Size << 25) | (MachO::GENERIC_RELOC_VANILLA << 28);
773     addRelocation(S, AddrSigSection, MRE);
774   }
775 }
776 
777 uint64_t MachObjectWriter::writeObject(MCAssembler &Asm) {
778   uint64_t StartOffset = W.OS.tell();
779 
780   populateAddrSigSection(Asm);
781 
782   // Compute symbol table information and bind symbol indices.
783   computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
784                      UndefinedSymbolData);
785 
786   if (!Asm.CGProfile.empty()) {
787     MCSection *CGProfileSection = Asm.getContext().getMachOSection(
788         "__LLVM", "__cg_profile", 0, SectionKind::getMetadata());
789     auto &Frag = cast<MCDataFragment>(*CGProfileSection->begin());
790     Frag.getContents().clear();
791     raw_svector_ostream OS(Frag.getContents());
792     for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
793       uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
794       uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
795       support::endian::write(OS, FromIndex, W.Endian);
796       support::endian::write(OS, ToIndex, W.Endian);
797       support::endian::write(OS, CGPE.Count, W.Endian);
798     }
799   }
800 
801   unsigned NumSections = Asm.size();
802   const MCAssembler::VersionInfoType &VersionInfo = Asm.getVersionInfo();
803 
804   // The section data starts after the header, the segment load command (and
805   // section headers) and the symbol table.
806   unsigned NumLoadCommands = 1;
807   uint64_t LoadCommandsSize = is64Bit() ?
808     sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
809     sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
810 
811   // Add the deployment target version info load command size, if used.
812   if (VersionInfo.Major != 0) {
813     ++NumLoadCommands;
814     if (VersionInfo.EmitBuildVersion)
815       LoadCommandsSize += sizeof(MachO::build_version_command);
816     else
817       LoadCommandsSize += sizeof(MachO::version_min_command);
818   }
819 
820   const MCAssembler::VersionInfoType &TargetVariantVersionInfo =
821       Asm.getDarwinTargetVariantVersionInfo();
822 
823   // Add the target variant version info load command size, if used.
824   if (TargetVariantVersionInfo.Major != 0) {
825     ++NumLoadCommands;
826     assert(TargetVariantVersionInfo.EmitBuildVersion &&
827            "target variant should use build version");
828     LoadCommandsSize += sizeof(MachO::build_version_command);
829   }
830 
831   // Add the data-in-code load command size, if used.
832   unsigned NumDataRegions = DataRegions.size();
833   if (NumDataRegions) {
834     ++NumLoadCommands;
835     LoadCommandsSize += sizeof(MachO::linkedit_data_command);
836   }
837 
838   // Add the loh load command size, if used.
839   uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(Asm, *this);
840   uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
841   if (LOHSize) {
842     ++NumLoadCommands;
843     LoadCommandsSize += sizeof(MachO::linkedit_data_command);
844   }
845 
846   // Add the symbol table load command sizes, if used.
847   unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
848     UndefinedSymbolData.size();
849   if (NumSymbols) {
850     NumLoadCommands += 2;
851     LoadCommandsSize += (sizeof(MachO::symtab_command) +
852                          sizeof(MachO::dysymtab_command));
853   }
854 
855   // Add the linker option load commands sizes.
856   for (const auto &Option : Asm.getLinkerOptions()) {
857     ++NumLoadCommands;
858     LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
859   }
860 
861   // Compute the total size of the section data, as well as its file size and vm
862   // size.
863   uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
864                                sizeof(MachO::mach_header)) + LoadCommandsSize;
865   uint64_t SectionDataSize = 0;
866   uint64_t SectionDataFileSize = 0;
867   uint64_t VMSize = 0;
868   for (const MCSection &Sec : Asm) {
869     uint64_t Address = getSectionAddress(&Sec);
870     uint64_t Size = Asm.getSectionAddressSize(Sec);
871     uint64_t FileSize = Asm.getSectionFileSize(Sec);
872     FileSize += getPaddingSize(Asm, &Sec);
873 
874     VMSize = std::max(VMSize, Address + Size);
875 
876     if (Sec.isVirtualSection())
877       continue;
878 
879     SectionDataSize = std::max(SectionDataSize, Address + Size);
880     SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
881   }
882 
883   // The section data is padded to pointer size bytes.
884   //
885   // FIXME: Is this machine dependent?
886   unsigned SectionDataPadding =
887       offsetToAlignment(SectionDataFileSize, is64Bit() ? Align(8) : Align(4));
888   SectionDataFileSize += SectionDataPadding;
889 
890   // Write the prolog, starting with the header and load command...
891   writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
892               Asm.getSubsectionsViaSymbols());
893   uint32_t Prot =
894       MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
895   writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
896                           SectionDataSize, Prot, Prot);
897 
898   // ... and then the section headers.
899   uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
900   for (const MCSection &Section : Asm) {
901     const auto &Sec = cast<MCSectionMachO>(Section);
902     std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
903     unsigned NumRelocs = Relocs.size();
904     uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
905     unsigned Flags = Sec.getTypeAndAttributes();
906     if (Sec.hasInstructions())
907       Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
908     writeSection(Asm, Sec, getSectionAddress(&Sec), SectionStart, Flags,
909                  RelocTableEnd, NumRelocs);
910     RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
911   }
912 
913   // Write out the deployment target information, if it's available.
914   auto EmitDeploymentTargetVersion =
915       [&](const MCAssembler::VersionInfoType &VersionInfo) {
916         auto EncodeVersion = [](VersionTuple V) -> uint32_t {
917           assert(!V.empty() && "empty version");
918           unsigned Update = V.getSubminor().value_or(0);
919           unsigned Minor = V.getMinor().value_or(0);
920           assert(Update < 256 && "unencodable update target version");
921           assert(Minor < 256 && "unencodable minor target version");
922           assert(V.getMajor() < 65536 && "unencodable major target version");
923           return Update | (Minor << 8) | (V.getMajor() << 16);
924         };
925         uint32_t EncodedVersion = EncodeVersion(VersionTuple(
926             VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
927         uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
928                                   ? EncodeVersion(VersionInfo.SDKVersion)
929                                   : 0;
930         if (VersionInfo.EmitBuildVersion) {
931           // FIXME: Currently empty tools. Add clang version in the future.
932           W.write<uint32_t>(MachO::LC_BUILD_VERSION);
933           W.write<uint32_t>(sizeof(MachO::build_version_command));
934           W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
935           W.write<uint32_t>(EncodedVersion);
936           W.write<uint32_t>(SDKVersion);
937           W.write<uint32_t>(0); // Empty tools list.
938         } else {
939           MachO::LoadCommandType LCType =
940               getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
941           W.write<uint32_t>(LCType);
942           W.write<uint32_t>(sizeof(MachO::version_min_command));
943           W.write<uint32_t>(EncodedVersion);
944           W.write<uint32_t>(SDKVersion);
945         }
946       };
947   if (VersionInfo.Major != 0)
948     EmitDeploymentTargetVersion(VersionInfo);
949   if (TargetVariantVersionInfo.Major != 0)
950     EmitDeploymentTargetVersion(TargetVariantVersionInfo);
951 
952   // Write the data-in-code load command, if used.
953   uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
954   if (NumDataRegions) {
955     uint64_t DataRegionsOffset = RelocTableEnd;
956     uint64_t DataRegionsSize = NumDataRegions * 8;
957     writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
958                              DataRegionsSize);
959   }
960 
961   // Write the loh load command, if used.
962   uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
963   if (LOHSize)
964     writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
965                              DataInCodeTableEnd, LOHSize);
966 
967   // Write the symbol table load command, if used.
968   if (NumSymbols) {
969     unsigned FirstLocalSymbol = 0;
970     unsigned NumLocalSymbols = LocalSymbolData.size();
971     unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
972     unsigned NumExternalSymbols = ExternalSymbolData.size();
973     unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
974     unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
975     unsigned NumIndirectSymbols = IndirectSymbols.size();
976     unsigned NumSymTabSymbols =
977       NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
978     uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
979     uint64_t IndirectSymbolOffset = 0;
980 
981     // If used, the indirect symbols are written after the section data.
982     if (NumIndirectSymbols)
983       IndirectSymbolOffset = LOHTableEnd;
984 
985     // The symbol table is written after the indirect symbol data.
986     uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
987 
988     // The string table is written after symbol table.
989     uint64_t StringTableOffset =
990       SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
991                                               sizeof(MachO::nlist_64) :
992                                               sizeof(MachO::nlist));
993     writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
994                            StringTableOffset, StringTable.getSize());
995 
996     writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
997                              FirstExternalSymbol, NumExternalSymbols,
998                              FirstUndefinedSymbol, NumUndefinedSymbols,
999                              IndirectSymbolOffset, NumIndirectSymbols);
1000   }
1001 
1002   // Write the linker options load commands.
1003   for (const auto &Option : Asm.getLinkerOptions())
1004     writeLinkerOptionsLoadCommand(Option);
1005 
1006   // Write the actual section data.
1007   for (const MCSection &Sec : Asm) {
1008     Asm.writeSectionData(W.OS, &Sec);
1009 
1010     uint64_t Pad = getPaddingSize(Asm, &Sec);
1011     W.OS.write_zeros(Pad);
1012   }
1013 
1014   // Write the extra padding.
1015   W.OS.write_zeros(SectionDataPadding);
1016 
1017   // Write the relocation entries.
1018   for (const MCSection &Sec : Asm) {
1019     // Write the section relocation entries, in reverse order to match 'as'
1020     // (approximately, the exact algorithm is more complicated than this).
1021     std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
1022     for (const RelAndSymbol &Rel : llvm::reverse(Relocs)) {
1023       W.write<uint32_t>(Rel.MRE.r_word0);
1024       W.write<uint32_t>(Rel.MRE.r_word1);
1025     }
1026   }
1027 
1028   // Write out the data-in-code region payload, if there is one.
1029   for (DataRegionData Data : DataRegions) {
1030     uint64_t Start = getSymbolAddress(*Data.Start, Asm);
1031     uint64_t End;
1032     if (Data.End)
1033       End = getSymbolAddress(*Data.End, Asm);
1034     else
1035       report_fatal_error("Data region not terminated");
1036 
1037     LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data.Kind
1038                       << "  start: " << Start << "(" << Data.Start->getName()
1039                       << ")" << "  end: " << End << "(" << Data.End->getName()
1040                       << ")" << "  size: " << End - Start << "\n");
1041     W.write<uint32_t>(Start);
1042     W.write<uint16_t>(End - Start);
1043     W.write<uint16_t>(Data.Kind);
1044   }
1045 
1046   // Write out the loh commands, if there is one.
1047   if (LOHSize) {
1048 #ifndef NDEBUG
1049     unsigned Start = W.OS.tell();
1050 #endif
1051     Asm.getLOHContainer().emit(Asm, *this);
1052     // Pad to a multiple of the pointer size.
1053     W.OS.write_zeros(
1054         offsetToAlignment(LOHRawSize, is64Bit() ? Align(8) : Align(4)));
1055     assert(W.OS.tell() - Start == LOHSize);
1056   }
1057 
1058   // Write the symbol table data, if used.
1059   if (NumSymbols) {
1060     // Write the indirect symbol entries.
1061     for (auto &ISD : IndirectSymbols) {
1062       // Indirect symbols in the non-lazy symbol pointer section have some
1063       // special handling.
1064       const MCSectionMachO &Section =
1065           static_cast<const MCSectionMachO &>(*ISD.Section);
1066       if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
1067         // If this symbol is defined and internal, mark it as such.
1068         if (ISD.Symbol->isDefined() && !ISD.Symbol->isExternal()) {
1069           uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
1070           if (ISD.Symbol->isAbsolute())
1071             Flags |= MachO::INDIRECT_SYMBOL_ABS;
1072           W.write<uint32_t>(Flags);
1073           continue;
1074         }
1075       }
1076 
1077       W.write<uint32_t>(ISD.Symbol->getIndex());
1078     }
1079 
1080     // FIXME: Check that offsets match computed ones.
1081 
1082     // Write the symbol table entries.
1083     for (auto *SymbolData :
1084          {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1085       for (MachSymbolData &Entry : *SymbolData)
1086         writeNlist(Entry, Asm);
1087 
1088     // Write the string table.
1089     StringTable.write(W.OS);
1090   }
1091 
1092   return W.OS.tell() - StartOffset;
1093 }
1094 
1095 std::unique_ptr<MCObjectWriter>
1096 llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1097                              raw_pwrite_stream &OS, bool IsLittleEndian) {
1098   return std::make_unique<MachObjectWriter>(std::move(MOTW), OS,
1099                                              IsLittleEndian);
1100 }
1101