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