a70b03d95cf8f2b6b5a965245838e0307a65b75a
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldMachO.cpp
1 //===-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-=//
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 // Implementation of the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "RuntimeDyldMachO.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 using namespace llvm;
18 using namespace llvm::object;
19
20 #define DEBUG_TYPE "dyld"
21
22 namespace llvm {
23
24 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText,
25                                  intptr_t DeltaForEH) {
26   DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
27                << ", Delta for EH: " << DeltaForEH << "\n");
28   uint32_t Length = *((uint32_t *)P);
29   P += 4;
30   unsigned char *Ret = P + Length;
31   uint32_t Offset = *((uint32_t *)P);
32   if (Offset == 0) // is a CIE
33     return Ret;
34
35   P += 4;
36   intptr_t FDELocation = *((intptr_t *)P);
37   intptr_t NewLocation = FDELocation - DeltaForText;
38   *((intptr_t *)P) = NewLocation;
39   P += sizeof(intptr_t);
40
41   // Skip the FDE address range
42   P += sizeof(intptr_t);
43
44   uint8_t Augmentationsize = *P;
45   P += 1;
46   if (Augmentationsize != 0) {
47     intptr_t LSDA = *((intptr_t *)P);
48     intptr_t NewLSDA = LSDA - DeltaForEH;
49     *((intptr_t *)P) = NewLSDA;
50   }
51
52   return Ret;
53 }
54
55 static intptr_t computeDelta(SectionEntry *A, SectionEntry *B) {
56   intptr_t ObjDistance = A->ObjAddress - B->ObjAddress;
57   intptr_t MemDistance = A->LoadAddress - B->LoadAddress;
58   return ObjDistance - MemDistance;
59 }
60
61 void RuntimeDyldMachO::registerEHFrames() {
62
63   if (!MemMgr)
64     return;
65   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
66     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
67     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
68         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
69       continue;
70     SectionEntry *Text = &Sections[SectionInfo.TextSID];
71     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
72     SectionEntry *ExceptTab = nullptr;
73     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
74       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
75
76     intptr_t DeltaForText = computeDelta(Text, EHFrame);
77     intptr_t DeltaForEH = 0;
78     if (ExceptTab)
79       DeltaForEH = computeDelta(ExceptTab, EHFrame);
80
81     unsigned char *P = EHFrame->Address;
82     unsigned char *End = P + EHFrame->Size;
83     do {
84       P = processFDE(P, DeltaForText, DeltaForEH);
85     } while (P != End);
86
87     MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
88                              EHFrame->Size);
89   }
90   UnregisteredEHFrameSections.clear();
91 }
92
93 void RuntimeDyldMachO::finalizeLoad(ObjectImage &ObjImg,
94                                     ObjSectionToIDMap &SectionMap) {
95   unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
96   unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
97   unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
98   ObjSectionToIDMap::iterator i, e;
99   for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
100     const SectionRef &Section = i->first;
101     StringRef Name;
102     Section.getName(Name);
103     if (Name == "__eh_frame")
104       EHFrameSID = i->second;
105     else if (Name == "__text")
106       TextSID = i->second;
107     else if (Name == "__gcc_except_tab")
108       ExceptTabSID = i->second;
109     else if (Name == "__jump_table")
110       populateJumpTable(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
111                         Section, i->second);
112     else if (Name == "__pointers")
113       populatePointersSection(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
114                               Section, i->second);
115   }
116   UnregisteredEHFrameSections.push_back(
117       EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
118 }
119
120 // The target location for the relocation is described by RE.SectionID and
121 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
122 // SectionEntry has three members describing its location.
123 // SectionEntry::Address is the address at which the section has been loaded
124 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
125 // address that the section will have in the target process.
126 // SectionEntry::ObjAddress is the address of the bits for this section in the
127 // original emitted object image (also in the current address space).
128 //
129 // Relocations will be applied as if the section were loaded at
130 // SectionEntry::LoadAddress, but they will be applied at an address based
131 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
132 // Target memory contents if they are required for value calculations.
133 //
134 // The Value parameter here is the load address of the symbol for the
135 // relocation to be applied.  For relocations which refer to symbols in the
136 // current object Value will be the LoadAddress of the section in which
137 // the symbol resides (RE.Addend provides additional information about the
138 // symbol location).  For external symbols, Value will be the address of the
139 // symbol in the target address space.
140 void RuntimeDyldMachO::resolveRelocation(const RelocationEntry &RE,
141                                          uint64_t Value) {
142   DEBUG (
143     const SectionEntry &Section = Sections[RE.SectionID];
144     uint8_t* LocalAddress = Section.Address + RE.Offset;
145     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
146
147     dbgs() << "resolveRelocation Section: " << RE.SectionID
148            << " LocalAddress: " << format("%p", LocalAddress)
149            << " FinalAddress: " << format("%p", FinalAddress)
150            << " Value: " << format("%p", Value)
151            << " Addend: " << RE.Addend
152            << " isPCRel: " << RE.IsPCRel
153            << " MachoType: " << RE.RelType
154            << " Size: " << (1 << RE.Size) << "\n";
155   );
156
157   // This just dispatches to the proper target specific routine.
158   switch (Arch) {
159   default:
160     llvm_unreachable("Unsupported CPU type!");
161   case Triple::x86_64:
162     resolveX86_64Relocation(RE, Value);
163     break;
164   case Triple::x86:
165     resolveI386Relocation(RE, Value);
166     break;
167   case Triple::arm: // Fall through.
168   case Triple::thumb:
169     resolveARMRelocation(RE, Value);
170     break;
171   case Triple::arm64:
172     resolveARM64Relocation(RE, Value);
173     break;
174   }
175 }
176
177 bool RuntimeDyldMachO::resolveI386Relocation(const RelocationEntry &RE,
178                                              uint64_t Value) {
179   const SectionEntry &Section = Sections[RE.SectionID];
180   uint8_t* LocalAddress = Section.Address + RE.Offset;
181
182   if (RE.IsPCRel) {
183     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
184     Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
185   }
186
187   switch (RE.RelType) {
188     default:
189       llvm_unreachable("Invalid relocation type!");
190     case MachO::GENERIC_RELOC_VANILLA:
191       return applyRelocationValue(LocalAddress, Value + RE.Addend,
192                                   1 << RE.Size);
193     case MachO::GENERIC_RELOC_SECTDIFF:
194     case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
195       uint64_t SectionABase = Sections[RE.Sections.SectionA].LoadAddress;
196       uint64_t SectionBBase = Sections[RE.Sections.SectionB].LoadAddress;
197       assert((Value == SectionABase || Value == SectionBBase) &&
198              "Unexpected SECTDIFF relocation value.");
199       Value = SectionABase - SectionBBase + RE.Addend;
200       return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
201     }
202     case MachO::GENERIC_RELOC_PB_LA_PTR:
203       return Error("Relocation type not implemented yet!");
204   }
205 }
206
207 bool RuntimeDyldMachO::resolveX86_64Relocation(const RelocationEntry &RE,
208                                                uint64_t Value) {
209   const SectionEntry &Section = Sections[RE.SectionID];
210   uint8_t* LocalAddress = Section.Address + RE.Offset;
211
212   // If the relocation is PC-relative, the value to be encoded is the
213   // pointer difference.
214   if (RE.IsPCRel) {
215     // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
216     // address. Is that expected? Only for branches, perhaps?
217     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
218     Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
219   }
220
221   switch (RE.RelType) {
222   default:
223     llvm_unreachable("Invalid relocation type!");
224   case MachO::X86_64_RELOC_SIGNED_1:
225   case MachO::X86_64_RELOC_SIGNED_2:
226   case MachO::X86_64_RELOC_SIGNED_4:
227   case MachO::X86_64_RELOC_SIGNED:
228   case MachO::X86_64_RELOC_UNSIGNED:
229   case MachO::X86_64_RELOC_BRANCH:
230     return applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
231   case MachO::X86_64_RELOC_GOT_LOAD:
232   case MachO::X86_64_RELOC_GOT:
233   case MachO::X86_64_RELOC_SUBTRACTOR:
234   case MachO::X86_64_RELOC_TLV:
235     return Error("Relocation type not implemented yet!");
236   }
237 }
238
239 bool RuntimeDyldMachO::resolveARMRelocation(const RelocationEntry &RE,
240                                             uint64_t Value) {
241   const SectionEntry &Section = Sections[RE.SectionID];
242   uint8_t* LocalAddress = Section.Address + RE.Offset;
243
244   // If the relocation is PC-relative, the value to be encoded is the
245   // pointer difference.
246   if (RE.IsPCRel) {
247     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
248     Value -= FinalAddress;
249     // ARM PCRel relocations have an effective-PC offset of two instructions
250     // (four bytes in Thumb mode, 8 bytes in ARM mode).
251     // FIXME: For now, assume ARM mode.
252     Value -= 8;
253   }
254
255   switch (RE.RelType) {
256   default:
257     llvm_unreachable("Invalid relocation type!");
258   case MachO::ARM_RELOC_VANILLA:
259     return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
260   case MachO::ARM_RELOC_BR24: {
261     // Mask the value into the target address. We know instructions are
262     // 32-bit aligned, so we can do it all at once.
263     uint32_t *p = (uint32_t *)LocalAddress;
264     // The low two bits of the value are not encoded.
265     Value >>= 2;
266     // Mask the value to 24 bits.
267     uint64_t FinalValue = Value & 0xffffff;
268     // Check for overflow.
269     if (Value != FinalValue)
270       return Error("ARM BR24 relocation out of range.");
271     // FIXME: If the destination is a Thumb function (and the instruction
272     // is a non-predicated BL instruction), we need to change it to a BLX
273     // instruction instead.
274
275     // Insert the value into the instruction.
276     *p = (*p & ~0xffffff) | FinalValue;
277     break;
278   }
279   case MachO::ARM_THUMB_RELOC_BR22:
280   case MachO::ARM_THUMB_32BIT_BRANCH:
281   case MachO::ARM_RELOC_HALF:
282   case MachO::ARM_RELOC_HALF_SECTDIFF:
283   case MachO::ARM_RELOC_PAIR:
284   case MachO::ARM_RELOC_SECTDIFF:
285   case MachO::ARM_RELOC_LOCAL_SECTDIFF:
286   case MachO::ARM_RELOC_PB_LA_PTR:
287     return Error("Relocation type not implemented yet!");
288   }
289   return false;
290 }
291
292 bool RuntimeDyldMachO::resolveARM64Relocation(const RelocationEntry &RE,
293                                               uint64_t Value) {
294   const SectionEntry &Section = Sections[RE.SectionID];
295   uint8_t* LocalAddress = Section.Address + RE.Offset;
296
297   // If the relocation is PC-relative, the value to be encoded is the
298   // pointer difference.
299   if (RE.IsPCRel) {
300     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
301     Value -= FinalAddress;
302   }
303
304   switch (RE.RelType) {
305   default:
306     llvm_unreachable("Invalid relocation type!");
307   case MachO::ARM64_RELOC_UNSIGNED:
308     return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
309   case MachO::ARM64_RELOC_BRANCH26: {
310     // Mask the value into the target address. We know instructions are
311     // 32-bit aligned, so we can do it all at once.
312     uint32_t *p = (uint32_t *)LocalAddress;
313     // The low two bits of the value are not encoded.
314     Value >>= 2;
315     // Mask the value to 26 bits.
316     uint64_t FinalValue = Value & 0x3ffffff;
317     // Check for overflow.
318     if (FinalValue != Value)
319       return Error("ARM64 BRANCH26 relocation out of range.");
320     // Insert the value into the instruction.
321     *p = (*p & ~0x3ffffff) | FinalValue;
322     break;
323   }
324   case MachO::ARM64_RELOC_SUBTRACTOR:
325   case MachO::ARM64_RELOC_PAGE21:
326   case MachO::ARM64_RELOC_PAGEOFF12:
327   case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
328   case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
329   case MachO::ARM64_RELOC_POINTER_TO_GOT:
330   case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
331   case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
332   case MachO::ARM64_RELOC_ADDEND:
333     return Error("Relocation type not implemented yet!");
334   }
335   return false;
336 }
337
338 void RuntimeDyldMachO::populateJumpTable(MachOObjectFile &Obj,
339                                          const SectionRef &JTSection,
340                                          unsigned JTSectionID) {
341   assert(!Obj.is64Bit() &&
342          "__jump_table section not supported in 64-bit MachO.");
343
344   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
345   MachO::section Sec32 = Obj.getSection(JTSection.getRawDataRefImpl());
346   uint32_t JTSectionSize = Sec32.size;
347   unsigned FirstIndirectSymbol = Sec32.reserved1;
348   unsigned JTEntrySize = Sec32.reserved2;
349   unsigned NumJTEntries = JTSectionSize / JTEntrySize;
350   uint8_t* JTSectionAddr = getSectionAddress(JTSectionID);
351   unsigned JTEntryOffset = 0;
352
353   assert((JTSectionSize % JTEntrySize) == 0 &&
354          "Jump-table section does not contain a whole number of stubs?");
355
356   for (unsigned i = 0; i < NumJTEntries; ++i) {
357     unsigned SymbolIndex =
358       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
359     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
360     StringRef IndirectSymbolName;
361     SI->getName(IndirectSymbolName);
362     uint8_t* JTEntryAddr = JTSectionAddr + JTEntryOffset;
363     createStubFunction(JTEntryAddr);
364     RelocationEntry RE(JTSectionID, JTEntryOffset + 1,
365                        MachO::GENERIC_RELOC_VANILLA, 0, true, 2);
366     addRelocationForSymbol(RE, IndirectSymbolName);
367     JTEntryOffset += JTEntrySize;
368   }
369 }
370
371 void RuntimeDyldMachO::populatePointersSection(MachOObjectFile &Obj,
372                                                const SectionRef &PTSection,
373                                                unsigned PTSectionID) {
374   assert(!Obj.is64Bit() &&
375          "__pointers section not supported in 64-bit MachO.");
376
377   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
378   MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
379   uint32_t PTSectionSize = Sec32.size;
380   unsigned FirstIndirectSymbol = Sec32.reserved1;
381   const unsigned PTEntrySize = 4;
382   unsigned NumPTEntries = PTSectionSize / PTEntrySize;
383   unsigned PTEntryOffset = 0;
384
385   assert((PTSectionSize % PTEntrySize) == 0 &&
386          "Pointers section does not contain a whole number of stubs?");
387
388   DEBUG(dbgs() << "Populating __pointers, Section ID " << PTSectionID
389                << ", " << NumPTEntries << " entries, "
390                << PTEntrySize << " bytes each:\n");
391
392   for (unsigned i = 0; i < NumPTEntries; ++i) {
393     unsigned SymbolIndex =
394       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
395     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
396     StringRef IndirectSymbolName;
397     SI->getName(IndirectSymbolName);
398     DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
399           << ", PT offset: " << PTEntryOffset << "\n");
400     RelocationEntry RE(PTSectionID, PTEntryOffset,
401                        MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
402     addRelocationForSymbol(RE, IndirectSymbolName);
403     PTEntryOffset += PTEntrySize;
404   }
405 }
406
407
408 section_iterator getSectionByAddress(const MachOObjectFile &Obj,
409                                      uint64_t Addr) {
410   section_iterator SI = Obj.section_begin();
411   section_iterator SE = Obj.section_end();
412
413   for (; SI != SE; ++SI) {
414     uint64_t SAddr, SSize;
415     SI->getAddress(SAddr);
416     SI->getSize(SSize);
417     if ((Addr >= SAddr) && (Addr < SAddr + SSize))
418       return SI;
419   }
420
421   return SE;
422 }
423
424 relocation_iterator RuntimeDyldMachO::processSECTDIFFRelocation(
425                                             unsigned SectionID,
426                                             relocation_iterator RelI,
427                                             ObjectImage &Obj,
428                                             ObjSectionToIDMap &ObjSectionToID) {
429   const MachOObjectFile *MachO =
430     static_cast<const MachOObjectFile*>(Obj.getObjectFile());
431   MachO::any_relocation_info RE =
432     MachO->getRelocation(RelI->getRawDataRefImpl());
433
434   SectionEntry &Section = Sections[SectionID];
435   uint32_t RelocType = MachO->getAnyRelocationType(RE);
436   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
437   unsigned Size = MachO->getAnyRelocationLength(RE);
438   uint64_t Offset;
439   RelI->getOffset(Offset);
440   uint8_t *LocalAddress = Section.Address + Offset;
441   unsigned NumBytes = 1 << Size;
442   int64_t Addend = 0;
443   memcpy(&Addend, LocalAddress, NumBytes);
444
445   ++RelI;
446   MachO::any_relocation_info RE2 =
447     MachO->getRelocation(RelI->getRawDataRefImpl());
448
449   uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
450   section_iterator SAI = getSectionByAddress(*MachO, AddrA);
451   assert(SAI != MachO->section_end() && "Can't find section for address A");
452   uint64_t SectionABase;
453   SAI->getAddress(SectionABase);
454   uint64_t SectionAOffset = AddrA - SectionABase;
455   SectionRef SectionA = *SAI;
456   bool IsCode;
457   SectionA.isText(IsCode);
458   uint32_t SectionAID = findOrEmitSection(Obj, SectionA, IsCode,
459                                           ObjSectionToID);
460
461   uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
462   section_iterator SBI = getSectionByAddress(*MachO, AddrB);
463   assert(SBI != MachO->section_end() && "Can't find section for address B");
464   uint64_t SectionBBase;
465   SBI->getAddress(SectionBBase);
466   uint64_t SectionBOffset = AddrB - SectionBBase;
467   SectionRef SectionB = *SBI;
468   uint32_t SectionBID = findOrEmitSection(Obj, SectionB, IsCode,
469                                           ObjSectionToID);
470
471   if (Addend != AddrA - AddrB)
472     Error("Unexpected SECTDIFF relocation addend.");
473
474   DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
475                << ", Addend: " << Addend << ", SectionA ID: "
476                << SectionAID << ", SectionAOffset: " << SectionAOffset
477                << ", SectionB ID: " << SectionBID << ", SectionBOffset: "
478                << SectionBOffset << "\n");
479   RelocationEntry R(SectionID, Offset, RelocType, 0,
480                     SectionAID, SectionAOffset, SectionBID, SectionBOffset,
481                     IsPCRel, Size);
482
483   addRelocationForSection(R, SectionAID);
484   addRelocationForSection(R, SectionBID);
485
486   return ++RelI;
487 }
488
489 relocation_iterator RuntimeDyldMachO::processI386ScatteredVANILLA(
490                                             unsigned SectionID,
491                                             relocation_iterator RelI,
492                                             ObjectImage &Obj,
493                                             ObjSectionToIDMap &ObjSectionToID) {
494   const MachOObjectFile *MachO =
495     static_cast<const MachOObjectFile*>(Obj.getObjectFile());
496   MachO::any_relocation_info RE =
497     MachO->getRelocation(RelI->getRawDataRefImpl());
498
499   SectionEntry &Section = Sections[SectionID];
500   uint32_t RelocType = MachO->getAnyRelocationType(RE);
501   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
502   unsigned Size = MachO->getAnyRelocationLength(RE);
503   uint64_t Offset;
504   RelI->getOffset(Offset);
505   uint8_t *LocalAddress = Section.Address + Offset;
506   unsigned NumBytes = 1 << Size;
507   int64_t Addend = 0;
508   memcpy(&Addend, LocalAddress, NumBytes);
509
510   unsigned SymbolBaseAddr = MachO->getScatteredRelocationValue(RE);
511   section_iterator TargetSI = getSectionByAddress(*MachO, SymbolBaseAddr);
512   assert(TargetSI != MachO->section_end() && "Can't find section for symbol");
513   uint64_t SectionBaseAddr;
514   TargetSI->getAddress(SectionBaseAddr);
515   SectionRef TargetSection = *TargetSI;
516   bool IsCode;
517   TargetSection.isText(IsCode);
518   uint32_t TargetSectionID = findOrEmitSection(Obj, TargetSection, IsCode,
519                                                ObjSectionToID);
520
521   Addend -= SectionBaseAddr;
522   RelocationEntry R(SectionID, Offset, RelocType, Addend,
523                     IsPCRel, Size);
524
525   addRelocationForSection(R, TargetSectionID);
526
527   return ++RelI;
528 }
529
530 relocation_iterator RuntimeDyldMachO::processRelocationRef(
531     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
532     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
533     StubMap &Stubs) {
534   const ObjectFile *OF = Obj.getObjectFile();
535   const MachOObjectFile *MachO = static_cast<const MachOObjectFile *>(OF);
536   MachO::any_relocation_info RE =
537       MachO->getRelocation(RelI->getRawDataRefImpl());
538
539   uint32_t RelType = MachO->getAnyRelocationType(RE);
540
541   // FIXME: Properly handle scattered relocations.
542   //        Special case the couple of scattered relocations that we know how
543   //        to handle: SECTDIFF relocations, and scattered VANILLA relocations
544   //        on I386.
545   //        For all other scattered relocations, just bail out and hope for the
546   //        best, since the offsets computed by scattered relocations have often
547   //        been optimisticaly filled in by the compiler. This will fail
548   //        horribly where the relocations *do* need to be applied, but that was
549   //        already the case.
550   if (MachO->isRelocationScattered(RE)) {
551     if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
552         RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
553       return processSECTDIFFRelocation(SectionID, RelI, Obj, ObjSectionToID);
554     else if (Arch == Triple::x86 && RelType == MachO::GENERIC_RELOC_VANILLA)
555       return processI386ScatteredVANILLA(SectionID, RelI, Obj, ObjSectionToID);
556     else
557       return ++RelI;
558   }
559
560   RelocationValueRef Value;
561   SectionEntry &Section = Sections[SectionID];
562
563   bool IsExtern = MachO->getPlainRelocationExternal(RE);
564   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
565   unsigned Size = MachO->getAnyRelocationLength(RE);
566   uint64_t Offset;
567   RelI->getOffset(Offset);
568   uint8_t *LocalAddress = Section.Address + Offset;
569   unsigned NumBytes = 1 << Size;
570   uint64_t Addend = 0;
571   memcpy(&Addend, LocalAddress, NumBytes);
572
573   if (IsExtern) {
574     // Obtain the symbol name which is referenced in the relocation
575     symbol_iterator Symbol = RelI->getSymbol();
576     StringRef TargetName;
577     Symbol->getName(TargetName);
578     // First search for the symbol in the local symbol table
579     SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
580     if (lsi != Symbols.end()) {
581       Value.SectionID = lsi->second.first;
582       Value.Addend = lsi->second.second + Addend;
583     } else {
584       // Search for the symbol in the global symbol table
585       SymbolTableMap::const_iterator gsi =
586           GlobalSymbolTable.find(TargetName.data());
587       if (gsi != GlobalSymbolTable.end()) {
588         Value.SectionID = gsi->second.first;
589         Value.Addend = gsi->second.second + Addend;
590       } else {
591         Value.SymbolName = TargetName.data();
592         Value.Addend = Addend;
593       }
594     }
595
596     // Addends for external, PC-rel relocations on i386 point back to the zero
597     // offset. Calculate the final offset from the relocation target instead.
598     // This allows us to use the same logic for both external and internal
599     // relocations in resolveI386RelocationRef.
600     if (Arch == Triple::x86 && IsPCRel) {
601       uint64_t RelocAddr = 0;
602       RelI->getAddress(RelocAddr);
603       Value.Addend += RelocAddr + 4;
604     }
605
606   } else {
607     SectionRef Sec = MachO->getRelocationSection(RE);
608     bool IsCode = false;
609     Sec.isText(IsCode);
610     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
611     uint64_t Addr;
612     Sec.getAddress(Addr);
613     Value.Addend = Addend - Addr;
614     if (IsPCRel)
615       Value.Addend += Offset + NumBytes;
616   }
617
618   if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
619                                  RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
620     assert(IsPCRel);
621     assert(Size == 2);
622
623     // FIXME: Teach the generic code above not to prematurely conflate
624     //        relocation addends and symbol offsets.
625     Value.Addend -= Addend;
626     StubMap::const_iterator i = Stubs.find(Value);
627     uint8_t *Addr;
628     if (i != Stubs.end()) {
629       Addr = Section.Address + i->second;
630     } else {
631       Stubs[Value] = Section.StubOffset;
632       uint8_t *GOTEntry = Section.Address + Section.StubOffset;
633       RelocationEntry GOTRE(SectionID, Section.StubOffset,
634                             MachO::X86_64_RELOC_UNSIGNED, Value.Addend, false,
635                             3);
636       if (Value.SymbolName)
637         addRelocationForSymbol(GOTRE, Value.SymbolName);
638       else
639         addRelocationForSection(GOTRE, Value.SectionID);
640       Section.StubOffset += 8;
641       Addr = GOTEntry;
642     }
643     RelocationEntry TargetRE(SectionID, Offset,
644                              MachO::X86_64_RELOC_UNSIGNED, Addend, true,
645                              2);
646     resolveRelocation(TargetRE, (uint64_t)Addr);
647   } else if (Arch == Triple::arm && (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
648     // This is an ARM branch relocation, need to use a stub function.
649
650     //  Look up for existing stub.
651     StubMap::const_iterator i = Stubs.find(Value);
652     uint8_t *Addr;
653     if (i != Stubs.end()) {
654       Addr = Section.Address + i->second;
655     } else {
656       // Create a new stub function.
657       Stubs[Value] = Section.StubOffset;
658       uint8_t *StubTargetAddr =
659           createStubFunction(Section.Address + Section.StubOffset);
660       RelocationEntry StubRE(SectionID, StubTargetAddr - Section.Address,
661                              MachO::GENERIC_RELOC_VANILLA, Value.Addend);
662       if (Value.SymbolName)
663         addRelocationForSymbol(StubRE, Value.SymbolName);
664       else
665         addRelocationForSection(StubRE, Value.SectionID);
666       Addr = Section.Address + Section.StubOffset;
667       Section.StubOffset += getMaxStubSize();
668     }
669     RelocationEntry TargetRE(Value.SectionID, Offset, RelType, 0, IsPCRel,
670                              Size);
671     resolveRelocation(TargetRE, (uint64_t)Addr);
672   } else {
673     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, IsPCRel, Size);
674     if (Value.SymbolName)
675       addRelocationForSymbol(RE, Value.SymbolName);
676     else
677       addRelocationForSection(RE, Value.SectionID);
678   }
679   return ++RelI;
680 }
681
682 bool
683 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
684   if (InputBuffer->getBufferSize() < 4)
685     return false;
686   StringRef Magic(InputBuffer->getBufferStart(), 4);
687   if (Magic == "\xFE\xED\xFA\xCE")
688     return true;
689   if (Magic == "\xCE\xFA\xED\xFE")
690     return true;
691   if (Magic == "\xFE\xED\xFA\xCF")
692     return true;
693   if (Magic == "\xCF\xFA\xED\xFE")
694     return true;
695   return false;
696 }
697
698 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
699   return Obj->isMachO();
700 }
701
702 } // end namespace llvm