0494ea20119f9a84604946e03fbfa265504967bd
[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::aarch64:
172   case Triple::arm64:
173     resolveAArch64Relocation(RE, Value);
174     break;
175   }
176 }
177
178 bool RuntimeDyldMachO::resolveI386Relocation(const RelocationEntry &RE,
179                                              uint64_t Value) {
180   const SectionEntry &Section = Sections[RE.SectionID];
181   uint8_t* LocalAddress = Section.Address + RE.Offset;
182
183   if (RE.IsPCRel) {
184     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
185     Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
186   }
187
188   switch (RE.RelType) {
189     default:
190       llvm_unreachable("Invalid relocation type!");
191     case MachO::GENERIC_RELOC_VANILLA:
192       return applyRelocationValue(LocalAddress, Value + RE.Addend,
193                                   1 << RE.Size);
194     case MachO::GENERIC_RELOC_SECTDIFF:
195     case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
196       uint64_t SectionABase = Sections[RE.Sections.SectionA].LoadAddress;
197       uint64_t SectionBBase = Sections[RE.Sections.SectionB].LoadAddress;
198       assert((Value == SectionABase || Value == SectionBBase) &&
199              "Unexpected SECTDIFF relocation value.");
200       Value = SectionABase - SectionBBase + RE.Addend;
201       return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
202     }
203     case MachO::GENERIC_RELOC_PB_LA_PTR:
204       return Error("Relocation type not implemented yet!");
205   }
206 }
207
208 bool RuntimeDyldMachO::resolveX86_64Relocation(const RelocationEntry &RE,
209                                                uint64_t Value) {
210   const SectionEntry &Section = Sections[RE.SectionID];
211   uint8_t* LocalAddress = Section.Address + RE.Offset;
212
213   // If the relocation is PC-relative, the value to be encoded is the
214   // pointer difference.
215   if (RE.IsPCRel) {
216     // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
217     // address. Is that expected? Only for branches, perhaps?
218     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
219     Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
220   }
221
222   switch (RE.RelType) {
223   default:
224     llvm_unreachable("Invalid relocation type!");
225   case MachO::X86_64_RELOC_SIGNED_1:
226   case MachO::X86_64_RELOC_SIGNED_2:
227   case MachO::X86_64_RELOC_SIGNED_4:
228   case MachO::X86_64_RELOC_SIGNED:
229   case MachO::X86_64_RELOC_UNSIGNED:
230   case MachO::X86_64_RELOC_BRANCH:
231     return applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
232   case MachO::X86_64_RELOC_GOT_LOAD:
233   case MachO::X86_64_RELOC_GOT:
234   case MachO::X86_64_RELOC_SUBTRACTOR:
235   case MachO::X86_64_RELOC_TLV:
236     return Error("Relocation type not implemented yet!");
237   }
238 }
239
240 bool RuntimeDyldMachO::resolveARMRelocation(const RelocationEntry &RE,
241                                             uint64_t Value) {
242   const SectionEntry &Section = Sections[RE.SectionID];
243   uint8_t* LocalAddress = Section.Address + RE.Offset;
244
245   // If the relocation is PC-relative, the value to be encoded is the
246   // pointer difference.
247   if (RE.IsPCRel) {
248     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
249     Value -= FinalAddress;
250     // ARM PCRel relocations have an effective-PC offset of two instructions
251     // (four bytes in Thumb mode, 8 bytes in ARM mode).
252     // FIXME: For now, assume ARM mode.
253     Value -= 8;
254   }
255
256   switch (RE.RelType) {
257   default:
258     llvm_unreachable("Invalid relocation type!");
259   case MachO::ARM_RELOC_VANILLA:
260     return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
261   case MachO::ARM_RELOC_BR24: {
262     // Mask the value into the target address. We know instructions are
263     // 32-bit aligned, so we can do it all at once.
264     uint32_t *p = (uint32_t *)LocalAddress;
265     // The low two bits of the value are not encoded.
266     Value >>= 2;
267     // Mask the value to 24 bits.
268     uint64_t FinalValue = Value & 0xffffff;
269     // Check for overflow.
270     if (Value != FinalValue)
271       return Error("ARM BR24 relocation out of range.");
272     // FIXME: If the destination is a Thumb function (and the instruction
273     // is a non-predicated BL instruction), we need to change it to a BLX
274     // instruction instead.
275
276     // Insert the value into the instruction.
277     *p = (*p & ~0xffffff) | FinalValue;
278     break;
279   }
280   case MachO::ARM_THUMB_RELOC_BR22:
281   case MachO::ARM_THUMB_32BIT_BRANCH:
282   case MachO::ARM_RELOC_HALF:
283   case MachO::ARM_RELOC_HALF_SECTDIFF:
284   case MachO::ARM_RELOC_PAIR:
285   case MachO::ARM_RELOC_SECTDIFF:
286   case MachO::ARM_RELOC_LOCAL_SECTDIFF:
287   case MachO::ARM_RELOC_PB_LA_PTR:
288     return Error("Relocation type not implemented yet!");
289   }
290   return false;
291 }
292
293 bool RuntimeDyldMachO::resolveAArch64Relocation(const RelocationEntry &RE,
294                                                 uint64_t Value) {
295   const SectionEntry &Section = Sections[RE.SectionID];
296   uint8_t* LocalAddress = Section.Address + RE.Offset;
297
298   switch (RE.RelType) {
299   default:
300     llvm_unreachable("Invalid relocation type!");
301   case MachO::ARM64_RELOC_UNSIGNED: {
302     assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_UNSIGNED not supported");
303     // Mask in the target value a byte at a time (we don't have an alignment
304     // guarantee for the target address, so this is safest).
305     if (RE.Size < 2)
306       llvm_unreachable("Invalid size for ARM64_RELOC_UNSIGNED");
307
308     applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
309     break;
310   }
311   case MachO::ARM64_RELOC_BRANCH26: {
312     assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_BRANCH26 not supported");
313     // Mask the value into the target address. We know instructions are
314     // 32-bit aligned, so we can do it all at once.
315     uint32_t *p = (uint32_t*)LocalAddress;
316     // Check if the addend is encoded in the instruction.
317     uint32_t EncodedAddend = *p & 0x03FFFFFF;
318     if (EncodedAddend != 0 ) {
319       if (RE.Addend == 0)
320         llvm_unreachable("branch26 instruction has embedded addend.");
321       else
322         llvm_unreachable("branch26 instruction has embedded addend and" \
323                          "ARM64_RELOC_ADDEND.");
324     }
325     // Check if branch is in range.
326     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
327     uint64_t PCRelVal = Value - FinalAddress + RE.Addend;
328     assert(isInt<26>(PCRelVal) && "Branch target out of range!");
329     // Insert the value into the instruction.
330     *p = (*p & 0xFC000000) | ((uint32_t)(PCRelVal >> 2) & 0x03FFFFFF);
331     break;
332   }
333   case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
334   case MachO::ARM64_RELOC_PAGE21: {
335     assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_PAGE21 not supported");
336     // Mask the value into the target address. We know instructions are
337     // 32-bit aligned, so we can do it all at once.
338     uint32_t *p = (uint32_t*)LocalAddress;
339     // Check if the addend is encoded in the instruction.
340     uint32_t EncodedAddend = ((*p & 0x60000000) >> 29) |
341                              ((*p & 0x01FFFFE0) >> 3);
342     if (EncodedAddend != 0) {
343       if (RE.Addend == 0)
344         llvm_unreachable("adrp instruction has embedded addend.");
345       else
346         llvm_unreachable("adrp instruction has embedded addend and" \
347                          "ARM64_RELOC_ADDEND.");
348     }
349     // Adjust for PC-relative relocation and offset.
350     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
351     uint64_t PCRelVal = ((Value + RE.Addend) & (-4096)) -
352                          (FinalAddress & (-4096));
353     // Check that the value fits into 21 bits (+ 12 lower bits).
354     assert(isInt<33>(PCRelVal) && "Invalid page reloc value!");
355     // Insert the value into the instruction.
356     uint32_t ImmLoValue = (uint32_t)(PCRelVal << 17) & 0x60000000;
357     uint32_t ImmHiValue = (uint32_t)(PCRelVal >>  9) & 0x00FFFFE0;
358     *p = (*p & 0x9F00001F) | ImmHiValue | ImmLoValue;
359     break;
360   }
361   case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
362   case MachO::ARM64_RELOC_PAGEOFF12: {
363     assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_PAGEOFF21 not supported");
364     // Mask the value into the target address. We know instructions are
365     // 32-bit aligned, so we can do it all at once.
366     uint32_t *p = (uint32_t*)LocalAddress;
367     // Check if the addend is encoded in the instruction.
368     uint32_t EncodedAddend = *p & 0x003FFC00;
369     if (EncodedAddend != 0) {
370       if (RE.Addend == 0)
371         llvm_unreachable("adrp instruction has embedded addend.");
372       else
373         llvm_unreachable("adrp instruction has embedded addend and" \
374                          "ARM64_RELOC_ADDEND.");
375     }
376     // Add the offset from the symbol.
377     Value += RE.Addend;
378     // Mask out the page address and only use the lower 12 bits.
379     Value &= 0xFFF;
380     // Check which instruction we are updating to obtain the implicit shift
381     // factor from LDR/STR instructions.
382     if (*p & 0x08000000) {
383       uint32_t ImplicitShift = ((*p >> 30) & 0x3);
384       switch (ImplicitShift) {
385       case 0:
386         // Check if this a vector op.
387         if ((*p & 0x04800000) == 0x04800000) {
388           ImplicitShift = 4;
389           assert(((Value & 0xF) == 0) &&
390                  "128-bit LDR/STR not 16-byte aligned.");
391         }
392         break;
393       case 1:
394         assert(((Value & 0x1) == 0) && "16-bit LDR/STR not 2-byte aligned.");
395       case 2:
396         assert(((Value & 0x3) == 0) && "32-bit LDR/STR not 4-byte aligned.");
397       case 3:
398         assert(((Value & 0x7) == 0) && "64-bit LDR/STR not 8-byte aligned.");
399       }
400       // Compensate for implicit shift.
401       Value >>= ImplicitShift;
402     }
403     // Insert the value into the instruction.
404     *p = (*p & 0xFFC003FF) | ((uint32_t)(Value << 10) & 0x003FFC00);
405     break;
406   }
407   case MachO::ARM64_RELOC_SUBTRACTOR:
408   case MachO::ARM64_RELOC_POINTER_TO_GOT:
409   case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
410   case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
411     llvm_unreachable("Relocation type not implemented yet!");
412     return Error("Relocation type not implemented yet!");
413   case MachO::ARM64_RELOC_ADDEND:
414     llvm_unreachable("ARM64_RELOC_ADDEND should have been handeled by " \
415                      "processRelocationRef!");
416   }
417   return false;
418 }
419
420 void RuntimeDyldMachO::populateJumpTable(MachOObjectFile &Obj,
421                                          const SectionRef &JTSection,
422                                          unsigned JTSectionID) {
423   assert(!Obj.is64Bit() &&
424          "__jump_table section not supported in 64-bit MachO.");
425
426   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
427   MachO::section Sec32 = Obj.getSection(JTSection.getRawDataRefImpl());
428   uint32_t JTSectionSize = Sec32.size;
429   unsigned FirstIndirectSymbol = Sec32.reserved1;
430   unsigned JTEntrySize = Sec32.reserved2;
431   unsigned NumJTEntries = JTSectionSize / JTEntrySize;
432   uint8_t* JTSectionAddr = getSectionAddress(JTSectionID);
433   unsigned JTEntryOffset = 0;
434
435   assert((JTSectionSize % JTEntrySize) == 0 &&
436          "Jump-table section does not contain a whole number of stubs?");
437
438   for (unsigned i = 0; i < NumJTEntries; ++i) {
439     unsigned SymbolIndex =
440       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
441     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
442     StringRef IndirectSymbolName;
443     SI->getName(IndirectSymbolName);
444     uint8_t* JTEntryAddr = JTSectionAddr + JTEntryOffset;
445     createStubFunction(JTEntryAddr);
446     RelocationEntry RE(JTSectionID, JTEntryOffset + 1,
447                        MachO::GENERIC_RELOC_VANILLA, 0, true, 2);
448     addRelocationForSymbol(RE, IndirectSymbolName);
449     JTEntryOffset += JTEntrySize;
450   }
451 }
452
453 void RuntimeDyldMachO::populatePointersSection(MachOObjectFile &Obj,
454                                                const SectionRef &PTSection,
455                                                unsigned PTSectionID) {
456   assert(!Obj.is64Bit() &&
457          "__pointers section not supported in 64-bit MachO.");
458
459   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
460   MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
461   uint32_t PTSectionSize = Sec32.size;
462   unsigned FirstIndirectSymbol = Sec32.reserved1;
463   const unsigned PTEntrySize = 4;
464   unsigned NumPTEntries = PTSectionSize / PTEntrySize;
465   unsigned PTEntryOffset = 0;
466
467   assert((PTSectionSize % PTEntrySize) == 0 &&
468          "Pointers section does not contain a whole number of stubs?");
469
470   DEBUG(dbgs() << "Populating __pointers, Section ID " << PTSectionID
471                << ", " << NumPTEntries << " entries, "
472                << PTEntrySize << " bytes each:\n");
473
474   for (unsigned i = 0; i < NumPTEntries; ++i) {
475     unsigned SymbolIndex =
476       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
477     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
478     StringRef IndirectSymbolName;
479     SI->getName(IndirectSymbolName);
480     DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
481           << ", PT offset: " << PTEntryOffset << "\n");
482     RelocationEntry RE(PTSectionID, PTEntryOffset,
483                        MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
484     addRelocationForSymbol(RE, IndirectSymbolName);
485     PTEntryOffset += PTEntrySize;
486   }
487 }
488
489
490 section_iterator getSectionByAddress(const MachOObjectFile &Obj,
491                                      uint64_t Addr) {
492   section_iterator SI = Obj.section_begin();
493   section_iterator SE = Obj.section_end();
494
495   for (; SI != SE; ++SI) {
496     uint64_t SAddr, SSize;
497     SI->getAddress(SAddr);
498     SI->getSize(SSize);
499     if ((Addr >= SAddr) && (Addr < SAddr + SSize))
500       return SI;
501   }
502
503   return SE;
504 }
505
506 relocation_iterator RuntimeDyldMachO::processSECTDIFFRelocation(
507                                             unsigned SectionID,
508                                             relocation_iterator RelI,
509                                             ObjectImage &Obj,
510                                             ObjSectionToIDMap &ObjSectionToID) {
511   const MachOObjectFile *MachO =
512     static_cast<const MachOObjectFile*>(Obj.getObjectFile());
513   MachO::any_relocation_info RE =
514     MachO->getRelocation(RelI->getRawDataRefImpl());
515
516   SectionEntry &Section = Sections[SectionID];
517   uint32_t RelocType = MachO->getAnyRelocationType(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   int64_t Addend = 0;
525   memcpy(&Addend, LocalAddress, NumBytes);
526
527   ++RelI;
528   MachO::any_relocation_info RE2 =
529     MachO->getRelocation(RelI->getRawDataRefImpl());
530
531   uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
532   section_iterator SAI = getSectionByAddress(*MachO, AddrA);
533   assert(SAI != MachO->section_end() && "Can't find section for address A");
534   uint64_t SectionABase;
535   SAI->getAddress(SectionABase);
536   uint64_t SectionAOffset = AddrA - SectionABase;
537   SectionRef SectionA = *SAI;
538   bool IsCode;
539   SectionA.isText(IsCode);
540   uint32_t SectionAID = findOrEmitSection(Obj, SectionA, IsCode,
541                                           ObjSectionToID);
542
543   uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
544   section_iterator SBI = getSectionByAddress(*MachO, AddrB);
545   assert(SBI != MachO->section_end() && "Can't find section for address B");
546   uint64_t SectionBBase;
547   SBI->getAddress(SectionBBase);
548   uint64_t SectionBOffset = AddrB - SectionBBase;
549   SectionRef SectionB = *SBI;
550   uint32_t SectionBID = findOrEmitSection(Obj, SectionB, IsCode,
551                                           ObjSectionToID);
552
553   if (Addend != AddrA - AddrB)
554     Error("Unexpected SECTDIFF relocation addend.");
555
556   DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
557                << ", Addend: " << Addend << ", SectionA ID: "
558                << SectionAID << ", SectionAOffset: " << SectionAOffset
559                << ", SectionB ID: " << SectionBID << ", SectionBOffset: "
560                << SectionBOffset << "\n");
561   RelocationEntry R(SectionID, Offset, RelocType, 0,
562                     SectionAID, SectionAOffset, SectionBID, SectionBOffset,
563                     IsPCRel, Size);
564
565   addRelocationForSection(R, SectionAID);
566   addRelocationForSection(R, SectionBID);
567
568   return ++RelI;
569 }
570
571 relocation_iterator RuntimeDyldMachO::processI386ScatteredVANILLA(
572                                             unsigned SectionID,
573                                             relocation_iterator RelI,
574                                             ObjectImage &Obj,
575                                             ObjSectionToIDMap &ObjSectionToID) {
576   const MachOObjectFile *MachO =
577     static_cast<const MachOObjectFile*>(Obj.getObjectFile());
578   MachO::any_relocation_info RE =
579     MachO->getRelocation(RelI->getRawDataRefImpl());
580
581   SectionEntry &Section = Sections[SectionID];
582   uint32_t RelocType = MachO->getAnyRelocationType(RE);
583   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
584   unsigned Size = MachO->getAnyRelocationLength(RE);
585   uint64_t Offset;
586   RelI->getOffset(Offset);
587   uint8_t *LocalAddress = Section.Address + Offset;
588   unsigned NumBytes = 1 << Size;
589   int64_t Addend = 0;
590   memcpy(&Addend, LocalAddress, NumBytes);
591
592   unsigned SymbolBaseAddr = MachO->getScatteredRelocationValue(RE);
593   section_iterator TargetSI = getSectionByAddress(*MachO, SymbolBaseAddr);
594   assert(TargetSI != MachO->section_end() && "Can't find section for symbol");
595   uint64_t SectionBaseAddr;
596   TargetSI->getAddress(SectionBaseAddr);
597   SectionRef TargetSection = *TargetSI;
598   bool IsCode;
599   TargetSection.isText(IsCode);
600   uint32_t TargetSectionID = findOrEmitSection(Obj, TargetSection, IsCode,
601                                                ObjSectionToID);
602
603   Addend -= SectionBaseAddr;
604   RelocationEntry R(SectionID, Offset, RelocType, Addend,
605                     IsPCRel, Size);
606
607   addRelocationForSection(R, TargetSectionID);
608
609   return ++RelI;
610 }
611
612 relocation_iterator RuntimeDyldMachO::processRelocationRef(
613     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
614     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
615     StubMap &Stubs) {
616   const ObjectFile *OF = Obj.getObjectFile();
617   const MachOObjectFile *MachO = static_cast<const MachOObjectFile *>(OF);
618   MachO::any_relocation_info RE =
619       MachO->getRelocation(RelI->getRawDataRefImpl());
620   int64_t RelocAddendValue = 0;
621   bool HasRelocAddendValue = false;
622
623   uint32_t RelType = MachO->getAnyRelocationType(RE);
624   if (Arch == Triple::arm64) {
625     // ARM64_RELOC_ADDEND provides the offset (addend) that will be used by the
626     // next relocation entry. Save the value and advance to the next relocation
627     // entry.
628     if (RelType == MachO::ARM64_RELOC_ADDEND) {
629       assert(!MachO->getPlainRelocationExternal(RE));
630       assert(!MachO->getAnyRelocationPCRel(RE));
631       assert(MachO->getAnyRelocationLength(RE) == 2);
632       uint64_t RawAddend = MachO->getPlainRelocationSymbolNum(RE);
633       // Sign-extend the 24-bit to 64-bit.
634       RelocAddendValue = RawAddend << 40;
635       RelocAddendValue >>= 40;
636       HasRelocAddendValue = true;
637
638       // Get the next entry.
639       RE = MachO->getRelocation((++RelI)->getRawDataRefImpl());
640       RelType = MachO->getAnyRelocationType(RE);
641       assert(RelType == MachO::ARM64_RELOC_BRANCH26 ||
642              RelType == MachO::ARM64_RELOC_PAGE21 ||
643              RelType == MachO::ARM64_RELOC_PAGEOFF12);
644
645     } else if (RelType == MachO::ARM64_RELOC_BRANCH26 ||
646                RelType == MachO::ARM64_RELOC_PAGE21 ||
647                RelType == MachO::ARM64_RELOC_PAGEOFF12 ||
648                RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
649                RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12) {
650       RelocAddendValue = 0;
651       HasRelocAddendValue = true;
652     }
653   }
654
655   // FIXME: Properly handle scattered relocations.
656   //        Special case the couple of scattered relocations that we know how
657   //        to handle: SECTDIFF relocations, and scattered VANILLA relocations
658   //        on I386.
659   //        For all other scattered relocations, just bail out and hope for the
660   //        best, since the offsets computed by scattered relocations have often
661   //        been optimisticaly filled in by the compiler. This will fail
662   //        horribly where the relocations *do* need to be applied, but that was
663   //        already the case.
664   if (MachO->isRelocationScattered(RE)) {
665     if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
666         RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
667       return processSECTDIFFRelocation(SectionID, RelI, Obj, ObjSectionToID);
668     else if (Arch == Triple::x86 && RelType == MachO::GENERIC_RELOC_VANILLA)
669       return processI386ScatteredVANILLA(SectionID, RelI, Obj, ObjSectionToID);
670     else
671       return ++RelI;
672   }
673
674   RelocationValueRef Value;
675   SectionEntry &Section = Sections[SectionID];
676
677   bool IsExtern = MachO->getPlainRelocationExternal(RE);
678   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
679   unsigned Size = MachO->getAnyRelocationLength(RE);
680   uint64_t Offset;
681   RelI->getOffset(Offset);
682   uint8_t *LocalAddress = Section.Address + Offset;
683   unsigned NumBytes = 1 << Size;
684   int64_t Addend = 0;
685   if (HasRelocAddendValue)
686     Addend = RelocAddendValue;
687   else
688     memcpy(&Addend, LocalAddress, NumBytes);
689
690   if (IsExtern) {
691     // Obtain the symbol name which is referenced in the relocation
692     symbol_iterator Symbol = RelI->getSymbol();
693     StringRef TargetName;
694     Symbol->getName(TargetName);
695     // First search for the symbol in the local symbol table
696     SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
697     if (lsi != Symbols.end()) {
698       Value.SectionID = lsi->second.first;
699       Value.Addend = lsi->second.second + Addend;
700     } else {
701       // Search for the symbol in the global symbol table
702       SymbolTableMap::const_iterator gsi =
703           GlobalSymbolTable.find(TargetName.data());
704       if (gsi != GlobalSymbolTable.end()) {
705         Value.SectionID = gsi->second.first;
706         Value.Addend = gsi->second.second + Addend;
707       } else {
708         Value.SymbolName = TargetName.data();
709         Value.Addend = Addend;
710       }
711     }
712
713     // Addends for external, PC-rel relocations on i386 point back to the zero
714     // offset. Calculate the final offset from the relocation target instead.
715     // This allows us to use the same logic for both external and internal
716     // relocations in resolveI386RelocationRef.
717     if (Arch == Triple::x86 && IsPCRel) {
718       uint64_t RelocAddr = 0;
719       RelI->getAddress(RelocAddr);
720       Value.Addend += RelocAddr + 4;
721     }
722
723   } else {
724     SectionRef Sec = MachO->getRelocationSection(RE);
725     bool IsCode = false;
726     Sec.isText(IsCode);
727     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
728     uint64_t Addr;
729     Sec.getAddress(Addr);
730     Value.Addend = Addend - Addr;
731     if (IsPCRel)
732       Value.Addend += Offset + NumBytes;
733   }
734
735   if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
736                                  RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
737     assert(IsPCRel);
738     assert(Size == 2);
739
740     // FIXME: Teach the generic code above not to prematurely conflate
741     //        relocation addends and symbol offsets.
742     Value.Addend -= Addend;
743     StubMap::const_iterator i = Stubs.find(Value);
744     uint8_t *Addr;
745     if (i != Stubs.end()) {
746       Addr = Section.Address + i->second;
747     } else {
748       Stubs[Value] = Section.StubOffset;
749       uint8_t *GOTEntry = Section.Address + Section.StubOffset;
750       RelocationEntry GOTRE(SectionID, Section.StubOffset,
751                             MachO::X86_64_RELOC_UNSIGNED, Value.Addend, false,
752                             3);
753       if (Value.SymbolName)
754         addRelocationForSymbol(GOTRE, Value.SymbolName);
755       else
756         addRelocationForSection(GOTRE, Value.SectionID);
757       Section.StubOffset += 8;
758       Addr = GOTEntry;
759     }
760     RelocationEntry TargetRE(SectionID, Offset,
761                              MachO::X86_64_RELOC_UNSIGNED, Addend, true,
762                              2);
763     resolveRelocation(TargetRE, (uint64_t)Addr);
764   } else if (Arch == Triple::arm && (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
765     // This is an ARM branch relocation, need to use a stub function.
766
767     //  Look up for existing stub.
768     StubMap::const_iterator i = Stubs.find(Value);
769     uint8_t *Addr;
770     if (i != Stubs.end()) {
771       Addr = Section.Address + i->second;
772     } else {
773       // Create a new stub function.
774       Stubs[Value] = Section.StubOffset;
775       uint8_t *StubTargetAddr =
776           createStubFunction(Section.Address + Section.StubOffset);
777       RelocationEntry StubRE(SectionID, StubTargetAddr - Section.Address,
778                              MachO::GENERIC_RELOC_VANILLA, Value.Addend);
779       if (Value.SymbolName)
780         addRelocationForSymbol(StubRE, Value.SymbolName);
781       else
782         addRelocationForSection(StubRE, Value.SectionID);
783       Addr = Section.Address + Section.StubOffset;
784       Section.StubOffset += getMaxStubSize();
785     }
786     RelocationEntry TargetRE(Value.SectionID, Offset, RelType, 0, IsPCRel,
787                              Size);
788     resolveRelocation(TargetRE, (uint64_t)Addr);
789   } else if (Arch == Triple::arm64 &&
790              (RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
791               RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12)) {
792     assert(Size == 2);
793     StubMap::const_iterator i = Stubs.find(Value);
794     uint8_t *Addr;
795     if (i != Stubs.end())
796       Addr = Section.Address + i->second;
797     else {
798       // FIXME: There must be a better way to do this then to check and fix the
799       // alignment every time!!!
800       uintptr_t BaseAddress = uintptr_t(Section.Address);
801       uintptr_t StubAlignment = getStubAlignment();
802       uintptr_t StubAddress
803         = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
804           -StubAlignment;
805       unsigned StubOffset = StubAddress - BaseAddress;
806       Stubs[Value] = StubOffset;
807       assert(((StubAddress % getStubAlignment()) == 0) &&
808              "GOT entry not aligned");
809       RelocationEntry GOTRE(SectionID, StubOffset, MachO::ARM64_RELOC_UNSIGNED,
810                             Value.Addend, /*IsPCRel=*/false, /*Size=*/3);
811       if (Value.SymbolName)
812         addRelocationForSymbol(GOTRE, Value.SymbolName);
813       else
814         addRelocationForSection(GOTRE, Value.SectionID);
815       Section.StubOffset = StubOffset + getMaxStubSize();
816
817       Addr = (uint8_t *)StubAddress;
818     }
819     RelocationEntry TargetRE(SectionID, Offset, RelType, /*Addend=*/0, IsPCRel,
820                              Size);
821     resolveRelocation(TargetRE, (uint64_t)Addr);
822   } else {
823
824     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, IsPCRel, Size);
825     if (Value.SymbolName)
826       addRelocationForSymbol(RE, Value.SymbolName);
827     else
828       addRelocationForSection(RE, Value.SectionID);
829   }
830   return ++RelI;
831 }
832
833 bool
834 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
835   if (InputBuffer->getBufferSize() < 4)
836     return false;
837   StringRef Magic(InputBuffer->getBufferStart(), 4);
838   if (Magic == "\xFE\xED\xFA\xCE")
839     return true;
840   if (Magic == "\xCE\xFA\xED\xFE")
841     return true;
842   if (Magic == "\xFE\xED\xFA\xCF")
843     return true;
844   if (Magic == "\xCF\xFA\xED\xFE")
845     return true;
846   return false;
847 }
848
849 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
850   return Obj->isMachO();
851 }
852
853 } // end namespace llvm