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