xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implementation of ELF support for the MC-JIT runtime dynamic linker.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RuntimeDyldELF.h"
14 #include "RuntimeDyldCheckerImpl.h"
15 #include "Targets/RuntimeDyldELFMips.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/BinaryFormat/ELF.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace llvm::support::endian;
28 
29 #define DEBUG_TYPE "dyld"
30 
or32le(void * P,int32_t V)31 static void or32le(void *P, int32_t V) { write32le(P, read32le(P) | V); }
32 
or32AArch64Imm(void * L,uint64_t Imm)33 static void or32AArch64Imm(void *L, uint64_t Imm) {
34   or32le(L, (Imm & 0xFFF) << 10);
35 }
36 
write(bool isBE,void * P,T V)37 template <class T> static void write(bool isBE, void *P, T V) {
38   isBE ? write<T, support::big>(P, V) : write<T, support::little>(P, V);
39 }
40 
write32AArch64Addr(void * L,uint64_t Imm)41 static void write32AArch64Addr(void *L, uint64_t Imm) {
42   uint32_t ImmLo = (Imm & 0x3) << 29;
43   uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
44   uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
45   write32le(L, (read32le(L) & ~Mask) | ImmLo | ImmHi);
46 }
47 
48 // Return the bits [Start, End] from Val shifted Start bits.
49 // For instance, getBits(0xF0, 4, 8) returns 0xF.
getBits(uint64_t Val,int Start,int End)50 static uint64_t getBits(uint64_t Val, int Start, int End) {
51   uint64_t Mask = ((uint64_t)1 << (End + 1 - Start)) - 1;
52   return (Val >> Start) & Mask;
53 }
54 
55 namespace {
56 
57 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
58   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
59 
60   typedef typename ELFT::uint addr_type;
61 
62   DyldELFObject(ELFObjectFile<ELFT> &&Obj);
63 
64 public:
65   static Expected<std::unique_ptr<DyldELFObject>>
66   create(MemoryBufferRef Wrapper);
67 
68   void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
69 
70   void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
71 
72   // Methods for type inquiry through isa, cast and dyn_cast
classof(const Binary * v)73   static bool classof(const Binary *v) {
74     return (isa<ELFObjectFile<ELFT>>(v) &&
75             classof(cast<ELFObjectFile<ELFT>>(v)));
76   }
classof(const ELFObjectFile<ELFT> * v)77   static bool classof(const ELFObjectFile<ELFT> *v) {
78     return v->isDyldType();
79   }
80 };
81 
82 
83 
84 // The MemoryBuffer passed into this constructor is just a wrapper around the
85 // actual memory.  Ultimately, the Binary parent class will take ownership of
86 // this MemoryBuffer object but not the underlying memory.
87 template <class ELFT>
DyldELFObject(ELFObjectFile<ELFT> && Obj)88 DyldELFObject<ELFT>::DyldELFObject(ELFObjectFile<ELFT> &&Obj)
89     : ELFObjectFile<ELFT>(std::move(Obj)) {
90   this->isDyldELFObject = true;
91 }
92 
93 template <class ELFT>
94 Expected<std::unique_ptr<DyldELFObject<ELFT>>>
create(MemoryBufferRef Wrapper)95 DyldELFObject<ELFT>::create(MemoryBufferRef Wrapper) {
96   auto Obj = ELFObjectFile<ELFT>::create(Wrapper);
97   if (auto E = Obj.takeError())
98     return std::move(E);
99   std::unique_ptr<DyldELFObject<ELFT>> Ret(
100       new DyldELFObject<ELFT>(std::move(*Obj)));
101   return std::move(Ret);
102 }
103 
104 template <class ELFT>
updateSectionAddress(const SectionRef & Sec,uint64_t Addr)105 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
106                                                uint64_t Addr) {
107   DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
108   Elf_Shdr *shdr =
109       const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
110 
111   // This assumes the address passed in matches the target address bitness
112   // The template-based type cast handles everything else.
113   shdr->sh_addr = static_cast<addr_type>(Addr);
114 }
115 
116 template <class ELFT>
updateSymbolAddress(const SymbolRef & SymRef,uint64_t Addr)117 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
118                                               uint64_t Addr) {
119 
120   Elf_Sym *sym = const_cast<Elf_Sym *>(
121       ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
122 
123   // This assumes the address passed in matches the target address bitness
124   // The template-based type cast handles everything else.
125   sym->st_value = static_cast<addr_type>(Addr);
126 }
127 
128 class LoadedELFObjectInfo final
129     : public LoadedObjectInfoHelper<LoadedELFObjectInfo,
130                                     RuntimeDyld::LoadedObjectInfo> {
131 public:
LoadedELFObjectInfo(RuntimeDyldImpl & RTDyld,ObjSectionToIDMap ObjSecToIDMap)132   LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
133       : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
134 
135   OwningBinary<ObjectFile>
136   getObjectForDebug(const ObjectFile &Obj) const override;
137 };
138 
139 template <typename ELFT>
140 static Expected<std::unique_ptr<DyldELFObject<ELFT>>>
createRTDyldELFObject(MemoryBufferRef Buffer,const ObjectFile & SourceObject,const LoadedELFObjectInfo & L)141 createRTDyldELFObject(MemoryBufferRef Buffer, const ObjectFile &SourceObject,
142                       const LoadedELFObjectInfo &L) {
143   typedef typename ELFT::Shdr Elf_Shdr;
144   typedef typename ELFT::uint addr_type;
145 
146   Expected<std::unique_ptr<DyldELFObject<ELFT>>> ObjOrErr =
147       DyldELFObject<ELFT>::create(Buffer);
148   if (Error E = ObjOrErr.takeError())
149     return std::move(E);
150 
151   std::unique_ptr<DyldELFObject<ELFT>> Obj = std::move(*ObjOrErr);
152 
153   // Iterate over all sections in the object.
154   auto SI = SourceObject.section_begin();
155   for (const auto &Sec : Obj->sections()) {
156     Expected<StringRef> NameOrErr = Sec.getName();
157     if (!NameOrErr) {
158       consumeError(NameOrErr.takeError());
159       continue;
160     }
161 
162     if (*NameOrErr != "") {
163       DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
164       Elf_Shdr *shdr = const_cast<Elf_Shdr *>(
165           reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
166 
167       if (uint64_t SecLoadAddr = L.getSectionLoadAddress(*SI)) {
168         // This assumes that the address passed in matches the target address
169         // bitness. The template-based type cast handles everything else.
170         shdr->sh_addr = static_cast<addr_type>(SecLoadAddr);
171       }
172     }
173     ++SI;
174   }
175 
176   return std::move(Obj);
177 }
178 
179 static OwningBinary<ObjectFile>
createELFDebugObject(const ObjectFile & Obj,const LoadedELFObjectInfo & L)180 createELFDebugObject(const ObjectFile &Obj, const LoadedELFObjectInfo &L) {
181   assert(Obj.isELF() && "Not an ELF object file.");
182 
183   std::unique_ptr<MemoryBuffer> Buffer =
184     MemoryBuffer::getMemBufferCopy(Obj.getData(), Obj.getFileName());
185 
186   Expected<std::unique_ptr<ObjectFile>> DebugObj(nullptr);
187   handleAllErrors(DebugObj.takeError());
188   if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian())
189     DebugObj =
190         createRTDyldELFObject<ELF32LE>(Buffer->getMemBufferRef(), Obj, L);
191   else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian())
192     DebugObj =
193         createRTDyldELFObject<ELF32BE>(Buffer->getMemBufferRef(), Obj, L);
194   else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian())
195     DebugObj =
196         createRTDyldELFObject<ELF64BE>(Buffer->getMemBufferRef(), Obj, L);
197   else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian())
198     DebugObj =
199         createRTDyldELFObject<ELF64LE>(Buffer->getMemBufferRef(), Obj, L);
200   else
201     llvm_unreachable("Unexpected ELF format");
202 
203   handleAllErrors(DebugObj.takeError());
204   return OwningBinary<ObjectFile>(std::move(*DebugObj), std::move(Buffer));
205 }
206 
207 OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile & Obj) const208 LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
209   return createELFDebugObject(Obj, *this);
210 }
211 
212 } // anonymous namespace
213 
214 namespace llvm {
215 
RuntimeDyldELF(RuntimeDyld::MemoryManager & MemMgr,JITSymbolResolver & Resolver)216 RuntimeDyldELF::RuntimeDyldELF(RuntimeDyld::MemoryManager &MemMgr,
217                                JITSymbolResolver &Resolver)
218     : RuntimeDyldImpl(MemMgr, Resolver), GOTSectionID(0), CurrentGOTIndex(0) {}
~RuntimeDyldELF()219 RuntimeDyldELF::~RuntimeDyldELF() {}
220 
registerEHFrames()221 void RuntimeDyldELF::registerEHFrames() {
222   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
223     SID EHFrameSID = UnregisteredEHFrameSections[i];
224     uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();
225     uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();
226     size_t EHFrameSize = Sections[EHFrameSID].getSize();
227     MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
228   }
229   UnregisteredEHFrameSections.clear();
230 }
231 
232 std::unique_ptr<RuntimeDyldELF>
create(Triple::ArchType Arch,RuntimeDyld::MemoryManager & MemMgr,JITSymbolResolver & Resolver)233 llvm::RuntimeDyldELF::create(Triple::ArchType Arch,
234                              RuntimeDyld::MemoryManager &MemMgr,
235                              JITSymbolResolver &Resolver) {
236   switch (Arch) {
237   default:
238     return std::make_unique<RuntimeDyldELF>(MemMgr, Resolver);
239   case Triple::mips:
240   case Triple::mipsel:
241   case Triple::mips64:
242   case Triple::mips64el:
243     return std::make_unique<RuntimeDyldELFMips>(MemMgr, Resolver);
244   }
245 }
246 
247 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
loadObject(const object::ObjectFile & O)248 RuntimeDyldELF::loadObject(const object::ObjectFile &O) {
249   if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
250     return std::make_unique<LoadedELFObjectInfo>(*this, *ObjSectionToIDOrErr);
251   else {
252     HasError = true;
253     raw_string_ostream ErrStream(ErrorStr);
254     logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream);
255     return nullptr;
256   }
257 }
258 
resolveX86_64Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend,uint64_t SymOffset)259 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
260                                              uint64_t Offset, uint64_t Value,
261                                              uint32_t Type, int64_t Addend,
262                                              uint64_t SymOffset) {
263   switch (Type) {
264   default:
265     report_fatal_error("Relocation type not implemented yet!");
266     break;
267   case ELF::R_X86_64_NONE:
268     break;
269   case ELF::R_X86_64_8: {
270     Value += Addend;
271     assert((int64_t)Value <= INT8_MAX && (int64_t)Value >= INT8_MIN);
272     uint8_t TruncatedAddr = (Value & 0xFF);
273     *Section.getAddressWithOffset(Offset) = TruncatedAddr;
274     LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
275                       << format("%p\n", Section.getAddressWithOffset(Offset)));
276     break;
277   }
278   case ELF::R_X86_64_16: {
279     Value += Addend;
280     assert((int64_t)Value <= INT16_MAX && (int64_t)Value >= INT16_MIN);
281     uint16_t TruncatedAddr = (Value & 0xFFFF);
282     support::ulittle16_t::ref(Section.getAddressWithOffset(Offset)) =
283         TruncatedAddr;
284     LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
285                       << format("%p\n", Section.getAddressWithOffset(Offset)));
286     break;
287   }
288   case ELF::R_X86_64_64: {
289     support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
290         Value + Addend;
291     LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
292                       << format("%p\n", Section.getAddressWithOffset(Offset)));
293     break;
294   }
295   case ELF::R_X86_64_32:
296   case ELF::R_X86_64_32S: {
297     Value += Addend;
298     assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
299            (Type == ELF::R_X86_64_32S &&
300             ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
301     uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
302     support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
303         TruncatedAddr;
304     LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
305                       << format("%p\n", Section.getAddressWithOffset(Offset)));
306     break;
307   }
308   case ELF::R_X86_64_PC8: {
309     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
310     int64_t RealOffset = Value + Addend - FinalAddress;
311     assert(isInt<8>(RealOffset));
312     int8_t TruncOffset = (RealOffset & 0xFF);
313     Section.getAddress()[Offset] = TruncOffset;
314     break;
315   }
316   case ELF::R_X86_64_PC32: {
317     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
318     int64_t RealOffset = Value + Addend - FinalAddress;
319     assert(isInt<32>(RealOffset));
320     int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
321     support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
322         TruncOffset;
323     break;
324   }
325   case ELF::R_X86_64_PC64: {
326     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
327     int64_t RealOffset = Value + Addend - FinalAddress;
328     support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
329         RealOffset;
330     LLVM_DEBUG(dbgs() << "Writing " << format("%p", RealOffset) << " at "
331                       << format("%p\n", FinalAddress));
332     break;
333   }
334   case ELF::R_X86_64_GOTOFF64: {
335     // Compute Value - GOTBase.
336     uint64_t GOTBase = 0;
337     for (const auto &Section : Sections) {
338       if (Section.getName() == ".got") {
339         GOTBase = Section.getLoadAddressWithOffset(0);
340         break;
341       }
342     }
343     assert(GOTBase != 0 && "missing GOT");
344     int64_t GOTOffset = Value - GOTBase + Addend;
345     support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = GOTOffset;
346     break;
347   }
348   }
349 }
350 
resolveX86Relocation(const SectionEntry & Section,uint64_t Offset,uint32_t Value,uint32_t Type,int32_t Addend)351 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
352                                           uint64_t Offset, uint32_t Value,
353                                           uint32_t Type, int32_t Addend) {
354   switch (Type) {
355   case ELF::R_386_32: {
356     support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
357         Value + Addend;
358     break;
359   }
360   // Handle R_386_PLT32 like R_386_PC32 since it should be able to
361   // reach any 32 bit address.
362   case ELF::R_386_PLT32:
363   case ELF::R_386_PC32: {
364     uint32_t FinalAddress =
365         Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
366     uint32_t RealOffset = Value + Addend - FinalAddress;
367     support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
368         RealOffset;
369     break;
370   }
371   default:
372     // There are other relocation types, but it appears these are the
373     // only ones currently used by the LLVM ELF object writer
374     report_fatal_error("Relocation type not implemented yet!");
375     break;
376   }
377 }
378 
resolveAArch64Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)379 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
380                                               uint64_t Offset, uint64_t Value,
381                                               uint32_t Type, int64_t Addend) {
382   uint32_t *TargetPtr =
383       reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
384   uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
385   // Data should use target endian. Code should always use little endian.
386   bool isBE = Arch == Triple::aarch64_be;
387 
388   LLVM_DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
389                     << format("%llx", Section.getAddressWithOffset(Offset))
390                     << " FinalAddress: 0x" << format("%llx", FinalAddress)
391                     << " Value: 0x" << format("%llx", Value) << " Type: 0x"
392                     << format("%x", Type) << " Addend: 0x"
393                     << format("%llx", Addend) << "\n");
394 
395   switch (Type) {
396   default:
397     report_fatal_error("Relocation type not implemented yet!");
398     break;
399   case ELF::R_AARCH64_ABS16: {
400     uint64_t Result = Value + Addend;
401     assert(static_cast<int64_t>(Result) >= INT16_MIN && Result < UINT16_MAX);
402     write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
403     break;
404   }
405   case ELF::R_AARCH64_ABS32: {
406     uint64_t Result = Value + Addend;
407     assert(static_cast<int64_t>(Result) >= INT32_MIN && Result < UINT32_MAX);
408     write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
409     break;
410   }
411   case ELF::R_AARCH64_ABS64:
412     write(isBE, TargetPtr, Value + Addend);
413     break;
414   case ELF::R_AARCH64_PLT32: {
415     uint64_t Result = Value + Addend - FinalAddress;
416     assert(static_cast<int64_t>(Result) >= INT32_MIN &&
417            static_cast<int64_t>(Result) <= INT32_MAX);
418     write(isBE, TargetPtr, static_cast<uint32_t>(Result));
419     break;
420   }
421   case ELF::R_AARCH64_PREL32: {
422     uint64_t Result = Value + Addend - FinalAddress;
423     assert(static_cast<int64_t>(Result) >= INT32_MIN &&
424            static_cast<int64_t>(Result) <= UINT32_MAX);
425     write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
426     break;
427   }
428   case ELF::R_AARCH64_PREL64:
429     write(isBE, TargetPtr, Value + Addend - FinalAddress);
430     break;
431   case ELF::R_AARCH64_CONDBR19: {
432     uint64_t BranchImm = Value + Addend - FinalAddress;
433 
434     assert(isInt<21>(BranchImm));
435     *TargetPtr &= 0xff00001fU;
436     // Immediate:20:2 goes in bits 23:5 of Bcc, CBZ, CBNZ
437     or32le(TargetPtr, (BranchImm & 0x001FFFFC) << 3);
438     break;
439   }
440   case ELF::R_AARCH64_TSTBR14: {
441     uint64_t BranchImm = Value + Addend - FinalAddress;
442 
443     assert(isInt<16>(BranchImm));
444 
445     *TargetPtr &= 0xfff8001fU;
446     // Immediate:15:2 goes in bits 18:5 of TBZ, TBNZ
447     or32le(TargetPtr, (BranchImm & 0x0FFFFFFC) << 3);
448     break;
449   }
450   case ELF::R_AARCH64_CALL26: // fallthrough
451   case ELF::R_AARCH64_JUMP26: {
452     // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
453     // calculation.
454     uint64_t BranchImm = Value + Addend - FinalAddress;
455 
456     // "Check that -2^27 <= result < 2^27".
457     assert(isInt<28>(BranchImm));
458     or32le(TargetPtr, (BranchImm & 0x0FFFFFFC) >> 2);
459     break;
460   }
461   case ELF::R_AARCH64_MOVW_UABS_G3:
462     or32le(TargetPtr, ((Value + Addend) & 0xFFFF000000000000) >> 43);
463     break;
464   case ELF::R_AARCH64_MOVW_UABS_G2_NC:
465     or32le(TargetPtr, ((Value + Addend) & 0xFFFF00000000) >> 27);
466     break;
467   case ELF::R_AARCH64_MOVW_UABS_G1_NC:
468     or32le(TargetPtr, ((Value + Addend) & 0xFFFF0000) >> 11);
469     break;
470   case ELF::R_AARCH64_MOVW_UABS_G0_NC:
471     or32le(TargetPtr, ((Value + Addend) & 0xFFFF) << 5);
472     break;
473   case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
474     // Operation: Page(S+A) - Page(P)
475     uint64_t Result =
476         ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
477 
478     // Check that -2^32 <= X < 2^32
479     assert(isInt<33>(Result) && "overflow check failed for relocation");
480 
481     // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
482     // from bits 32:12 of X.
483     write32AArch64Addr(TargetPtr, Result >> 12);
484     break;
485   }
486   case ELF::R_AARCH64_ADD_ABS_LO12_NC:
487     // Operation: S + A
488     // Immediate goes in bits 21:10 of LD/ST instruction, taken
489     // from bits 11:0 of X
490     or32AArch64Imm(TargetPtr, Value + Addend);
491     break;
492   case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
493     // Operation: S + A
494     // Immediate goes in bits 21:10 of LD/ST instruction, taken
495     // from bits 11:0 of X
496     or32AArch64Imm(TargetPtr, getBits(Value + Addend, 0, 11));
497     break;
498   case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
499     // Operation: S + A
500     // Immediate goes in bits 21:10 of LD/ST instruction, taken
501     // from bits 11:1 of X
502     or32AArch64Imm(TargetPtr, getBits(Value + Addend, 1, 11));
503     break;
504   case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
505     // Operation: S + A
506     // Immediate goes in bits 21:10 of LD/ST instruction, taken
507     // from bits 11:2 of X
508     or32AArch64Imm(TargetPtr, getBits(Value + Addend, 2, 11));
509     break;
510   case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
511     // Operation: S + A
512     // Immediate goes in bits 21:10 of LD/ST instruction, taken
513     // from bits 11:3 of X
514     or32AArch64Imm(TargetPtr, getBits(Value + Addend, 3, 11));
515     break;
516   case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
517     // Operation: S + A
518     // Immediate goes in bits 21:10 of LD/ST instruction, taken
519     // from bits 11:4 of X
520     or32AArch64Imm(TargetPtr, getBits(Value + Addend, 4, 11));
521     break;
522   case ELF::R_AARCH64_LD_PREL_LO19: {
523     // Operation: S + A - P
524     uint64_t Result = Value + Addend - FinalAddress;
525 
526     // "Check that -2^20 <= result < 2^20".
527     assert(isInt<21>(Result));
528 
529     *TargetPtr &= 0xff00001fU;
530     // Immediate goes in bits 23:5 of LD imm instruction, taken
531     // from bits 20:2 of X
532     *TargetPtr |= ((Result & 0xffc) << (5 - 2));
533     break;
534   }
535   case ELF::R_AARCH64_ADR_PREL_LO21: {
536     // Operation: S + A - P
537     uint64_t Result = Value + Addend - FinalAddress;
538 
539     // "Check that -2^20 <= result < 2^20".
540     assert(isInt<21>(Result));
541 
542     *TargetPtr &= 0x9f00001fU;
543     // Immediate goes in bits 23:5, 30:29 of ADR imm instruction, taken
544     // from bits 20:0 of X
545     *TargetPtr |= ((Result & 0xffc) << (5 - 2));
546     *TargetPtr |= (Result & 0x3) << 29;
547     break;
548   }
549   }
550 }
551 
resolveARMRelocation(const SectionEntry & Section,uint64_t Offset,uint32_t Value,uint32_t Type,int32_t Addend)552 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
553                                           uint64_t Offset, uint32_t Value,
554                                           uint32_t Type, int32_t Addend) {
555   // TODO: Add Thumb relocations.
556   uint32_t *TargetPtr =
557       reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
558   uint32_t FinalAddress = Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
559   Value += Addend;
560 
561   LLVM_DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
562                     << Section.getAddressWithOffset(Offset)
563                     << " FinalAddress: " << format("%p", FinalAddress)
564                     << " Value: " << format("%x", Value)
565                     << " Type: " << format("%x", Type)
566                     << " Addend: " << format("%x", Addend) << "\n");
567 
568   switch (Type) {
569   default:
570     llvm_unreachable("Not implemented relocation type!");
571 
572   case ELF::R_ARM_NONE:
573     break;
574     // Write a 31bit signed offset
575   case ELF::R_ARM_PREL31:
576     support::ulittle32_t::ref{TargetPtr} =
577         (support::ulittle32_t::ref{TargetPtr} & 0x80000000) |
578         ((Value - FinalAddress) & ~0x80000000);
579     break;
580   case ELF::R_ARM_TARGET1:
581   case ELF::R_ARM_ABS32:
582     support::ulittle32_t::ref{TargetPtr} = Value;
583     break;
584     // Write first 16 bit of 32 bit value to the mov instruction.
585     // Last 4 bit should be shifted.
586   case ELF::R_ARM_MOVW_ABS_NC:
587   case ELF::R_ARM_MOVT_ABS:
588     if (Type == ELF::R_ARM_MOVW_ABS_NC)
589       Value = Value & 0xFFFF;
590     else if (Type == ELF::R_ARM_MOVT_ABS)
591       Value = (Value >> 16) & 0xFFFF;
592     support::ulittle32_t::ref{TargetPtr} =
593         (support::ulittle32_t::ref{TargetPtr} & ~0x000F0FFF) | (Value & 0xFFF) |
594         (((Value >> 12) & 0xF) << 16);
595     break;
596     // Write 24 bit relative value to the branch instruction.
597   case ELF::R_ARM_PC24: // Fall through.
598   case ELF::R_ARM_CALL: // Fall through.
599   case ELF::R_ARM_JUMP24:
600     int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
601     RelValue = (RelValue & 0x03FFFFFC) >> 2;
602     assert((support::ulittle32_t::ref{TargetPtr} & 0xFFFFFF) == 0xFFFFFE);
603     support::ulittle32_t::ref{TargetPtr} =
604         (support::ulittle32_t::ref{TargetPtr} & 0xFF000000) | RelValue;
605     break;
606   }
607 }
608 
setMipsABI(const ObjectFile & Obj)609 void RuntimeDyldELF::setMipsABI(const ObjectFile &Obj) {
610   if (Arch == Triple::UnknownArch ||
611       !StringRef(Triple::getArchTypePrefix(Arch)).equals("mips")) {
612     IsMipsO32ABI = false;
613     IsMipsN32ABI = false;
614     IsMipsN64ABI = false;
615     return;
616   }
617   if (auto *E = dyn_cast<ELFObjectFileBase>(&Obj)) {
618     unsigned AbiVariant = E->getPlatformFlags();
619     IsMipsO32ABI = AbiVariant & ELF::EF_MIPS_ABI_O32;
620     IsMipsN32ABI = AbiVariant & ELF::EF_MIPS_ABI2;
621   }
622   IsMipsN64ABI = Obj.getFileFormatName().equals("elf64-mips");
623 }
624 
625 // Return the .TOC. section and offset.
findPPC64TOCSection(const ELFObjectFileBase & Obj,ObjSectionToIDMap & LocalSections,RelocationValueRef & Rel)626 Error RuntimeDyldELF::findPPC64TOCSection(const ELFObjectFileBase &Obj,
627                                           ObjSectionToIDMap &LocalSections,
628                                           RelocationValueRef &Rel) {
629   // Set a default SectionID in case we do not find a TOC section below.
630   // This may happen for references to TOC base base (sym@toc, .odp
631   // relocation) without a .toc directive.  In this case just use the
632   // first section (which is usually the .odp) since the code won't
633   // reference the .toc base directly.
634   Rel.SymbolName = nullptr;
635   Rel.SectionID = 0;
636 
637   // The TOC consists of sections .got, .toc, .tocbss, .plt in that
638   // order. The TOC starts where the first of these sections starts.
639   for (auto &Section : Obj.sections()) {
640     Expected<StringRef> NameOrErr = Section.getName();
641     if (!NameOrErr)
642       return NameOrErr.takeError();
643     StringRef SectionName = *NameOrErr;
644 
645     if (SectionName == ".got"
646         || SectionName == ".toc"
647         || SectionName == ".tocbss"
648         || SectionName == ".plt") {
649       if (auto SectionIDOrErr =
650             findOrEmitSection(Obj, Section, false, LocalSections))
651         Rel.SectionID = *SectionIDOrErr;
652       else
653         return SectionIDOrErr.takeError();
654       break;
655     }
656   }
657 
658   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
659   // thus permitting a full 64 Kbytes segment.
660   Rel.Addend = 0x8000;
661 
662   return Error::success();
663 }
664 
665 // Returns the sections and offset associated with the ODP entry referenced
666 // by Symbol.
findOPDEntrySection(const ELFObjectFileBase & Obj,ObjSectionToIDMap & LocalSections,RelocationValueRef & Rel)667 Error RuntimeDyldELF::findOPDEntrySection(const ELFObjectFileBase &Obj,
668                                           ObjSectionToIDMap &LocalSections,
669                                           RelocationValueRef &Rel) {
670   // Get the ELF symbol value (st_value) to compare with Relocation offset in
671   // .opd entries
672   for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
673        si != se; ++si) {
674 
675     Expected<section_iterator> RelSecOrErr = si->getRelocatedSection();
676     if (!RelSecOrErr)
677       report_fatal_error(toString(RelSecOrErr.takeError()));
678 
679     section_iterator RelSecI = *RelSecOrErr;
680     if (RelSecI == Obj.section_end())
681       continue;
682 
683     Expected<StringRef> NameOrErr = RelSecI->getName();
684     if (!NameOrErr)
685       return NameOrErr.takeError();
686     StringRef RelSectionName = *NameOrErr;
687 
688     if (RelSectionName != ".opd")
689       continue;
690 
691     for (elf_relocation_iterator i = si->relocation_begin(),
692                                  e = si->relocation_end();
693          i != e;) {
694       // The R_PPC64_ADDR64 relocation indicates the first field
695       // of a .opd entry
696       uint64_t TypeFunc = i->getType();
697       if (TypeFunc != ELF::R_PPC64_ADDR64) {
698         ++i;
699         continue;
700       }
701 
702       uint64_t TargetSymbolOffset = i->getOffset();
703       symbol_iterator TargetSymbol = i->getSymbol();
704       int64_t Addend;
705       if (auto AddendOrErr = i->getAddend())
706         Addend = *AddendOrErr;
707       else
708         return AddendOrErr.takeError();
709 
710       ++i;
711       if (i == e)
712         break;
713 
714       // Just check if following relocation is a R_PPC64_TOC
715       uint64_t TypeTOC = i->getType();
716       if (TypeTOC != ELF::R_PPC64_TOC)
717         continue;
718 
719       // Finally compares the Symbol value and the target symbol offset
720       // to check if this .opd entry refers to the symbol the relocation
721       // points to.
722       if (Rel.Addend != (int64_t)TargetSymbolOffset)
723         continue;
724 
725       section_iterator TSI = Obj.section_end();
726       if (auto TSIOrErr = TargetSymbol->getSection())
727         TSI = *TSIOrErr;
728       else
729         return TSIOrErr.takeError();
730       assert(TSI != Obj.section_end() && "TSI should refer to a valid section");
731 
732       bool IsCode = TSI->isText();
733       if (auto SectionIDOrErr = findOrEmitSection(Obj, *TSI, IsCode,
734                                                   LocalSections))
735         Rel.SectionID = *SectionIDOrErr;
736       else
737         return SectionIDOrErr.takeError();
738       Rel.Addend = (intptr_t)Addend;
739       return Error::success();
740     }
741   }
742   llvm_unreachable("Attempting to get address of ODP entry!");
743 }
744 
745 // Relocation masks following the #lo(value), #hi(value), #ha(value),
746 // #higher(value), #highera(value), #highest(value), and #highesta(value)
747 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
748 // document.
749 
applyPPClo(uint64_t value)750 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
751 
applyPPChi(uint64_t value)752 static inline uint16_t applyPPChi(uint64_t value) {
753   return (value >> 16) & 0xffff;
754 }
755 
applyPPCha(uint64_t value)756 static inline uint16_t applyPPCha (uint64_t value) {
757   return ((value + 0x8000) >> 16) & 0xffff;
758 }
759 
applyPPChigher(uint64_t value)760 static inline uint16_t applyPPChigher(uint64_t value) {
761   return (value >> 32) & 0xffff;
762 }
763 
applyPPChighera(uint64_t value)764 static inline uint16_t applyPPChighera (uint64_t value) {
765   return ((value + 0x8000) >> 32) & 0xffff;
766 }
767 
applyPPChighest(uint64_t value)768 static inline uint16_t applyPPChighest(uint64_t value) {
769   return (value >> 48) & 0xffff;
770 }
771 
applyPPChighesta(uint64_t value)772 static inline uint16_t applyPPChighesta (uint64_t value) {
773   return ((value + 0x8000) >> 48) & 0xffff;
774 }
775 
resolvePPC32Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)776 void RuntimeDyldELF::resolvePPC32Relocation(const SectionEntry &Section,
777                                             uint64_t Offset, uint64_t Value,
778                                             uint32_t Type, int64_t Addend) {
779   uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
780   switch (Type) {
781   default:
782     report_fatal_error("Relocation type not implemented yet!");
783     break;
784   case ELF::R_PPC_ADDR16_LO:
785     writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
786     break;
787   case ELF::R_PPC_ADDR16_HI:
788     writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
789     break;
790   case ELF::R_PPC_ADDR16_HA:
791     writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
792     break;
793   }
794 }
795 
resolvePPC64Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)796 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
797                                             uint64_t Offset, uint64_t Value,
798                                             uint32_t Type, int64_t Addend) {
799   uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
800   switch (Type) {
801   default:
802     report_fatal_error("Relocation type not implemented yet!");
803     break;
804   case ELF::R_PPC64_ADDR16:
805     writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
806     break;
807   case ELF::R_PPC64_ADDR16_DS:
808     writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
809     break;
810   case ELF::R_PPC64_ADDR16_LO:
811     writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
812     break;
813   case ELF::R_PPC64_ADDR16_LO_DS:
814     writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
815     break;
816   case ELF::R_PPC64_ADDR16_HI:
817   case ELF::R_PPC64_ADDR16_HIGH:
818     writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
819     break;
820   case ELF::R_PPC64_ADDR16_HA:
821   case ELF::R_PPC64_ADDR16_HIGHA:
822     writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
823     break;
824   case ELF::R_PPC64_ADDR16_HIGHER:
825     writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
826     break;
827   case ELF::R_PPC64_ADDR16_HIGHERA:
828     writeInt16BE(LocalAddress, applyPPChighera(Value + Addend));
829     break;
830   case ELF::R_PPC64_ADDR16_HIGHEST:
831     writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
832     break;
833   case ELF::R_PPC64_ADDR16_HIGHESTA:
834     writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend));
835     break;
836   case ELF::R_PPC64_ADDR14: {
837     assert(((Value + Addend) & 3) == 0);
838     // Preserve the AA/LK bits in the branch instruction
839     uint8_t aalk = *(LocalAddress + 3);
840     writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
841   } break;
842   case ELF::R_PPC64_REL16_LO: {
843     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
844     uint64_t Delta = Value - FinalAddress + Addend;
845     writeInt16BE(LocalAddress, applyPPClo(Delta));
846   } break;
847   case ELF::R_PPC64_REL16_HI: {
848     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
849     uint64_t Delta = Value - FinalAddress + Addend;
850     writeInt16BE(LocalAddress, applyPPChi(Delta));
851   } break;
852   case ELF::R_PPC64_REL16_HA: {
853     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
854     uint64_t Delta = Value - FinalAddress + Addend;
855     writeInt16BE(LocalAddress, applyPPCha(Delta));
856   } break;
857   case ELF::R_PPC64_ADDR32: {
858     int64_t Result = static_cast<int64_t>(Value + Addend);
859     if (SignExtend64<32>(Result) != Result)
860       llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
861     writeInt32BE(LocalAddress, Result);
862   } break;
863   case ELF::R_PPC64_REL24: {
864     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
865     int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
866     if (SignExtend64<26>(delta) != delta)
867       llvm_unreachable("Relocation R_PPC64_REL24 overflow");
868     // We preserve bits other than LI field, i.e. PO and AA/LK fields.
869     uint32_t Inst = readBytesUnaligned(LocalAddress, 4);
870     writeInt32BE(LocalAddress, (Inst & 0xFC000003) | (delta & 0x03FFFFFC));
871   } break;
872   case ELF::R_PPC64_REL32: {
873     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
874     int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
875     if (SignExtend64<32>(delta) != delta)
876       llvm_unreachable("Relocation R_PPC64_REL32 overflow");
877     writeInt32BE(LocalAddress, delta);
878   } break;
879   case ELF::R_PPC64_REL64: {
880     uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
881     uint64_t Delta = Value - FinalAddress + Addend;
882     writeInt64BE(LocalAddress, Delta);
883   } break;
884   case ELF::R_PPC64_ADDR64:
885     writeInt64BE(LocalAddress, Value + Addend);
886     break;
887   }
888 }
889 
resolveSystemZRelocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)890 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
891                                               uint64_t Offset, uint64_t Value,
892                                               uint32_t Type, int64_t Addend) {
893   uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
894   switch (Type) {
895   default:
896     report_fatal_error("Relocation type not implemented yet!");
897     break;
898   case ELF::R_390_PC16DBL:
899   case ELF::R_390_PLT16DBL: {
900     int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
901     assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
902     writeInt16BE(LocalAddress, Delta / 2);
903     break;
904   }
905   case ELF::R_390_PC32DBL:
906   case ELF::R_390_PLT32DBL: {
907     int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
908     assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
909     writeInt32BE(LocalAddress, Delta / 2);
910     break;
911   }
912   case ELF::R_390_PC16: {
913     int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
914     assert(int16_t(Delta) == Delta && "R_390_PC16 overflow");
915     writeInt16BE(LocalAddress, Delta);
916     break;
917   }
918   case ELF::R_390_PC32: {
919     int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
920     assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
921     writeInt32BE(LocalAddress, Delta);
922     break;
923   }
924   case ELF::R_390_PC64: {
925     int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
926     writeInt64BE(LocalAddress, Delta);
927     break;
928   }
929   case ELF::R_390_8:
930     *LocalAddress = (uint8_t)(Value + Addend);
931     break;
932   case ELF::R_390_16:
933     writeInt16BE(LocalAddress, Value + Addend);
934     break;
935   case ELF::R_390_32:
936     writeInt32BE(LocalAddress, Value + Addend);
937     break;
938   case ELF::R_390_64:
939     writeInt64BE(LocalAddress, Value + Addend);
940     break;
941   }
942 }
943 
resolveBPFRelocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)944 void RuntimeDyldELF::resolveBPFRelocation(const SectionEntry &Section,
945                                           uint64_t Offset, uint64_t Value,
946                                           uint32_t Type, int64_t Addend) {
947   bool isBE = Arch == Triple::bpfeb;
948 
949   switch (Type) {
950   default:
951     report_fatal_error("Relocation type not implemented yet!");
952     break;
953   case ELF::R_BPF_NONE:
954     break;
955   case ELF::R_BPF_64_64: {
956     write(isBE, Section.getAddressWithOffset(Offset), Value + Addend);
957     LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
958                       << format("%p\n", Section.getAddressWithOffset(Offset)));
959     break;
960   }
961   case ELF::R_BPF_64_32: {
962     Value += Addend;
963     assert(Value <= UINT32_MAX);
964     write(isBE, Section.getAddressWithOffset(Offset), static_cast<uint32_t>(Value));
965     LLVM_DEBUG(dbgs() << "Writing " << format("%p", Value) << " at "
966                       << format("%p\n", Section.getAddressWithOffset(Offset)));
967     break;
968   }
969   }
970 }
971 
972 // The target location for the relocation is described by RE.SectionID and
973 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
974 // SectionEntry has three members describing its location.
975 // SectionEntry::Address is the address at which the section has been loaded
976 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
977 // address that the section will have in the target process.
978 // SectionEntry::ObjAddress is the address of the bits for this section in the
979 // original emitted object image (also in the current address space).
980 //
981 // Relocations will be applied as if the section were loaded at
982 // SectionEntry::LoadAddress, but they will be applied at an address based
983 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
984 // Target memory contents if they are required for value calculations.
985 //
986 // The Value parameter here is the load address of the symbol for the
987 // relocation to be applied.  For relocations which refer to symbols in the
988 // current object Value will be the LoadAddress of the section in which
989 // the symbol resides (RE.Addend provides additional information about the
990 // symbol location).  For external symbols, Value will be the address of the
991 // symbol in the target address space.
resolveRelocation(const RelocationEntry & RE,uint64_t Value)992 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
993                                        uint64_t Value) {
994   const SectionEntry &Section = Sections[RE.SectionID];
995   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
996                            RE.SymOffset, RE.SectionID);
997 }
998 
resolveRelocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend,uint64_t SymOffset,SID SectionID)999 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
1000                                        uint64_t Offset, uint64_t Value,
1001                                        uint32_t Type, int64_t Addend,
1002                                        uint64_t SymOffset, SID SectionID) {
1003   switch (Arch) {
1004   case Triple::x86_64:
1005     resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
1006     break;
1007   case Triple::x86:
1008     resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
1009                          (uint32_t)(Addend & 0xffffffffL));
1010     break;
1011   case Triple::aarch64:
1012   case Triple::aarch64_be:
1013     resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
1014     break;
1015   case Triple::arm: // Fall through.
1016   case Triple::armeb:
1017   case Triple::thumb:
1018   case Triple::thumbeb:
1019     resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
1020                          (uint32_t)(Addend & 0xffffffffL));
1021     break;
1022   case Triple::ppc: // Fall through.
1023   case Triple::ppcle:
1024     resolvePPC32Relocation(Section, Offset, Value, Type, Addend);
1025     break;
1026   case Triple::ppc64: // Fall through.
1027   case Triple::ppc64le:
1028     resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
1029     break;
1030   case Triple::systemz:
1031     resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
1032     break;
1033   case Triple::bpfel:
1034   case Triple::bpfeb:
1035     resolveBPFRelocation(Section, Offset, Value, Type, Addend);
1036     break;
1037   default:
1038     llvm_unreachable("Unsupported CPU type!");
1039   }
1040 }
1041 
computePlaceholderAddress(unsigned SectionID,uint64_t Offset) const1042 void *RuntimeDyldELF::computePlaceholderAddress(unsigned SectionID, uint64_t Offset) const {
1043   return (void *)(Sections[SectionID].getObjAddress() + Offset);
1044 }
1045 
processSimpleRelocation(unsigned SectionID,uint64_t Offset,unsigned RelType,RelocationValueRef Value)1046 void RuntimeDyldELF::processSimpleRelocation(unsigned SectionID, uint64_t Offset, unsigned RelType, RelocationValueRef Value) {
1047   RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1048   if (Value.SymbolName)
1049     addRelocationForSymbol(RE, Value.SymbolName);
1050   else
1051     addRelocationForSection(RE, Value.SectionID);
1052 }
1053 
getMatchingLoRelocation(uint32_t RelType,bool IsLocal) const1054 uint32_t RuntimeDyldELF::getMatchingLoRelocation(uint32_t RelType,
1055                                                  bool IsLocal) const {
1056   switch (RelType) {
1057   case ELF::R_MICROMIPS_GOT16:
1058     if (IsLocal)
1059       return ELF::R_MICROMIPS_LO16;
1060     break;
1061   case ELF::R_MICROMIPS_HI16:
1062     return ELF::R_MICROMIPS_LO16;
1063   case ELF::R_MIPS_GOT16:
1064     if (IsLocal)
1065       return ELF::R_MIPS_LO16;
1066     break;
1067   case ELF::R_MIPS_HI16:
1068     return ELF::R_MIPS_LO16;
1069   case ELF::R_MIPS_PCHI16:
1070     return ELF::R_MIPS_PCLO16;
1071   default:
1072     break;
1073   }
1074   return ELF::R_MIPS_NONE;
1075 }
1076 
1077 // Sometimes we don't need to create thunk for a branch.
1078 // This typically happens when branch target is located
1079 // in the same object file. In such case target is either
1080 // a weak symbol or symbol in a different executable section.
1081 // This function checks if branch target is located in the
1082 // same object file and if distance between source and target
1083 // fits R_AARCH64_CALL26 relocation. If both conditions are
1084 // met, it emits direct jump to the target and returns true.
1085 // Otherwise false is returned and thunk is created.
resolveAArch64ShortBranch(unsigned SectionID,relocation_iterator RelI,const RelocationValueRef & Value)1086 bool RuntimeDyldELF::resolveAArch64ShortBranch(
1087     unsigned SectionID, relocation_iterator RelI,
1088     const RelocationValueRef &Value) {
1089   uint64_t Address;
1090   if (Value.SymbolName) {
1091     auto Loc = GlobalSymbolTable.find(Value.SymbolName);
1092 
1093     // Don't create direct branch for external symbols.
1094     if (Loc == GlobalSymbolTable.end())
1095       return false;
1096 
1097     const auto &SymInfo = Loc->second;
1098     Address =
1099         uint64_t(Sections[SymInfo.getSectionID()].getLoadAddressWithOffset(
1100             SymInfo.getOffset()));
1101   } else {
1102     Address = uint64_t(Sections[Value.SectionID].getLoadAddress());
1103   }
1104   uint64_t Offset = RelI->getOffset();
1105   uint64_t SourceAddress = Sections[SectionID].getLoadAddressWithOffset(Offset);
1106 
1107   // R_AARCH64_CALL26 requires immediate to be in range -2^27 <= imm < 2^27
1108   // If distance between source and target is out of range then we should
1109   // create thunk.
1110   if (!isInt<28>(Address + Value.Addend - SourceAddress))
1111     return false;
1112 
1113   resolveRelocation(Sections[SectionID], Offset, Address, RelI->getType(),
1114                     Value.Addend);
1115 
1116   return true;
1117 }
1118 
resolveAArch64Branch(unsigned SectionID,const RelocationValueRef & Value,relocation_iterator RelI,StubMap & Stubs)1119 void RuntimeDyldELF::resolveAArch64Branch(unsigned SectionID,
1120                                           const RelocationValueRef &Value,
1121                                           relocation_iterator RelI,
1122                                           StubMap &Stubs) {
1123 
1124   LLVM_DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
1125   SectionEntry &Section = Sections[SectionID];
1126 
1127   uint64_t Offset = RelI->getOffset();
1128   unsigned RelType = RelI->getType();
1129   // Look for an existing stub.
1130   StubMap::const_iterator i = Stubs.find(Value);
1131   if (i != Stubs.end()) {
1132     resolveRelocation(Section, Offset,
1133                       (uint64_t)Section.getAddressWithOffset(i->second),
1134                       RelType, 0);
1135     LLVM_DEBUG(dbgs() << " Stub function found\n");
1136   } else if (!resolveAArch64ShortBranch(SectionID, RelI, Value)) {
1137     // Create a new stub function.
1138     LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1139     Stubs[Value] = Section.getStubOffset();
1140     uint8_t *StubTargetAddr = createStubFunction(
1141         Section.getAddressWithOffset(Section.getStubOffset()));
1142 
1143     RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.getAddress(),
1144                               ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
1145     RelocationEntry REmovk_g2(SectionID,
1146                               StubTargetAddr - Section.getAddress() + 4,
1147                               ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
1148     RelocationEntry REmovk_g1(SectionID,
1149                               StubTargetAddr - Section.getAddress() + 8,
1150                               ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
1151     RelocationEntry REmovk_g0(SectionID,
1152                               StubTargetAddr - Section.getAddress() + 12,
1153                               ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1154 
1155     if (Value.SymbolName) {
1156       addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1157       addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1158       addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1159       addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1160     } else {
1161       addRelocationForSection(REmovz_g3, Value.SectionID);
1162       addRelocationForSection(REmovk_g2, Value.SectionID);
1163       addRelocationForSection(REmovk_g1, Value.SectionID);
1164       addRelocationForSection(REmovk_g0, Value.SectionID);
1165     }
1166     resolveRelocation(Section, Offset,
1167                       reinterpret_cast<uint64_t>(Section.getAddressWithOffset(
1168                           Section.getStubOffset())),
1169                       RelType, 0);
1170     Section.advanceStubOffset(getMaxStubSize());
1171   }
1172 }
1173 
1174 Expected<relocation_iterator>
processRelocationRef(unsigned SectionID,relocation_iterator RelI,const ObjectFile & O,ObjSectionToIDMap & ObjSectionToID,StubMap & Stubs)1175 RuntimeDyldELF::processRelocationRef(
1176     unsigned SectionID, relocation_iterator RelI, const ObjectFile &O,
1177     ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) {
1178   const auto &Obj = cast<ELFObjectFileBase>(O);
1179   uint64_t RelType = RelI->getType();
1180   int64_t Addend = 0;
1181   if (Expected<int64_t> AddendOrErr = ELFRelocationRef(*RelI).getAddend())
1182     Addend = *AddendOrErr;
1183   else
1184     consumeError(AddendOrErr.takeError());
1185   elf_symbol_iterator Symbol = RelI->getSymbol();
1186 
1187   // Obtain the symbol name which is referenced in the relocation
1188   StringRef TargetName;
1189   if (Symbol != Obj.symbol_end()) {
1190     if (auto TargetNameOrErr = Symbol->getName())
1191       TargetName = *TargetNameOrErr;
1192     else
1193       return TargetNameOrErr.takeError();
1194   }
1195   LLVM_DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
1196                     << " TargetName: " << TargetName << "\n");
1197   RelocationValueRef Value;
1198   // First search for the symbol in the local symbol table
1199   SymbolRef::Type SymType = SymbolRef::ST_Unknown;
1200 
1201   // Search for the symbol in the global symbol table
1202   RTDyldSymbolTable::const_iterator gsi = GlobalSymbolTable.end();
1203   if (Symbol != Obj.symbol_end()) {
1204     gsi = GlobalSymbolTable.find(TargetName.data());
1205     Expected<SymbolRef::Type> SymTypeOrErr = Symbol->getType();
1206     if (!SymTypeOrErr) {
1207       std::string Buf;
1208       raw_string_ostream OS(Buf);
1209       logAllUnhandledErrors(SymTypeOrErr.takeError(), OS);
1210       OS.flush();
1211       report_fatal_error(Buf);
1212     }
1213     SymType = *SymTypeOrErr;
1214   }
1215   if (gsi != GlobalSymbolTable.end()) {
1216     const auto &SymInfo = gsi->second;
1217     Value.SectionID = SymInfo.getSectionID();
1218     Value.Offset = SymInfo.getOffset();
1219     Value.Addend = SymInfo.getOffset() + Addend;
1220   } else {
1221     switch (SymType) {
1222     case SymbolRef::ST_Debug: {
1223       // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
1224       // and can be changed by another developers. Maybe best way is add
1225       // a new symbol type ST_Section to SymbolRef and use it.
1226       auto SectionOrErr = Symbol->getSection();
1227       if (!SectionOrErr) {
1228         std::string Buf;
1229         raw_string_ostream OS(Buf);
1230         logAllUnhandledErrors(SectionOrErr.takeError(), OS);
1231         OS.flush();
1232         report_fatal_error(Buf);
1233       }
1234       section_iterator si = *SectionOrErr;
1235       if (si == Obj.section_end())
1236         llvm_unreachable("Symbol section not found, bad object file format!");
1237       LLVM_DEBUG(dbgs() << "\t\tThis is section symbol\n");
1238       bool isCode = si->isText();
1239       if (auto SectionIDOrErr = findOrEmitSection(Obj, (*si), isCode,
1240                                                   ObjSectionToID))
1241         Value.SectionID = *SectionIDOrErr;
1242       else
1243         return SectionIDOrErr.takeError();
1244       Value.Addend = Addend;
1245       break;
1246     }
1247     case SymbolRef::ST_Data:
1248     case SymbolRef::ST_Function:
1249     case SymbolRef::ST_Unknown: {
1250       Value.SymbolName = TargetName.data();
1251       Value.Addend = Addend;
1252 
1253       // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
1254       // will manifest here as a NULL symbol name.
1255       // We can set this as a valid (but empty) symbol name, and rely
1256       // on addRelocationForSymbol to handle this.
1257       if (!Value.SymbolName)
1258         Value.SymbolName = "";
1259       break;
1260     }
1261     default:
1262       llvm_unreachable("Unresolved symbol type!");
1263       break;
1264     }
1265   }
1266 
1267   uint64_t Offset = RelI->getOffset();
1268 
1269   LLVM_DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
1270                     << "\n");
1271   if ((Arch == Triple::aarch64 || Arch == Triple::aarch64_be)) {
1272     if ((RelType == ELF::R_AARCH64_CALL26 ||
1273          RelType == ELF::R_AARCH64_JUMP26) &&
1274         MemMgr.allowStubAllocation()) {
1275       resolveAArch64Branch(SectionID, Value, RelI, Stubs);
1276     } else if (RelType == ELF::R_AARCH64_ADR_GOT_PAGE) {
1277       // Craete new GOT entry or find existing one. If GOT entry is
1278       // to be created, then we also emit ABS64 relocation for it.
1279       uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1280       resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1281                                  ELF::R_AARCH64_ADR_PREL_PG_HI21);
1282 
1283     } else if (RelType == ELF::R_AARCH64_LD64_GOT_LO12_NC) {
1284       uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1285       resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1286                                  ELF::R_AARCH64_LDST64_ABS_LO12_NC);
1287     } else {
1288       processSimpleRelocation(SectionID, Offset, RelType, Value);
1289     }
1290   } else if (Arch == Triple::arm) {
1291     if (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1292       RelType == ELF::R_ARM_JUMP24) {
1293       // This is an ARM branch relocation, need to use a stub function.
1294       LLVM_DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.\n");
1295       SectionEntry &Section = Sections[SectionID];
1296 
1297       // Look for an existing stub.
1298       StubMap::const_iterator i = Stubs.find(Value);
1299       if (i != Stubs.end()) {
1300         resolveRelocation(
1301             Section, Offset,
1302             reinterpret_cast<uint64_t>(Section.getAddressWithOffset(i->second)),
1303             RelType, 0);
1304         LLVM_DEBUG(dbgs() << " Stub function found\n");
1305       } else {
1306         // Create a new stub function.
1307         LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1308         Stubs[Value] = Section.getStubOffset();
1309         uint8_t *StubTargetAddr = createStubFunction(
1310             Section.getAddressWithOffset(Section.getStubOffset()));
1311         RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1312                            ELF::R_ARM_ABS32, Value.Addend);
1313         if (Value.SymbolName)
1314           addRelocationForSymbol(RE, Value.SymbolName);
1315         else
1316           addRelocationForSection(RE, Value.SectionID);
1317 
1318         resolveRelocation(Section, Offset, reinterpret_cast<uint64_t>(
1319                                                Section.getAddressWithOffset(
1320                                                    Section.getStubOffset())),
1321                           RelType, 0);
1322         Section.advanceStubOffset(getMaxStubSize());
1323       }
1324     } else {
1325       uint32_t *Placeholder =
1326         reinterpret_cast<uint32_t*>(computePlaceholderAddress(SectionID, Offset));
1327       if (RelType == ELF::R_ARM_PREL31 || RelType == ELF::R_ARM_TARGET1 ||
1328           RelType == ELF::R_ARM_ABS32) {
1329         Value.Addend += *Placeholder;
1330       } else if (RelType == ELF::R_ARM_MOVW_ABS_NC || RelType == ELF::R_ARM_MOVT_ABS) {
1331         // See ELF for ARM documentation
1332         Value.Addend += (int16_t)((*Placeholder & 0xFFF) | (((*Placeholder >> 16) & 0xF) << 12));
1333       }
1334       processSimpleRelocation(SectionID, Offset, RelType, Value);
1335     }
1336   } else if (IsMipsO32ABI) {
1337     uint8_t *Placeholder = reinterpret_cast<uint8_t *>(
1338         computePlaceholderAddress(SectionID, Offset));
1339     uint32_t Opcode = readBytesUnaligned(Placeholder, 4);
1340     if (RelType == ELF::R_MIPS_26) {
1341       // This is an Mips branch relocation, need to use a stub function.
1342       LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1343       SectionEntry &Section = Sections[SectionID];
1344 
1345       // Extract the addend from the instruction.
1346       // We shift up by two since the Value will be down shifted again
1347       // when applying the relocation.
1348       uint32_t Addend = (Opcode & 0x03ffffff) << 2;
1349 
1350       Value.Addend += Addend;
1351 
1352       //  Look up for existing stub.
1353       StubMap::const_iterator i = Stubs.find(Value);
1354       if (i != Stubs.end()) {
1355         RelocationEntry RE(SectionID, Offset, RelType, i->second);
1356         addRelocationForSection(RE, SectionID);
1357         LLVM_DEBUG(dbgs() << " Stub function found\n");
1358       } else {
1359         // Create a new stub function.
1360         LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1361         Stubs[Value] = Section.getStubOffset();
1362 
1363         unsigned AbiVariant = Obj.getPlatformFlags();
1364 
1365         uint8_t *StubTargetAddr = createStubFunction(
1366             Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1367 
1368         // Creating Hi and Lo relocations for the filled stub instructions.
1369         RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1370                              ELF::R_MIPS_HI16, Value.Addend);
1371         RelocationEntry RELo(SectionID,
1372                              StubTargetAddr - Section.getAddress() + 4,
1373                              ELF::R_MIPS_LO16, Value.Addend);
1374 
1375         if (Value.SymbolName) {
1376           addRelocationForSymbol(REHi, Value.SymbolName);
1377           addRelocationForSymbol(RELo, Value.SymbolName);
1378         } else {
1379           addRelocationForSection(REHi, Value.SectionID);
1380           addRelocationForSection(RELo, Value.SectionID);
1381         }
1382 
1383         RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1384         addRelocationForSection(RE, SectionID);
1385         Section.advanceStubOffset(getMaxStubSize());
1386       }
1387     } else if (RelType == ELF::R_MIPS_HI16 || RelType == ELF::R_MIPS_PCHI16) {
1388       int64_t Addend = (Opcode & 0x0000ffff) << 16;
1389       RelocationEntry RE(SectionID, Offset, RelType, Addend);
1390       PendingRelocs.push_back(std::make_pair(Value, RE));
1391     } else if (RelType == ELF::R_MIPS_LO16 || RelType == ELF::R_MIPS_PCLO16) {
1392       int64_t Addend = Value.Addend + SignExtend32<16>(Opcode & 0x0000ffff);
1393       for (auto I = PendingRelocs.begin(); I != PendingRelocs.end();) {
1394         const RelocationValueRef &MatchingValue = I->first;
1395         RelocationEntry &Reloc = I->second;
1396         if (MatchingValue == Value &&
1397             RelType == getMatchingLoRelocation(Reloc.RelType) &&
1398             SectionID == Reloc.SectionID) {
1399           Reloc.Addend += Addend;
1400           if (Value.SymbolName)
1401             addRelocationForSymbol(Reloc, Value.SymbolName);
1402           else
1403             addRelocationForSection(Reloc, Value.SectionID);
1404           I = PendingRelocs.erase(I);
1405         } else
1406           ++I;
1407       }
1408       RelocationEntry RE(SectionID, Offset, RelType, Addend);
1409       if (Value.SymbolName)
1410         addRelocationForSymbol(RE, Value.SymbolName);
1411       else
1412         addRelocationForSection(RE, Value.SectionID);
1413     } else {
1414       if (RelType == ELF::R_MIPS_32)
1415         Value.Addend += Opcode;
1416       else if (RelType == ELF::R_MIPS_PC16)
1417         Value.Addend += SignExtend32<18>((Opcode & 0x0000ffff) << 2);
1418       else if (RelType == ELF::R_MIPS_PC19_S2)
1419         Value.Addend += SignExtend32<21>((Opcode & 0x0007ffff) << 2);
1420       else if (RelType == ELF::R_MIPS_PC21_S2)
1421         Value.Addend += SignExtend32<23>((Opcode & 0x001fffff) << 2);
1422       else if (RelType == ELF::R_MIPS_PC26_S2)
1423         Value.Addend += SignExtend32<28>((Opcode & 0x03ffffff) << 2);
1424       processSimpleRelocation(SectionID, Offset, RelType, Value);
1425     }
1426   } else if (IsMipsN32ABI || IsMipsN64ABI) {
1427     uint32_t r_type = RelType & 0xff;
1428     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1429     if (r_type == ELF::R_MIPS_CALL16 || r_type == ELF::R_MIPS_GOT_PAGE
1430         || r_type == ELF::R_MIPS_GOT_DISP) {
1431       StringMap<uint64_t>::iterator i = GOTSymbolOffsets.find(TargetName);
1432       if (i != GOTSymbolOffsets.end())
1433         RE.SymOffset = i->second;
1434       else {
1435         RE.SymOffset = allocateGOTEntries(1);
1436         GOTSymbolOffsets[TargetName] = RE.SymOffset;
1437       }
1438       if (Value.SymbolName)
1439         addRelocationForSymbol(RE, Value.SymbolName);
1440       else
1441         addRelocationForSection(RE, Value.SectionID);
1442     } else if (RelType == ELF::R_MIPS_26) {
1443       // This is an Mips branch relocation, need to use a stub function.
1444       LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1445       SectionEntry &Section = Sections[SectionID];
1446 
1447       //  Look up for existing stub.
1448       StubMap::const_iterator i = Stubs.find(Value);
1449       if (i != Stubs.end()) {
1450         RelocationEntry RE(SectionID, Offset, RelType, i->second);
1451         addRelocationForSection(RE, SectionID);
1452         LLVM_DEBUG(dbgs() << " Stub function found\n");
1453       } else {
1454         // Create a new stub function.
1455         LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1456         Stubs[Value] = Section.getStubOffset();
1457 
1458         unsigned AbiVariant = Obj.getPlatformFlags();
1459 
1460         uint8_t *StubTargetAddr = createStubFunction(
1461             Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1462 
1463         if (IsMipsN32ABI) {
1464           // Creating Hi and Lo relocations for the filled stub instructions.
1465           RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1466                                ELF::R_MIPS_HI16, Value.Addend);
1467           RelocationEntry RELo(SectionID,
1468                                StubTargetAddr - Section.getAddress() + 4,
1469                                ELF::R_MIPS_LO16, Value.Addend);
1470           if (Value.SymbolName) {
1471             addRelocationForSymbol(REHi, Value.SymbolName);
1472             addRelocationForSymbol(RELo, Value.SymbolName);
1473           } else {
1474             addRelocationForSection(REHi, Value.SectionID);
1475             addRelocationForSection(RELo, Value.SectionID);
1476           }
1477         } else {
1478           // Creating Highest, Higher, Hi and Lo relocations for the filled stub
1479           // instructions.
1480           RelocationEntry REHighest(SectionID,
1481                                     StubTargetAddr - Section.getAddress(),
1482                                     ELF::R_MIPS_HIGHEST, Value.Addend);
1483           RelocationEntry REHigher(SectionID,
1484                                    StubTargetAddr - Section.getAddress() + 4,
1485                                    ELF::R_MIPS_HIGHER, Value.Addend);
1486           RelocationEntry REHi(SectionID,
1487                                StubTargetAddr - Section.getAddress() + 12,
1488                                ELF::R_MIPS_HI16, Value.Addend);
1489           RelocationEntry RELo(SectionID,
1490                                StubTargetAddr - Section.getAddress() + 20,
1491                                ELF::R_MIPS_LO16, Value.Addend);
1492           if (Value.SymbolName) {
1493             addRelocationForSymbol(REHighest, Value.SymbolName);
1494             addRelocationForSymbol(REHigher, Value.SymbolName);
1495             addRelocationForSymbol(REHi, Value.SymbolName);
1496             addRelocationForSymbol(RELo, Value.SymbolName);
1497           } else {
1498             addRelocationForSection(REHighest, Value.SectionID);
1499             addRelocationForSection(REHigher, Value.SectionID);
1500             addRelocationForSection(REHi, Value.SectionID);
1501             addRelocationForSection(RELo, Value.SectionID);
1502           }
1503         }
1504         RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1505         addRelocationForSection(RE, SectionID);
1506         Section.advanceStubOffset(getMaxStubSize());
1507       }
1508     } else {
1509       processSimpleRelocation(SectionID, Offset, RelType, Value);
1510     }
1511 
1512   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1513     if (RelType == ELF::R_PPC64_REL24) {
1514       // Determine ABI variant in use for this object.
1515       unsigned AbiVariant = Obj.getPlatformFlags();
1516       AbiVariant &= ELF::EF_PPC64_ABI;
1517       // A PPC branch relocation will need a stub function if the target is
1518       // an external symbol (either Value.SymbolName is set, or SymType is
1519       // Symbol::ST_Unknown) or if the target address is not within the
1520       // signed 24-bits branch address.
1521       SectionEntry &Section = Sections[SectionID];
1522       uint8_t *Target = Section.getAddressWithOffset(Offset);
1523       bool RangeOverflow = false;
1524       bool IsExtern = Value.SymbolName || SymType == SymbolRef::ST_Unknown;
1525       if (!IsExtern) {
1526         if (AbiVariant != 2) {
1527           // In the ELFv1 ABI, a function call may point to the .opd entry,
1528           // so the final symbol value is calculated based on the relocation
1529           // values in the .opd section.
1530           if (auto Err = findOPDEntrySection(Obj, ObjSectionToID, Value))
1531             return std::move(Err);
1532         } else {
1533           // In the ELFv2 ABI, a function symbol may provide a local entry
1534           // point, which must be used for direct calls.
1535           if (Value.SectionID == SectionID){
1536             uint8_t SymOther = Symbol->getOther();
1537             Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther);
1538           }
1539         }
1540         uint8_t *RelocTarget =
1541             Sections[Value.SectionID].getAddressWithOffset(Value.Addend);
1542         int64_t delta = static_cast<int64_t>(Target - RelocTarget);
1543         // If it is within 26-bits branch range, just set the branch target
1544         if (SignExtend64<26>(delta) != delta) {
1545           RangeOverflow = true;
1546         } else if ((AbiVariant != 2) ||
1547                    (AbiVariant == 2  && Value.SectionID == SectionID)) {
1548           RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1549           addRelocationForSection(RE, Value.SectionID);
1550         }
1551       }
1552       if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID) ||
1553           RangeOverflow) {
1554         // It is an external symbol (either Value.SymbolName is set, or
1555         // SymType is SymbolRef::ST_Unknown) or out of range.
1556         StubMap::const_iterator i = Stubs.find(Value);
1557         if (i != Stubs.end()) {
1558           // Symbol function stub already created, just relocate to it
1559           resolveRelocation(Section, Offset,
1560                             reinterpret_cast<uint64_t>(
1561                                 Section.getAddressWithOffset(i->second)),
1562                             RelType, 0);
1563           LLVM_DEBUG(dbgs() << " Stub function found\n");
1564         } else {
1565           // Create a new stub function.
1566           LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1567           Stubs[Value] = Section.getStubOffset();
1568           uint8_t *StubTargetAddr = createStubFunction(
1569               Section.getAddressWithOffset(Section.getStubOffset()),
1570               AbiVariant);
1571           RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1572                              ELF::R_PPC64_ADDR64, Value.Addend);
1573 
1574           // Generates the 64-bits address loads as exemplified in section
1575           // 4.5.1 in PPC64 ELF ABI.  Note that the relocations need to
1576           // apply to the low part of the instructions, so we have to update
1577           // the offset according to the target endianness.
1578           uint64_t StubRelocOffset = StubTargetAddr - Section.getAddress();
1579           if (!IsTargetLittleEndian)
1580             StubRelocOffset += 2;
1581 
1582           RelocationEntry REhst(SectionID, StubRelocOffset + 0,
1583                                 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1584           RelocationEntry REhr(SectionID, StubRelocOffset + 4,
1585                                ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1586           RelocationEntry REh(SectionID, StubRelocOffset + 12,
1587                               ELF::R_PPC64_ADDR16_HI, Value.Addend);
1588           RelocationEntry REl(SectionID, StubRelocOffset + 16,
1589                               ELF::R_PPC64_ADDR16_LO, Value.Addend);
1590 
1591           if (Value.SymbolName) {
1592             addRelocationForSymbol(REhst, Value.SymbolName);
1593             addRelocationForSymbol(REhr, Value.SymbolName);
1594             addRelocationForSymbol(REh, Value.SymbolName);
1595             addRelocationForSymbol(REl, Value.SymbolName);
1596           } else {
1597             addRelocationForSection(REhst, Value.SectionID);
1598             addRelocationForSection(REhr, Value.SectionID);
1599             addRelocationForSection(REh, Value.SectionID);
1600             addRelocationForSection(REl, Value.SectionID);
1601           }
1602 
1603           resolveRelocation(Section, Offset, reinterpret_cast<uint64_t>(
1604                                                  Section.getAddressWithOffset(
1605                                                      Section.getStubOffset())),
1606                             RelType, 0);
1607           Section.advanceStubOffset(getMaxStubSize());
1608         }
1609         if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID)) {
1610           // Restore the TOC for external calls
1611           if (AbiVariant == 2)
1612             writeInt32BE(Target + 4, 0xE8410018); // ld r2,24(r1)
1613           else
1614             writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1615         }
1616       }
1617     } else if (RelType == ELF::R_PPC64_TOC16 ||
1618                RelType == ELF::R_PPC64_TOC16_DS ||
1619                RelType == ELF::R_PPC64_TOC16_LO ||
1620                RelType == ELF::R_PPC64_TOC16_LO_DS ||
1621                RelType == ELF::R_PPC64_TOC16_HI ||
1622                RelType == ELF::R_PPC64_TOC16_HA) {
1623       // These relocations are supposed to subtract the TOC address from
1624       // the final value.  This does not fit cleanly into the RuntimeDyld
1625       // scheme, since there may be *two* sections involved in determining
1626       // the relocation value (the section of the symbol referred to by the
1627       // relocation, and the TOC section associated with the current module).
1628       //
1629       // Fortunately, these relocations are currently only ever generated
1630       // referring to symbols that themselves reside in the TOC, which means
1631       // that the two sections are actually the same.  Thus they cancel out
1632       // and we can immediately resolve the relocation right now.
1633       switch (RelType) {
1634       case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break;
1635       case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break;
1636       case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break;
1637       case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break;
1638       case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break;
1639       case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break;
1640       default: llvm_unreachable("Wrong relocation type.");
1641       }
1642 
1643       RelocationValueRef TOCValue;
1644       if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, TOCValue))
1645         return std::move(Err);
1646       if (Value.SymbolName || Value.SectionID != TOCValue.SectionID)
1647         llvm_unreachable("Unsupported TOC relocation.");
1648       Value.Addend -= TOCValue.Addend;
1649       resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0);
1650     } else {
1651       // There are two ways to refer to the TOC address directly: either
1652       // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are
1653       // ignored), or via any relocation that refers to the magic ".TOC."
1654       // symbols (in which case the addend is respected).
1655       if (RelType == ELF::R_PPC64_TOC) {
1656         RelType = ELF::R_PPC64_ADDR64;
1657         if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1658           return std::move(Err);
1659       } else if (TargetName == ".TOC.") {
1660         if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1661           return std::move(Err);
1662         Value.Addend += Addend;
1663       }
1664 
1665       RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1666 
1667       if (Value.SymbolName)
1668         addRelocationForSymbol(RE, Value.SymbolName);
1669       else
1670         addRelocationForSection(RE, Value.SectionID);
1671     }
1672   } else if (Arch == Triple::systemz &&
1673              (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1674     // Create function stubs for both PLT and GOT references, regardless of
1675     // whether the GOT reference is to data or code.  The stub contains the
1676     // full address of the symbol, as needed by GOT references, and the
1677     // executable part only adds an overhead of 8 bytes.
1678     //
1679     // We could try to conserve space by allocating the code and data
1680     // parts of the stub separately.  However, as things stand, we allocate
1681     // a stub for every relocation, so using a GOT in JIT code should be
1682     // no less space efficient than using an explicit constant pool.
1683     LLVM_DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1684     SectionEntry &Section = Sections[SectionID];
1685 
1686     // Look for an existing stub.
1687     StubMap::const_iterator i = Stubs.find(Value);
1688     uintptr_t StubAddress;
1689     if (i != Stubs.end()) {
1690       StubAddress = uintptr_t(Section.getAddressWithOffset(i->second));
1691       LLVM_DEBUG(dbgs() << " Stub function found\n");
1692     } else {
1693       // Create a new stub function.
1694       LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1695 
1696       uintptr_t BaseAddress = uintptr_t(Section.getAddress());
1697       uintptr_t StubAlignment = getStubAlignment();
1698       StubAddress =
1699           (BaseAddress + Section.getStubOffset() + StubAlignment - 1) &
1700           -StubAlignment;
1701       unsigned StubOffset = StubAddress - BaseAddress;
1702 
1703       Stubs[Value] = StubOffset;
1704       createStubFunction((uint8_t *)StubAddress);
1705       RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1706                          Value.Offset);
1707       if (Value.SymbolName)
1708         addRelocationForSymbol(RE, Value.SymbolName);
1709       else
1710         addRelocationForSection(RE, Value.SectionID);
1711       Section.advanceStubOffset(getMaxStubSize());
1712     }
1713 
1714     if (RelType == ELF::R_390_GOTENT)
1715       resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1716                         Addend);
1717     else
1718       resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1719   } else if (Arch == Triple::x86_64) {
1720     if (RelType == ELF::R_X86_64_PLT32) {
1721       // The way the PLT relocations normally work is that the linker allocates
1722       // the
1723       // PLT and this relocation makes a PC-relative call into the PLT.  The PLT
1724       // entry will then jump to an address provided by the GOT.  On first call,
1725       // the
1726       // GOT address will point back into PLT code that resolves the symbol. After
1727       // the first call, the GOT entry points to the actual function.
1728       //
1729       // For local functions we're ignoring all of that here and just replacing
1730       // the PLT32 relocation type with PC32, which will translate the relocation
1731       // into a PC-relative call directly to the function. For external symbols we
1732       // can't be sure the function will be within 2^32 bytes of the call site, so
1733       // we need to create a stub, which calls into the GOT.  This case is
1734       // equivalent to the usual PLT implementation except that we use the stub
1735       // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1736       // rather than allocating a PLT section.
1737       if (Value.SymbolName && MemMgr.allowStubAllocation()) {
1738         // This is a call to an external function.
1739         // Look for an existing stub.
1740         SectionEntry *Section = &Sections[SectionID];
1741         StubMap::const_iterator i = Stubs.find(Value);
1742         uintptr_t StubAddress;
1743         if (i != Stubs.end()) {
1744           StubAddress = uintptr_t(Section->getAddress()) + i->second;
1745           LLVM_DEBUG(dbgs() << " Stub function found\n");
1746         } else {
1747           // Create a new stub function (equivalent to a PLT entry).
1748           LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1749 
1750           uintptr_t BaseAddress = uintptr_t(Section->getAddress());
1751           uintptr_t StubAlignment = getStubAlignment();
1752           StubAddress =
1753               (BaseAddress + Section->getStubOffset() + StubAlignment - 1) &
1754               -StubAlignment;
1755           unsigned StubOffset = StubAddress - BaseAddress;
1756           Stubs[Value] = StubOffset;
1757           createStubFunction((uint8_t *)StubAddress);
1758 
1759           // Bump our stub offset counter
1760           Section->advanceStubOffset(getMaxStubSize());
1761 
1762           // Allocate a GOT Entry
1763           uint64_t GOTOffset = allocateGOTEntries(1);
1764           // This potentially creates a new Section which potentially
1765           // invalidates the Section pointer, so reload it.
1766           Section = &Sections[SectionID];
1767 
1768           // The load of the GOT address has an addend of -4
1769           resolveGOTOffsetRelocation(SectionID, StubOffset + 2, GOTOffset - 4,
1770                                      ELF::R_X86_64_PC32);
1771 
1772           // Fill in the value of the symbol we're targeting into the GOT
1773           addRelocationForSymbol(
1774               computeGOTOffsetRE(GOTOffset, 0, ELF::R_X86_64_64),
1775               Value.SymbolName);
1776         }
1777 
1778         // Make the target call a call into the stub table.
1779         resolveRelocation(*Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1780                           Addend);
1781       } else {
1782         Value.Addend += support::ulittle32_t::ref(
1783             computePlaceholderAddress(SectionID, Offset));
1784         processSimpleRelocation(SectionID, Offset, ELF::R_X86_64_PC32, Value);
1785       }
1786     } else if (RelType == ELF::R_X86_64_GOTPCREL ||
1787                RelType == ELF::R_X86_64_GOTPCRELX ||
1788                RelType == ELF::R_X86_64_REX_GOTPCRELX) {
1789       uint64_t GOTOffset = allocateGOTEntries(1);
1790       resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1791                                  ELF::R_X86_64_PC32);
1792 
1793       // Fill in the value of the symbol we're targeting into the GOT
1794       RelocationEntry RE =
1795           computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
1796       if (Value.SymbolName)
1797         addRelocationForSymbol(RE, Value.SymbolName);
1798       else
1799         addRelocationForSection(RE, Value.SectionID);
1800     } else if (RelType == ELF::R_X86_64_GOT64) {
1801       // Fill in a 64-bit GOT offset.
1802       uint64_t GOTOffset = allocateGOTEntries(1);
1803       resolveRelocation(Sections[SectionID], Offset, GOTOffset,
1804                         ELF::R_X86_64_64, 0);
1805 
1806       // Fill in the value of the symbol we're targeting into the GOT
1807       RelocationEntry RE =
1808           computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
1809       if (Value.SymbolName)
1810         addRelocationForSymbol(RE, Value.SymbolName);
1811       else
1812         addRelocationForSection(RE, Value.SectionID);
1813     } else if (RelType == ELF::R_X86_64_GOTPC64) {
1814       // Materialize the address of the base of the GOT relative to the PC.
1815       // This doesn't create a GOT entry, but it does mean we need a GOT
1816       // section.
1817       (void)allocateGOTEntries(0);
1818       resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC64);
1819     } else if (RelType == ELF::R_X86_64_GOTOFF64) {
1820       // GOTOFF relocations ultimately require a section difference relocation.
1821       (void)allocateGOTEntries(0);
1822       processSimpleRelocation(SectionID, Offset, RelType, Value);
1823     } else if (RelType == ELF::R_X86_64_PC32) {
1824       Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1825       processSimpleRelocation(SectionID, Offset, RelType, Value);
1826     } else if (RelType == ELF::R_X86_64_PC64) {
1827       Value.Addend += support::ulittle64_t::ref(computePlaceholderAddress(SectionID, Offset));
1828       processSimpleRelocation(SectionID, Offset, RelType, Value);
1829     } else {
1830       processSimpleRelocation(SectionID, Offset, RelType, Value);
1831     }
1832   } else {
1833     if (Arch == Triple::x86) {
1834       Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1835     }
1836     processSimpleRelocation(SectionID, Offset, RelType, Value);
1837   }
1838   return ++RelI;
1839 }
1840 
getGOTEntrySize()1841 size_t RuntimeDyldELF::getGOTEntrySize() {
1842   // We don't use the GOT in all of these cases, but it's essentially free
1843   // to put them all here.
1844   size_t Result = 0;
1845   switch (Arch) {
1846   case Triple::x86_64:
1847   case Triple::aarch64:
1848   case Triple::aarch64_be:
1849   case Triple::ppc64:
1850   case Triple::ppc64le:
1851   case Triple::systemz:
1852     Result = sizeof(uint64_t);
1853     break;
1854   case Triple::x86:
1855   case Triple::arm:
1856   case Triple::thumb:
1857     Result = sizeof(uint32_t);
1858     break;
1859   case Triple::mips:
1860   case Triple::mipsel:
1861   case Triple::mips64:
1862   case Triple::mips64el:
1863     if (IsMipsO32ABI || IsMipsN32ABI)
1864       Result = sizeof(uint32_t);
1865     else if (IsMipsN64ABI)
1866       Result = sizeof(uint64_t);
1867     else
1868       llvm_unreachable("Mips ABI not handled");
1869     break;
1870   default:
1871     llvm_unreachable("Unsupported CPU type!");
1872   }
1873   return Result;
1874 }
1875 
allocateGOTEntries(unsigned no)1876 uint64_t RuntimeDyldELF::allocateGOTEntries(unsigned no) {
1877   if (GOTSectionID == 0) {
1878     GOTSectionID = Sections.size();
1879     // Reserve a section id. We'll allocate the section later
1880     // once we know the total size
1881     Sections.push_back(SectionEntry(".got", nullptr, 0, 0, 0));
1882   }
1883   uint64_t StartOffset = CurrentGOTIndex * getGOTEntrySize();
1884   CurrentGOTIndex += no;
1885   return StartOffset;
1886 }
1887 
findOrAllocGOTEntry(const RelocationValueRef & Value,unsigned GOTRelType)1888 uint64_t RuntimeDyldELF::findOrAllocGOTEntry(const RelocationValueRef &Value,
1889                                              unsigned GOTRelType) {
1890   auto E = GOTOffsetMap.insert({Value, 0});
1891   if (E.second) {
1892     uint64_t GOTOffset = allocateGOTEntries(1);
1893 
1894     // Create relocation for newly created GOT entry
1895     RelocationEntry RE =
1896         computeGOTOffsetRE(GOTOffset, Value.Offset, GOTRelType);
1897     if (Value.SymbolName)
1898       addRelocationForSymbol(RE, Value.SymbolName);
1899     else
1900       addRelocationForSection(RE, Value.SectionID);
1901 
1902     E.first->second = GOTOffset;
1903   }
1904 
1905   return E.first->second;
1906 }
1907 
resolveGOTOffsetRelocation(unsigned SectionID,uint64_t Offset,uint64_t GOTOffset,uint32_t Type)1908 void RuntimeDyldELF::resolveGOTOffsetRelocation(unsigned SectionID,
1909                                                 uint64_t Offset,
1910                                                 uint64_t GOTOffset,
1911                                                 uint32_t Type) {
1912   // Fill in the relative address of the GOT Entry into the stub
1913   RelocationEntry GOTRE(SectionID, Offset, Type, GOTOffset);
1914   addRelocationForSection(GOTRE, GOTSectionID);
1915 }
1916 
computeGOTOffsetRE(uint64_t GOTOffset,uint64_t SymbolOffset,uint32_t Type)1917 RelocationEntry RuntimeDyldELF::computeGOTOffsetRE(uint64_t GOTOffset,
1918                                                    uint64_t SymbolOffset,
1919                                                    uint32_t Type) {
1920   return RelocationEntry(GOTSectionID, GOTOffset, Type, SymbolOffset);
1921 }
1922 
finalizeLoad(const ObjectFile & Obj,ObjSectionToIDMap & SectionMap)1923 Error RuntimeDyldELF::finalizeLoad(const ObjectFile &Obj,
1924                                   ObjSectionToIDMap &SectionMap) {
1925   if (IsMipsO32ABI)
1926     if (!PendingRelocs.empty())
1927       return make_error<RuntimeDyldError>("Can't find matching LO16 reloc");
1928 
1929   // If necessary, allocate the global offset table
1930   if (GOTSectionID != 0) {
1931     // Allocate memory for the section
1932     size_t TotalSize = CurrentGOTIndex * getGOTEntrySize();
1933     uint8_t *Addr = MemMgr.allocateDataSection(TotalSize, getGOTEntrySize(),
1934                                                 GOTSectionID, ".got", false);
1935     if (!Addr)
1936       return make_error<RuntimeDyldError>("Unable to allocate memory for GOT!");
1937 
1938     Sections[GOTSectionID] =
1939         SectionEntry(".got", Addr, TotalSize, TotalSize, 0);
1940 
1941     // For now, initialize all GOT entries to zero.  We'll fill them in as
1942     // needed when GOT-based relocations are applied.
1943     memset(Addr, 0, TotalSize);
1944     if (IsMipsN32ABI || IsMipsN64ABI) {
1945       // To correctly resolve Mips GOT relocations, we need a mapping from
1946       // object's sections to GOTs.
1947       for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
1948            SI != SE; ++SI) {
1949         if (SI->relocation_begin() != SI->relocation_end()) {
1950           Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
1951           if (!RelSecOrErr)
1952             return make_error<RuntimeDyldError>(
1953                 toString(RelSecOrErr.takeError()));
1954 
1955           section_iterator RelocatedSection = *RelSecOrErr;
1956           ObjSectionToIDMap::iterator i = SectionMap.find(*RelocatedSection);
1957           assert (i != SectionMap.end());
1958           SectionToGOTMap[i->second] = GOTSectionID;
1959         }
1960       }
1961       GOTSymbolOffsets.clear();
1962     }
1963   }
1964 
1965   // Look for and record the EH frame section.
1966   ObjSectionToIDMap::iterator i, e;
1967   for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1968     const SectionRef &Section = i->first;
1969 
1970     StringRef Name;
1971     Expected<StringRef> NameOrErr = Section.getName();
1972     if (NameOrErr)
1973       Name = *NameOrErr;
1974     else
1975       consumeError(NameOrErr.takeError());
1976 
1977     if (Name == ".eh_frame") {
1978       UnregisteredEHFrameSections.push_back(i->second);
1979       break;
1980     }
1981   }
1982 
1983   GOTSectionID = 0;
1984   CurrentGOTIndex = 0;
1985 
1986   return Error::success();
1987 }
1988 
isCompatibleFile(const object::ObjectFile & Obj) const1989 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile &Obj) const {
1990   return Obj.isELF();
1991 }
1992 
relocationNeedsGot(const RelocationRef & R) const1993 bool RuntimeDyldELF::relocationNeedsGot(const RelocationRef &R) const {
1994   unsigned RelTy = R.getType();
1995   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be)
1996     return RelTy == ELF::R_AARCH64_ADR_GOT_PAGE ||
1997            RelTy == ELF::R_AARCH64_LD64_GOT_LO12_NC;
1998 
1999   if (Arch == Triple::x86_64)
2000     return RelTy == ELF::R_X86_64_GOTPCREL ||
2001            RelTy == ELF::R_X86_64_GOTPCRELX ||
2002            RelTy == ELF::R_X86_64_GOT64 ||
2003            RelTy == ELF::R_X86_64_REX_GOTPCRELX;
2004   return false;
2005 }
2006 
relocationNeedsStub(const RelocationRef & R) const2007 bool RuntimeDyldELF::relocationNeedsStub(const RelocationRef &R) const {
2008   if (Arch != Triple::x86_64)
2009     return true;  // Conservative answer
2010 
2011   switch (R.getType()) {
2012   default:
2013     return true;  // Conservative answer
2014 
2015 
2016   case ELF::R_X86_64_GOTPCREL:
2017   case ELF::R_X86_64_GOTPCRELX:
2018   case ELF::R_X86_64_REX_GOTPCRELX:
2019   case ELF::R_X86_64_GOTPC64:
2020   case ELF::R_X86_64_GOT64:
2021   case ELF::R_X86_64_GOTOFF64:
2022   case ELF::R_X86_64_PC32:
2023   case ELF::R_X86_64_PC64:
2024   case ELF::R_X86_64_64:
2025     // We know that these reloation types won't need a stub function.  This list
2026     // can be extended as needed.
2027     return false;
2028   }
2029 }
2030 
2031 } // namespace llvm
2032