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