Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp
35269 views
//===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Implementation of the MC-JIT runtime dynamic linker.9//10//===----------------------------------------------------------------------===//1112#include "llvm/ExecutionEngine/RuntimeDyld.h"13#include "RuntimeDyldCOFF.h"14#include "RuntimeDyldELF.h"15#include "RuntimeDyldImpl.h"16#include "RuntimeDyldMachO.h"17#include "llvm/Object/COFF.h"18#include "llvm/Object/ELFObjectFile.h"19#include "llvm/Support/Alignment.h"20#include "llvm/Support/MSVCErrorWorkarounds.h"21#include "llvm/Support/MathExtras.h"22#include <mutex>2324#include <future>2526using namespace llvm;27using namespace llvm::object;2829#define DEBUG_TYPE "dyld"3031namespace {3233enum RuntimeDyldErrorCode {34GenericRTDyldError = 135};3637// FIXME: This class is only here to support the transition to llvm::Error. It38// will be removed once this transition is complete. Clients should prefer to39// deal with the Error value directly, rather than converting to error_code.40class RuntimeDyldErrorCategory : public std::error_category {41public:42const char *name() const noexcept override { return "runtimedyld"; }4344std::string message(int Condition) const override {45switch (static_cast<RuntimeDyldErrorCode>(Condition)) {46case GenericRTDyldError: return "Generic RuntimeDyld error";47}48llvm_unreachable("Unrecognized RuntimeDyldErrorCode");49}50};5152}5354char RuntimeDyldError::ID = 0;5556void RuntimeDyldError::log(raw_ostream &OS) const {57OS << ErrMsg << "\n";58}5960std::error_code RuntimeDyldError::convertToErrorCode() const {61static RuntimeDyldErrorCategory RTDyldErrorCategory;62return std::error_code(GenericRTDyldError, RTDyldErrorCategory);63}6465// Empty out-of-line virtual destructor as the key function.66RuntimeDyldImpl::~RuntimeDyldImpl() = default;6768// Pin LoadedObjectInfo's vtables to this file.69void RuntimeDyld::LoadedObjectInfo::anchor() {}7071namespace llvm {7273void RuntimeDyldImpl::registerEHFrames() {}7475void RuntimeDyldImpl::deregisterEHFrames() {76MemMgr.deregisterEHFrames();77}7879#ifndef NDEBUG80static void dumpSectionMemory(const SectionEntry &S, StringRef State) {81dbgs() << "----- Contents of section " << S.getName() << " " << State82<< " -----";8384if (S.getAddress() == nullptr) {85dbgs() << "\n <section not emitted>\n";86return;87}8889const unsigned ColsPerRow = 16;9091uint8_t *DataAddr = S.getAddress();92uint64_t LoadAddr = S.getLoadAddress();9394unsigned StartPadding = LoadAddr & (ColsPerRow - 1);95unsigned BytesRemaining = S.getSize();9697if (StartPadding) {98dbgs() << "\n" << format("0x%016" PRIx64,99LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";100while (StartPadding--)101dbgs() << " ";102}103104while (BytesRemaining > 0) {105if ((LoadAddr & (ColsPerRow - 1)) == 0)106dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";107108dbgs() << " " << format("%02x", *DataAddr);109110++DataAddr;111++LoadAddr;112--BytesRemaining;113}114115dbgs() << "\n";116}117#endif118119// Resolve the relocations for all symbols we currently know about.120void RuntimeDyldImpl::resolveRelocations() {121std::lock_guard<sys::Mutex> locked(lock);122123// Print out the sections prior to relocation.124LLVM_DEBUG({125for (SectionEntry &S : Sections)126dumpSectionMemory(S, "before relocations");127});128129// First, resolve relocations associated with external symbols.130if (auto Err = resolveExternalSymbols()) {131HasError = true;132ErrorStr = toString(std::move(Err));133}134135resolveLocalRelocations();136137// Print out sections after relocation.138LLVM_DEBUG({139for (SectionEntry &S : Sections)140dumpSectionMemory(S, "after relocations");141});142}143144void RuntimeDyldImpl::resolveLocalRelocations() {145// Iterate over all outstanding relocations146for (const auto &Rel : Relocations) {147// The Section here (Sections[i]) refers to the section in which the148// symbol for the relocation is located. The SectionID in the relocation149// entry provides the section to which the relocation will be applied.150unsigned Idx = Rel.first;151uint64_t Addr = getSectionLoadAddress(Idx);152LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"153<< format("%p", (uintptr_t)Addr) << "\n");154resolveRelocationList(Rel.second, Addr);155}156Relocations.clear();157}158159void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,160uint64_t TargetAddress) {161std::lock_guard<sys::Mutex> locked(lock);162for (unsigned i = 0, e = Sections.size(); i != e; ++i) {163if (Sections[i].getAddress() == LocalAddress) {164reassignSectionAddress(i, TargetAddress);165return;166}167}168llvm_unreachable("Attempting to remap address of unknown section!");169}170171static Error getOffset(const SymbolRef &Sym, SectionRef Sec,172uint64_t &Result) {173Expected<uint64_t> AddressOrErr = Sym.getAddress();174if (!AddressOrErr)175return AddressOrErr.takeError();176Result = *AddressOrErr - Sec.getAddress();177return Error::success();178}179180Expected<RuntimeDyldImpl::ObjSectionToIDMap>181RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {182std::lock_guard<sys::Mutex> locked(lock);183184// Save information about our target185Arch = (Triple::ArchType)Obj.getArch();186IsTargetLittleEndian = Obj.isLittleEndian();187setMipsABI(Obj);188189// Compute the memory size required to load all sections to be loaded190// and pass this information to the memory manager191if (MemMgr.needsToReserveAllocationSpace()) {192uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;193Align CodeAlign, RODataAlign, RWDataAlign;194if (auto Err = computeTotalAllocSize(Obj, CodeSize, CodeAlign, RODataSize,195RODataAlign, RWDataSize, RWDataAlign))196return std::move(Err);197MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,198RWDataSize, RWDataAlign);199}200201// Used sections from the object file202ObjSectionToIDMap LocalSections;203204// Common symbols requiring allocation, with their sizes and alignments205CommonSymbolList CommonSymbolsToAllocate;206207uint64_t CommonSize = 0;208uint32_t CommonAlign = 0;209210// First, collect all weak and common symbols. We need to know if stronger211// definitions occur elsewhere.212JITSymbolResolver::LookupSet ResponsibilitySet;213{214JITSymbolResolver::LookupSet Symbols;215for (auto &Sym : Obj.symbols()) {216Expected<uint32_t> FlagsOrErr = Sym.getFlags();217if (!FlagsOrErr)218// TODO: Test this error.219return FlagsOrErr.takeError();220if ((*FlagsOrErr & SymbolRef::SF_Common) ||221(*FlagsOrErr & SymbolRef::SF_Weak)) {222// Get symbol name.223if (auto NameOrErr = Sym.getName())224Symbols.insert(*NameOrErr);225else226return NameOrErr.takeError();227}228}229230if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))231ResponsibilitySet = std::move(*ResultOrErr);232else233return ResultOrErr.takeError();234}235236// Parse symbols237LLVM_DEBUG(dbgs() << "Parse symbols:\n");238for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;239++I) {240Expected<uint32_t> FlagsOrErr = I->getFlags();241if (!FlagsOrErr)242// TODO: Test this error.243return FlagsOrErr.takeError();244245// Skip undefined symbols.246if (*FlagsOrErr & SymbolRef::SF_Undefined)247continue;248249// Get the symbol type.250object::SymbolRef::Type SymType;251if (auto SymTypeOrErr = I->getType())252SymType = *SymTypeOrErr;253else254return SymTypeOrErr.takeError();255256// Get symbol name.257StringRef Name;258if (auto NameOrErr = I->getName())259Name = *NameOrErr;260else261return NameOrErr.takeError();262263// Compute JIT symbol flags.264auto JITSymFlags = getJITSymbolFlags(*I);265if (!JITSymFlags)266return JITSymFlags.takeError();267268// If this is a weak definition, check to see if there's a strong one.269// If there is, skip this symbol (we won't be providing it: the strong270// definition will). If there's no strong definition, make this definition271// strong.272if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {273// First check whether there's already a definition in this instance.274if (GlobalSymbolTable.count(Name))275continue;276277// If we're not responsible for this symbol, skip it.278if (!ResponsibilitySet.count(Name))279continue;280281// Otherwise update the flags on the symbol to make this definition282// strong.283if (JITSymFlags->isWeak())284*JITSymFlags &= ~JITSymbolFlags::Weak;285if (JITSymFlags->isCommon()) {286*JITSymFlags &= ~JITSymbolFlags::Common;287uint32_t Align = I->getAlignment();288uint64_t Size = I->getCommonSize();289if (!CommonAlign)290CommonAlign = Align;291CommonSize = alignTo(CommonSize, Align) + Size;292CommonSymbolsToAllocate.push_back(*I);293}294}295296if (*FlagsOrErr & SymbolRef::SF_Absolute &&297SymType != object::SymbolRef::ST_File) {298uint64_t Addr = 0;299if (auto AddrOrErr = I->getAddress())300Addr = *AddrOrErr;301else302return AddrOrErr.takeError();303304unsigned SectionID = AbsoluteSymbolSection;305306LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name307<< " SID: " << SectionID308<< " Offset: " << format("%p", (uintptr_t)Addr)309<< " flags: " << *FlagsOrErr << "\n");310// Skip absolute symbol relocations.311if (!Name.empty()) {312auto Result = GlobalSymbolTable.insert_or_assign(313Name, SymbolTableEntry(SectionID, Addr, *JITSymFlags));314processNewSymbol(*I, Result.first->getValue());315}316} else if (SymType == object::SymbolRef::ST_Function ||317SymType == object::SymbolRef::ST_Data ||318SymType == object::SymbolRef::ST_Unknown ||319SymType == object::SymbolRef::ST_Other) {320321section_iterator SI = Obj.section_end();322if (auto SIOrErr = I->getSection())323SI = *SIOrErr;324else325return SIOrErr.takeError();326327if (SI == Obj.section_end())328continue;329330// Get symbol offset.331uint64_t SectOffset;332if (auto Err = getOffset(*I, *SI, SectOffset))333return std::move(Err);334335bool IsCode = SI->isText();336unsigned SectionID;337if (auto SectionIDOrErr =338findOrEmitSection(Obj, *SI, IsCode, LocalSections))339SectionID = *SectionIDOrErr;340else341return SectionIDOrErr.takeError();342343LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name344<< " SID: " << SectionID345<< " Offset: " << format("%p", (uintptr_t)SectOffset)346<< " flags: " << *FlagsOrErr << "\n");347// Skip absolute symbol relocations.348if (!Name.empty()) {349auto Result = GlobalSymbolTable.insert_or_assign(350Name, SymbolTableEntry(SectionID, SectOffset, *JITSymFlags));351processNewSymbol(*I, Result.first->getValue());352}353}354}355356// Allocate common symbols357if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,358CommonAlign))359return std::move(Err);360361// Parse and process relocations362LLVM_DEBUG(dbgs() << "Parse relocations:\n");363for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();364SI != SE; ++SI) {365StubMap Stubs;366367Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();368if (!RelSecOrErr)369return RelSecOrErr.takeError();370371section_iterator RelocatedSection = *RelSecOrErr;372if (RelocatedSection == SE)373continue;374375relocation_iterator I = SI->relocation_begin();376relocation_iterator E = SI->relocation_end();377378if (I == E && !ProcessAllSections)379continue;380381bool IsCode = RelocatedSection->isText();382unsigned SectionID = 0;383if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,384LocalSections))385SectionID = *SectionIDOrErr;386else387return SectionIDOrErr.takeError();388389LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");390391for (; I != E;)392if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))393I = *IOrErr;394else395return IOrErr.takeError();396397// If there is a NotifyStubEmitted callback set, call it to register any398// stubs created for this section.399if (NotifyStubEmitted) {400StringRef FileName = Obj.getFileName();401StringRef SectionName = Sections[SectionID].getName();402for (auto &KV : Stubs) {403404auto &VR = KV.first;405uint64_t StubAddr = KV.second;406407// If this is a named stub, just call NotifyStubEmitted.408if (VR.SymbolName) {409NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,410StubAddr);411continue;412}413414// Otherwise we will have to try a reverse lookup on the globla symbol table.415for (auto &GSTMapEntry : GlobalSymbolTable) {416StringRef SymbolName = GSTMapEntry.first();417auto &GSTEntry = GSTMapEntry.second;418if (GSTEntry.getSectionID() == VR.SectionID &&419GSTEntry.getOffset() == VR.Offset) {420NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,421StubAddr);422break;423}424}425}426}427}428429// Process remaining sections430if (ProcessAllSections) {431LLVM_DEBUG(dbgs() << "Process remaining sections:\n");432for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();433SI != SE; ++SI) {434435/* Ignore already loaded sections */436if (LocalSections.find(*SI) != LocalSections.end())437continue;438439bool IsCode = SI->isText();440if (auto SectionIDOrErr =441findOrEmitSection(Obj, *SI, IsCode, LocalSections))442LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");443else444return SectionIDOrErr.takeError();445}446}447448// Give the subclasses a chance to tie-up any loose ends.449if (auto Err = finalizeLoad(Obj, LocalSections))450return std::move(Err);451452// for (auto E : LocalSections)453// llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";454455return LocalSections;456}457458// A helper method for computeTotalAllocSize.459// Computes the memory size required to allocate sections with the given sizes,460// assuming that all sections are allocated with the given alignment461static uint64_t462computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,463Align Alignment) {464uint64_t TotalSize = 0;465for (uint64_t SectionSize : SectionSizes)466TotalSize += alignTo(SectionSize, Alignment);467return TotalSize;468}469470static bool isRequiredForExecution(const SectionRef Section) {471const ObjectFile *Obj = Section.getObject();472if (isa<object::ELFObjectFileBase>(Obj))473return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;474if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {475const coff_section *CoffSection = COFFObj->getCOFFSection(Section);476// Avoid loading zero-sized COFF sections.477// In PE files, VirtualSize gives the section size, and SizeOfRawData478// may be zero for sections with content. In Obj files, SizeOfRawData479// gives the section size, and VirtualSize is always zero. Hence480// the need to check for both cases below.481bool HasContent =482(CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);483bool IsDiscardable =484CoffSection->Characteristics &485(COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);486return HasContent && !IsDiscardable;487}488489assert(isa<MachOObjectFile>(Obj));490return true;491}492493static bool isReadOnlyData(const SectionRef Section) {494const ObjectFile *Obj = Section.getObject();495if (isa<object::ELFObjectFileBase>(Obj))496return !(ELFSectionRef(Section).getFlags() &497(ELF::SHF_WRITE | ELF::SHF_EXECINSTR));498if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))499return ((COFFObj->getCOFFSection(Section)->Characteristics &500(COFF::IMAGE_SCN_CNT_INITIALIZED_DATA501| COFF::IMAGE_SCN_MEM_READ502| COFF::IMAGE_SCN_MEM_WRITE))503==504(COFF::IMAGE_SCN_CNT_INITIALIZED_DATA505| COFF::IMAGE_SCN_MEM_READ));506507assert(isa<MachOObjectFile>(Obj));508return false;509}510511static bool isZeroInit(const SectionRef Section) {512const ObjectFile *Obj = Section.getObject();513if (isa<object::ELFObjectFileBase>(Obj))514return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;515if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))516return COFFObj->getCOFFSection(Section)->Characteristics &517COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;518519auto *MachO = cast<MachOObjectFile>(Obj);520unsigned SectionType = MachO->getSectionType(Section);521return SectionType == MachO::S_ZEROFILL ||522SectionType == MachO::S_GB_ZEROFILL;523}524525static bool isTLS(const SectionRef Section) {526const ObjectFile *Obj = Section.getObject();527if (isa<object::ELFObjectFileBase>(Obj))528return ELFSectionRef(Section).getFlags() & ELF::SHF_TLS;529return false;530}531532// Compute an upper bound of the memory size that is required to load all533// sections534Error RuntimeDyldImpl::computeTotalAllocSize(535const ObjectFile &Obj, uint64_t &CodeSize, Align &CodeAlign,536uint64_t &RODataSize, Align &RODataAlign, uint64_t &RWDataSize,537Align &RWDataAlign) {538// Compute the size of all sections required for execution539std::vector<uint64_t> CodeSectionSizes;540std::vector<uint64_t> ROSectionSizes;541std::vector<uint64_t> RWSectionSizes;542543// Collect sizes of all sections to be loaded;544// also determine the max alignment of all sections545for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();546SI != SE; ++SI) {547const SectionRef &Section = *SI;548549bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;550551// Consider only the sections that are required to be loaded for execution552if (IsRequired) {553uint64_t DataSize = Section.getSize();554Align Alignment = Section.getAlignment();555bool IsCode = Section.isText();556bool IsReadOnly = isReadOnlyData(Section);557bool IsTLS = isTLS(Section);558559Expected<StringRef> NameOrErr = Section.getName();560if (!NameOrErr)561return NameOrErr.takeError();562StringRef Name = *NameOrErr;563564uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);565566uint64_t PaddingSize = 0;567if (Name == ".eh_frame")568PaddingSize += 4;569if (StubBufSize != 0)570PaddingSize += getStubAlignment().value() - 1;571572uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;573574// The .eh_frame section (at least on Linux) needs an extra four bytes575// padded576// with zeroes added at the end. For MachO objects, this section has a577// slightly different name, so this won't have any effect for MachO578// objects.579if (Name == ".eh_frame")580SectionSize += 4;581582if (!SectionSize)583SectionSize = 1;584585if (IsCode) {586CodeAlign = std::max(CodeAlign, Alignment);587CodeSectionSizes.push_back(SectionSize);588} else if (IsReadOnly) {589RODataAlign = std::max(RODataAlign, Alignment);590ROSectionSizes.push_back(SectionSize);591} else if (!IsTLS) {592RWDataAlign = std::max(RWDataAlign, Alignment);593RWSectionSizes.push_back(SectionSize);594}595}596}597598// Compute Global Offset Table size. If it is not zero we599// also update alignment, which is equal to a size of a600// single GOT entry.601if (unsigned GotSize = computeGOTSize(Obj)) {602RWSectionSizes.push_back(GotSize);603RWDataAlign = std::max(RWDataAlign, Align(getGOTEntrySize()));604}605606// Compute the size of all common symbols607uint64_t CommonSize = 0;608Align CommonAlign;609for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;610++I) {611Expected<uint32_t> FlagsOrErr = I->getFlags();612if (!FlagsOrErr)613// TODO: Test this error.614return FlagsOrErr.takeError();615if (*FlagsOrErr & SymbolRef::SF_Common) {616// Add the common symbols to a list. We'll allocate them all below.617uint64_t Size = I->getCommonSize();618Align Alignment = Align(I->getAlignment());619// If this is the first common symbol, use its alignment as the alignment620// for the common symbols section.621if (CommonSize == 0)622CommonAlign = Alignment;623CommonSize = alignTo(CommonSize, Alignment) + Size;624}625}626if (CommonSize != 0) {627RWSectionSizes.push_back(CommonSize);628RWDataAlign = std::max(RWDataAlign, CommonAlign);629}630631if (!CodeSectionSizes.empty()) {632// Add 64 bytes for a potential IFunc resolver stub633CodeSectionSizes.push_back(64);634}635636// Compute the required allocation space for each different type of sections637// (code, read-only data, read-write data) assuming that all sections are638// allocated with the max alignment. Note that we cannot compute with the639// individual alignments of the sections, because then the required size640// depends on the order, in which the sections are allocated.641CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);642RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);643RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);644645return Error::success();646}647648// compute GOT size649unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {650size_t GotEntrySize = getGOTEntrySize();651if (!GotEntrySize)652return 0;653654size_t GotSize = 0;655for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();656SI != SE; ++SI) {657658for (const RelocationRef &Reloc : SI->relocations())659if (relocationNeedsGot(Reloc))660GotSize += GotEntrySize;661}662663return GotSize;664}665666// compute stub buffer size for the given section667unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,668const SectionRef &Section) {669if (!MemMgr.allowStubAllocation()) {670return 0;671}672673unsigned StubSize = getMaxStubSize();674if (StubSize == 0) {675return 0;676}677// FIXME: this is an inefficient way to handle this. We should computed the678// necessary section allocation size in loadObject by walking all the sections679// once.680unsigned StubBufSize = 0;681for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();682SI != SE; ++SI) {683684Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();685if (!RelSecOrErr)686report_fatal_error(Twine(toString(RelSecOrErr.takeError())));687688section_iterator RelSecI = *RelSecOrErr;689if (!(RelSecI == Section))690continue;691692for (const RelocationRef &Reloc : SI->relocations())693if (relocationNeedsStub(Reloc))694StubBufSize += StubSize;695}696697// Get section data size and alignment698uint64_t DataSize = Section.getSize();699Align Alignment = Section.getAlignment();700701// Add stubbuf size alignment702Align StubAlignment = getStubAlignment();703Align EndAlignment = commonAlignment(Alignment, DataSize);704if (StubAlignment > EndAlignment)705StubBufSize += StubAlignment.value() - EndAlignment.value();706return StubBufSize;707}708709uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,710unsigned Size) const {711uint64_t Result = 0;712if (IsTargetLittleEndian) {713Src += Size - 1;714while (Size--)715Result = (Result << 8) | *Src--;716} else717while (Size--)718Result = (Result << 8) | *Src++;719720return Result;721}722723void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,724unsigned Size) const {725if (IsTargetLittleEndian) {726while (Size--) {727*Dst++ = Value & 0xFF;728Value >>= 8;729}730} else {731Dst += Size - 1;732while (Size--) {733*Dst-- = Value & 0xFF;734Value >>= 8;735}736}737}738739Expected<JITSymbolFlags>740RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {741return JITSymbolFlags::fromObjectSymbol(SR);742}743744Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,745CommonSymbolList &SymbolsToAllocate,746uint64_t CommonSize,747uint32_t CommonAlign) {748if (SymbolsToAllocate.empty())749return Error::success();750751// Allocate memory for the section752unsigned SectionID = Sections.size();753uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,754"<common symbols>", false);755if (!Addr)756report_fatal_error("Unable to allocate memory for common symbols!");757uint64_t Offset = 0;758Sections.push_back(759SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));760memset(Addr, 0, CommonSize);761762LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID763<< " new addr: " << format("%p", Addr)764<< " DataSize: " << CommonSize << "\n");765766// Assign the address of each symbol767for (auto &Sym : SymbolsToAllocate) {768uint32_t Alignment = Sym.getAlignment();769uint64_t Size = Sym.getCommonSize();770StringRef Name;771if (auto NameOrErr = Sym.getName())772Name = *NameOrErr;773else774return NameOrErr.takeError();775if (Alignment) {776// This symbol has an alignment requirement.777uint64_t AlignOffset =778offsetToAlignment((uint64_t)Addr, Align(Alignment));779Addr += AlignOffset;780Offset += AlignOffset;781}782auto JITSymFlags = getJITSymbolFlags(Sym);783784if (!JITSymFlags)785return JITSymFlags.takeError();786787LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "788<< format("%p", Addr) << "\n");789if (!Name.empty()) // Skip absolute symbol relocations.790GlobalSymbolTable[Name] =791SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));792Offset += Size;793Addr += Size;794}795796return Error::success();797}798799Expected<unsigned>800RuntimeDyldImpl::emitSection(const ObjectFile &Obj,801const SectionRef &Section,802bool IsCode) {803StringRef data;804Align Alignment = Section.getAlignment();805806unsigned PaddingSize = 0;807unsigned StubBufSize = 0;808bool IsRequired = isRequiredForExecution(Section);809bool IsVirtual = Section.isVirtual();810bool IsZeroInit = isZeroInit(Section);811bool IsReadOnly = isReadOnlyData(Section);812bool IsTLS = isTLS(Section);813uint64_t DataSize = Section.getSize();814815Expected<StringRef> NameOrErr = Section.getName();816if (!NameOrErr)817return NameOrErr.takeError();818StringRef Name = *NameOrErr;819820StubBufSize = computeSectionStubBufSize(Obj, Section);821822// The .eh_frame section (at least on Linux) needs an extra four bytes padded823// with zeroes added at the end. For MachO objects, this section has a824// slightly different name, so this won't have any effect for MachO objects.825if (Name == ".eh_frame")826PaddingSize = 4;827828uintptr_t Allocate;829unsigned SectionID = Sections.size();830uint8_t *Addr;831uint64_t LoadAddress = 0;832const char *pData = nullptr;833834// If this section contains any bits (i.e. isn't a virtual or bss section),835// grab a reference to them.836if (!IsVirtual && !IsZeroInit) {837// In either case, set the location of the unrelocated section in memory,838// since we still process relocations for it even if we're not applying them.839if (Expected<StringRef> E = Section.getContents())840data = *E;841else842return E.takeError();843pData = data.data();844}845846// If there are any stubs then the section alignment needs to be at least as847// high as stub alignment or padding calculations may by incorrect when the848// section is remapped.849if (StubBufSize != 0) {850Alignment = std::max(Alignment, getStubAlignment());851PaddingSize += getStubAlignment().value() - 1;852}853854// Some sections, such as debug info, don't need to be loaded for execution.855// Process those only if explicitly requested.856if (IsRequired || ProcessAllSections) {857Allocate = DataSize + PaddingSize + StubBufSize;858if (!Allocate)859Allocate = 1;860if (IsTLS) {861auto TLSSection = MemMgr.allocateTLSSection(Allocate, Alignment.value(),862SectionID, Name);863Addr = TLSSection.InitializationImage;864LoadAddress = TLSSection.Offset;865} else if (IsCode) {866Addr = MemMgr.allocateCodeSection(Allocate, Alignment.value(), SectionID,867Name);868} else {869Addr = MemMgr.allocateDataSection(Allocate, Alignment.value(), SectionID,870Name, IsReadOnly);871}872if (!Addr)873report_fatal_error("Unable to allocate section memory!");874875// Zero-initialize or copy the data from the image876if (IsZeroInit || IsVirtual)877memset(Addr, 0, DataSize);878else879memcpy(Addr, pData, DataSize);880881// Fill in any extra bytes we allocated for padding882if (PaddingSize != 0) {883memset(Addr + DataSize, 0, PaddingSize);884// Update the DataSize variable to include padding.885DataSize += PaddingSize;886887// Align DataSize to stub alignment if we have any stubs (PaddingSize will888// have been increased above to account for this).889if (StubBufSize > 0)890DataSize &= -(uint64_t)getStubAlignment().value();891}892893LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "894<< Name << " obj addr: " << format("%p", pData)895<< " new addr: " << format("%p", Addr) << " DataSize: "896<< DataSize << " StubBufSize: " << StubBufSize897<< " Allocate: " << Allocate << "\n");898} else {899// Even if we didn't load the section, we need to record an entry for it900// to handle later processing (and by 'handle' I mean don't do anything901// with these sections).902Allocate = 0;903Addr = nullptr;904LLVM_DEBUG(905dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name906<< " obj addr: " << format("%p", data.data()) << " new addr: 0"907<< " DataSize: " << DataSize << " StubBufSize: " << StubBufSize908<< " Allocate: " << Allocate << "\n");909}910911Sections.push_back(912SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));913914// The load address of a TLS section is not equal to the address of its915// initialization image916if (IsTLS)917Sections.back().setLoadAddress(LoadAddress);918// Debug info sections are linked as if their load address was zero919if (!IsRequired)920Sections.back().setLoadAddress(0);921922return SectionID;923}924925Expected<unsigned>926RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,927const SectionRef &Section,928bool IsCode,929ObjSectionToIDMap &LocalSections) {930931unsigned SectionID = 0;932ObjSectionToIDMap::iterator i = LocalSections.find(Section);933if (i != LocalSections.end())934SectionID = i->second;935else {936if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))937SectionID = *SectionIDOrErr;938else939return SectionIDOrErr.takeError();940LocalSections[Section] = SectionID;941}942return SectionID;943}944945void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,946unsigned SectionID) {947Relocations[SectionID].push_back(RE);948}949950void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,951StringRef SymbolName) {952// Relocation by symbol. If the symbol is found in the global symbol table,953// create an appropriate section relocation. Otherwise, add it to954// ExternalSymbolRelocations.955RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);956if (Loc == GlobalSymbolTable.end()) {957ExternalSymbolRelocations[SymbolName].push_back(RE);958} else {959assert(!SymbolName.empty() &&960"Empty symbol should not be in GlobalSymbolTable");961// Copy the RE since we want to modify its addend.962RelocationEntry RECopy = RE;963const auto &SymInfo = Loc->second;964RECopy.Addend += SymInfo.getOffset();965Relocations[SymInfo.getSectionID()].push_back(RECopy);966}967}968969uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,970unsigned AbiVariant) {971if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be ||972Arch == Triple::aarch64_32) {973// This stub has to be able to access the full address space,974// since symbol lookup won't necessarily find a handy, in-range,975// PLT stub for functions which could be anywhere.976// Stub can use ip0 (== x16) to calculate address977writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>978writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>979writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>980writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>981writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0982983return Addr;984} else if (Arch == Triple::arm || Arch == Triple::armeb) {985// TODO: There is only ARM far stub now. We should add the Thumb stub,986// and stubs for branches Thumb - ARM and ARM - Thumb.987writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]988return Addr + 4;989} else if (IsMipsO32ABI || IsMipsN32ABI) {990// 0: 3c190000 lui t9,%hi(addr).991// 4: 27390000 addiu t9,t9,%lo(addr).992// 8: 03200008 jr t9.993// c: 00000000 nop.994const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;995const unsigned NopInstr = 0x0;996unsigned JrT9Instr = 0x03200008;997if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||998(AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)999JrT9Instr = 0x03200009;10001001writeBytesUnaligned(LuiT9Instr, Addr, 4);1002writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);1003writeBytesUnaligned(JrT9Instr, Addr + 8, 4);1004writeBytesUnaligned(NopInstr, Addr + 12, 4);1005return Addr;1006} else if (IsMipsN64ABI) {1007// 0: 3c190000 lui t9,%highest(addr).1008// 4: 67390000 daddiu t9,t9,%higher(addr).1009// 8: 0019CC38 dsll t9,t9,16.1010// c: 67390000 daddiu t9,t9,%hi(addr).1011// 10: 0019CC38 dsll t9,t9,16.1012// 14: 67390000 daddiu t9,t9,%lo(addr).1013// 18: 03200008 jr t9.1014// 1c: 00000000 nop.1015const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,1016DsllT9Instr = 0x19CC38;1017const unsigned NopInstr = 0x0;1018unsigned JrT9Instr = 0x03200008;1019if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)1020JrT9Instr = 0x03200009;10211022writeBytesUnaligned(LuiT9Instr, Addr, 4);1023writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);1024writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);1025writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);1026writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);1027writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);1028writeBytesUnaligned(JrT9Instr, Addr + 24, 4);1029writeBytesUnaligned(NopInstr, Addr + 28, 4);1030return Addr;1031} else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {1032// Depending on which version of the ELF ABI is in use, we need to1033// generate one of two variants of the stub. They both start with1034// the same sequence to load the target address into r12.1035writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)1036writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)1037writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 321038writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)1039writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)1040if (AbiVariant == 2) {1041// PowerPC64 stub ELFv2 ABI: The address points to the function itself.1042// The address is already in r12 as required by the ABI. Branch to it.1043writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)1044writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r121045writeInt32BE(Addr+28, 0x4E800420); // bctr1046} else {1047// PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.1048// Load the function address on r11 and sets it to control register. Also1049// loads the function TOC in r2 and environment pointer to r11.1050writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)1051writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)1052writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)1053writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r111054writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)1055writeInt32BE(Addr+40, 0x4E800420); // bctr1056}1057return Addr;1058} else if (Arch == Triple::systemz) {1059writeInt16BE(Addr, 0xC418); // lgrl %r1,.+81060writeInt16BE(Addr+2, 0x0000);1061writeInt16BE(Addr+4, 0x0004);1062writeInt16BE(Addr+6, 0x07F1); // brc 15,%r11063// 8-byte address stored at Addr + 81064return Addr;1065} else if (Arch == Triple::x86_64) {1066*Addr = 0xFF; // jmp1067*(Addr+1) = 0x25; // rip1068// 32-bit PC-relative address of the GOT entry will be stored at Addr+21069} else if (Arch == Triple::x86) {1070*Addr = 0xE9; // 32-bit pc-relative jump.1071}1072return Addr;1073}10741075// Assign an address to a symbol name and resolve all the relocations1076// associated with it.1077void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,1078uint64_t Addr) {1079// The address to use for relocation resolution is not1080// the address of the local section buffer. We must be doing1081// a remote execution environment of some sort. Relocations can't1082// be applied until all the sections have been moved. The client must1083// trigger this with a call to MCJIT::finalize() or1084// RuntimeDyld::resolveRelocations().1085//1086// Addr is a uint64_t because we can't assume the pointer width1087// of the target is the same as that of the host. Just use a generic1088// "big enough" type.1089LLVM_DEBUG(1090dbgs() << "Reassigning address for section " << SectionID << " ("1091<< Sections[SectionID].getName() << "): "1092<< format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())1093<< " -> " << format("0x%016" PRIx64, Addr) << "\n");1094Sections[SectionID].setLoadAddress(Addr);1095}10961097void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,1098uint64_t Value) {1099for (const RelocationEntry &RE : Relocs) {1100// Ignore relocations for sections that were not loaded1101if (RE.SectionID != AbsoluteSymbolSection &&1102Sections[RE.SectionID].getAddress() == nullptr)1103continue;1104resolveRelocation(RE, Value);1105}1106}11071108void RuntimeDyldImpl::applyExternalSymbolRelocations(1109const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {1110for (auto &RelocKV : ExternalSymbolRelocations) {1111StringRef Name = RelocKV.first();1112RelocationList &Relocs = RelocKV.second;1113if (Name.size() == 0) {1114// This is an absolute symbol, use an address of zero.1115LLVM_DEBUG(dbgs() << "Resolving absolute relocations."1116<< "\n");1117resolveRelocationList(Relocs, 0);1118} else {1119uint64_t Addr = 0;1120JITSymbolFlags Flags;1121RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);1122if (Loc == GlobalSymbolTable.end()) {1123auto RRI = ExternalSymbolMap.find(Name);1124assert(RRI != ExternalSymbolMap.end() && "No result for symbol");1125Addr = RRI->second.getAddress();1126Flags = RRI->second.getFlags();1127} else {1128// We found the symbol in our global table. It was probably in a1129// Module that we loaded previously.1130const auto &SymInfo = Loc->second;1131Addr = getSectionLoadAddress(SymInfo.getSectionID()) +1132SymInfo.getOffset();1133Flags = SymInfo.getFlags();1134}11351136// FIXME: Implement error handling that doesn't kill the host program!1137if (!Addr && !Resolver.allowsZeroSymbols())1138report_fatal_error(Twine("Program used external function '") + Name +1139"' which could not be resolved!");11401141// If Resolver returned UINT64_MAX, the client wants to handle this symbol1142// manually and we shouldn't resolve its relocations.1143if (Addr != UINT64_MAX) {11441145// Tweak the address based on the symbol flags if necessary.1146// For example, this is used by RuntimeDyldMachOARM to toggle the low bit1147// if the target symbol is Thumb.1148Addr = modifyAddressBasedOnFlags(Addr, Flags);11491150LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"1151<< format("0x%lx", Addr) << "\n");1152resolveRelocationList(Relocs, Addr);1153}1154}1155}1156ExternalSymbolRelocations.clear();1157}11581159Error RuntimeDyldImpl::resolveExternalSymbols() {1160StringMap<JITEvaluatedSymbol> ExternalSymbolMap;11611162// Resolution can trigger emission of more symbols, so iterate until1163// we've resolved *everything*.1164{1165JITSymbolResolver::LookupSet ResolvedSymbols;11661167while (true) {1168JITSymbolResolver::LookupSet NewSymbols;11691170for (auto &RelocKV : ExternalSymbolRelocations) {1171StringRef Name = RelocKV.first();1172if (!Name.empty() && !GlobalSymbolTable.count(Name) &&1173!ResolvedSymbols.count(Name))1174NewSymbols.insert(Name);1175}11761177if (NewSymbols.empty())1178break;11791180#ifdef _MSC_VER1181using ExpectedLookupResult =1182MSVCPExpected<JITSymbolResolver::LookupResult>;1183#else1184using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;1185#endif11861187auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();1188auto NewSymbolsF = NewSymbolsP->get_future();1189Resolver.lookup(NewSymbols,1190[=](Expected<JITSymbolResolver::LookupResult> Result) {1191NewSymbolsP->set_value(std::move(Result));1192});11931194auto NewResolverResults = NewSymbolsF.get();11951196if (!NewResolverResults)1197return NewResolverResults.takeError();11981199assert(NewResolverResults->size() == NewSymbols.size() &&1200"Should have errored on unresolved symbols");12011202for (auto &RRKV : *NewResolverResults) {1203assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");1204ExternalSymbolMap.insert(RRKV);1205ResolvedSymbols.insert(RRKV.first);1206}1207}1208}12091210applyExternalSymbolRelocations(ExternalSymbolMap);12111212return Error::success();1213}12141215void RuntimeDyldImpl::finalizeAsync(1216std::unique_ptr<RuntimeDyldImpl> This,1217unique_function<void(object::OwningBinary<object::ObjectFile>,1218std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>1219OnEmitted,1220object::OwningBinary<object::ObjectFile> O,1221std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info) {12221223auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));1224auto PostResolveContinuation =1225[SharedThis, OnEmitted = std::move(OnEmitted), O = std::move(O),1226Info = std::move(Info)](1227Expected<JITSymbolResolver::LookupResult> Result) mutable {1228if (!Result) {1229OnEmitted(std::move(O), std::move(Info), Result.takeError());1230return;1231}12321233/// Copy the result into a StringMap, where the keys are held by value.1234StringMap<JITEvaluatedSymbol> Resolved;1235for (auto &KV : *Result)1236Resolved[KV.first] = KV.second;12371238SharedThis->applyExternalSymbolRelocations(Resolved);1239SharedThis->resolveLocalRelocations();1240SharedThis->registerEHFrames();1241std::string ErrMsg;1242if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))1243OnEmitted(std::move(O), std::move(Info),1244make_error<StringError>(std::move(ErrMsg),1245inconvertibleErrorCode()));1246else1247OnEmitted(std::move(O), std::move(Info), Error::success());1248};12491250JITSymbolResolver::LookupSet Symbols;12511252for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {1253StringRef Name = RelocKV.first();1254if (Name.empty()) // Skip absolute symbol relocations.1255continue;1256assert(!SharedThis->GlobalSymbolTable.count(Name) &&1257"Name already processed. RuntimeDyld instances can not be re-used "1258"when finalizing with finalizeAsync.");1259Symbols.insert(Name);1260}12611262if (!Symbols.empty()) {1263SharedThis->Resolver.lookup(Symbols, std::move(PostResolveContinuation));1264} else1265PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());1266}12671268//===----------------------------------------------------------------------===//1269// RuntimeDyld class implementation12701271uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(1272const object::SectionRef &Sec) const {12731274auto I = ObjSecToIDMap.find(Sec);1275if (I != ObjSecToIDMap.end())1276return RTDyld.Sections[I->second].getLoadAddress();12771278return 0;1279}12801281RuntimeDyld::MemoryManager::TLSSection1282RuntimeDyld::MemoryManager::allocateTLSSection(uintptr_t Size,1283unsigned Alignment,1284unsigned SectionID,1285StringRef SectionName) {1286report_fatal_error("allocation of TLS not implemented");1287}12881289void RuntimeDyld::MemoryManager::anchor() {}1290void JITSymbolResolver::anchor() {}1291void LegacyJITSymbolResolver::anchor() {}12921293RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,1294JITSymbolResolver &Resolver)1295: MemMgr(MemMgr), Resolver(Resolver) {1296// FIXME: There's a potential issue lurking here if a single instance of1297// RuntimeDyld is used to load multiple objects. The current implementation1298// associates a single memory manager with a RuntimeDyld instance. Even1299// though the public class spawns a new 'impl' instance for each load,1300// they share a single memory manager. This can become a problem when page1301// permissions are applied.1302Dyld = nullptr;1303ProcessAllSections = false;1304}13051306RuntimeDyld::~RuntimeDyld() = default;13071308static std::unique_ptr<RuntimeDyldCOFF>1309createRuntimeDyldCOFF(1310Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,1311JITSymbolResolver &Resolver, bool ProcessAllSections,1312RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {1313std::unique_ptr<RuntimeDyldCOFF> Dyld =1314RuntimeDyldCOFF::create(Arch, MM, Resolver);1315Dyld->setProcessAllSections(ProcessAllSections);1316Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));1317return Dyld;1318}13191320static std::unique_ptr<RuntimeDyldELF>1321createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,1322JITSymbolResolver &Resolver, bool ProcessAllSections,1323RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {1324std::unique_ptr<RuntimeDyldELF> Dyld =1325RuntimeDyldELF::create(Arch, MM, Resolver);1326Dyld->setProcessAllSections(ProcessAllSections);1327Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));1328return Dyld;1329}13301331static std::unique_ptr<RuntimeDyldMachO>1332createRuntimeDyldMachO(1333Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,1334JITSymbolResolver &Resolver,1335bool ProcessAllSections,1336RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {1337std::unique_ptr<RuntimeDyldMachO> Dyld =1338RuntimeDyldMachO::create(Arch, MM, Resolver);1339Dyld->setProcessAllSections(ProcessAllSections);1340Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));1341return Dyld;1342}13431344std::unique_ptr<RuntimeDyld::LoadedObjectInfo>1345RuntimeDyld::loadObject(const ObjectFile &Obj) {1346if (!Dyld) {1347if (Obj.isELF())1348Dyld =1349createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),1350MemMgr, Resolver, ProcessAllSections,1351std::move(NotifyStubEmitted));1352else if (Obj.isMachO())1353Dyld = createRuntimeDyldMachO(1354static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,1355ProcessAllSections, std::move(NotifyStubEmitted));1356else if (Obj.isCOFF())1357Dyld = createRuntimeDyldCOFF(1358static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,1359ProcessAllSections, std::move(NotifyStubEmitted));1360else1361report_fatal_error("Incompatible object format!");1362}13631364if (!Dyld->isCompatibleFile(Obj))1365report_fatal_error("Incompatible object format!");13661367auto LoadedObjInfo = Dyld->loadObject(Obj);1368MemMgr.notifyObjectLoaded(*this, Obj);1369return LoadedObjInfo;1370}13711372void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {1373if (!Dyld)1374return nullptr;1375return Dyld->getSymbolLocalAddress(Name);1376}13771378unsigned RuntimeDyld::getSymbolSectionID(StringRef Name) const {1379assert(Dyld && "No RuntimeDyld instance attached");1380return Dyld->getSymbolSectionID(Name);1381}13821383JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {1384if (!Dyld)1385return nullptr;1386return Dyld->getSymbol(Name);1387}13881389std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {1390if (!Dyld)1391return std::map<StringRef, JITEvaluatedSymbol>();1392return Dyld->getSymbolTable();1393}13941395void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }13961397void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {1398Dyld->reassignSectionAddress(SectionID, Addr);1399}14001401void RuntimeDyld::mapSectionAddress(const void *LocalAddress,1402uint64_t TargetAddress) {1403Dyld->mapSectionAddress(LocalAddress, TargetAddress);1404}14051406bool RuntimeDyld::hasError() { return Dyld->hasError(); }14071408StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }14091410void RuntimeDyld::finalizeWithMemoryManagerLocking() {1411bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;1412MemMgr.FinalizationLocked = true;1413resolveRelocations();1414registerEHFrames();1415if (!MemoryFinalizationLocked) {1416MemMgr.finalizeMemory();1417MemMgr.FinalizationLocked = false;1418}1419}14201421StringRef RuntimeDyld::getSectionContent(unsigned SectionID) const {1422assert(Dyld && "No Dyld instance attached");1423return Dyld->getSectionContent(SectionID);1424}14251426uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {1427assert(Dyld && "No Dyld instance attached");1428return Dyld->getSectionLoadAddress(SectionID);1429}14301431void RuntimeDyld::registerEHFrames() {1432if (Dyld)1433Dyld->registerEHFrames();1434}14351436void RuntimeDyld::deregisterEHFrames() {1437if (Dyld)1438Dyld->deregisterEHFrames();1439}1440// FIXME: Kill this with fire once we have a new JIT linker: this is only here1441// so that we can re-use RuntimeDyld's implementation without twisting the1442// interface any further for ORC's purposes.1443void jitLinkForORC(1444object::OwningBinary<object::ObjectFile> O,1445RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,1446bool ProcessAllSections,1447unique_function<Error(const object::ObjectFile &Obj,1448RuntimeDyld::LoadedObjectInfo &LoadedObj,1449std::map<StringRef, JITEvaluatedSymbol>)>1450OnLoaded,1451unique_function<void(object::OwningBinary<object::ObjectFile>,1452std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>1453OnEmitted) {14541455RuntimeDyld RTDyld(MemMgr, Resolver);1456RTDyld.setProcessAllSections(ProcessAllSections);14571458auto Info = RTDyld.loadObject(*O.getBinary());14591460if (RTDyld.hasError()) {1461OnEmitted(std::move(O), std::move(Info),1462make_error<StringError>(RTDyld.getErrorString(),1463inconvertibleErrorCode()));1464return;1465}14661467if (auto Err = OnLoaded(*O.getBinary(), *Info, RTDyld.getSymbolTable())) {1468OnEmitted(std::move(O), std::move(Info), std::move(Err));1469return;1470}14711472RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),1473std::move(O), std::move(Info));1474}14751476} // end namespace llvm147714781479