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