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