[RuntimeDyld] Add GOT support for AArch64 to RuntimeDyldMachO.
[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 #include "ObjectImageCommon.h"
18 #include "JITRegistrar.h"
19 using namespace llvm;
20 using namespace llvm::object;
21
22 #define DEBUG_TYPE "dyld"
23
24 namespace llvm {
25
26 class MachOObjectImage : public ObjectImageCommon {
27 private:
28   typedef SmallVector<uint64_t, 1> SectionAddrList;
29   SectionAddrList OldSectionAddrList;
30
31 protected:
32   bool is64;
33   bool Registered;
34
35 private:
36   void initOldAddress() {
37     MachOObjectFile *objf = static_cast<MachOObjectFile *>(ObjFile.get());
38     // Unfortunately we need to do this, since there's information encoded
39     // in the original addr of the section that we could not otherwise
40     // recover. The reason for this is that symbols do not actually store
41     // their file offset, but only their vmaddr. This means that in order
42     // to locate the symbol correctly in the object file, we need to know
43     // where the original start of the section was (including any padding,
44     // etc).
45     for (section_iterator i = objf->section_begin(), e = objf->section_end();
46          i != e; ++i) {
47       uint64_t Addr;
48       i->getAddress(Addr);
49       OldSectionAddrList[i->getRawDataRefImpl().d.a] = Addr;
50     }
51   }
52
53 public:
54   MachOObjectImage(ObjectBuffer *Input, bool is64)
55       : ObjectImageCommon(Input),
56         OldSectionAddrList(ObjFile->section_end()->getRawDataRefImpl().d.a, 0),
57         is64(is64), Registered(false) {
58     initOldAddress();
59   }
60
61   MachOObjectImage(std::unique_ptr<object::ObjectFile> Input, bool is64)
62       : ObjectImageCommon(std::move(Input)),
63         OldSectionAddrList(ObjFile->section_end()->getRawDataRefImpl().d.a, 0),
64         is64(is64), Registered(false) {
65     initOldAddress();
66   }
67
68   virtual ~MachOObjectImage() {
69     if (Registered)
70       deregisterWithDebugger();
71   }
72
73   // Subclasses can override these methods to update the image with loaded
74   // addresses for sections and common symbols
75   virtual void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) {
76     MachOObjectFile *objf = static_cast<MachOObjectFile *>(ObjFile.get());
77     char *data =
78         const_cast<char *>(objf->getSectionPointer(Sec.getRawDataRefImpl()));
79
80     uint64_t oldAddr = OldSectionAddrList[Sec.getRawDataRefImpl().d.a];
81
82     if (is64) {
83       ((MachO::section_64 *)data)->addr = Addr;
84     } else {
85       ((MachO::section *)data)->addr = Addr;
86     }
87
88     for (symbol_iterator i = objf->symbol_begin(), e = objf->symbol_end();
89          i != e; ++i) {
90       section_iterator symSec(objf->section_end());
91       (*i).getSection(symSec);
92       if (*symSec == Sec) {
93         uint64_t symAddr;
94         (*i).getAddress(symAddr);
95         updateSymbolAddress(*i, symAddr + Addr - oldAddr);
96       }
97     }
98   }
99
100   uint64_t getOldSectionAddr(const SectionRef &Sec) const {
101     return OldSectionAddrList[Sec.getRawDataRefImpl().d.a];
102   }
103
104   virtual void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) {
105     char *data = const_cast<char *>(
106         reinterpret_cast<const char *>(Sym.getRawDataRefImpl().p));
107     if (is64)
108       ((MachO::nlist_64 *)data)->n_value = Addr;
109     else
110       ((MachO::nlist *)data)->n_value = Addr;
111   }
112
113   virtual void registerWithDebugger() {
114     JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
115     Registered = true;
116   }
117
118   virtual void deregisterWithDebugger() {
119     JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
120   }
121 };
122
123 ObjectImage *RuntimeDyldMachO::createObjectImage(ObjectBuffer *Buffer) {
124   uint32_t magic = *((const uint32_t *)Buffer->getBufferStart());
125   bool is64 = (magic == MachO::MH_MAGIC_64);
126   assert((magic == MachO::MH_MAGIC_64 || magic == MachO::MH_MAGIC) &&
127          "Unrecognized Macho Magic");
128   return new MachOObjectImage(Buffer, is64);
129 }
130
131 ObjectImage *RuntimeDyldMachO::createObjectImageFromFile(
132     std::unique_ptr<object::ObjectFile> ObjFile) {
133   if (!ObjFile)
134     return nullptr;
135
136   MemoryBuffer *Buffer =
137       MemoryBuffer::getMemBuffer(ObjFile->getData(), "", false);
138
139   uint32_t magic = *((const uint32_t *)Buffer->getBufferStart());
140   bool is64 = (magic == MachO::MH_MAGIC_64);
141   assert((magic == MachO::MH_MAGIC_64 || magic == MachO::MH_MAGIC) &&
142          "Unrecognized Macho Magic");
143   return new MachOObjectImage(std::move(ObjFile), is64);
144 }
145
146 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText,
147                                  intptr_t DeltaForEH) {
148   DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
149                << ", Delta for EH: " << DeltaForEH << "\n");
150   uint32_t Length = *((uint32_t *)P);
151   P += 4;
152   unsigned char *Ret = P + Length;
153   uint32_t Offset = *((uint32_t *)P);
154   if (Offset == 0) // is a CIE
155     return Ret;
156
157   P += 4;
158   intptr_t FDELocation = *((intptr_t *)P);
159   intptr_t NewLocation = FDELocation - DeltaForText;
160   *((intptr_t *)P) = NewLocation;
161   P += sizeof(intptr_t);
162
163   // Skip the FDE address range
164   P += sizeof(intptr_t);
165
166   uint8_t Augmentationsize = *P;
167   P += 1;
168   if (Augmentationsize != 0) {
169     intptr_t LSDA = *((intptr_t *)P);
170     intptr_t NewLSDA = LSDA - DeltaForEH;
171     *((intptr_t *)P) = NewLSDA;
172   }
173
174   return Ret;
175 }
176
177 static intptr_t computeDelta(SectionEntry *A, SectionEntry *B) {
178   intptr_t ObjDistance = A->ObjAddress - B->ObjAddress;
179   intptr_t MemDistance = A->LoadAddress - B->LoadAddress;
180   return ObjDistance - MemDistance;
181 }
182
183 void RuntimeDyldMachO::registerEHFrames() {
184
185   if (!MemMgr)
186     return;
187   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
188     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
189     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
190         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
191       continue;
192     SectionEntry *Text = &Sections[SectionInfo.TextSID];
193     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
194     SectionEntry *ExceptTab = nullptr;
195     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
196       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
197
198     intptr_t DeltaForText = computeDelta(Text, EHFrame);
199     intptr_t DeltaForEH = 0;
200     if (ExceptTab)
201       DeltaForEH = computeDelta(ExceptTab, EHFrame);
202
203     unsigned char *P = EHFrame->Address;
204     unsigned char *End = P + EHFrame->Size;
205     do {
206       P = processFDE(P, DeltaForText, DeltaForEH);
207     } while (P != End);
208
209     MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
210                              EHFrame->Size);
211   }
212   UnregisteredEHFrameSections.clear();
213 }
214
215 void RuntimeDyldMachO::finalizeLoad(ObjectImage &ObjImg,
216                                     ObjSectionToIDMap &SectionMap) {
217   unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
218   unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
219   unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
220   ObjSectionToIDMap::iterator i, e;
221   for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
222     const SectionRef &Section = i->first;
223     StringRef Name;
224     Section.getName(Name);
225     if (Name == "__eh_frame")
226       EHFrameSID = i->second;
227     else if (Name == "__text")
228       TextSID = i->second;
229     else if (Name == "__gcc_except_tab")
230       ExceptTabSID = i->second;
231     else if (Name == "__jump_table")
232       populateJumpTable(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
233                         Section, i->second);
234     else if (Name == "__pointers")
235       populatePointersSection(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
236                               Section, i->second);
237   }
238   UnregisteredEHFrameSections.push_back(
239       EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
240 }
241
242 // The target location for the relocation is described by RE.SectionID and
243 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
244 // SectionEntry has three members describing its location.
245 // SectionEntry::Address is the address at which the section has been loaded
246 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
247 // address that the section will have in the target process.
248 // SectionEntry::ObjAddress is the address of the bits for this section in the
249 // original emitted object image (also in the current address space).
250 //
251 // Relocations will be applied as if the section were loaded at
252 // SectionEntry::LoadAddress, but they will be applied at an address based
253 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
254 // Target memory contents if they are required for value calculations.
255 //
256 // The Value parameter here is the load address of the symbol for the
257 // relocation to be applied.  For relocations which refer to symbols in the
258 // current object Value will be the LoadAddress of the section in which
259 // the symbol resides (RE.Addend provides additional information about the
260 // symbol location).  For external symbols, Value will be the address of the
261 // symbol in the target address space.
262 void RuntimeDyldMachO::resolveRelocation(const RelocationEntry &RE,
263                                          uint64_t Value) {
264   DEBUG (
265     const SectionEntry &Section = Sections[RE.SectionID];
266     uint8_t* LocalAddress = Section.Address + RE.Offset;
267     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
268
269     dbgs() << "resolveRelocation Section: " << RE.SectionID
270            << " LocalAddress: " << format("%p", LocalAddress)
271            << " FinalAddress: " << format("%p", FinalAddress)
272            << " Value: " << format("%p", Value)
273            << " Addend: " << RE.Addend
274            << " isPCRel: " << RE.IsPCRel
275            << " MachoType: " << RE.RelType
276            << " Size: " << (1 << RE.Size) << "\n";
277   );
278
279   // This just dispatches to the proper target specific routine.
280   switch (Arch) {
281   default:
282     llvm_unreachable("Unsupported CPU type!");
283   case Triple::x86_64:
284     resolveX86_64Relocation(RE, Value);
285     break;
286   case Triple::x86:
287     resolveI386Relocation(RE, Value);
288     break;
289   case Triple::arm: // Fall through.
290   case Triple::thumb:
291     resolveARMRelocation(RE, Value);
292     break;
293   case Triple::aarch64:
294   case Triple::arm64:
295     resolveAArch64Relocation(RE, Value);
296     break;
297   }
298 }
299
300 bool RuntimeDyldMachO::resolveI386Relocation(const RelocationEntry &RE,
301                                              uint64_t Value) {
302   const SectionEntry &Section = Sections[RE.SectionID];
303   uint8_t* LocalAddress = Section.Address + RE.Offset;
304
305   if (RE.IsPCRel) {
306     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
307     Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
308   }
309
310   switch (RE.RelType) {
311     default:
312       llvm_unreachable("Invalid relocation type!");
313     case MachO::GENERIC_RELOC_VANILLA:
314       return applyRelocationValue(LocalAddress, Value + RE.Addend,
315                                   1 << RE.Size);
316     case MachO::GENERIC_RELOC_SECTDIFF:
317     case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
318       uint64_t SectionABase = Sections[RE.Sections.SectionA].LoadAddress;
319       uint64_t SectionBBase = Sections[RE.Sections.SectionB].LoadAddress;
320       assert((Value == SectionABase || Value == SectionBBase) &&
321              "Unexpected SECTDIFF relocation value.");
322       Value = SectionABase - SectionBBase + RE.Addend;
323       return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
324     }
325     case MachO::GENERIC_RELOC_PB_LA_PTR:
326       return Error("Relocation type not implemented yet!");
327   }
328 }
329
330 bool RuntimeDyldMachO::resolveX86_64Relocation(const RelocationEntry &RE,
331                                                uint64_t Value) {
332   const SectionEntry &Section = Sections[RE.SectionID];
333   uint8_t* LocalAddress = Section.Address + RE.Offset;
334
335   // If the relocation is PC-relative, the value to be encoded is the
336   // pointer difference.
337   if (RE.IsPCRel) {
338     // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
339     // address. Is that expected? Only for branches, perhaps?
340     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
341     Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
342   }
343
344   switch (RE.RelType) {
345   default:
346     llvm_unreachable("Invalid relocation type!");
347   case MachO::X86_64_RELOC_SIGNED_1:
348   case MachO::X86_64_RELOC_SIGNED_2:
349   case MachO::X86_64_RELOC_SIGNED_4:
350   case MachO::X86_64_RELOC_SIGNED:
351   case MachO::X86_64_RELOC_UNSIGNED:
352   case MachO::X86_64_RELOC_BRANCH:
353     return applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
354   case MachO::X86_64_RELOC_GOT_LOAD:
355   case MachO::X86_64_RELOC_GOT:
356   case MachO::X86_64_RELOC_SUBTRACTOR:
357   case MachO::X86_64_RELOC_TLV:
358     return Error("Relocation type not implemented yet!");
359   }
360 }
361
362 bool RuntimeDyldMachO::resolveARMRelocation(const RelocationEntry &RE,
363                                             uint64_t Value) {
364   const SectionEntry &Section = Sections[RE.SectionID];
365   uint8_t* LocalAddress = Section.Address + RE.Offset;
366
367   // If the relocation is PC-relative, the value to be encoded is the
368   // pointer difference.
369   if (RE.IsPCRel) {
370     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
371     Value -= FinalAddress;
372     // ARM PCRel relocations have an effective-PC offset of two instructions
373     // (four bytes in Thumb mode, 8 bytes in ARM mode).
374     // FIXME: For now, assume ARM mode.
375     Value -= 8;
376   }
377
378   switch (RE.RelType) {
379   default:
380     llvm_unreachable("Invalid relocation type!");
381   case MachO::ARM_RELOC_VANILLA:
382     return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
383   case MachO::ARM_RELOC_BR24: {
384     // Mask the value into the target address. We know instructions are
385     // 32-bit aligned, so we can do it all at once.
386     uint32_t *p = (uint32_t *)LocalAddress;
387     // The low two bits of the value are not encoded.
388     Value >>= 2;
389     // Mask the value to 24 bits.
390     uint64_t FinalValue = Value & 0xffffff;
391     // Check for overflow.
392     if (Value != FinalValue)
393       return Error("ARM BR24 relocation out of range.");
394     // FIXME: If the destination is a Thumb function (and the instruction
395     // is a non-predicated BL instruction), we need to change it to a BLX
396     // instruction instead.
397
398     // Insert the value into the instruction.
399     *p = (*p & ~0xffffff) | FinalValue;
400     break;
401   }
402   case MachO::ARM_THUMB_RELOC_BR22:
403   case MachO::ARM_THUMB_32BIT_BRANCH:
404   case MachO::ARM_RELOC_HALF:
405   case MachO::ARM_RELOC_HALF_SECTDIFF:
406   case MachO::ARM_RELOC_PAIR:
407   case MachO::ARM_RELOC_SECTDIFF:
408   case MachO::ARM_RELOC_LOCAL_SECTDIFF:
409   case MachO::ARM_RELOC_PB_LA_PTR:
410     return Error("Relocation type not implemented yet!");
411   }
412   return false;
413 }
414
415 bool RuntimeDyldMachO::resolveAArch64Relocation(const RelocationEntry &RE,
416                                                 uint64_t Value) {
417   const SectionEntry &Section = Sections[RE.SectionID];
418   uint8_t* LocalAddress = Section.Address + RE.Offset;
419
420   switch (RE.RelType) {
421   default:
422     llvm_unreachable("Invalid relocation type!");
423   case MachO::ARM64_RELOC_UNSIGNED: {
424     assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_UNSIGNED not supported");
425     // Mask in the target value a byte at a time (we don't have an alignment
426     // guarantee for the target address, so this is safest).
427     if (RE.Size < 2)
428       llvm_unreachable("Invalid size for ARM64_RELOC_UNSIGNED");
429
430     applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
431     break;
432   }
433   case MachO::ARM64_RELOC_BRANCH26: {
434     assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_BRANCH26 not supported");
435     // Mask the value into the target address. We know instructions are
436     // 32-bit aligned, so we can do it all at once.
437     uint32_t *p = (uint32_t*)LocalAddress;
438     // Check if the addend is encoded in the instruction.
439     uint32_t EncodedAddend = *p & 0x03FFFFFF;
440     if (EncodedAddend != 0 ) {
441       if (RE.Addend == 0)
442         llvm_unreachable("branch26 instruction has embedded addend.");
443       else
444         llvm_unreachable("branch26 instruction has embedded addend and" \
445                          "ARM64_RELOC_ADDEND.");
446     }
447     // Check if branch is in range.
448     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
449     uint64_t PCRelVal = Value - FinalAddress + RE.Addend;
450     assert(isInt<26>(PCRelVal) && "Branch target out of range!");
451     // Insert the value into the instruction.
452     *p = (*p & 0xFC000000) | ((uint32_t)(PCRelVal >> 2) & 0x03FFFFFF);
453     break;
454   }
455   case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
456   case MachO::ARM64_RELOC_PAGE21: {
457     assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_PAGE21 not supported");
458     // Mask the value into the target address. We know instructions are
459     // 32-bit aligned, so we can do it all at once.
460     uint32_t *p = (uint32_t*)LocalAddress;
461     // Check if the addend is encoded in the instruction.
462     uint32_t EncodedAddend = ((*p & 0x60000000) >> 29) |
463                              ((*p & 0x01FFFFE0) >> 3);
464     if (EncodedAddend != 0) {
465       if (RE.Addend == 0)
466         llvm_unreachable("adrp instruction has embedded addend.");
467       else
468         llvm_unreachable("adrp instruction has embedded addend and" \
469                          "ARM64_RELOC_ADDEND.");
470     }
471     // Adjust for PC-relative relocation and offset.
472     uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
473     uint64_t PCRelVal = ((Value + RE.Addend) & (-4096)) -
474                          (FinalAddress & (-4096));
475     // Check that the value fits into 21 bits (+ 12 lower bits).
476     assert(isInt<33>(PCRelVal) && "Invalid page reloc value!");
477     // Insert the value into the instruction.
478     uint32_t ImmLoValue = (uint32_t)(PCRelVal << 17) & 0x60000000;
479     uint32_t ImmHiValue = (uint32_t)(PCRelVal >>  9) & 0x00FFFFE0;
480     *p = (*p & 0x9F00001F) | ImmHiValue | ImmLoValue;
481     break;
482   }
483   case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
484   case MachO::ARM64_RELOC_PAGEOFF12: {
485     assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_PAGEOFF21 not supported");
486     // Mask the value into the target address. We know instructions are
487     // 32-bit aligned, so we can do it all at once.
488     uint32_t *p = (uint32_t*)LocalAddress;
489     // Check if the addend is encoded in the instruction.
490     uint32_t EncodedAddend = *p & 0x003FFC00;
491     if (EncodedAddend != 0) {
492       if (RE.Addend == 0)
493         llvm_unreachable("adrp instruction has embedded addend.");
494       else
495         llvm_unreachable("adrp instruction has embedded addend and" \
496                          "ARM64_RELOC_ADDEND.");
497     }
498     // Add the offset from the symbol.
499     Value += RE.Addend;
500     // Mask out the page address and only use the lower 12 bits.
501     Value &= 0xFFF;
502     // Check which instruction we are updating to obtain the implicit shift
503     // factor from LDR/STR instructions.
504     if (*p & 0x08000000) {
505       uint32_t ImplicitShift = ((*p >> 30) & 0x3);
506       switch (ImplicitShift) {
507       case 0:
508         // Check if this a vector op.
509         if ((*p & 0x04800000) == 0x04800000) {
510           ImplicitShift = 4;
511           assert(((Value & 0xF) == 0) &&
512                  "128-bit LDR/STR not 16-byte aligned.");
513         }
514         break;
515       case 1:
516         assert(((Value & 0x1) == 0) && "16-bit LDR/STR not 2-byte aligned.");
517       case 2:
518         assert(((Value & 0x3) == 0) && "32-bit LDR/STR not 4-byte aligned.");
519       case 3:
520         assert(((Value & 0x7) == 0) && "64-bit LDR/STR not 8-byte aligned.");
521       }
522       // Compensate for implicit shift.
523       Value >>= ImplicitShift;
524     }
525     // Insert the value into the instruction.
526     *p = (*p & 0xFFC003FF) | ((uint32_t)(Value << 10) & 0x003FFC00);
527     break;
528   }
529   case MachO::ARM64_RELOC_SUBTRACTOR:
530   case MachO::ARM64_RELOC_POINTER_TO_GOT:
531   case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
532   case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
533     llvm_unreachable("Relocation type not implemented yet!");
534     return Error("Relocation type not implemented yet!");
535   case MachO::ARM64_RELOC_ADDEND:
536     llvm_unreachable("ARM64_RELOC_ADDEND should have been handeled by " \
537                      "processRelocationRef!");
538   }
539   return false;
540 }
541
542 void RuntimeDyldMachO::populateJumpTable(MachOObjectFile &Obj,
543                                          const SectionRef &JTSection,
544                                          unsigned JTSectionID) {
545   assert(!Obj.is64Bit() &&
546          "__jump_table section not supported in 64-bit MachO.");
547
548   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
549   MachO::section Sec32 = Obj.getSection(JTSection.getRawDataRefImpl());
550   uint32_t JTSectionSize = Sec32.size;
551   unsigned FirstIndirectSymbol = Sec32.reserved1;
552   unsigned JTEntrySize = Sec32.reserved2;
553   unsigned NumJTEntries = JTSectionSize / JTEntrySize;
554   uint8_t* JTSectionAddr = getSectionAddress(JTSectionID);
555   unsigned JTEntryOffset = 0;
556
557   assert((JTSectionSize % JTEntrySize) == 0 &&
558          "Jump-table section does not contain a whole number of stubs?");
559
560   for (unsigned i = 0; i < NumJTEntries; ++i) {
561     unsigned SymbolIndex =
562       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
563     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
564     StringRef IndirectSymbolName;
565     SI->getName(IndirectSymbolName);
566     uint8_t* JTEntryAddr = JTSectionAddr + JTEntryOffset;
567     createStubFunction(JTEntryAddr);
568     RelocationEntry RE(JTSectionID, JTEntryOffset + 1,
569                        MachO::GENERIC_RELOC_VANILLA, 0, true, 2);
570     addRelocationForSymbol(RE, IndirectSymbolName);
571     JTEntryOffset += JTEntrySize;
572   }
573 }
574
575 void RuntimeDyldMachO::populatePointersSection(MachOObjectFile &Obj,
576                                                const SectionRef &PTSection,
577                                                unsigned PTSectionID) {
578   assert(!Obj.is64Bit() &&
579          "__pointers section not supported in 64-bit MachO.");
580
581   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
582   MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
583   uint32_t PTSectionSize = Sec32.size;
584   unsigned FirstIndirectSymbol = Sec32.reserved1;
585   const unsigned PTEntrySize = 4;
586   unsigned NumPTEntries = PTSectionSize / PTEntrySize;
587   unsigned PTEntryOffset = 0;
588
589   assert((PTSectionSize % PTEntrySize) == 0 &&
590          "Pointers section does not contain a whole number of stubs?");
591
592   DEBUG(dbgs() << "Populating __pointers, Section ID " << PTSectionID
593                << ", " << NumPTEntries << " entries, "
594                << PTEntrySize << " bytes each:\n");
595
596   for (unsigned i = 0; i < NumPTEntries; ++i) {
597     unsigned SymbolIndex =
598       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
599     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
600     StringRef IndirectSymbolName;
601     SI->getName(IndirectSymbolName);
602     DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
603           << ", PT offset: " << PTEntryOffset << "\n");
604     RelocationEntry RE(PTSectionID, PTEntryOffset,
605                        MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
606     addRelocationForSymbol(RE, IndirectSymbolName);
607     PTEntryOffset += PTEntrySize;
608   }
609 }
610
611
612 section_iterator getSectionByAddress(const MachOObjectFile &Obj,
613                                      uint64_t Addr) {
614   section_iterator SI = Obj.section_begin();
615   section_iterator SE = Obj.section_end();
616
617   for (; SI != SE; ++SI) {
618     uint64_t SAddr, SSize;
619     SI->getAddress(SAddr);
620     SI->getSize(SSize);
621     if ((Addr >= SAddr) && (Addr < SAddr + SSize))
622       return SI;
623   }
624
625   return SE;
626 }
627
628 relocation_iterator RuntimeDyldMachO::processSECTDIFFRelocation(
629                                             unsigned SectionID,
630                                             relocation_iterator RelI,
631                                             ObjectImage &Obj,
632                                             ObjSectionToIDMap &ObjSectionToID) {
633   const MachOObjectFile *MachO =
634     static_cast<const MachOObjectFile*>(Obj.getObjectFile());
635   MachO::any_relocation_info RE =
636     MachO->getRelocation(RelI->getRawDataRefImpl());
637
638   SectionEntry &Section = Sections[SectionID];
639   uint32_t RelocType = MachO->getAnyRelocationType(RE);
640   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
641   unsigned Size = MachO->getAnyRelocationLength(RE);
642   uint64_t Offset;
643   RelI->getOffset(Offset);
644   uint8_t *LocalAddress = Section.Address + Offset;
645   unsigned NumBytes = 1 << Size;
646   int64_t Addend = 0;
647   memcpy(&Addend, LocalAddress, NumBytes);
648
649   ++RelI;
650   MachO::any_relocation_info RE2 =
651     MachO->getRelocation(RelI->getRawDataRefImpl());
652
653   uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
654   section_iterator SAI = getSectionByAddress(*MachO, AddrA);
655   assert(SAI != MachO->section_end() && "Can't find section for address A");
656   uint64_t SectionABase;
657   SAI->getAddress(SectionABase);
658   uint64_t SectionAOffset = AddrA - SectionABase;
659   SectionRef SectionA = *SAI;
660   bool IsCode;
661   SectionA.isText(IsCode);
662   uint32_t SectionAID = findOrEmitSection(Obj, SectionA, IsCode,
663                                           ObjSectionToID);
664
665   uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
666   section_iterator SBI = getSectionByAddress(*MachO, AddrB);
667   assert(SBI != MachO->section_end() && "Can't find section for address B");
668   uint64_t SectionBBase;
669   SBI->getAddress(SectionBBase);
670   uint64_t SectionBOffset = AddrB - SectionBBase;
671   SectionRef SectionB = *SBI;
672   uint32_t SectionBID = findOrEmitSection(Obj, SectionB, IsCode,
673                                           ObjSectionToID);
674
675   if (Addend != AddrA - AddrB)
676     Error("Unexpected SECTDIFF relocation addend.");
677
678   DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
679                << ", Addend: " << Addend << ", SectionA ID: "
680                << SectionAID << ", SectionAOffset: " << SectionAOffset
681                << ", SectionB ID: " << SectionBID << ", SectionBOffset: "
682                << SectionBOffset << "\n");
683   RelocationEntry R(SectionID, Offset, RelocType, 0,
684                     SectionAID, SectionAOffset, SectionBID, SectionBOffset,
685                     IsPCRel, Size);
686
687   addRelocationForSection(R, SectionAID);
688   addRelocationForSection(R, SectionBID);
689
690   return ++RelI;
691 }
692
693 relocation_iterator RuntimeDyldMachO::processI386ScatteredVANILLA(
694                                             unsigned SectionID,
695                                             relocation_iterator RelI,
696                                             ObjectImage &Obj,
697                                             ObjSectionToIDMap &ObjSectionToID) {
698   const MachOObjectFile *MachO =
699     static_cast<const MachOObjectFile*>(Obj.getObjectFile());
700   MachO::any_relocation_info RE =
701     MachO->getRelocation(RelI->getRawDataRefImpl());
702
703   SectionEntry &Section = Sections[SectionID];
704   uint32_t RelocType = MachO->getAnyRelocationType(RE);
705   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
706   unsigned Size = MachO->getAnyRelocationLength(RE);
707   uint64_t Offset;
708   RelI->getOffset(Offset);
709   uint8_t *LocalAddress = Section.Address + Offset;
710   unsigned NumBytes = 1 << Size;
711   int64_t Addend = 0;
712   memcpy(&Addend, LocalAddress, NumBytes);
713
714   unsigned SymbolBaseAddr = MachO->getScatteredRelocationValue(RE);
715   section_iterator TargetSI = getSectionByAddress(*MachO, SymbolBaseAddr);
716   assert(TargetSI != MachO->section_end() && "Can't find section for symbol");
717   uint64_t SectionBaseAddr;
718   TargetSI->getAddress(SectionBaseAddr);
719   SectionRef TargetSection = *TargetSI;
720   bool IsCode;
721   TargetSection.isText(IsCode);
722   uint32_t TargetSectionID = findOrEmitSection(Obj, TargetSection, IsCode,
723                                                ObjSectionToID);
724
725   Addend -= SectionBaseAddr;
726   RelocationEntry R(SectionID, Offset, RelocType, Addend,
727                     IsPCRel, Size);
728
729   addRelocationForSection(R, TargetSectionID);
730
731   return ++RelI;
732 }
733
734 relocation_iterator RuntimeDyldMachO::processRelocationRef(
735     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
736     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
737     StubMap &Stubs) {
738   const ObjectFile *OF = Obj.getObjectFile();
739   const MachOObjectImage &MachOObj = *static_cast<MachOObjectImage *>(&Obj);
740   const MachOObjectFile *MachO = static_cast<const MachOObjectFile *>(OF);
741   MachO::any_relocation_info RE =
742       MachO->getRelocation(RelI->getRawDataRefImpl());
743   int64_t RelocAddendValue = 0;
744   bool HasRelocAddendValue = false;
745
746   uint32_t RelType = MachO->getAnyRelocationType(RE);
747   if (Arch == Triple::arm64) {
748     // ARM64_RELOC_ADDEND provides the offset (addend) that will be used by the
749     // next relocation entry. Save the value and advance to the next relocation
750     // entry.
751     if (RelType == MachO::ARM64_RELOC_ADDEND) {
752       assert(!MachO->getPlainRelocationExternal(RE));
753       assert(!MachO->getAnyRelocationPCRel(RE));
754       assert(MachO->getAnyRelocationLength(RE) == 2);
755       uint64_t RawAddend = MachO->getPlainRelocationSymbolNum(RE);
756       // Sign-extend the 24-bit to 64-bit.
757       RelocAddendValue = RawAddend << 40;
758       RelocAddendValue >>= 40;
759       HasRelocAddendValue = true;
760
761       // Get the next entry.
762       RE = MachO->getRelocation((++RelI)->getRawDataRefImpl());
763       RelType = MachO->getAnyRelocationType(RE);
764       assert(RelType == MachO::ARM64_RELOC_BRANCH26 ||
765              RelType == MachO::ARM64_RELOC_PAGE21 ||
766              RelType == MachO::ARM64_RELOC_PAGEOFF12);
767
768     } else if (RelType == MachO::ARM64_RELOC_BRANCH26 ||
769                RelType == MachO::ARM64_RELOC_PAGE21 ||
770                RelType == MachO::ARM64_RELOC_PAGEOFF12 ||
771                RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
772                RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12) {
773       RelocAddendValue = 0;
774       HasRelocAddendValue = true;
775     }
776   }
777
778   // FIXME: Properly handle scattered relocations.
779   //        Special case the couple of scattered relocations that we know how
780   //        to handle: SECTDIFF relocations, and scattered VANILLA relocations
781   //        on I386.
782   //        For all other scattered relocations, just bail out and hope for the
783   //        best, since the offsets computed by scattered relocations have often
784   //        been optimisticaly filled in by the compiler. This will fail
785   //        horribly where the relocations *do* need to be applied, but that was
786   //        already the case.
787   if (MachO->isRelocationScattered(RE)) {
788     if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
789         RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
790       return processSECTDIFFRelocation(SectionID, RelI, Obj, ObjSectionToID);
791     else if (Arch == Triple::x86 && RelType == MachO::GENERIC_RELOC_VANILLA)
792       return processI386ScatteredVANILLA(SectionID, RelI, Obj, ObjSectionToID);
793     else
794       return ++RelI;
795   }
796
797   RelocationValueRef Value;
798   SectionEntry &Section = Sections[SectionID];
799
800   bool IsExtern = MachO->getPlainRelocationExternal(RE);
801   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
802   unsigned Size = MachO->getAnyRelocationLength(RE);
803   uint64_t Offset;
804   RelI->getOffset(Offset);
805   uint8_t *LocalAddress = Section.Address + Offset;
806   unsigned NumBytes = 1 << Size;
807   int64_t Addend = 0;
808   if (HasRelocAddendValue)
809     Addend = RelocAddendValue;
810   else
811     memcpy(&Addend, LocalAddress, NumBytes);
812
813   if (IsExtern) {
814     // Obtain the symbol name which is referenced in the relocation
815     symbol_iterator Symbol = RelI->getSymbol();
816     StringRef TargetName;
817     Symbol->getName(TargetName);
818     // First search for the symbol in the local symbol table
819     SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
820     if (lsi != Symbols.end()) {
821       Value.SectionID = lsi->second.first;
822       Value.Addend = lsi->second.second + Addend;
823     } else {
824       // Search for the symbol in the global symbol table
825       SymbolTableMap::const_iterator gsi =
826           GlobalSymbolTable.find(TargetName.data());
827       if (gsi != GlobalSymbolTable.end()) {
828         Value.SectionID = gsi->second.first;
829         Value.Addend = gsi->second.second + Addend;
830       } else {
831         Value.SymbolName = TargetName.data();
832         Value.Addend = Addend;
833       }
834     }
835
836     // Addends for external, PC-rel relocations on i386 point back to the zero
837     // offset. Calculate the final offset from the relocation target instead.
838     // This allows us to use the same logic for both external and internal
839     // relocations in resolveI386RelocationRef.
840     if (Arch == Triple::x86 && IsPCRel) {
841       uint64_t RelocAddr = 0;
842       RelI->getAddress(RelocAddr);
843       Value.Addend += RelocAddr + 4;
844     }
845
846   } else {
847     SectionRef Sec = MachO->getRelocationSection(RE);
848     bool IsCode = false;
849     Sec.isText(IsCode);
850     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
851     uint64_t Addr = MachOObj.getOldSectionAddr(Sec);
852     DEBUG(dbgs() << "\nAddr: " << Addr << "\nAddend: " << Addend);
853     Value.Addend = Addend - Addr;
854     if (IsPCRel)
855       Value.Addend += Offset + NumBytes;
856   }
857
858   if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
859                                  RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
860     assert(IsPCRel);
861     assert(Size == 2);
862
863     // FIXME: Teach the generic code above not to prematurely conflate
864     //        relocation addends and symbol offsets.
865     Value.Addend -= Addend;
866     StubMap::const_iterator i = Stubs.find(Value);
867     uint8_t *Addr;
868     if (i != Stubs.end()) {
869       Addr = Section.Address + i->second;
870     } else {
871       Stubs[Value] = Section.StubOffset;
872       uint8_t *GOTEntry = Section.Address + Section.StubOffset;
873       RelocationEntry GOTRE(SectionID, Section.StubOffset,
874                             MachO::X86_64_RELOC_UNSIGNED, Value.Addend, false,
875                             3);
876       if (Value.SymbolName)
877         addRelocationForSymbol(GOTRE, Value.SymbolName);
878       else
879         addRelocationForSection(GOTRE, Value.SectionID);
880       Section.StubOffset += 8;
881       Addr = GOTEntry;
882     }
883     RelocationEntry TargetRE(SectionID, Offset,
884                              MachO::X86_64_RELOC_UNSIGNED, Addend, true,
885                              2);
886     resolveRelocation(TargetRE, (uint64_t)Addr);
887   } else if (Arch == Triple::arm && (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
888     // This is an ARM branch relocation, need to use a stub function.
889
890     //  Look up for existing stub.
891     StubMap::const_iterator i = Stubs.find(Value);
892     uint8_t *Addr;
893     if (i != Stubs.end()) {
894       Addr = Section.Address + i->second;
895     } else {
896       // Create a new stub function.
897       Stubs[Value] = Section.StubOffset;
898       uint8_t *StubTargetAddr =
899           createStubFunction(Section.Address + Section.StubOffset);
900       RelocationEntry StubRE(SectionID, StubTargetAddr - Section.Address,
901                              MachO::GENERIC_RELOC_VANILLA, Value.Addend);
902       if (Value.SymbolName)
903         addRelocationForSymbol(StubRE, Value.SymbolName);
904       else
905         addRelocationForSection(StubRE, Value.SectionID);
906       Addr = Section.Address + Section.StubOffset;
907       Section.StubOffset += getMaxStubSize();
908     }
909     RelocationEntry TargetRE(Value.SectionID, Offset, RelType, 0, IsPCRel,
910                              Size);
911     resolveRelocation(TargetRE, (uint64_t)Addr);
912   } else if (Arch == Triple::arm64 &&
913              (RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
914               RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12)) {
915     assert(Size == 2);
916     StubMap::const_iterator i = Stubs.find(Value);
917     uint8_t *Addr;
918     if (i != Stubs.end())
919       Addr = Section.Address + i->second;
920     else {
921       // FIXME: There must be a better way to do this then to check and fix the
922       // alignment every time!!!
923       uintptr_t BaseAddress = uintptr_t(Section.Address);
924       uintptr_t StubAlignment = getStubAlignment();
925       uintptr_t StubAddress
926         = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
927           -StubAlignment;
928       unsigned StubOffset = StubAddress - BaseAddress;
929       Stubs[Value] = StubOffset;
930       assert(((StubAddress % getStubAlignment()) == 0) &&
931              "GOT entry not aligned");
932       RelocationEntry GOTRE(SectionID, StubOffset, MachO::ARM64_RELOC_UNSIGNED,
933                             Value.Addend, /*IsPCRel=*/false, /*Size=*/3);
934       if (Value.SymbolName)
935         addRelocationForSymbol(GOTRE, Value.SymbolName);
936       else
937         addRelocationForSection(GOTRE, Value.SectionID);
938       Section.StubOffset = StubOffset + getMaxStubSize();
939
940       Addr = (uint8_t *)StubAddress;
941     }
942     RelocationEntry TargetRE(SectionID, Offset, RelType, /*Addend=*/0, IsPCRel,
943                              Size);
944     resolveRelocation(TargetRE, (uint64_t)Addr);
945   } else {
946
947     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, IsPCRel, Size);
948     if (Value.SymbolName)
949       addRelocationForSymbol(RE, Value.SymbolName);
950     else
951       addRelocationForSection(RE, Value.SectionID);
952   }
953   return ++RelI;
954 }
955
956 bool
957 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
958   if (InputBuffer->getBufferSize() < 4)
959     return false;
960   StringRef Magic(InputBuffer->getBufferStart(), 4);
961   if (Magic == "\xFE\xED\xFA\xCE")
962     return true;
963   if (Magic == "\xCE\xFA\xED\xFE")
964     return true;
965   if (Magic == "\xFE\xED\xFA\xCF")
966     return true;
967   if (Magic == "\xCF\xFA\xED\xFE")
968     return true;
969   return false;
970 }
971
972 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
973   return Obj->isMachO();
974 }
975
976 } // end namespace llvm