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