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