Fix a comment.
[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/ADT/StringMap.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCAsmLayout.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Object/MachOFormat.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23
24 // FIXME: Gross.
25 #include "../Target/X86/X86FixupKinds.h"
26
27 #include <vector>
28 using namespace llvm;
29 using namespace llvm::object;
30
31 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
32 static unsigned getFixupKindLog2Size(unsigned Kind) {
33   switch (Kind) {
34   default: llvm_unreachable("invalid fixup kind!");
35   case X86::reloc_pcrel_1byte:
36   case FK_Data_1: return 0;
37   case X86::reloc_pcrel_2byte:
38   case FK_Data_2: return 1;
39   case X86::reloc_pcrel_4byte:
40   case X86::reloc_riprel_4byte:
41   case X86::reloc_riprel_4byte_movq_load:
42   case X86::reloc_signed_4byte:
43   case FK_Data_4: return 2;
44   case FK_Data_8: return 3;
45   }
46 }
47
48 static bool isFixupKindPCRel(unsigned Kind) {
49   switch (Kind) {
50   default:
51     return false;
52   case X86::reloc_pcrel_1byte:
53   case X86::reloc_pcrel_2byte:
54   case X86::reloc_pcrel_4byte:
55   case X86::reloc_riprel_4byte:
56   case X86::reloc_riprel_4byte_movq_load:
57     return true;
58   }
59 }
60
61 static bool isFixupKindRIPRel(unsigned Kind) {
62   return Kind == X86::reloc_riprel_4byte ||
63     Kind == X86::reloc_riprel_4byte_movq_load;
64 }
65
66 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
67   // Undefined symbols are always extern.
68   if (SD->Symbol->isUndefined())
69     return true;
70
71   // References to weak definitions require external relocation entries; the
72   // definition may not always be the one in the same object file.
73   if (SD->getFlags() & SF_WeakDefinition)
74     return true;
75
76   // Otherwise, we can use an internal relocation.
77   return false;
78 }
79
80 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
81                                           const MCValue Target,
82                                           const MCSymbolData *BaseSymbol) {
83   // The effective fixup address is
84   //     addr(atom(A)) + offset(A)
85   //   - addr(atom(B)) - offset(B)
86   //   - addr(BaseSymbol) + <fixup offset from base symbol>
87   // and the offsets are not relocatable, so the fixup is fully resolved when
88   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
89   //
90   // Note that "false" is almost always conservatively correct (it means we emit
91   // a relocation which is unnecessary), except when it would force us to emit a
92   // relocation which the target cannot encode.
93
94   const MCSymbolData *A_Base = 0, *B_Base = 0;
95   if (const MCSymbolRefExpr *A = Target.getSymA()) {
96     // Modified symbol references cannot be resolved.
97     if (A->getKind() != MCSymbolRefExpr::VK_None)
98       return false;
99
100     A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
101     if (!A_Base)
102       return false;
103   }
104
105   if (const MCSymbolRefExpr *B = Target.getSymB()) {
106     // Modified symbol references cannot be resolved.
107     if (B->getKind() != MCSymbolRefExpr::VK_None)
108       return false;
109
110     B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
111     if (!B_Base)
112       return false;
113   }
114
115   // If there is no base, A and B have to be the same atom for this fixup to be
116   // fully resolved.
117   if (!BaseSymbol)
118     return A_Base == B_Base;
119
120   // Otherwise, B must be missing and A must be the base.
121   return !B_Base && BaseSymbol == A_Base;
122 }
123
124 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
125                                                 const MCValue Target,
126                                                 const MCSection *BaseSection) {
127   // The effective fixup address is
128   //     addr(atom(A)) + offset(A)
129   //   - addr(atom(B)) - offset(B)
130   //   - addr(<base symbol>) + <fixup offset from base symbol>
131   // and the offsets are not relocatable, so the fixup is fully resolved when
132   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
133   //
134   // The simple (Darwin, except on x86_64) way of dealing with this was to
135   // assume that any reference to a temporary symbol *must* be a temporary
136   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
137   // relocation to a temporary symbol (in the same section) is fully
138   // resolved. This also works in conjunction with absolutized .set, which
139   // requires the compiler to use .set to absolutize the differences between
140   // symbols which the compiler knows to be assembly time constants, so we don't
141   // need to worry about considering symbol differences fully resolved.
142
143   // Non-relative fixups are only resolved if constant.
144   if (!BaseSection)
145     return Target.isAbsolute();
146
147   // Otherwise, relative fixups are only resolved if not a difference and the
148   // target is a temporary in the same section.
149   if (Target.isAbsolute() || Target.getSymB())
150     return false;
151
152   const MCSymbol *A = &Target.getSymA()->getSymbol();
153   if (!A->isTemporary() || !A->isInSection() ||
154       &A->getSection() != BaseSection)
155     return false;
156
157   return true;
158 }
159
160 namespace {
161
162 class MachObjectWriter : public MCObjectWriter {
163   /// MachSymbolData - Helper struct for containing some precomputed information
164   /// on symbols.
165   struct MachSymbolData {
166     MCSymbolData *SymbolData;
167     uint64_t StringIndex;
168     uint8_t SectionIndex;
169
170     // Support lexicographic sorting.
171     bool operator<(const MachSymbolData &RHS) const {
172       return SymbolData->getSymbol().getName() <
173              RHS.SymbolData->getSymbol().getName();
174     }
175   };
176
177   /// @name Relocation Data
178   /// @{
179
180   struct MachRelocationEntry {
181     uint32_t Word0;
182     uint32_t Word1;
183   };
184
185   llvm::DenseMap<const MCSectionData*,
186                  std::vector<MachRelocationEntry> > Relocations;
187   llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
188
189   /// @}
190   /// @name Symbol Table Data
191   /// @{
192
193   SmallString<256> StringTable;
194   std::vector<MachSymbolData> LocalSymbolData;
195   std::vector<MachSymbolData> ExternalSymbolData;
196   std::vector<MachSymbolData> UndefinedSymbolData;
197
198   /// @}
199
200   unsigned Is64Bit : 1;
201
202   uint32_t CPUType;
203   uint32_t CPUSubtype;
204
205 public:
206   MachObjectWriter(raw_ostream &_OS,
207                    bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
208                    bool _IsLittleEndian)
209     : MCObjectWriter(_OS, _IsLittleEndian),
210       Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
211   }
212
213   void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
214                    bool SubsectionsViaSymbols) {
215     uint32_t Flags = 0;
216
217     if (SubsectionsViaSymbols)
218       Flags |= macho::HF_SubsectionsViaSymbols;
219
220     // struct mach_header (28 bytes) or
221     // struct mach_header_64 (32 bytes)
222
223     uint64_t Start = OS.tell();
224     (void) Start;
225
226     Write32(Is64Bit ? macho::HM_Object64 : macho::HM_Object32);
227
228     Write32(CPUType);
229     Write32(CPUSubtype);
230
231     Write32(macho::HFT_Object);
232     Write32(NumLoadCommands);
233     Write32(LoadCommandsSize);
234     Write32(Flags);
235     if (Is64Bit)
236       Write32(0); // reserved
237
238     assert(OS.tell() - Start == Is64Bit ? 
239            macho::Header64Size : macho::Header32Size);
240   }
241
242   /// WriteSegmentLoadCommand - Write a segment load command.
243   ///
244   /// \arg NumSections - The number of sections in this segment.
245   /// \arg SectionDataSize - The total size of the sections.
246   void WriteSegmentLoadCommand(unsigned NumSections,
247                                uint64_t VMSize,
248                                uint64_t SectionDataStartOffset,
249                                uint64_t SectionDataSize) {
250     // struct segment_command (56 bytes) or
251     // struct segment_command_64 (72 bytes)
252
253     uint64_t Start = OS.tell();
254     (void) Start;
255
256     unsigned SegmentLoadCommandSize = Is64Bit ? macho::SegmentLoadCommand64Size:
257       macho::SegmentLoadCommand32Size;
258     Write32(Is64Bit ? macho::LCT_Segment64 : macho::LCT_Segment);
259     Write32(SegmentLoadCommandSize +
260             NumSections * (Is64Bit ? macho::Section64Size :
261                            macho::Section32Size));
262
263     WriteBytes("", 16);
264     if (Is64Bit) {
265       Write64(0); // vmaddr
266       Write64(VMSize); // vmsize
267       Write64(SectionDataStartOffset); // file offset
268       Write64(SectionDataSize); // file size
269     } else {
270       Write32(0); // vmaddr
271       Write32(VMSize); // vmsize
272       Write32(SectionDataStartOffset); // file offset
273       Write32(SectionDataSize); // file size
274     }
275     Write32(0x7); // maxprot
276     Write32(0x7); // initprot
277     Write32(NumSections);
278     Write32(0); // flags
279
280     assert(OS.tell() - Start == SegmentLoadCommandSize);
281   }
282
283   void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
284                     const MCSectionData &SD, uint64_t FileOffset,
285                     uint64_t RelocationsStart, unsigned NumRelocations) {
286     uint64_t SectionSize = Layout.getSectionSize(&SD);
287
288     // The offset is unused for virtual sections.
289     if (SD.getSection().isVirtualSection()) {
290       assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
291       FileOffset = 0;
292     }
293
294     // struct section (68 bytes) or
295     // struct section_64 (80 bytes)
296
297     uint64_t Start = OS.tell();
298     (void) Start;
299
300     const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
301     WriteBytes(Section.getSectionName(), 16);
302     WriteBytes(Section.getSegmentName(), 16);
303     if (Is64Bit) {
304       Write64(Layout.getSectionAddress(&SD)); // address
305       Write64(SectionSize); // size
306     } else {
307       Write32(Layout.getSectionAddress(&SD)); // address
308       Write32(SectionSize); // size
309     }
310     Write32(FileOffset);
311
312     unsigned Flags = Section.getTypeAndAttributes();
313     if (SD.hasInstructions())
314       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
315
316     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
317     Write32(Log2_32(SD.getAlignment()));
318     Write32(NumRelocations ? RelocationsStart : 0);
319     Write32(NumRelocations);
320     Write32(Flags);
321     Write32(IndirectSymBase.lookup(&SD)); // reserved1
322     Write32(Section.getStubSize()); // reserved2
323     if (Is64Bit)
324       Write32(0); // reserved3
325
326     assert(OS.tell() - Start == Is64Bit ? macho::Section64Size :
327            macho::Section32Size);
328   }
329
330   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
331                               uint32_t StringTableOffset,
332                               uint32_t StringTableSize) {
333     // struct symtab_command (24 bytes)
334
335     uint64_t Start = OS.tell();
336     (void) Start;
337
338     Write32(macho::LCT_Symtab);
339     Write32(macho::SymtabLoadCommandSize);
340     Write32(SymbolOffset);
341     Write32(NumSymbols);
342     Write32(StringTableOffset);
343     Write32(StringTableSize);
344
345     assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
346   }
347
348   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
349                                 uint32_t NumLocalSymbols,
350                                 uint32_t FirstExternalSymbol,
351                                 uint32_t NumExternalSymbols,
352                                 uint32_t FirstUndefinedSymbol,
353                                 uint32_t NumUndefinedSymbols,
354                                 uint32_t IndirectSymbolOffset,
355                                 uint32_t NumIndirectSymbols) {
356     // struct dysymtab_command (80 bytes)
357
358     uint64_t Start = OS.tell();
359     (void) Start;
360
361     Write32(macho::LCT_Dysymtab);
362     Write32(macho::DysymtabLoadCommandSize);
363     Write32(FirstLocalSymbol);
364     Write32(NumLocalSymbols);
365     Write32(FirstExternalSymbol);
366     Write32(NumExternalSymbols);
367     Write32(FirstUndefinedSymbol);
368     Write32(NumUndefinedSymbols);
369     Write32(0); // tocoff
370     Write32(0); // ntoc
371     Write32(0); // modtaboff
372     Write32(0); // nmodtab
373     Write32(0); // extrefsymoff
374     Write32(0); // nextrefsyms
375     Write32(IndirectSymbolOffset);
376     Write32(NumIndirectSymbols);
377     Write32(0); // extreloff
378     Write32(0); // nextrel
379     Write32(0); // locreloff
380     Write32(0); // nlocrel
381
382     assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
383   }
384
385   void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
386     MCSymbolData &Data = *MSD.SymbolData;
387     const MCSymbol &Symbol = Data.getSymbol();
388     uint8_t Type = 0;
389     uint16_t Flags = Data.getFlags();
390     uint32_t Address = 0;
391
392     // Set the N_TYPE bits. See <mach-o/nlist.h>.
393     //
394     // FIXME: Are the prebound or indirect fields possible here?
395     if (Symbol.isUndefined())
396       Type = macho::STT_Undefined;
397     else if (Symbol.isAbsolute())
398       Type = macho::STT_Absolute;
399     else
400       Type = macho::STT_Section;
401
402     // FIXME: Set STAB bits.
403
404     if (Data.isPrivateExtern())
405       Type |= macho::STF_PrivateExtern;
406
407     // Set external bit.
408     if (Data.isExternal() || Symbol.isUndefined())
409       Type |= macho::STF_External;
410
411     // Compute the symbol address.
412     if (Symbol.isDefined()) {
413       if (Symbol.isAbsolute()) {
414         Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
415       } else {
416         Address = Layout.getSymbolAddress(&Data);
417       }
418     } else if (Data.isCommon()) {
419       // Common symbols are encoded with the size in the address
420       // field, and their alignment in the flags.
421       Address = Data.getCommonSize();
422
423       // Common alignment is packed into the 'desc' bits.
424       if (unsigned Align = Data.getCommonAlignment()) {
425         unsigned Log2Size = Log2_32(Align);
426         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
427         if (Log2Size > 15)
428           report_fatal_error("invalid 'common' alignment '" +
429                             Twine(Align) + "'");
430         // FIXME: Keep this mask with the SymbolFlags enumeration.
431         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
432       }
433     }
434
435     // struct nlist (12 bytes)
436
437     Write32(MSD.StringIndex);
438     Write8(Type);
439     Write8(MSD.SectionIndex);
440
441     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
442     // value.
443     Write16(Flags);
444     if (Is64Bit)
445       Write64(Address);
446     else
447       Write32(Address);
448   }
449
450   // FIXME: We really need to improve the relocation validation. Basically, we
451   // want to implement a separate computation which evaluates the relocation
452   // entry as the linker would, and verifies that the resultant fixup value is
453   // exactly what the encoder wanted. This will catch several classes of
454   // problems:
455   //
456   //  - Relocation entry bugs, the two algorithms are unlikely to have the same
457   //    exact bug.
458   //
459   //  - Relaxation issues, where we forget to relax something.
460   //
461   //  - Input errors, where something cannot be correctly encoded. 'as' allows
462   //    these through in many cases.
463
464   void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
465                               const MCFragment *Fragment,
466                               const MCFixup &Fixup, MCValue Target,
467                               uint64_t &FixedValue) {
468     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
469     unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
470     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
471
472     // See <reloc.h>.
473     uint32_t FixupOffset =
474       Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
475     uint32_t FixupAddress =
476       Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
477     int64_t Value = 0;
478     unsigned Index = 0;
479     unsigned IsExtern = 0;
480     unsigned Type = 0;
481
482     Value = Target.getConstant();
483
484     if (IsPCRel) {
485       // Compensate for the relocation offset, Darwin x86_64 relocations only
486       // have the addend and appear to have attempted to define it to be the
487       // actual expression addend without the PCrel bias. However, instructions
488       // with data following the relocation are not accomodated for (see comment
489       // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
490       Value += 1LL << Log2Size;
491     }
492
493     if (Target.isAbsolute()) { // constant
494       // SymbolNum of 0 indicates the absolute section.
495       Type = macho::RIT_X86_64_Unsigned;
496       Index = 0;
497
498       // FIXME: I believe this is broken, I don't think the linker can
499       // understand it. I think it would require a local relocation, but I'm not
500       // sure if that would work either. The official way to get an absolute
501       // PCrel relocation is to use an absolute symbol (which we don't support
502       // yet).
503       if (IsPCRel) {
504         IsExtern = 1;
505         Type = macho::RIT_X86_64_Branch;
506       }
507     } else if (Target.getSymB()) { // A - B + constant
508       const MCSymbol *A = &Target.getSymA()->getSymbol();
509       MCSymbolData &A_SD = Asm.getSymbolData(*A);
510       const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
511
512       const MCSymbol *B = &Target.getSymB()->getSymbol();
513       MCSymbolData &B_SD = Asm.getSymbolData(*B);
514       const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
515
516       // Neither symbol can be modified.
517       if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
518           Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
519         report_fatal_error("unsupported relocation of modified symbol");
520
521       // We don't support PCrel relocations of differences. Darwin 'as' doesn't
522       // implement most of these correctly.
523       if (IsPCRel)
524         report_fatal_error("unsupported pc-relative relocation of difference");
525
526       // The support for the situation where one or both of the symbols would
527       // require a local relocation is handled just like if the symbols were
528       // external.  This is certainly used in the case of debug sections where
529       // the section has only temporary symbols and thus the symbols don't have
530       // base symbols.  This is encoded using the section ordinal and
531       // non-extern relocation entries.
532
533       // Darwin 'as' doesn't emit correct relocations for this (it ends up with
534       // a single SIGNED relocation); reject it for now.  Except the case where
535       // both symbols don't have a base, equal but both NULL.
536       if (A_Base == B_Base && A_Base)
537         report_fatal_error("unsupported relocation with identical base");
538
539       Value += Layout.getSymbolAddress(&A_SD) -
540                (A_Base == NULL ? 0 : Layout.getSymbolAddress(A_Base));
541       Value -= Layout.getSymbolAddress(&B_SD) -
542                (B_Base == NULL ? 0 : Layout.getSymbolAddress(B_Base));
543
544       if (A_Base) {
545         Index = A_Base->getIndex();
546         IsExtern = 1;
547       }
548       else {
549         Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
550         IsExtern = 0;
551       }
552       Type = macho::RIT_X86_64_Unsigned;
553
554       MachRelocationEntry MRE;
555       MRE.Word0 = FixupOffset;
556       MRE.Word1 = ((Index     <<  0) |
557                    (IsPCRel   << 24) |
558                    (Log2Size  << 25) |
559                    (IsExtern  << 27) |
560                    (Type      << 28));
561       Relocations[Fragment->getParent()].push_back(MRE);
562
563       if (B_Base) {
564         Index = B_Base->getIndex();
565         IsExtern = 1;
566       }
567       else {
568         Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
569         IsExtern = 0;
570       }
571       Type = macho::RIT_X86_64_Subtractor;
572     } else {
573       const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
574       MCSymbolData &SD = Asm.getSymbolData(*Symbol);
575       const MCSymbolData *Base = Asm.getAtom(&SD);
576
577       // Relocations inside debug sections always use local relocations when
578       // possible. This seems to be done because the debugger doesn't fully
579       // understand x86_64 relocation entries, and expects to find values that
580       // have already been fixed up.
581       if (Symbol->isInSection()) {
582         const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
583           Fragment->getParent()->getSection());
584         if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
585           Base = 0;
586       }
587
588       // x86_64 almost always uses external relocations, except when there is no
589       // symbol to use as a base address (a local symbol with no preceeding
590       // non-local symbol).
591       if (Base) {
592         Index = Base->getIndex();
593         IsExtern = 1;
594
595         // Add the local offset, if needed.
596         if (Base != &SD)
597           Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
598       } else if (Symbol->isInSection()) {
599         // The index is the section ordinal (1-based).
600         Index = SD.getFragment()->getParent()->getOrdinal() + 1;
601         IsExtern = 0;
602         Value += Layout.getSymbolAddress(&SD);
603
604         if (IsPCRel)
605           Value -= FixupAddress + (1 << Log2Size);
606       } else {
607         report_fatal_error("unsupported relocation of undefined symbol '" +
608                            Symbol->getName() + "'");
609       }
610
611       MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
612       if (IsPCRel) {
613         if (IsRIPRel) {
614           if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
615             // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
616             // rewrite the movq to an leaq at link time if the symbol ends up in
617             // the same linkage unit.
618             if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
619               Type = macho::RIT_X86_64_GOTLoad;
620             else
621               Type = macho::RIT_X86_64_GOT;
622           }  else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
623             Type = macho::RIT_X86_64_TLV;
624           }  else if (Modifier != MCSymbolRefExpr::VK_None) {
625             report_fatal_error("unsupported symbol modifier in relocation");
626           } else {
627             Type = macho::RIT_X86_64_Signed;
628
629             // The Darwin x86_64 relocation format has a problem where it cannot
630             // encode an address (L<foo> + <constant>) which is outside the atom
631             // containing L<foo>. Generally, this shouldn't occur but it does
632             // happen when we have a RIPrel instruction with data following the
633             // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
634             // adjustment Darwin x86_64 uses, the offset is still negative and
635             // the linker has no way to recognize this.
636             //
637             // To work around this, Darwin uses several special relocation types
638             // to indicate the offsets. However, the specification or
639             // implementation of these seems to also be incomplete; they should
640             // adjust the addend as well based on the actual encoded instruction
641             // (the additional bias), but instead appear to just look at the
642             // final offset.
643             switch (-(Target.getConstant() + (1LL << Log2Size))) {
644             case 1: Type = macho::RIT_X86_64_Signed1; break;
645             case 2: Type = macho::RIT_X86_64_Signed2; break;
646             case 4: Type = macho::RIT_X86_64_Signed4; break;
647             }
648           }
649         } else {
650           if (Modifier != MCSymbolRefExpr::VK_None)
651             report_fatal_error("unsupported symbol modifier in branch "
652                               "relocation");
653
654           Type = macho::RIT_X86_64_Branch;
655         }
656       } else {
657         if (Modifier == MCSymbolRefExpr::VK_GOT) {
658           Type = macho::RIT_X86_64_GOT;
659         } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
660           // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
661           // which case all we do is set the PCrel bit in the relocation entry;
662           // this is used with exception handling, for example. The source is
663           // required to include any necessary offset directly.
664           Type = macho::RIT_X86_64_GOT;
665           IsPCRel = 1;
666         } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
667           report_fatal_error("TLVP symbol modifier should have been rip-rel");
668         } else if (Modifier != MCSymbolRefExpr::VK_None)
669           report_fatal_error("unsupported symbol modifier in relocation");
670         else
671           Type = macho::RIT_X86_64_Unsigned;
672       }
673     }
674
675     // x86_64 always writes custom values into the fixups.
676     FixedValue = Value;
677
678     // struct relocation_info (8 bytes)
679     MachRelocationEntry MRE;
680     MRE.Word0 = FixupOffset;
681     MRE.Word1 = ((Index     <<  0) |
682                  (IsPCRel   << 24) |
683                  (Log2Size  << 25) |
684                  (IsExtern  << 27) |
685                  (Type      << 28));
686     Relocations[Fragment->getParent()].push_back(MRE);
687   }
688
689   void RecordScatteredRelocation(const MCAssembler &Asm,
690                                  const MCAsmLayout &Layout,
691                                  const MCFragment *Fragment,
692                                  const MCFixup &Fixup, MCValue Target,
693                                  uint64_t &FixedValue) {
694     uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
695     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
696     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
697     unsigned Type = macho::RIT_Vanilla;
698
699     // See <reloc.h>.
700     const MCSymbol *A = &Target.getSymA()->getSymbol();
701     MCSymbolData *A_SD = &Asm.getSymbolData(*A);
702
703     if (!A_SD->getFragment())
704       report_fatal_error("symbol '" + A->getName() +
705                         "' can not be undefined in a subtraction expression");
706
707     uint32_t Value = Layout.getSymbolAddress(A_SD);
708     uint32_t Value2 = 0;
709
710     if (const MCSymbolRefExpr *B = Target.getSymB()) {
711       MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
712
713       if (!B_SD->getFragment())
714         report_fatal_error("symbol '" + B->getSymbol().getName() +
715                           "' can not be undefined in a subtraction expression");
716
717       // Select the appropriate difference relocation type.
718       //
719       // Note that there is no longer any semantic difference between these two
720       // relocation types from the linkers point of view, this is done solely
721       // for pedantic compatibility with 'as'.
722       Type = A_SD->isExternal() ? macho::RIT_Difference :
723         macho::RIT_LocalDifference;
724       Value2 = Layout.getSymbolAddress(B_SD);
725     }
726
727     // Relocations are written out in reverse order, so the PAIR comes first.
728     if (Type == macho::RIT_Difference || Type == macho::RIT_LocalDifference) {
729       MachRelocationEntry MRE;
730       MRE.Word0 = ((0         <<  0) |
731                    (macho::RIT_Pair  << 24) |
732                    (Log2Size  << 28) |
733                    (IsPCRel   << 30) |
734                    macho::RF_Scattered);
735       MRE.Word1 = Value2;
736       Relocations[Fragment->getParent()].push_back(MRE);
737     }
738
739     MachRelocationEntry MRE;
740     MRE.Word0 = ((FixupOffset <<  0) |
741                  (Type        << 24) |
742                  (Log2Size    << 28) |
743                  (IsPCRel     << 30) |
744                  macho::RF_Scattered);
745     MRE.Word1 = Value;
746     Relocations[Fragment->getParent()].push_back(MRE);
747   }
748
749   void RecordTLVPRelocation(const MCAssembler &Asm,
750                             const MCAsmLayout &Layout,
751                             const MCFragment *Fragment,
752                             const MCFixup &Fixup, MCValue Target,
753                             uint64_t &FixedValue) {
754     assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
755            !Is64Bit &&
756            "Should only be called with a 32-bit TLVP relocation!");
757
758     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
759     uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
760     unsigned IsPCRel = 0;
761
762     // Get the symbol data.
763     MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
764     unsigned Index = SD_A->getIndex();
765
766     // We're only going to have a second symbol in pic mode and it'll be a
767     // subtraction from the picbase. For 32-bit pic the addend is the difference
768     // between the picbase and the next address.  For 32-bit static the addend
769     // is zero.
770     if (Target.getSymB()) {
771       // If this is a subtraction then we're pcrel.
772       uint32_t FixupAddress =
773       Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
774       MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
775       IsPCRel = 1;
776       FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
777                     Target.getConstant());
778       FixedValue += 1ULL << Log2Size;
779     } else {
780       FixedValue = 0;
781     }
782
783     // struct relocation_info (8 bytes)
784     MachRelocationEntry MRE;
785     MRE.Word0 = Value;
786     MRE.Word1 = ((Index     <<  0) |
787                  (IsPCRel   << 24) |
788                  (Log2Size  << 25) |
789                  (1         << 27) | // Extern
790                  (macho::RIT_TLV   << 28)); // Type
791     Relocations[Fragment->getParent()].push_back(MRE);
792   }
793
794   void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
795                         const MCFragment *Fragment, const MCFixup &Fixup,
796                         MCValue Target, uint64_t &FixedValue) {
797     if (Is64Bit) {
798       RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
799       return;
800     }
801
802     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
803     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
804
805     // If this is a 32-bit TLVP reloc it's handled a bit differently.
806     if (Target.getSymA() &&
807         Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
808       RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
809       return;
810     }
811
812     // If this is a difference or a defined symbol plus an offset, then we need
813     // a scattered relocation entry.
814     // Differences always require scattered relocations.
815     if (Target.getSymB())
816         return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
817                                          Target, FixedValue);
818
819     // Get the symbol data, if any.
820     MCSymbolData *SD = 0;
821     if (Target.getSymA())
822       SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
823
824     // If this is an internal relocation with an offset, it also needs a
825     // scattered relocation entry.
826     uint32_t Offset = Target.getConstant();
827     if (IsPCRel)
828       Offset += 1 << Log2Size;
829     if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
830       return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
831                                        Target, FixedValue);
832
833     // See <reloc.h>.
834     uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
835     unsigned Index = 0;
836     unsigned IsExtern = 0;
837     unsigned Type = 0;
838
839     if (Target.isAbsolute()) { // constant
840       // SymbolNum of 0 indicates the absolute section.
841       //
842       // FIXME: Currently, these are never generated (see code below). I cannot
843       // find a case where they are actually emitted.
844       Type = macho::RIT_Vanilla;
845     } else {
846       // Check whether we need an external or internal relocation.
847       if (doesSymbolRequireExternRelocation(SD)) {
848         IsExtern = 1;
849         Index = SD->getIndex();
850         // For external relocations, make sure to offset the fixup value to
851         // compensate for the addend of the symbol address, if it was
852         // undefined. This occurs with weak definitions, for example.
853         if (!SD->Symbol->isUndefined())
854           FixedValue -= Layout.getSymbolAddress(SD);
855       } else {
856         // The index is the section ordinal (1-based).
857         Index = SD->getFragment()->getParent()->getOrdinal() + 1;
858       }
859
860       Type = macho::RIT_Vanilla;
861     }
862
863     // struct relocation_info (8 bytes)
864     MachRelocationEntry MRE;
865     MRE.Word0 = FixupOffset;
866     MRE.Word1 = ((Index     <<  0) |
867                  (IsPCRel   << 24) |
868                  (Log2Size  << 25) |
869                  (IsExtern  << 27) |
870                  (Type      << 28));
871     Relocations[Fragment->getParent()].push_back(MRE);
872   }
873
874   void BindIndirectSymbols(MCAssembler &Asm) {
875     // This is the point where 'as' creates actual symbols for indirect symbols
876     // (in the following two passes). It would be easier for us to do this
877     // sooner when we see the attribute, but that makes getting the order in the
878     // symbol table much more complicated than it is worth.
879     //
880     // FIXME: Revisit this when the dust settles.
881
882     // Bind non lazy symbol pointers first.
883     unsigned IndirectIndex = 0;
884     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
885            ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
886       const MCSectionMachO &Section =
887         cast<MCSectionMachO>(it->SectionData->getSection());
888
889       if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
890         continue;
891
892       // Initialize the section indirect symbol base, if necessary.
893       if (!IndirectSymBase.count(it->SectionData))
894         IndirectSymBase[it->SectionData] = IndirectIndex;
895
896       Asm.getOrCreateSymbolData(*it->Symbol);
897     }
898
899     // Then lazy symbol pointers and symbol stubs.
900     IndirectIndex = 0;
901     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
902            ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
903       const MCSectionMachO &Section =
904         cast<MCSectionMachO>(it->SectionData->getSection());
905
906       if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
907           Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
908         continue;
909
910       // Initialize the section indirect symbol base, if necessary.
911       if (!IndirectSymBase.count(it->SectionData))
912         IndirectSymBase[it->SectionData] = IndirectIndex;
913
914       // Set the symbol type to undefined lazy, but only on construction.
915       //
916       // FIXME: Do not hardcode.
917       bool Created;
918       MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
919       if (Created)
920         Entry.setFlags(Entry.getFlags() | 0x0001);
921     }
922   }
923
924   /// ComputeSymbolTable - Compute the symbol table data
925   ///
926   /// \param StringTable [out] - The string table data.
927   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
928   /// string table.
929   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
930                           std::vector<MachSymbolData> &LocalSymbolData,
931                           std::vector<MachSymbolData> &ExternalSymbolData,
932                           std::vector<MachSymbolData> &UndefinedSymbolData) {
933     // Build section lookup table.
934     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
935     unsigned Index = 1;
936     for (MCAssembler::iterator it = Asm.begin(),
937            ie = Asm.end(); it != ie; ++it, ++Index)
938       SectionIndexMap[&it->getSection()] = Index;
939     assert(Index <= 256 && "Too many sections!");
940
941     // Index 0 is always the empty string.
942     StringMap<uint64_t> StringIndexMap;
943     StringTable += '\x00';
944
945     // Build the symbol arrays and the string table, but only for non-local
946     // symbols.
947     //
948     // The particular order that we collect the symbols and create the string
949     // table, then sort the symbols is chosen to match 'as'. Even though it
950     // doesn't matter for correctness, this is important for letting us diff .o
951     // files.
952     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
953            ie = Asm.symbol_end(); it != ie; ++it) {
954       const MCSymbol &Symbol = it->getSymbol();
955
956       // Ignore non-linker visible symbols.
957       if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
958         continue;
959
960       if (!it->isExternal() && !Symbol.isUndefined())
961         continue;
962
963       uint64_t &Entry = StringIndexMap[Symbol.getName()];
964       if (!Entry) {
965         Entry = StringTable.size();
966         StringTable += Symbol.getName();
967         StringTable += '\x00';
968       }
969
970       MachSymbolData MSD;
971       MSD.SymbolData = it;
972       MSD.StringIndex = Entry;
973
974       if (Symbol.isUndefined()) {
975         MSD.SectionIndex = 0;
976         UndefinedSymbolData.push_back(MSD);
977       } else if (Symbol.isAbsolute()) {
978         MSD.SectionIndex = 0;
979         ExternalSymbolData.push_back(MSD);
980       } else {
981         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
982         assert(MSD.SectionIndex && "Invalid section index!");
983         ExternalSymbolData.push_back(MSD);
984       }
985     }
986
987     // Now add the data for local symbols.
988     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
989            ie = Asm.symbol_end(); it != ie; ++it) {
990       const MCSymbol &Symbol = it->getSymbol();
991
992       // Ignore non-linker visible symbols.
993       if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
994         continue;
995
996       if (it->isExternal() || Symbol.isUndefined())
997         continue;
998
999       uint64_t &Entry = StringIndexMap[Symbol.getName()];
1000       if (!Entry) {
1001         Entry = StringTable.size();
1002         StringTable += Symbol.getName();
1003         StringTable += '\x00';
1004       }
1005
1006       MachSymbolData MSD;
1007       MSD.SymbolData = it;
1008       MSD.StringIndex = Entry;
1009
1010       if (Symbol.isAbsolute()) {
1011         MSD.SectionIndex = 0;
1012         LocalSymbolData.push_back(MSD);
1013       } else {
1014         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1015         assert(MSD.SectionIndex && "Invalid section index!");
1016         LocalSymbolData.push_back(MSD);
1017       }
1018     }
1019
1020     // External and undefined symbols are required to be in lexicographic order.
1021     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1022     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1023
1024     // Set the symbol indices.
1025     Index = 0;
1026     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1027       LocalSymbolData[i].SymbolData->setIndex(Index++);
1028     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1029       ExternalSymbolData[i].SymbolData->setIndex(Index++);
1030     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1031       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1032
1033     // The string table is padded to a multiple of 4.
1034     while (StringTable.size() % 4)
1035       StringTable += '\x00';
1036   }
1037
1038   void ExecutePostLayoutBinding(MCAssembler &Asm) {
1039     // Create symbol data for any indirect symbols.
1040     BindIndirectSymbols(Asm);
1041
1042     // Compute symbol table information and bind symbol indices.
1043     ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1044                        UndefinedSymbolData);
1045   }
1046
1047
1048   bool IsFixupFullyResolved(const MCAssembler &Asm,
1049                             const MCValue Target,
1050                             bool IsPCRel,
1051                             const MCFragment *DF) const {
1052     // If we aren't using scattered symbols, the fixup is fully resolved.
1053     if (!Asm.getBackend().hasScatteredSymbols())
1054       return true;
1055
1056     // Otherwise, determine whether this value is actually resolved; scattering
1057     // may cause atoms to move.
1058
1059     // Check if we are using the "simple" resolution algorithm (e.g.,
1060     // i386).
1061     if (!Asm.getBackend().hasReliableSymbolDifference()) {
1062       const MCSection *BaseSection = 0;
1063       if (IsPCRel)
1064         BaseSection = &DF->getParent()->getSection();
1065
1066       return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1067     }
1068
1069     // Otherwise, compute the proper answer as reliably as possible.
1070
1071     // If this is a PCrel relocation, find the base atom (identified by its
1072     // symbol) that the fixup value is relative to.
1073     const MCSymbolData *BaseSymbol = 0;
1074     if (IsPCRel) {
1075       BaseSymbol = DF->getAtom();
1076       if (!BaseSymbol)
1077         return false;
1078     }
1079
1080     return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1081   }
1082
1083   void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1084     unsigned NumSections = Asm.size();
1085
1086     // The section data starts after the header, the segment load command (and
1087     // section headers) and the symbol table.
1088     unsigned NumLoadCommands = 1;
1089     uint64_t LoadCommandsSize = Is64Bit ?
1090       macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1091       macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1092
1093     // Add the symbol table load command sizes, if used.
1094     unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1095       UndefinedSymbolData.size();
1096     if (NumSymbols) {
1097       NumLoadCommands += 2;
1098       LoadCommandsSize += (macho::SymtabLoadCommandSize +
1099                            macho::DysymtabLoadCommandSize);
1100     }
1101
1102     // Compute the total size of the section data, as well as its file size and
1103     // vm size.
1104     uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1105                                  macho::Header32Size) + LoadCommandsSize;
1106     uint64_t SectionDataSize = 0;
1107     uint64_t SectionDataFileSize = 0;
1108     uint64_t VMSize = 0;
1109     for (MCAssembler::const_iterator it = Asm.begin(),
1110            ie = Asm.end(); it != ie; ++it) {
1111       const MCSectionData &SD = *it;
1112       uint64_t Address = Layout.getSectionAddress(&SD);
1113       uint64_t Size = Layout.getSectionSize(&SD);
1114       uint64_t FileSize = Layout.getSectionFileSize(&SD);
1115
1116       VMSize = std::max(VMSize, Address + Size);
1117
1118       if (SD.getSection().isVirtualSection())
1119         continue;
1120
1121       SectionDataSize = std::max(SectionDataSize, Address + Size);
1122       SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1123     }
1124
1125     // The section data is padded to 4 bytes.
1126     //
1127     // FIXME: Is this machine dependent?
1128     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1129     SectionDataFileSize += SectionDataPadding;
1130
1131     // Write the prolog, starting with the header and load command...
1132     WriteHeader(NumLoadCommands, LoadCommandsSize,
1133                 Asm.getSubsectionsViaSymbols());
1134     WriteSegmentLoadCommand(NumSections, VMSize,
1135                             SectionDataStart, SectionDataSize);
1136
1137     // ... and then the section headers.
1138     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1139     for (MCAssembler::const_iterator it = Asm.begin(),
1140            ie = Asm.end(); it != ie; ++it) {
1141       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1142       unsigned NumRelocs = Relocs.size();
1143       uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1144       WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1145       RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1146     }
1147
1148     // Write the symbol table load command, if used.
1149     if (NumSymbols) {
1150       unsigned FirstLocalSymbol = 0;
1151       unsigned NumLocalSymbols = LocalSymbolData.size();
1152       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1153       unsigned NumExternalSymbols = ExternalSymbolData.size();
1154       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1155       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1156       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1157       unsigned NumSymTabSymbols =
1158         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1159       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1160       uint64_t IndirectSymbolOffset = 0;
1161
1162       // If used, the indirect symbols are written after the section data.
1163       if (NumIndirectSymbols)
1164         IndirectSymbolOffset = RelocTableEnd;
1165
1166       // The symbol table is written after the indirect symbol data.
1167       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1168
1169       // The string table is written after symbol table.
1170       uint64_t StringTableOffset =
1171         SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1172                                                 macho::Nlist32Size);
1173       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1174                              StringTableOffset, StringTable.size());
1175
1176       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1177                                FirstExternalSymbol, NumExternalSymbols,
1178                                FirstUndefinedSymbol, NumUndefinedSymbols,
1179                                IndirectSymbolOffset, NumIndirectSymbols);
1180     }
1181
1182     // Write the actual section data.
1183     for (MCAssembler::const_iterator it = Asm.begin(),
1184            ie = Asm.end(); it != ie; ++it)
1185       Asm.WriteSectionData(it, Layout, this);
1186
1187     // Write the extra padding.
1188     WriteZeros(SectionDataPadding);
1189
1190     // Write the relocation entries.
1191     for (MCAssembler::const_iterator it = Asm.begin(),
1192            ie = Asm.end(); it != ie; ++it) {
1193       // Write the section relocation entries, in reverse order to match 'as'
1194       // (approximately, the exact algorithm is more complicated than this).
1195       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1196       for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1197         Write32(Relocs[e - i - 1].Word0);
1198         Write32(Relocs[e - i - 1].Word1);
1199       }
1200     }
1201
1202     // Write the symbol table data, if used.
1203     if (NumSymbols) {
1204       // Write the indirect symbol entries.
1205       for (MCAssembler::const_indirect_symbol_iterator
1206              it = Asm.indirect_symbol_begin(),
1207              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1208         // Indirect symbols in the non lazy symbol pointer section have some
1209         // special handling.
1210         const MCSectionMachO &Section =
1211           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1212         if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1213           // If this symbol is defined and internal, mark it as such.
1214           if (it->Symbol->isDefined() &&
1215               !Asm.getSymbolData(*it->Symbol).isExternal()) {
1216             uint32_t Flags = macho::ISF_Local;
1217             if (it->Symbol->isAbsolute())
1218               Flags |= macho::ISF_Absolute;
1219             Write32(Flags);
1220             continue;
1221           }
1222         }
1223
1224         Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1225       }
1226
1227       // FIXME: Check that offsets match computed ones.
1228
1229       // Write the symbol table entries.
1230       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1231         WriteNlist(LocalSymbolData[i], Layout);
1232       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1233         WriteNlist(ExternalSymbolData[i], Layout);
1234       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1235         WriteNlist(UndefinedSymbolData[i], Layout);
1236
1237       // Write the string table.
1238       OS << StringTable.str();
1239     }
1240   }
1241 };
1242
1243 }
1244
1245 MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1246                                              uint32_t CPUType,
1247                                              uint32_t CPUSubtype,
1248                                              bool IsLittleEndian) {
1249   return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);
1250 }