LCOV - code coverage report
Current view: top level - lib/ExecutionEngine/RuntimeDyld - RuntimeDyldELF.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 611 924 66.1 %
Date: 2018-10-20 13:21:21 Functions: 35 44 79.5 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13