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