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

Generated by: LCOV version 1.13