0dbb2c1c0e98be262fc19abcaa650c883c546e52
[oota-llvm.git] / lib / MC / MachObjectWriter.cpp
1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MachObjectWriter.h"
11 #include "llvm/ADT/StringMap.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCObjectWriter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCMachOSymbolFlags.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MachO.h"
23 #include "llvm/Target/TargetAsmBackend.h"
24
25 // FIXME: Gross.
26 #include "../Target/X86/X86FixupKinds.h"
27
28 #include <vector>
29 using namespace llvm;
30
31 static unsigned getFixupKindLog2Size(unsigned Kind) {
32   switch (Kind) {
33   default: llvm_unreachable("invalid fixup kind!");
34   case X86::reloc_pcrel_1byte:
35   case FK_Data_1: return 0;
36   case FK_Data_2: return 1;
37   case X86::reloc_pcrel_4byte:
38   case X86::reloc_riprel_4byte:
39   case X86::reloc_riprel_4byte_movq_load:
40   case FK_Data_4: return 2;
41   case FK_Data_8: return 3;
42   }
43 }
44
45 static bool isFixupKindPCRel(unsigned Kind) {
46   switch (Kind) {
47   default:
48     return false;
49   case X86::reloc_pcrel_1byte:
50   case X86::reloc_pcrel_4byte:
51   case X86::reloc_riprel_4byte:
52   case X86::reloc_riprel_4byte_movq_load:
53     return true;
54   }
55 }
56
57 static bool isFixupKindRIPRel(unsigned Kind) {
58   return Kind == X86::reloc_riprel_4byte ||
59     Kind == X86::reloc_riprel_4byte_movq_load;
60 }
61
62 namespace {
63
64 class MachObjectWriterImpl {
65   // See <mach-o/loader.h>.
66   enum {
67     Header_Magic32 = 0xFEEDFACE,
68     Header_Magic64 = 0xFEEDFACF
69   };
70
71   enum {
72     Header32Size = 28,
73     Header64Size = 32,
74     SegmentLoadCommand32Size = 56,
75     SegmentLoadCommand64Size = 72,
76     Section32Size = 68,
77     Section64Size = 80,
78     SymtabLoadCommandSize = 24,
79     DysymtabLoadCommandSize = 80,
80     Nlist32Size = 12,
81     Nlist64Size = 16,
82     RelocationInfoSize = 8
83   };
84
85   enum HeaderFileType {
86     HFT_Object = 0x1
87   };
88
89   enum HeaderFlags {
90     HF_SubsectionsViaSymbols = 0x2000
91   };
92
93   enum LoadCommandType {
94     LCT_Segment = 0x1,
95     LCT_Symtab = 0x2,
96     LCT_Dysymtab = 0xb,
97     LCT_Segment64 = 0x19
98   };
99
100   // See <mach-o/nlist.h>.
101   enum SymbolTypeType {
102     STT_Undefined = 0x00,
103     STT_Absolute  = 0x02,
104     STT_Section   = 0x0e
105   };
106
107   enum SymbolTypeFlags {
108     // If any of these bits are set, then the entry is a stab entry number (see
109     // <mach-o/stab.h>. Otherwise the other masks apply.
110     STF_StabsEntryMask = 0xe0,
111
112     STF_TypeMask       = 0x0e,
113     STF_External       = 0x01,
114     STF_PrivateExtern  = 0x10
115   };
116
117   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
118   /// symbol entry.
119   enum IndirectSymbolFlags {
120     ISF_Local    = 0x80000000,
121     ISF_Absolute = 0x40000000
122   };
123
124   /// RelocationFlags - Special flags for addresses.
125   enum RelocationFlags {
126     RF_Scattered = 0x80000000
127   };
128
129   enum RelocationInfoType {
130     RIT_Vanilla             = 0,
131     RIT_Pair                = 1,
132     RIT_Difference          = 2,
133     RIT_PreboundLazyPointer = 3,
134     RIT_LocalDifference     = 4
135   };
136
137   /// X86_64 uses its own relocation types.
138   enum RelocationInfoTypeX86_64 {
139     RIT_X86_64_Unsigned   = 0,
140     RIT_X86_64_Signed     = 1,
141     RIT_X86_64_Branch     = 2,
142     RIT_X86_64_GOTLoad    = 3,
143     RIT_X86_64_GOT        = 4,
144     RIT_X86_64_Subtractor = 5,
145     RIT_X86_64_Signed1    = 6,
146     RIT_X86_64_Signed2    = 7,
147     RIT_X86_64_Signed4    = 8
148   };
149
150   /// MachSymbolData - Helper struct for containing some precomputed information
151   /// on symbols.
152   struct MachSymbolData {
153     MCSymbolData *SymbolData;
154     uint64_t StringIndex;
155     uint8_t SectionIndex;
156
157     // Support lexicographic sorting.
158     bool operator<(const MachSymbolData &RHS) const {
159       const std::string &Name = SymbolData->getSymbol().getName();
160       return Name < RHS.SymbolData->getSymbol().getName();
161     }
162   };
163
164   /// @name Relocation Data
165   /// @{
166
167   struct MachRelocationEntry {
168     uint32_t Word0;
169     uint32_t Word1;
170   };
171
172   llvm::DenseMap<const MCSectionData*,
173                  std::vector<MachRelocationEntry> > Relocations;
174
175   /// @}
176   /// @name Symbol Table Data
177   /// @{
178
179   SmallString<256> StringTable;
180   std::vector<MachSymbolData> LocalSymbolData;
181   std::vector<MachSymbolData> ExternalSymbolData;
182   std::vector<MachSymbolData> UndefinedSymbolData;
183
184   /// @}
185
186   MachObjectWriter *Writer;
187
188   raw_ostream &OS;
189
190   unsigned Is64Bit : 1;
191
192 public:
193   MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
194     : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
195   }
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 MCAsmLayout &Layout,
277                     const MCSectionData &SD, uint64_t FileOffset,
278                     uint64_t RelocationsStart, unsigned NumRelocations) {
279     uint64_t SectionSize = Layout.getSectionSize(&SD);
280
281     // The offset is unused for virtual sections.
282     if (Asm.getBackend().isVirtualSection(SD.getSection())) {
283       assert(Layout.getSectionFileSize(&SD) == 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         Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
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           report_fatal_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 += 1LL << 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         report_fatal_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         report_fatal_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         report_fatal_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         report_fatal_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       // Relocations inside debug sections always use local relocations when
553       // possible. This seems to be done because the debugger doesn't fully
554       // understand x86_64 relocation entries, and expects to find values that
555       // have already been fixed up.
556       if (Symbol->isInSection()) {
557         const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
558           Fragment->getParent()->getSection());
559         if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
560           Base = 0;
561       }
562
563       // x86_64 almost always uses external relocations, except when there is no
564       // symbol to use as a base address (a local symbol with no preceeding
565       // non-local symbol).
566       if (Base) {
567         Index = Base->getIndex();
568         IsExtern = 1;
569
570         // Add the local offset, if needed.
571         if (Base != &SD)
572           Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
573       } else {
574         // The index is the section ordinal (1-based).
575         Index = SD.getFragment()->getParent()->getOrdinal() + 1;
576         IsExtern = 0;
577         Value += Layout.getSymbolAddress(&SD);
578
579         if (IsPCRel)
580           Value -= Address + (1 << Log2Size);
581       }
582
583       MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
584       if (IsPCRel) {
585         if (IsRIPRel) {
586           if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
587             // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
588             // rewrite the movq to an leaq at link time if the symbol ends up in
589             // the same linkage unit.
590             if (unsigned(Fixup.Kind) == X86::reloc_riprel_4byte_movq_load)
591               Type = RIT_X86_64_GOTLoad;
592             else
593               Type = RIT_X86_64_GOT;
594           } else if (Modifier != MCSymbolRefExpr::VK_None)
595             report_fatal_error("unsupported symbol modifier in relocation");
596           else
597             Type = RIT_X86_64_Signed;
598         } else {
599           if (Modifier != MCSymbolRefExpr::VK_None)
600             report_fatal_error("unsupported symbol modifier in branch "
601                               "relocation");
602
603           Type = RIT_X86_64_Branch;
604         }
605
606         // The Darwin x86_64 relocation format has a problem where it cannot
607         // encode an address (L<foo> + <constant>) which is outside the atom
608         // containing L<foo>. Generally, this shouldn't occur but it does happen
609         // when we have a RIPrel instruction with data following the relocation
610         // entry (e.g., movb $012, L0(%rip)). Even with the PCrel adjustment
611         // Darwin x86_64 uses, the offset is still negative and the linker has
612         // no way to recognize this.
613         //
614         // To work around this, Darwin uses several special relocation types to
615         // indicate the offsets. However, the specification or implementation of
616         // these seems to also be incomplete; they should adjust the addend as
617         // well based on the actual encoded instruction (the additional bias),
618         // but instead appear to just look at the final offset.
619         if (IsRIPRel) {
620           switch (-(Target.getConstant() + (1LL << Log2Size))) {
621           case 1: Type = RIT_X86_64_Signed1; break;
622           case 2: Type = RIT_X86_64_Signed2; break;
623           case 4: Type = RIT_X86_64_Signed4; break;
624           }
625         }
626       } else {
627         if (Modifier == MCSymbolRefExpr::VK_GOT) {
628           Type = RIT_X86_64_GOT;
629         } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
630           // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
631           // which case all we do is set the PCrel bit in the relocation entry;
632           // this is used with exception handling, for example. The source is
633           // required to include any necessary offset directly.
634           Type = RIT_X86_64_GOT;
635           IsPCRel = 1;
636         } else if (Modifier != MCSymbolRefExpr::VK_None)
637           report_fatal_error("unsupported symbol modifier in relocation");
638         else
639           Type = RIT_X86_64_Unsigned;
640       }
641     }
642
643     // x86_64 always writes custom values into the fixups.
644     FixedValue = Value;
645
646     // struct relocation_info (8 bytes)
647     MachRelocationEntry MRE;
648     MRE.Word0 = Address;
649     MRE.Word1 = ((Index     <<  0) |
650                  (IsPCRel   << 24) |
651                  (Log2Size  << 25) |
652                  (IsExtern  << 27) |
653                  (Type      << 28));
654     Relocations[Fragment->getParent()].push_back(MRE);
655   }
656
657   void RecordScatteredRelocation(const MCAssembler &Asm,
658                                  const MCAsmLayout &Layout,
659                                  const MCFragment *Fragment,
660                                  const MCAsmFixup &Fixup, MCValue Target,
661                                  uint64_t &FixedValue) {
662     uint32_t Address = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
663     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
664     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
665     unsigned Type = RIT_Vanilla;
666
667     // See <reloc.h>.
668     const MCSymbol *A = &Target.getSymA()->getSymbol();
669     MCSymbolData *A_SD = &Asm.getSymbolData(*A);
670
671     if (!A_SD->getFragment())
672       report_fatal_error("symbol '" + A->getName() +
673                         "' can not be undefined in a subtraction expression");
674
675     uint32_t Value = Layout.getSymbolAddress(A_SD);
676     uint32_t Value2 = 0;
677
678     if (const MCSymbolRefExpr *B = Target.getSymB()) {
679       MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
680
681       if (!B_SD->getFragment())
682         report_fatal_error("symbol '" + B->getSymbol().getName() +
683                           "' can not be undefined in a subtraction expression");
684
685       // Select the appropriate difference relocation type.
686       //
687       // Note that there is no longer any semantic difference between these two
688       // relocation types from the linkers point of view, this is done solely
689       // for pedantic compatibility with 'as'.
690       Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
691       Value2 = Layout.getSymbolAddress(B_SD);
692     }
693
694     // Relocations are written out in reverse order, so the PAIR comes first.
695     if (Type == RIT_Difference || Type == RIT_LocalDifference) {
696       MachRelocationEntry MRE;
697       MRE.Word0 = ((0         <<  0) |
698                    (RIT_Pair  << 24) |
699                    (Log2Size  << 28) |
700                    (IsPCRel   << 30) |
701                    RF_Scattered);
702       MRE.Word1 = Value2;
703       Relocations[Fragment->getParent()].push_back(MRE);
704     }
705
706     MachRelocationEntry MRE;
707     MRE.Word0 = ((Address   <<  0) |
708                  (Type      << 24) |
709                  (Log2Size  << 28) |
710                  (IsPCRel   << 30) |
711                  RF_Scattered);
712     MRE.Word1 = Value;
713     Relocations[Fragment->getParent()].push_back(MRE);
714   }
715
716   void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
717                         const MCFragment *Fragment, const MCAsmFixup &Fixup,
718                         MCValue Target, uint64_t &FixedValue) {
719     if (Is64Bit) {
720       RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
721       return;
722     }
723
724     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
725     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
726
727     // If this is a difference or a defined symbol plus an offset, then we need
728     // a scattered relocation entry.
729     uint32_t Offset = Target.getConstant();
730     if (IsPCRel)
731       Offset += 1 << Log2Size;
732     if (Target.getSymB() ||
733         (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
734          Offset)) {
735       RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,Target,FixedValue);
736       return;
737     }
738
739     // See <reloc.h>.
740     uint32_t Address = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
741     uint32_t Value = 0;
742     unsigned Index = 0;
743     unsigned IsExtern = 0;
744     unsigned Type = 0;
745
746     if (Target.isAbsolute()) { // constant
747       // SymbolNum of 0 indicates the absolute section.
748       //
749       // FIXME: Currently, these are never generated (see code below). I cannot
750       // find a case where they are actually emitted.
751       Type = RIT_Vanilla;
752       Value = 0;
753     } else {
754       const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
755       MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
756
757       // Both references to undefined symbols and references to Weak Definitions
758       // get external relocation entries.  This is so the static and then the
759       // the dynamic linker can resolve them to the actual definition that will
760       // be used.  And in the case of Weak Definitions a reference to one will
761       // not always be to the definition in the same object file.
762       if (Symbol->isUndefined() || (SD->getFlags() & SF_WeakDefinition)) {
763         IsExtern = 1;
764         Index = SD->getIndex();
765         // In the case of a Weak Definition the FixedValue needs to be set to
766         // to not have the address of the symbol.  In the case of an undefined
767         // symbol you can't call getSymbolAddress().
768         if (SD->getFlags() & SF_WeakDefinition)
769           FixedValue -= Layout.getSymbolAddress(SD);
770         Value = 0;
771       } else {
772         // The index is the section ordinal (1-based).
773         Index = SD->getFragment()->getParent()->getOrdinal() + 1;
774         Value = Layout.getSymbolAddress(SD);
775       }
776
777       Type = RIT_Vanilla;
778     }
779
780     // struct relocation_info (8 bytes)
781     MachRelocationEntry MRE;
782     MRE.Word0 = Address;
783     MRE.Word1 = ((Index     <<  0) |
784                  (IsPCRel   << 24) |
785                  (Log2Size  << 25) |
786                  (IsExtern  << 27) |
787                  (Type      << 28));
788     Relocations[Fragment->getParent()].push_back(MRE);
789   }
790
791   void BindIndirectSymbols(MCAssembler &Asm) {
792     // This is the point where 'as' creates actual symbols for indirect symbols
793     // (in the following two passes). It would be easier for us to do this
794     // sooner when we see the attribute, but that makes getting the order in the
795     // symbol table much more complicated than it is worth.
796     //
797     // FIXME: Revisit this when the dust settles.
798
799     // Bind non lazy symbol pointers first.
800     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
801            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
802       // FIXME: cast<> support!
803       const MCSectionMachO &Section =
804         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
805
806       if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
807         continue;
808
809       Asm.getOrCreateSymbolData(*it->Symbol);
810     }
811
812     // Then lazy symbol pointers and symbol stubs.
813     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
814            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
815       // FIXME: cast<> support!
816       const MCSectionMachO &Section =
817         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
818
819       if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
820           Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
821         continue;
822
823       // Set the symbol type to undefined lazy, but only on construction.
824       //
825       // FIXME: Do not hardcode.
826       bool Created;
827       MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
828       if (Created)
829         Entry.setFlags(Entry.getFlags() | 0x0001);
830     }
831   }
832
833   /// ComputeSymbolTable - Compute the symbol table data
834   ///
835   /// \param StringTable [out] - The string table data.
836   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
837   /// string table.
838   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
839                           std::vector<MachSymbolData> &LocalSymbolData,
840                           std::vector<MachSymbolData> &ExternalSymbolData,
841                           std::vector<MachSymbolData> &UndefinedSymbolData) {
842     // Build section lookup table.
843     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
844     unsigned Index = 1;
845     for (MCAssembler::iterator it = Asm.begin(),
846            ie = Asm.end(); it != ie; ++it, ++Index)
847       SectionIndexMap[&it->getSection()] = Index;
848     assert(Index <= 256 && "Too many sections!");
849
850     // Index 0 is always the empty string.
851     StringMap<uint64_t> StringIndexMap;
852     StringTable += '\x00';
853
854     // Build the symbol arrays and the string table, but only for non-local
855     // symbols.
856     //
857     // The particular order that we collect the symbols and create the string
858     // table, then sort the symbols is chosen to match 'as'. Even though it
859     // doesn't matter for correctness, this is important for letting us diff .o
860     // files.
861     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
862            ie = Asm.symbol_end(); it != ie; ++it) {
863       const MCSymbol &Symbol = it->getSymbol();
864
865       // Ignore non-linker visible symbols.
866       if (!Asm.isSymbolLinkerVisible(it))
867         continue;
868
869       if (!it->isExternal() && !Symbol.isUndefined())
870         continue;
871
872       uint64_t &Entry = StringIndexMap[Symbol.getName()];
873       if (!Entry) {
874         Entry = StringTable.size();
875         StringTable += Symbol.getName();
876         StringTable += '\x00';
877       }
878
879       MachSymbolData MSD;
880       MSD.SymbolData = it;
881       MSD.StringIndex = Entry;
882
883       if (Symbol.isUndefined()) {
884         MSD.SectionIndex = 0;
885         UndefinedSymbolData.push_back(MSD);
886       } else if (Symbol.isAbsolute()) {
887         MSD.SectionIndex = 0;
888         ExternalSymbolData.push_back(MSD);
889       } else {
890         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
891         assert(MSD.SectionIndex && "Invalid section index!");
892         ExternalSymbolData.push_back(MSD);
893       }
894     }
895
896     // Now add the data for local symbols.
897     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
898            ie = Asm.symbol_end(); it != ie; ++it) {
899       const MCSymbol &Symbol = it->getSymbol();
900
901       // Ignore non-linker visible symbols.
902       if (!Asm.isSymbolLinkerVisible(it))
903         continue;
904
905       if (it->isExternal() || Symbol.isUndefined())
906         continue;
907
908       uint64_t &Entry = StringIndexMap[Symbol.getName()];
909       if (!Entry) {
910         Entry = StringTable.size();
911         StringTable += Symbol.getName();
912         StringTable += '\x00';
913       }
914
915       MachSymbolData MSD;
916       MSD.SymbolData = it;
917       MSD.StringIndex = Entry;
918
919       if (Symbol.isAbsolute()) {
920         MSD.SectionIndex = 0;
921         LocalSymbolData.push_back(MSD);
922       } else {
923         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
924         assert(MSD.SectionIndex && "Invalid section index!");
925         LocalSymbolData.push_back(MSD);
926       }
927     }
928
929     // External and undefined symbols are required to be in lexicographic order.
930     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
931     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
932
933     // Set the symbol indices.
934     Index = 0;
935     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
936       LocalSymbolData[i].SymbolData->setIndex(Index++);
937     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
938       ExternalSymbolData[i].SymbolData->setIndex(Index++);
939     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
940       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
941
942     // The string table is padded to a multiple of 4.
943     while (StringTable.size() % 4)
944       StringTable += '\x00';
945   }
946
947   void ExecutePostLayoutBinding(MCAssembler &Asm) {
948     // Create symbol data for any indirect symbols.
949     BindIndirectSymbols(Asm);
950
951     // Compute symbol table information and bind symbol indices.
952     ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
953                        UndefinedSymbolData);
954   }
955
956   void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
957     unsigned NumSections = Asm.size();
958
959     // The section data starts after the header, the segment load command (and
960     // section headers) and the symbol table.
961     unsigned NumLoadCommands = 1;
962     uint64_t LoadCommandsSize = Is64Bit ?
963       SegmentLoadCommand64Size + NumSections * Section64Size :
964       SegmentLoadCommand32Size + NumSections * Section32Size;
965
966     // Add the symbol table load command sizes, if used.
967     unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
968       UndefinedSymbolData.size();
969     if (NumSymbols) {
970       NumLoadCommands += 2;
971       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
972     }
973
974     // Compute the total size of the section data, as well as its file size and
975     // vm size.
976     uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
977       + LoadCommandsSize;
978     uint64_t SectionDataSize = 0;
979     uint64_t SectionDataFileSize = 0;
980     uint64_t VMSize = 0;
981     for (MCAssembler::const_iterator it = Asm.begin(),
982            ie = Asm.end(); it != ie; ++it) {
983       const MCSectionData &SD = *it;
984       uint64_t Address = Layout.getSectionAddress(&SD);
985       uint64_t Size = Layout.getSectionSize(&SD);
986       uint64_t FileSize = Layout.getSectionFileSize(&SD);
987
988       VMSize = std::max(VMSize, Address + Size);
989
990       if (Asm.getBackend().isVirtualSection(SD.getSection()))
991         continue;
992
993       SectionDataSize = std::max(SectionDataSize, Address + Size);
994       SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
995     }
996
997     // The section data is padded to 4 bytes.
998     //
999     // FIXME: Is this machine dependent?
1000     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1001     SectionDataFileSize += SectionDataPadding;
1002
1003     // Write the prolog, starting with the header and load command...
1004     WriteHeader(NumLoadCommands, LoadCommandsSize,
1005                 Asm.getSubsectionsViaSymbols());
1006     WriteSegmentLoadCommand(NumSections, VMSize,
1007                             SectionDataStart, SectionDataSize);
1008
1009     // ... and then the section headers.
1010     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1011     for (MCAssembler::const_iterator it = Asm.begin(),
1012            ie = Asm.end(); it != ie; ++it) {
1013       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1014       unsigned NumRelocs = Relocs.size();
1015       uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1016       WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1017       RelocTableEnd += NumRelocs * RelocationInfoSize;
1018     }
1019
1020     // Write the symbol table load command, if used.
1021     if (NumSymbols) {
1022       unsigned FirstLocalSymbol = 0;
1023       unsigned NumLocalSymbols = LocalSymbolData.size();
1024       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1025       unsigned NumExternalSymbols = ExternalSymbolData.size();
1026       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1027       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1028       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1029       unsigned NumSymTabSymbols =
1030         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1031       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1032       uint64_t IndirectSymbolOffset = 0;
1033
1034       // If used, the indirect symbols are written after the section data.
1035       if (NumIndirectSymbols)
1036         IndirectSymbolOffset = RelocTableEnd;
1037
1038       // The symbol table is written after the indirect symbol data.
1039       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1040
1041       // The string table is written after symbol table.
1042       uint64_t StringTableOffset =
1043         SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1044                                                 Nlist32Size);
1045       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1046                              StringTableOffset, StringTable.size());
1047
1048       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1049                                FirstExternalSymbol, NumExternalSymbols,
1050                                FirstUndefinedSymbol, NumUndefinedSymbols,
1051                                IndirectSymbolOffset, NumIndirectSymbols);
1052     }
1053
1054     // Write the actual section data.
1055     for (MCAssembler::const_iterator it = Asm.begin(),
1056            ie = Asm.end(); it != ie; ++it)
1057       Asm.WriteSectionData(it, Layout, Writer);
1058
1059     // Write the extra padding.
1060     WriteZeros(SectionDataPadding);
1061
1062     // Write the relocation entries.
1063     for (MCAssembler::const_iterator it = Asm.begin(),
1064            ie = Asm.end(); it != ie; ++it) {
1065       // Write the section relocation entries, in reverse order to match 'as'
1066       // (approximately, the exact algorithm is more complicated than this).
1067       std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1068       for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1069         Write32(Relocs[e - i - 1].Word0);
1070         Write32(Relocs[e - i - 1].Word1);
1071       }
1072     }
1073
1074     // Write the symbol table data, if used.
1075     if (NumSymbols) {
1076       // Write the indirect symbol entries.
1077       for (MCAssembler::const_indirect_symbol_iterator
1078              it = Asm.indirect_symbol_begin(),
1079              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1080         // Indirect symbols in the non lazy symbol pointer section have some
1081         // special handling.
1082         const MCSectionMachO &Section =
1083           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1084         if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1085           // If this symbol is defined and internal, mark it as such.
1086           if (it->Symbol->isDefined() &&
1087               !Asm.getSymbolData(*it->Symbol).isExternal()) {
1088             uint32_t Flags = ISF_Local;
1089             if (it->Symbol->isAbsolute())
1090               Flags |= ISF_Absolute;
1091             Write32(Flags);
1092             continue;
1093           }
1094         }
1095
1096         Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1097       }
1098
1099       // FIXME: Check that offsets match computed ones.
1100
1101       // Write the symbol table entries.
1102       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1103         WriteNlist(LocalSymbolData[i], Layout);
1104       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1105         WriteNlist(ExternalSymbolData[i], Layout);
1106       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1107         WriteNlist(UndefinedSymbolData[i], Layout);
1108
1109       // Write the string table.
1110       OS << StringTable.str();
1111     }
1112   }
1113 };
1114
1115 }
1116
1117 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1118                                    bool Is64Bit,
1119                                    bool IsLittleEndian)
1120   : MCObjectWriter(OS, IsLittleEndian)
1121 {
1122   Impl = new MachObjectWriterImpl(this, Is64Bit);
1123 }
1124
1125 MachObjectWriter::~MachObjectWriter() {
1126   delete (MachObjectWriterImpl*) Impl;
1127 }
1128
1129 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1130   ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1131 }
1132
1133 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1134                                         const MCAsmLayout &Layout,
1135                                         const MCFragment *Fragment,
1136                                         const MCAsmFixup &Fixup, MCValue Target,
1137                                         uint64_t &FixedValue) {
1138   ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1139                                                    Target, FixedValue);
1140 }
1141
1142 void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1143                                    const MCAsmLayout &Layout) {
1144   ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1145 }