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