[RuntimeDyld] Fix handling of i386 PC-rel external relocations. This fixes
[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 seciton 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::processRelocationRef(
490     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
491     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
492     StubMap &Stubs) {
493   const ObjectFile *OF = Obj.getObjectFile();
494   const MachOObjectFile *MachO = static_cast<const MachOObjectFile *>(OF);
495   MachO::any_relocation_info RE =
496       MachO->getRelocation(RelI->getRawDataRefImpl());
497
498   uint32_t RelType = MachO->getAnyRelocationType(RE);
499
500   // FIXME: Properly handle scattered relocations.
501   //        For now, optimistically skip these: they can often be ignored, as
502   //        the static linker will already have applied the relocation, and it
503   //        only needs to be reapplied if symbols move relative to one another.
504   //        Note: This will fail horribly where the relocations *do* need to be
505   //        applied, but that was already the case.
506   if (MachO->isRelocationScattered(RE)) {
507     if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
508         RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
509       return processSECTDIFFRelocation(SectionID, RelI, Obj, ObjSectionToID);
510
511     return ++RelI;
512   }
513
514   RelocationValueRef Value;
515   SectionEntry &Section = Sections[SectionID];
516
517   bool IsExtern = MachO->getPlainRelocationExternal(RE);
518   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
519   unsigned Size = MachO->getAnyRelocationLength(RE);
520   uint64_t Offset;
521   RelI->getOffset(Offset);
522   uint8_t *LocalAddress = Section.Address + Offset;
523   unsigned NumBytes = 1 << Size;
524   uint64_t Addend = 0;
525   memcpy(&Addend, LocalAddress, NumBytes);
526
527   if (IsExtern) {
528     // Obtain the symbol name which is referenced in the relocation
529     symbol_iterator Symbol = RelI->getSymbol();
530     StringRef TargetName;
531     Symbol->getName(TargetName);
532     // First search for the symbol in the local symbol table
533     SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
534     if (lsi != Symbols.end()) {
535       Value.SectionID = lsi->second.first;
536       Value.Addend = lsi->second.second + Addend;
537     } else {
538       // Search for the symbol in the global symbol table
539       SymbolTableMap::const_iterator gsi =
540           GlobalSymbolTable.find(TargetName.data());
541       if (gsi != GlobalSymbolTable.end()) {
542         Value.SectionID = gsi->second.first;
543         Value.Addend = gsi->second.second + Addend;
544       } else {
545         Value.SymbolName = TargetName.data();
546         Value.Addend = Addend;
547       }
548     }
549
550     // Addends for external, PC-rel relocations on i386 point back to the zero
551     // offset. Calculate the final offset from the relocation target instead.
552     // This allows us to use the same logic for both external and internal
553     // relocations in resolveI386RelocationRef.
554     if (Arch == Triple::x86 && IsPCRel) {
555       uint64_t RelocAddr = 0;
556       RelI->getAddress(RelocAddr);
557       Value.Addend += RelocAddr + 4;
558     }
559
560   } else {
561     SectionRef Sec = MachO->getRelocationSection(RE);
562     bool IsCode = false;
563     Sec.isText(IsCode);
564     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
565     uint64_t Addr;
566     Sec.getAddress(Addr);
567     Value.Addend = Addend - Addr;
568     if (IsPCRel)
569       Value.Addend += Offset + NumBytes;
570   }
571
572   if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
573                                  RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
574     assert(IsPCRel);
575     assert(Size == 2);
576     StubMap::const_iterator i = Stubs.find(Value);
577     uint8_t *Addr;
578     if (i != Stubs.end()) {
579       Addr = Section.Address + i->second;
580     } else {
581       Stubs[Value] = Section.StubOffset;
582       uint8_t *GOTEntry = Section.Address + Section.StubOffset;
583       RelocationEntry GOTRE(SectionID, Section.StubOffset,
584                             MachO::X86_64_RELOC_UNSIGNED, 0, false, 3);
585       if (Value.SymbolName)
586         addRelocationForSymbol(GOTRE, Value.SymbolName);
587       else
588         addRelocationForSection(GOTRE, Value.SectionID);
589       Section.StubOffset += 8;
590       Addr = GOTEntry;
591     }
592     RelocationEntry TargetRE(SectionID, Offset,
593                              MachO::X86_64_RELOC_UNSIGNED, Value.Addend, true,
594                              2);
595     resolveRelocation(TargetRE, (uint64_t)Addr);
596   } else if (Arch == Triple::arm && (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
597     // This is an ARM branch relocation, need to use a stub function.
598
599     //  Look up for existing stub.
600     StubMap::const_iterator i = Stubs.find(Value);
601     uint8_t *Addr;
602     if (i != Stubs.end()) {
603       Addr = Section.Address + i->second;
604     } else {
605       // Create a new stub function.
606       Stubs[Value] = Section.StubOffset;
607       uint8_t *StubTargetAddr =
608           createStubFunction(Section.Address + Section.StubOffset);
609       RelocationEntry StubRE(SectionID, StubTargetAddr - Section.Address,
610                              MachO::GENERIC_RELOC_VANILLA, Value.Addend);
611       if (Value.SymbolName)
612         addRelocationForSymbol(StubRE, Value.SymbolName);
613       else
614         addRelocationForSection(StubRE, Value.SectionID);
615       Addr = Section.Address + Section.StubOffset;
616       Section.StubOffset += getMaxStubSize();
617     }
618     RelocationEntry TargetRE(Value.SectionID, Offset, RelType, 0, IsPCRel,
619                              Size);
620     resolveRelocation(TargetRE, (uint64_t)Addr);
621   } else {
622     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, IsPCRel, Size);
623     if (Value.SymbolName)
624       addRelocationForSymbol(RE, Value.SymbolName);
625     else
626       addRelocationForSection(RE, Value.SectionID);
627   }
628   return ++RelI;
629 }
630
631 bool
632 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
633   if (InputBuffer->getBufferSize() < 4)
634     return false;
635   StringRef Magic(InputBuffer->getBufferStart(), 4);
636   if (Magic == "\xFE\xED\xFA\xCE")
637     return true;
638   if (Magic == "\xCE\xFA\xED\xFE")
639     return true;
640   if (Magic == "\xFE\xED\xFA\xCF")
641     return true;
642   if (Magic == "\xCF\xFA\xED\xFE")
643     return true;
644   return false;
645 }
646
647 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
648   return Obj->isMachO();
649 }
650
651 } // end namespace llvm