xref: /llvm-project/llvm/lib/MC/MachObjectWriter.cpp (revision b75453bc07dabe8e0dc0efb0766a4238e3df6712)
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 (MCSection &Sec : Asm)
576     SectionIndexMap[&Sec] = Index++;
577   assert(Index <= 256 && "Too many sections!");
578 
579   // Build the string table.
580   for (const MCSymbol &Symbol : Asm.symbols()) {
581     if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
582       continue;
583 
584     StringTable.add(Symbol.getName());
585   }
586   StringTable.finalize();
587 
588   // Build the symbol arrays but only for non-local symbols.
589   //
590   // The particular order that we collect and then sort the symbols is chosen to
591   // match 'as'. Even though it doesn't matter for correctness, this is
592   // important for letting us diff .o files.
593   for (const MCSymbol &Symbol : Asm.symbols()) {
594     // Ignore non-linker visible symbols.
595     if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
596       continue;
597 
598     if (!Symbol.isExternal() && !Symbol.isUndefined())
599       continue;
600 
601     MachSymbolData MSD;
602     MSD.Symbol = &Symbol;
603     MSD.StringIndex = StringTable.getOffset(Symbol.getName());
604 
605     if (Symbol.isUndefined()) {
606       MSD.SectionIndex = 0;
607       UndefinedSymbolData.push_back(MSD);
608     } else if (Symbol.isAbsolute()) {
609       MSD.SectionIndex = 0;
610       ExternalSymbolData.push_back(MSD);
611     } else {
612       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
613       assert(MSD.SectionIndex && "Invalid section index!");
614       ExternalSymbolData.push_back(MSD);
615     }
616   }
617 
618   // Now add the data for local symbols.
619   for (const MCSymbol &Symbol : Asm.symbols()) {
620     // Ignore non-linker visible symbols.
621     if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
622       continue;
623 
624     if (Symbol.isExternal() || Symbol.isUndefined())
625       continue;
626 
627     MachSymbolData MSD;
628     MSD.Symbol = &Symbol;
629     MSD.StringIndex = StringTable.getOffset(Symbol.getName());
630 
631     if (Symbol.isAbsolute()) {
632       MSD.SectionIndex = 0;
633       LocalSymbolData.push_back(MSD);
634     } else {
635       MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
636       assert(MSD.SectionIndex && "Invalid section index!");
637       LocalSymbolData.push_back(MSD);
638     }
639   }
640 
641   // External and undefined symbols are required to be in lexicographic order.
642   llvm::sort(ExternalSymbolData);
643   llvm::sort(UndefinedSymbolData);
644 
645   // Set the symbol indices.
646   Index = 0;
647   for (auto *SymbolData :
648        {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
649     for (MachSymbolData &Entry : *SymbolData)
650       Entry.Symbol->setIndex(Index++);
651 
652   for (const MCSection &Section : Asm) {
653     for (RelAndSymbol &Rel : Relocations[&Section]) {
654       if (!Rel.Sym)
655         continue;
656 
657       // Set the Index and the IsExtern bit.
658       unsigned Index = Rel.Sym->getIndex();
659       assert(isInt<24>(Index));
660       if (W.Endian == llvm::endianness::little)
661         Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
662       else
663         Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
664     }
665   }
666 }
667 
668 void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm) {
669   // Assign layout order indices to sections.
670   unsigned i = 0;
671   // Compute the section layout order. Virtual sections must go last.
672   for (MCSection &Sec : Asm) {
673     if (!Sec.isVirtualSection()) {
674       SectionOrder.push_back(&Sec);
675       cast<MCSectionMachO>(Sec).setLayoutOrder(i++);
676     }
677   }
678   for (MCSection &Sec : Asm) {
679     if (Sec.isVirtualSection()) {
680       SectionOrder.push_back(&Sec);
681       cast<MCSectionMachO>(Sec).setLayoutOrder(i++);
682     }
683   }
684 
685   uint64_t StartAddress = 0;
686   for (const MCSection *Sec : SectionOrder) {
687     StartAddress = alignTo(StartAddress, Sec->getAlign());
688     SectionAddress[Sec] = StartAddress;
689     StartAddress += Asm.getSectionAddressSize(*Sec);
690 
691     // Explicitly pad the section to match the alignment requirements of the
692     // following one. This is for 'gas' compatibility, it shouldn't
693     /// strictly be necessary.
694     StartAddress += getPaddingSize(Asm, Sec);
695   }
696 }
697 
698 void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm) {
699   computeSectionAddresses(Asm);
700 
701   // Create symbol data for any indirect symbols.
702   bindIndirectSymbols(Asm);
703 }
704 
705 bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
706     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
707     bool InSet, bool IsPCRel) const {
708   if (InSet)
709     return true;
710 
711   // The effective address is
712   //     addr(atom(A)) + offset(A)
713   //   - addr(atom(B)) - offset(B)
714   // and the offsets are not relocatable, so the fixup is fully resolved when
715   //  addr(atom(A)) - addr(atom(B)) == 0.
716   const MCSymbol &SA = findAliasedSymbol(SymA);
717   const MCSection &SecA = SA.getSection();
718   const MCSection &SecB = *FB.getParent();
719 
720   if (IsPCRel) {
721     // The simple (Darwin, except on x86_64) way of dealing with this was to
722     // assume that any reference to a temporary symbol *must* be a temporary
723     // symbol in the same atom, unless the sections differ. Therefore, any PCrel
724     // relocation to a temporary symbol (in the same section) is fully
725     // resolved. This also works in conjunction with absolutized .set, which
726     // requires the compiler to use .set to absolutize the differences between
727     // symbols which the compiler knows to be assembly time constants, so we
728     // don't need to worry about considering symbol differences fully resolved.
729     //
730     // If the file isn't using sub-sections-via-symbols, we can make the
731     // same assumptions about any symbol that we normally make about
732     // assembler locals.
733 
734     bool hasReliableSymbolDifference = isX86_64();
735     if (!hasReliableSymbolDifference) {
736       if (!SA.isInSection() || &SecA != &SecB ||
737           (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
738            Asm.getSubsectionsViaSymbols()))
739         return false;
740       return true;
741     }
742   }
743 
744   // If they are not in the same section, we can't compute the diff.
745   if (&SecA != &SecB)
746     return false;
747 
748   // If the atoms are the same, they are guaranteed to have the same address.
749   return SA.getFragment()->getAtom() == FB.getAtom();
750 }
751 
752 static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) {
753   switch (Type) {
754   case MCVM_OSXVersionMin:     return MachO::LC_VERSION_MIN_MACOSX;
755   case MCVM_IOSVersionMin:     return MachO::LC_VERSION_MIN_IPHONEOS;
756   case MCVM_TvOSVersionMin:    return MachO::LC_VERSION_MIN_TVOS;
757   case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
758   }
759   llvm_unreachable("Invalid mc version min type");
760 }
761 
762 void MachObjectWriter::populateAddrSigSection(MCAssembler &Asm) {
763   MCSection *AddrSigSection =
764       Asm.getContext().getObjectFileInfo()->getAddrSigSection();
765   unsigned Log2Size = is64Bit() ? 3 : 2;
766   for (const MCSymbol *S : getAddrsigSyms()) {
767     if (!S->isRegistered())
768       continue;
769     MachO::any_relocation_info MRE;
770     MRE.r_word0 = 0;
771     MRE.r_word1 = (Log2Size << 25) | (MachO::GENERIC_RELOC_VANILLA << 28);
772     addRelocation(S, AddrSigSection, MRE);
773   }
774 }
775 
776 uint64_t MachObjectWriter::writeObject(MCAssembler &Asm) {
777   uint64_t StartOffset = W.OS.tell();
778 
779   populateAddrSigSection(Asm);
780 
781   // Compute symbol table information and bind symbol indices.
782   computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
783                      UndefinedSymbolData);
784 
785   if (!Asm.CGProfile.empty()) {
786     MCSection *CGProfileSection = Asm.getContext().getMachOSection(
787         "__LLVM", "__cg_profile", 0, SectionKind::getMetadata());
788     auto &Frag = cast<MCDataFragment>(*CGProfileSection->begin());
789     Frag.getContents().clear();
790     raw_svector_ostream OS(Frag.getContents());
791     for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
792       uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
793       uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
794       support::endian::write(OS, FromIndex, W.Endian);
795       support::endian::write(OS, ToIndex, W.Endian);
796       support::endian::write(OS, CGPE.Count, W.Endian);
797     }
798   }
799 
800   unsigned NumSections = Asm.end() - Asm.begin();
801   const MCAssembler::VersionInfoType &VersionInfo = Asm.getVersionInfo();
802 
803   // The section data starts after the header, the segment load command (and
804   // section headers) and the symbol table.
805   unsigned NumLoadCommands = 1;
806   uint64_t LoadCommandsSize = is64Bit() ?
807     sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
808     sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
809 
810   // Add the deployment target version info load command size, if used.
811   if (VersionInfo.Major != 0) {
812     ++NumLoadCommands;
813     if (VersionInfo.EmitBuildVersion)
814       LoadCommandsSize += sizeof(MachO::build_version_command);
815     else
816       LoadCommandsSize += sizeof(MachO::version_min_command);
817   }
818 
819   const MCAssembler::VersionInfoType &TargetVariantVersionInfo =
820       Asm.getDarwinTargetVariantVersionInfo();
821 
822   // Add the target variant version info load command size, if used.
823   if (TargetVariantVersionInfo.Major != 0) {
824     ++NumLoadCommands;
825     assert(TargetVariantVersionInfo.EmitBuildVersion &&
826            "target variant should use build version");
827     LoadCommandsSize += sizeof(MachO::build_version_command);
828   }
829 
830   // Add the data-in-code load command size, if used.
831   unsigned NumDataRegions = DataRegions.size();
832   if (NumDataRegions) {
833     ++NumLoadCommands;
834     LoadCommandsSize += sizeof(MachO::linkedit_data_command);
835   }
836 
837   // Add the loh load command size, if used.
838   uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(Asm, *this);
839   uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
840   if (LOHSize) {
841     ++NumLoadCommands;
842     LoadCommandsSize += sizeof(MachO::linkedit_data_command);
843   }
844 
845   // Add the symbol table load command sizes, if used.
846   unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
847     UndefinedSymbolData.size();
848   if (NumSymbols) {
849     NumLoadCommands += 2;
850     LoadCommandsSize += (sizeof(MachO::symtab_command) +
851                          sizeof(MachO::dysymtab_command));
852   }
853 
854   // Add the linker option load commands sizes.
855   for (const auto &Option : Asm.getLinkerOptions()) {
856     ++NumLoadCommands;
857     LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
858   }
859 
860   // Compute the total size of the section data, as well as its file size and vm
861   // size.
862   uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
863                                sizeof(MachO::mach_header)) + LoadCommandsSize;
864   uint64_t SectionDataSize = 0;
865   uint64_t SectionDataFileSize = 0;
866   uint64_t VMSize = 0;
867   for (const MCSection &Sec : Asm) {
868     uint64_t Address = getSectionAddress(&Sec);
869     uint64_t Size = Asm.getSectionAddressSize(Sec);
870     uint64_t FileSize = Asm.getSectionFileSize(Sec);
871     FileSize += getPaddingSize(Asm, &Sec);
872 
873     VMSize = std::max(VMSize, Address + Size);
874 
875     if (Sec.isVirtualSection())
876       continue;
877 
878     SectionDataSize = std::max(SectionDataSize, Address + Size);
879     SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
880   }
881 
882   // The section data is padded to pointer size bytes.
883   //
884   // FIXME: Is this machine dependent?
885   unsigned SectionDataPadding =
886       offsetToAlignment(SectionDataFileSize, is64Bit() ? Align(8) : Align(4));
887   SectionDataFileSize += SectionDataPadding;
888 
889   // Write the prolog, starting with the header and load command...
890   writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
891               Asm.getSubsectionsViaSymbols());
892   uint32_t Prot =
893       MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
894   writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
895                           SectionDataSize, Prot, Prot);
896 
897   // ... and then the section headers.
898   uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
899   for (const MCSection &Section : Asm) {
900     const auto &Sec = cast<MCSectionMachO>(Section);
901     std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
902     unsigned NumRelocs = Relocs.size();
903     uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
904     unsigned Flags = Sec.getTypeAndAttributes();
905     if (Sec.hasInstructions())
906       Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
907     writeSection(Asm, Sec, getSectionAddress(&Sec), SectionStart, Flags,
908                  RelocTableEnd, NumRelocs);
909     RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
910   }
911 
912   // Write out the deployment target information, if it's available.
913   auto EmitDeploymentTargetVersion =
914       [&](const MCAssembler::VersionInfoType &VersionInfo) {
915         auto EncodeVersion = [](VersionTuple V) -> uint32_t {
916           assert(!V.empty() && "empty version");
917           unsigned Update = V.getSubminor().value_or(0);
918           unsigned Minor = V.getMinor().value_or(0);
919           assert(Update < 256 && "unencodable update target version");
920           assert(Minor < 256 && "unencodable minor target version");
921           assert(V.getMajor() < 65536 && "unencodable major target version");
922           return Update | (Minor << 8) | (V.getMajor() << 16);
923         };
924         uint32_t EncodedVersion = EncodeVersion(VersionTuple(
925             VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
926         uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
927                                   ? EncodeVersion(VersionInfo.SDKVersion)
928                                   : 0;
929         if (VersionInfo.EmitBuildVersion) {
930           // FIXME: Currently empty tools. Add clang version in the future.
931           W.write<uint32_t>(MachO::LC_BUILD_VERSION);
932           W.write<uint32_t>(sizeof(MachO::build_version_command));
933           W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
934           W.write<uint32_t>(EncodedVersion);
935           W.write<uint32_t>(SDKVersion);
936           W.write<uint32_t>(0); // Empty tools list.
937         } else {
938           MachO::LoadCommandType LCType =
939               getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
940           W.write<uint32_t>(LCType);
941           W.write<uint32_t>(sizeof(MachO::version_min_command));
942           W.write<uint32_t>(EncodedVersion);
943           W.write<uint32_t>(SDKVersion);
944         }
945       };
946   if (VersionInfo.Major != 0)
947     EmitDeploymentTargetVersion(VersionInfo);
948   if (TargetVariantVersionInfo.Major != 0)
949     EmitDeploymentTargetVersion(TargetVariantVersionInfo);
950 
951   // Write the data-in-code load command, if used.
952   uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
953   if (NumDataRegions) {
954     uint64_t DataRegionsOffset = RelocTableEnd;
955     uint64_t DataRegionsSize = NumDataRegions * 8;
956     writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
957                              DataRegionsSize);
958   }
959 
960   // Write the loh load command, if used.
961   uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
962   if (LOHSize)
963     writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
964                              DataInCodeTableEnd, LOHSize);
965 
966   // Write the symbol table load command, if used.
967   if (NumSymbols) {
968     unsigned FirstLocalSymbol = 0;
969     unsigned NumLocalSymbols = LocalSymbolData.size();
970     unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
971     unsigned NumExternalSymbols = ExternalSymbolData.size();
972     unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
973     unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
974     unsigned NumIndirectSymbols = IndirectSymbols.size();
975     unsigned NumSymTabSymbols =
976       NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
977     uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
978     uint64_t IndirectSymbolOffset = 0;
979 
980     // If used, the indirect symbols are written after the section data.
981     if (NumIndirectSymbols)
982       IndirectSymbolOffset = LOHTableEnd;
983 
984     // The symbol table is written after the indirect symbol data.
985     uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
986 
987     // The string table is written after symbol table.
988     uint64_t StringTableOffset =
989       SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
990                                               sizeof(MachO::nlist_64) :
991                                               sizeof(MachO::nlist));
992     writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
993                            StringTableOffset, StringTable.getSize());
994 
995     writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
996                              FirstExternalSymbol, NumExternalSymbols,
997                              FirstUndefinedSymbol, NumUndefinedSymbols,
998                              IndirectSymbolOffset, NumIndirectSymbols);
999   }
1000 
1001   // Write the linker options load commands.
1002   for (const auto &Option : Asm.getLinkerOptions())
1003     writeLinkerOptionsLoadCommand(Option);
1004 
1005   // Write the actual section data.
1006   for (const MCSection &Sec : Asm) {
1007     Asm.writeSectionData(W.OS, &Sec);
1008 
1009     uint64_t Pad = getPaddingSize(Asm, &Sec);
1010     W.OS.write_zeros(Pad);
1011   }
1012 
1013   // Write the extra padding.
1014   W.OS.write_zeros(SectionDataPadding);
1015 
1016   // Write the relocation entries.
1017   for (const MCSection &Sec : Asm) {
1018     // Write the section relocation entries, in reverse order to match 'as'
1019     // (approximately, the exact algorithm is more complicated than this).
1020     std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
1021     for (const RelAndSymbol &Rel : llvm::reverse(Relocs)) {
1022       W.write<uint32_t>(Rel.MRE.r_word0);
1023       W.write<uint32_t>(Rel.MRE.r_word1);
1024     }
1025   }
1026 
1027   // Write out the data-in-code region payload, if there is one.
1028   for (DataRegionData Data : DataRegions) {
1029     uint64_t Start = getSymbolAddress(*Data.Start, Asm);
1030     uint64_t End;
1031     if (Data.End)
1032       End = getSymbolAddress(*Data.End, Asm);
1033     else
1034       report_fatal_error("Data region not terminated");
1035 
1036     LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data.Kind
1037                       << "  start: " << Start << "(" << Data.Start->getName()
1038                       << ")" << "  end: " << End << "(" << Data.End->getName()
1039                       << ")" << "  size: " << End - Start << "\n");
1040     W.write<uint32_t>(Start);
1041     W.write<uint16_t>(End - Start);
1042     W.write<uint16_t>(Data.Kind);
1043   }
1044 
1045   // Write out the loh commands, if there is one.
1046   if (LOHSize) {
1047 #ifndef NDEBUG
1048     unsigned Start = W.OS.tell();
1049 #endif
1050     Asm.getLOHContainer().emit(Asm, *this);
1051     // Pad to a multiple of the pointer size.
1052     W.OS.write_zeros(
1053         offsetToAlignment(LOHRawSize, is64Bit() ? Align(8) : Align(4)));
1054     assert(W.OS.tell() - Start == LOHSize);
1055   }
1056 
1057   // Write the symbol table data, if used.
1058   if (NumSymbols) {
1059     // Write the indirect symbol entries.
1060     for (auto &ISD : IndirectSymbols) {
1061       // Indirect symbols in the non-lazy symbol pointer section have some
1062       // special handling.
1063       const MCSectionMachO &Section =
1064           static_cast<const MCSectionMachO &>(*ISD.Section);
1065       if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
1066         // If this symbol is defined and internal, mark it as such.
1067         if (ISD.Symbol->isDefined() && !ISD.Symbol->isExternal()) {
1068           uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
1069           if (ISD.Symbol->isAbsolute())
1070             Flags |= MachO::INDIRECT_SYMBOL_ABS;
1071           W.write<uint32_t>(Flags);
1072           continue;
1073         }
1074       }
1075 
1076       W.write<uint32_t>(ISD.Symbol->getIndex());
1077     }
1078 
1079     // FIXME: Check that offsets match computed ones.
1080 
1081     // Write the symbol table entries.
1082     for (auto *SymbolData :
1083          {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1084       for (MachSymbolData &Entry : *SymbolData)
1085         writeNlist(Entry, Asm);
1086 
1087     // Write the string table.
1088     StringTable.write(W.OS);
1089   }
1090 
1091   return W.OS.tell() - StartOffset;
1092 }
1093 
1094 std::unique_ptr<MCObjectWriter>
1095 llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1096                              raw_pwrite_stream &OS, bool IsLittleEndian) {
1097   return std::make_unique<MachObjectWriter>(std::move(MOTW), OS,
1098                                              IsLittleEndian);
1099 }
1100