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