Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_x86_64.cpp
35271 views
//===---- ELF_x86_64.cpp -JIT linker implementation for ELF/x86-64 ----===//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// ELF/x86-64 jit-link implementation.9//10//===----------------------------------------------------------------------===//1112#include "llvm/ExecutionEngine/JITLink/ELF_x86_64.h"13#include "llvm/ExecutionEngine/JITLink/DWARFRecordSectionSplitter.h"14#include "llvm/ExecutionEngine/JITLink/JITLink.h"15#include "llvm/ExecutionEngine/JITLink/TableManager.h"16#include "llvm/ExecutionEngine/JITLink/x86_64.h"17#include "llvm/Object/ELFObjectFile.h"1819#include "DefineExternalSectionStartAndEndSymbols.h"20#include "EHFrameSupportImpl.h"21#include "ELFLinkGraphBuilder.h"22#include "JITLinkGeneric.h"2324#define DEBUG_TYPE "jitlink"2526using namespace llvm;27using namespace llvm::jitlink;2829namespace {3031constexpr StringRef ELFGOTSymbolName = "_GLOBAL_OFFSET_TABLE_";32constexpr StringRef ELFTLSInfoSectionName = "$__TLSINFO";3334class TLSInfoTableManager_ELF_x86_6435: public TableManager<TLSInfoTableManager_ELF_x86_64> {36public:37static const uint8_t TLSInfoEntryContent[16];3839static StringRef getSectionName() { return ELFTLSInfoSectionName; }4041bool visitEdge(LinkGraph &G, Block *B, Edge &E) {42if (E.getKind() == x86_64::RequestTLSDescInGOTAndTransformToDelta32) {43LLVM_DEBUG({44dbgs() << " Fixing " << G.getEdgeKindName(E.getKind()) << " edge at "45<< formatv("{0:x}", B->getFixupAddress(E)) << " ("46<< formatv("{0:x}", B->getAddress()) << " + "47<< formatv("{0:x}", E.getOffset()) << ")\n";48});49E.setKind(x86_64::Delta32);50E.setTarget(getEntryForTarget(G, E.getTarget()));51return true;52}53return false;54}5556Symbol &createEntry(LinkGraph &G, Symbol &Target) {57// the TLS Info entry's key value will be written by the fixTLVSectionByName58// pass, so create mutable content.59auto &TLSInfoEntry = G.createMutableContentBlock(60getTLSInfoSection(G), G.allocateContent(getTLSInfoEntryContent()),61orc::ExecutorAddr(), 8, 0);62TLSInfoEntry.addEdge(x86_64::Pointer64, 8, Target, 0);63return G.addAnonymousSymbol(TLSInfoEntry, 0, 16, false, false);64}6566private:67Section &getTLSInfoSection(LinkGraph &G) {68if (!TLSInfoTable)69TLSInfoTable =70&G.createSection(ELFTLSInfoSectionName, orc::MemProt::Read);71return *TLSInfoTable;72}7374ArrayRef<char> getTLSInfoEntryContent() const {75return {reinterpret_cast<const char *>(TLSInfoEntryContent),76sizeof(TLSInfoEntryContent)};77}7879Section *TLSInfoTable = nullptr;80};8182const uint8_t TLSInfoTableManager_ELF_x86_64::TLSInfoEntryContent[16] = {830x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*pthread key */840x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*data address*/85};8687Error buildTables_ELF_x86_64(LinkGraph &G) {88LLVM_DEBUG(dbgs() << "Visiting edges in graph:\n");8990x86_64::GOTTableManager GOT;91x86_64::PLTTableManager PLT(GOT);92TLSInfoTableManager_ELF_x86_64 TLSInfo;93visitExistingEdges(G, GOT, PLT, TLSInfo);94return Error::success();95}96} // namespace9798namespace llvm {99namespace jitlink {100101class ELFLinkGraphBuilder_x86_64 : public ELFLinkGraphBuilder<object::ELF64LE> {102private:103using ELFT = object::ELF64LE;104105Error addRelocations() override {106LLVM_DEBUG(dbgs() << "Processing relocations:\n");107108using Base = ELFLinkGraphBuilder<ELFT>;109using Self = ELFLinkGraphBuilder_x86_64;110for (const auto &RelSect : Base::Sections) {111// Validate the section to read relocation entries from.112if (RelSect.sh_type == ELF::SHT_REL)113return make_error<StringError>(114"No SHT_REL in valid x64 ELF object files",115inconvertibleErrorCode());116117if (Error Err = Base::forEachRelaRelocation(RelSect, this,118&Self::addSingleRelocation))119return Err;120}121122return Error::success();123}124125Error addSingleRelocation(const typename ELFT::Rela &Rel,126const typename ELFT::Shdr &FixupSection,127Block &BlockToFix) {128using Base = ELFLinkGraphBuilder<ELFT>;129130auto ELFReloc = Rel.getType(false);131132// R_X86_64_NONE is a no-op.133if (LLVM_UNLIKELY(ELFReloc == ELF::R_X86_64_NONE))134return Error::success();135136uint32_t SymbolIndex = Rel.getSymbol(false);137auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);138if (!ObjSymbol)139return ObjSymbol.takeError();140141Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);142if (!GraphSymbol)143return make_error<StringError>(144formatv("Could not find symbol at given index, did you add it to "145"JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",146SymbolIndex, (*ObjSymbol)->st_shndx,147Base::GraphSymbols.size()),148inconvertibleErrorCode());149150// Validate the relocation kind.151int64_t Addend = Rel.r_addend;152Edge::Kind Kind = Edge::Invalid;153154switch (ELFReloc) {155case ELF::R_X86_64_PC8:156Kind = x86_64::Delta8;157break;158case ELF::R_X86_64_PC32:159case ELF::R_X86_64_GOTPC32:160Kind = x86_64::Delta32;161break;162case ELF::R_X86_64_PC64:163case ELF::R_X86_64_GOTPC64:164Kind = x86_64::Delta64;165break;166case ELF::R_X86_64_32:167Kind = x86_64::Pointer32;168break;169case ELF::R_X86_64_16:170Kind = x86_64::Pointer16;171break;172case ELF::R_X86_64_8:173Kind = x86_64::Pointer8;174break;175case ELF::R_X86_64_32S:176Kind = x86_64::Pointer32Signed;177break;178case ELF::R_X86_64_64:179Kind = x86_64::Pointer64;180break;181case ELF::R_X86_64_GOTPCREL:182Kind = x86_64::RequestGOTAndTransformToDelta32;183break;184case ELF::R_X86_64_REX_GOTPCRELX:185Kind = x86_64::RequestGOTAndTransformToPCRel32GOTLoadREXRelaxable;186Addend = 0;187break;188case ELF::R_X86_64_TLSGD:189Kind = x86_64::RequestTLSDescInGOTAndTransformToDelta32;190break;191case ELF::R_X86_64_GOTPCRELX:192Kind = x86_64::RequestGOTAndTransformToPCRel32GOTLoadRelaxable;193Addend = 0;194break;195case ELF::R_X86_64_GOTPCREL64:196Kind = x86_64::RequestGOTAndTransformToDelta64;197break;198case ELF::R_X86_64_GOT64:199Kind = x86_64::RequestGOTAndTransformToDelta64FromGOT;200break;201case ELF::R_X86_64_GOTOFF64:202Kind = x86_64::Delta64FromGOT;203break;204case ELF::R_X86_64_PLT32:205Kind = x86_64::BranchPCRel32;206// BranchPCRel32 implicitly handles the '-4' PC adjustment, so we have to207// adjust the addend by '+4' to compensate.208Addend += 4;209break;210default:211return make_error<JITLinkError>(212"In " + G->getName() + ": Unsupported x86-64 relocation type " +213object::getELFRelocationTypeName(ELF::EM_X86_64, ELFReloc));214}215216auto FixupAddress = orc::ExecutorAddr(FixupSection.sh_addr) + Rel.r_offset;217Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();218Edge GE(Kind, Offset, *GraphSymbol, Addend);219LLVM_DEBUG({220dbgs() << " ";221printEdge(dbgs(), BlockToFix, GE, x86_64::getEdgeKindName(Kind));222dbgs() << "\n";223});224225BlockToFix.addEdge(std::move(GE));226return Error::success();227}228229public:230ELFLinkGraphBuilder_x86_64(StringRef FileName,231const object::ELFFile<object::ELF64LE> &Obj,232SubtargetFeatures Features)233: ELFLinkGraphBuilder(Obj, Triple("x86_64-unknown-linux"),234std::move(Features), FileName,235x86_64::getEdgeKindName) {}236};237238class ELFJITLinker_x86_64 : public JITLinker<ELFJITLinker_x86_64> {239friend class JITLinker<ELFJITLinker_x86_64>;240241public:242ELFJITLinker_x86_64(std::unique_ptr<JITLinkContext> Ctx,243std::unique_ptr<LinkGraph> G,244PassConfiguration PassConfig)245: JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {246247if (shouldAddDefaultTargetPasses(getGraph().getTargetTriple()))248getPassConfig().PostAllocationPasses.push_back(249[this](LinkGraph &G) { return getOrCreateGOTSymbol(G); });250}251252private:253Symbol *GOTSymbol = nullptr;254255Error getOrCreateGOTSymbol(LinkGraph &G) {256auto DefineExternalGOTSymbolIfPresent =257createDefineExternalSectionStartAndEndSymbolsPass(258[&](LinkGraph &LG, Symbol &Sym) -> SectionRangeSymbolDesc {259if (Sym.getName() == ELFGOTSymbolName)260if (auto *GOTSection = G.findSectionByName(261x86_64::GOTTableManager::getSectionName())) {262GOTSymbol = &Sym;263return {*GOTSection, true};264}265return {};266});267268// Try to attach _GLOBAL_OFFSET_TABLE_ to the GOT if it's defined as an269// external.270if (auto Err = DefineExternalGOTSymbolIfPresent(G))271return Err;272273// If we succeeded then we're done.274if (GOTSymbol)275return Error::success();276277// Otherwise look for a GOT section: If it already has a start symbol we'll278// record it, otherwise we'll create our own.279// If there's a GOT section but we didn't find an external GOT symbol...280if (auto *GOTSection =281G.findSectionByName(x86_64::GOTTableManager::getSectionName())) {282283// Check for an existing defined symbol.284for (auto *Sym : GOTSection->symbols())285if (Sym->getName() == ELFGOTSymbolName) {286GOTSymbol = Sym;287return Error::success();288}289290// If there's no defined symbol then create one.291SectionRange SR(*GOTSection);292if (SR.empty())293GOTSymbol =294&G.addAbsoluteSymbol(ELFGOTSymbolName, orc::ExecutorAddr(), 0,295Linkage::Strong, Scope::Local, true);296else297GOTSymbol =298&G.addDefinedSymbol(*SR.getFirstBlock(), 0, ELFGOTSymbolName, 0,299Linkage::Strong, Scope::Local, false, true);300}301302// If we still haven't found a GOT symbol then double check the externals.303// We may have a GOT-relative reference but no GOT section, in which case304// we just need to point the GOT symbol at some address in this graph.305if (!GOTSymbol) {306for (auto *Sym : G.external_symbols()) {307if (Sym->getName() == ELFGOTSymbolName) {308auto Blocks = G.blocks();309if (!Blocks.empty()) {310G.makeAbsolute(*Sym, (*Blocks.begin())->getAddress());311GOTSymbol = Sym;312break;313}314}315}316}317318return Error::success();319}320321Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {322return x86_64::applyFixup(G, B, E, GOTSymbol);323}324};325326Expected<std::unique_ptr<LinkGraph>>327createLinkGraphFromELFObject_x86_64(MemoryBufferRef ObjectBuffer) {328LLVM_DEBUG({329dbgs() << "Building jitlink graph for new input "330<< ObjectBuffer.getBufferIdentifier() << "...\n";331});332333auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);334if (!ELFObj)335return ELFObj.takeError();336337auto Features = (*ELFObj)->getFeatures();338if (!Features)339return Features.takeError();340341auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF64LE>>(**ELFObj);342return ELFLinkGraphBuilder_x86_64((*ELFObj)->getFileName(),343ELFObjFile.getELFFile(),344std::move(*Features))345.buildGraph();346}347348void link_ELF_x86_64(std::unique_ptr<LinkGraph> G,349std::unique_ptr<JITLinkContext> Ctx) {350PassConfiguration Config;351352if (Ctx->shouldAddDefaultTargetPasses(G->getTargetTriple())) {353354Config.PrePrunePasses.push_back(DWARFRecordSectionSplitter(".eh_frame"));355Config.PrePrunePasses.push_back(EHFrameEdgeFixer(356".eh_frame", x86_64::PointerSize, x86_64::Pointer32, x86_64::Pointer64,357x86_64::Delta32, x86_64::Delta64, x86_64::NegDelta32));358Config.PrePrunePasses.push_back(EHFrameNullTerminator(".eh_frame"));359360// Construct a JITLinker and run the link function.361// Add a mark-live pass.362if (auto MarkLive = Ctx->getMarkLivePass(G->getTargetTriple()))363Config.PrePrunePasses.push_back(std::move(MarkLive));364else365Config.PrePrunePasses.push_back(markAllSymbolsLive);366367// Add an in-place GOT/Stubs/TLSInfoEntry build pass.368Config.PostPrunePasses.push_back(buildTables_ELF_x86_64);369370// Resolve any external section start / end symbols.371Config.PostAllocationPasses.push_back(372createDefineExternalSectionStartAndEndSymbolsPass(373identifyELFSectionStartAndEndSymbols));374375// Add GOT/Stubs optimizer pass.376Config.PreFixupPasses.push_back(x86_64::optimizeGOTAndStubAccesses);377}378379if (auto Err = Ctx->modifyPassConfig(*G, Config))380return Ctx->notifyFailed(std::move(Err));381382ELFJITLinker_x86_64::link(std::move(Ctx), std::move(G), std::move(Config));383}384} // end namespace jitlink385} // end namespace llvm386387388