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