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