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