Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_ppc64.cpp
35271 views
//===------- ELF_ppc64.cpp -JIT linker implementation for ELF/ppc64 -------===//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/ppc64 jit-link implementation.9//10//===----------------------------------------------------------------------===//1112#include "llvm/ExecutionEngine/JITLink/ELF_ppc64.h"13#include "llvm/ExecutionEngine/JITLink/DWARFRecordSectionSplitter.h"14#include "llvm/ExecutionEngine/JITLink/TableManager.h"15#include "llvm/ExecutionEngine/JITLink/ppc64.h"16#include "llvm/Object/ELFObjectFile.h"1718#include "EHFrameSupportImpl.h"19#include "ELFLinkGraphBuilder.h"20#include "JITLinkGeneric.h"2122#define DEBUG_TYPE "jitlink"2324namespace {2526using namespace llvm;27using namespace llvm::jitlink;2829constexpr StringRef ELFTOCSymbolName = ".TOC.";30constexpr StringRef TOCSymbolAliasIdent = "__TOC__";31constexpr uint64_t ELFTOCBaseOffset = 0x8000;32constexpr StringRef ELFTLSInfoSectionName = "$__TLSINFO";3334template <llvm::endianness Endianness>35class TLSInfoTableManager_ELF_ppc6436: public TableManager<TLSInfoTableManager_ELF_ppc64<Endianness>> {37public:38static const uint8_t TLSInfoEntryContent[16];3940static StringRef getSectionName() { return ELFTLSInfoSectionName; }4142bool visitEdge(LinkGraph &G, Block *B, Edge &E) {43Edge::Kind K = E.getKind();44switch (K) {45case ppc64::RequestTLSDescInGOTAndTransformToTOCDelta16HA:46E.setKind(ppc64::TOCDelta16HA);47E.setTarget(this->getEntryForTarget(G, E.getTarget()));48return true;49case ppc64::RequestTLSDescInGOTAndTransformToTOCDelta16LO:50E.setKind(ppc64::TOCDelta16LO);51E.setTarget(this->getEntryForTarget(G, E.getTarget()));52return true;53case ppc64::RequestTLSDescInGOTAndTransformToDelta34:54E.setKind(ppc64::Delta34);55E.setTarget(this->getEntryForTarget(G, E.getTarget()));56return true;57default:58return false;59}60}6162Symbol &createEntry(LinkGraph &G, Symbol &Target) {63// The TLS Info entry's key value will be written by64// `fixTLVSectionsAndEdges`, so create mutable content.65auto &TLSInfoEntry = G.createMutableContentBlock(66getTLSInfoSection(G), G.allocateContent(getTLSInfoEntryContent()),67orc::ExecutorAddr(), 8, 0);68TLSInfoEntry.addEdge(ppc64::Pointer64, 8, Target, 0);69return G.addAnonymousSymbol(TLSInfoEntry, 0, 16, false, false);70}7172private:73Section &getTLSInfoSection(LinkGraph &G) {74if (!TLSInfoTable)75TLSInfoTable =76&G.createSection(ELFTLSInfoSectionName, orc::MemProt::Read);77return *TLSInfoTable;78}7980ArrayRef<char> getTLSInfoEntryContent() const {81return {reinterpret_cast<const char *>(TLSInfoEntryContent),82sizeof(TLSInfoEntryContent)};83}8485Section *TLSInfoTable = nullptr;86};8788template <>89const uint8_t TLSInfoTableManager_ELF_ppc64<90llvm::endianness::little>::TLSInfoEntryContent[16] = {910x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*pthread key */920x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*data address*/93};9495template <>96const uint8_t TLSInfoTableManager_ELF_ppc64<97llvm::endianness::big>::TLSInfoEntryContent[16] = {980x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /*pthread key */990x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /*data address*/100};101102template <llvm::endianness Endianness>103Symbol &createELFGOTHeader(LinkGraph &G,104ppc64::TOCTableManager<Endianness> &TOC) {105Symbol *TOCSymbol = nullptr;106107for (Symbol *Sym : G.defined_symbols())108if (LLVM_UNLIKELY(Sym->getName() == ELFTOCSymbolName)) {109TOCSymbol = Sym;110break;111}112113if (LLVM_LIKELY(TOCSymbol == nullptr)) {114for (Symbol *Sym : G.external_symbols())115if (Sym->getName() == ELFTOCSymbolName) {116TOCSymbol = Sym;117break;118}119}120121if (!TOCSymbol)122TOCSymbol = &G.addExternalSymbol(ELFTOCSymbolName, 0, false);123124return TOC.getEntryForTarget(G, *TOCSymbol);125}126127// Register preexisting GOT entries with TOC table manager.128template <llvm::endianness Endianness>129inline void130registerExistingGOTEntries(LinkGraph &G,131ppc64::TOCTableManager<Endianness> &TOC) {132auto isGOTEntry = [](const Edge &E) {133return E.getKind() == ppc64::Pointer64 && E.getTarget().isExternal();134};135if (Section *dotTOCSection = G.findSectionByName(".toc")) {136for (Block *B : dotTOCSection->blocks())137for (Edge &E : B->edges())138if (isGOTEntry(E))139TOC.registerPreExistingEntry(E.getTarget(),140G.addAnonymousSymbol(*B, E.getOffset(),141G.getPointerSize(),142false, false));143}144}145146template <llvm::endianness Endianness>147Error buildTables_ELF_ppc64(LinkGraph &G) {148LLVM_DEBUG(dbgs() << "Visiting edges in graph:\n");149ppc64::TOCTableManager<Endianness> TOC;150// Before visiting edges, we create a header containing the address of TOC151// base as ELFABIv2 suggests:152// > The GOT consists of an 8-byte header that contains the TOC base (the153// first TOC base when multiple TOCs are present), followed by an array of154// 8-byte addresses.155createELFGOTHeader(G, TOC);156157// There might be compiler-generated GOT entries in ELF relocatable file.158registerExistingGOTEntries(G, TOC);159160ppc64::PLTTableManager<Endianness> PLT(TOC);161TLSInfoTableManager_ELF_ppc64<Endianness> TLSInfo;162visitExistingEdges(G, TOC, PLT, TLSInfo);163164// After visiting edges in LinkGraph, we have GOT entries built in the165// synthesized section.166// Merge sections included in TOC into synthesized TOC section,167// thus TOC is compact and reducing chances of relocation168// overflow.169if (Section *TOCSection = G.findSectionByName(TOC.getSectionName())) {170// .got and .plt are not normally present in a relocatable object file171// because they are linker generated.172if (Section *gotSection = G.findSectionByName(".got"))173G.mergeSections(*TOCSection, *gotSection);174if (Section *tocSection = G.findSectionByName(".toc"))175G.mergeSections(*TOCSection, *tocSection);176if (Section *sdataSection = G.findSectionByName(".sdata"))177G.mergeSections(*TOCSection, *sdataSection);178if (Section *sbssSection = G.findSectionByName(".sbss"))179G.mergeSections(*TOCSection, *sbssSection);180// .tocbss no longer appears in ELFABIv2. Leave it here to be compatible181// with rtdyld.182if (Section *tocbssSection = G.findSectionByName(".tocbss"))183G.mergeSections(*TOCSection, *tocbssSection);184if (Section *pltSection = G.findSectionByName(".plt"))185G.mergeSections(*TOCSection, *pltSection);186}187188return Error::success();189}190191} // namespace192193namespace llvm::jitlink {194195template <llvm::endianness Endianness>196class ELFLinkGraphBuilder_ppc64197: public ELFLinkGraphBuilder<object::ELFType<Endianness, true>> {198private:199using ELFT = object::ELFType<Endianness, true>;200using Base = ELFLinkGraphBuilder<ELFT>;201202using Base::G; // Use LinkGraph pointer from base class.203204Error addRelocations() override {205LLVM_DEBUG(dbgs() << "Processing relocations:\n");206207using Self = ELFLinkGraphBuilder_ppc64<Endianness>;208for (const auto &RelSect : Base::Sections) {209// Validate the section to read relocation entries from.210if (RelSect.sh_type == ELF::SHT_REL)211return make_error<StringError>("No SHT_REL in valid " +212G->getTargetTriple().getArchName() +213" ELF object files",214inconvertibleErrorCode());215216if (Error Err = Base::forEachRelaRelocation(RelSect, this,217&Self::addSingleRelocation))218return Err;219}220221return Error::success();222}223224Error addSingleRelocation(const typename ELFT::Rela &Rel,225const typename ELFT::Shdr &FixupSection,226Block &BlockToFix) {227using Base = ELFLinkGraphBuilder<ELFT>;228auto ELFReloc = Rel.getType(false);229230// R_PPC64_NONE is a no-op.231if (LLVM_UNLIKELY(ELFReloc == ELF::R_PPC64_NONE))232return Error::success();233234// TLS model markers. We only support global-dynamic model now.235if (ELFReloc == ELF::R_PPC64_TLSGD)236return Error::success();237if (ELFReloc == ELF::R_PPC64_TLSLD)238return make_error<StringError>("Local-dynamic TLS model is not supported",239inconvertibleErrorCode());240241if (ELFReloc == ELF::R_PPC64_PCREL_OPT)242// TODO: Support PCREL optimization, now ignore it.243return Error::success();244245if (ELFReloc == ELF::R_PPC64_TPREL34)246return make_error<StringError>("Local-exec TLS model is not supported",247inconvertibleErrorCode());248249auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);250if (!ObjSymbol)251return ObjSymbol.takeError();252253uint32_t SymbolIndex = Rel.getSymbol(false);254Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);255if (!GraphSymbol)256return make_error<StringError>(257formatv("Could not find symbol at given index, did you add it to "258"JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",259SymbolIndex, (*ObjSymbol)->st_shndx,260Base::GraphSymbols.size()),261inconvertibleErrorCode());262263int64_t Addend = Rel.r_addend;264orc::ExecutorAddr FixupAddress =265orc::ExecutorAddr(FixupSection.sh_addr) + Rel.r_offset;266Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();267Edge::Kind Kind = Edge::Invalid;268269switch (ELFReloc) {270default:271return make_error<JITLinkError>(272"In " + G->getName() + ": Unsupported ppc64 relocation type " +273object::getELFRelocationTypeName(ELF::EM_PPC64, ELFReloc));274case ELF::R_PPC64_ADDR64:275Kind = ppc64::Pointer64;276break;277case ELF::R_PPC64_ADDR32:278Kind = ppc64::Pointer32;279break;280case ELF::R_PPC64_ADDR16:281Kind = ppc64::Pointer16;282break;283case ELF::R_PPC64_ADDR16_DS:284Kind = ppc64::Pointer16DS;285break;286case ELF::R_PPC64_ADDR16_HA:287Kind = ppc64::Pointer16HA;288break;289case ELF::R_PPC64_ADDR16_HI:290Kind = ppc64::Pointer16HI;291break;292case ELF::R_PPC64_ADDR16_HIGH:293Kind = ppc64::Pointer16HIGH;294break;295case ELF::R_PPC64_ADDR16_HIGHA:296Kind = ppc64::Pointer16HIGHA;297break;298case ELF::R_PPC64_ADDR16_HIGHER:299Kind = ppc64::Pointer16HIGHER;300break;301case ELF::R_PPC64_ADDR16_HIGHERA:302Kind = ppc64::Pointer16HIGHERA;303break;304case ELF::R_PPC64_ADDR16_HIGHEST:305Kind = ppc64::Pointer16HIGHEST;306break;307case ELF::R_PPC64_ADDR16_HIGHESTA:308Kind = ppc64::Pointer16HIGHESTA;309break;310case ELF::R_PPC64_ADDR16_LO:311Kind = ppc64::Pointer16LO;312break;313case ELF::R_PPC64_ADDR16_LO_DS:314Kind = ppc64::Pointer16LODS;315break;316case ELF::R_PPC64_ADDR14:317Kind = ppc64::Pointer14;318break;319case ELF::R_PPC64_TOC:320Kind = ppc64::TOC;321break;322case ELF::R_PPC64_TOC16:323Kind = ppc64::TOCDelta16;324break;325case ELF::R_PPC64_TOC16_HA:326Kind = ppc64::TOCDelta16HA;327break;328case ELF::R_PPC64_TOC16_HI:329Kind = ppc64::TOCDelta16HI;330break;331case ELF::R_PPC64_TOC16_DS:332Kind = ppc64::TOCDelta16DS;333break;334case ELF::R_PPC64_TOC16_LO:335Kind = ppc64::TOCDelta16LO;336break;337case ELF::R_PPC64_TOC16_LO_DS:338Kind = ppc64::TOCDelta16LODS;339break;340case ELF::R_PPC64_REL16:341Kind = ppc64::Delta16;342break;343case ELF::R_PPC64_REL16_HA:344Kind = ppc64::Delta16HA;345break;346case ELF::R_PPC64_REL16_HI:347Kind = ppc64::Delta16HI;348break;349case ELF::R_PPC64_REL16_LO:350Kind = ppc64::Delta16LO;351break;352case ELF::R_PPC64_REL32:353Kind = ppc64::Delta32;354break;355case ELF::R_PPC64_REL24_NOTOC:356Kind = ppc64::RequestCallNoTOC;357break;358case ELF::R_PPC64_REL24:359Kind = ppc64::RequestCall;360// Determining a target is external or not is deferred in PostPrunePass.361// We assume branching to local entry by default, since in PostPrunePass,362// we don't have any context to determine LocalEntryOffset. If it finally363// turns out to be an external call, we'll have a stub for the external364// target, the target of this edge will be the stub and its addend will be365// set 0.366Addend += ELF::decodePPC64LocalEntryOffset((*ObjSymbol)->st_other);367break;368case ELF::R_PPC64_REL64:369Kind = ppc64::Delta64;370break;371case ELF::R_PPC64_PCREL34:372Kind = ppc64::Delta34;373break;374case ELF::R_PPC64_GOT_PCREL34:375Kind = ppc64::RequestGOTAndTransformToDelta34;376break;377case ELF::R_PPC64_GOT_TLSGD16_HA:378Kind = ppc64::RequestTLSDescInGOTAndTransformToTOCDelta16HA;379break;380case ELF::R_PPC64_GOT_TLSGD16_LO:381Kind = ppc64::RequestTLSDescInGOTAndTransformToTOCDelta16LO;382break;383case ELF::R_PPC64_GOT_TLSGD_PCREL34:384Kind = ppc64::RequestTLSDescInGOTAndTransformToDelta34;385break;386}387388Edge GE(Kind, Offset, *GraphSymbol, Addend);389BlockToFix.addEdge(std::move(GE));390return Error::success();391}392393public:394ELFLinkGraphBuilder_ppc64(StringRef FileName,395const object::ELFFile<ELFT> &Obj, Triple TT,396SubtargetFeatures Features)397: ELFLinkGraphBuilder<ELFT>(Obj, std::move(TT), std::move(Features),398FileName, ppc64::getEdgeKindName) {}399};400401template <llvm::endianness Endianness>402class ELFJITLinker_ppc64 : public JITLinker<ELFJITLinker_ppc64<Endianness>> {403using JITLinkerBase = JITLinker<ELFJITLinker_ppc64<Endianness>>;404friend JITLinkerBase;405406public:407ELFJITLinker_ppc64(std::unique_ptr<JITLinkContext> Ctx,408std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)409: JITLinkerBase(std::move(Ctx), std::move(G), std::move(PassConfig)) {410JITLinkerBase::getPassConfig().PostAllocationPasses.push_back(411[this](LinkGraph &G) { return defineTOCBase(G); });412}413414private:415Symbol *TOCSymbol = nullptr;416417Error defineTOCBase(LinkGraph &G) {418for (Symbol *Sym : G.defined_symbols()) {419if (LLVM_UNLIKELY(Sym->getName() == ELFTOCSymbolName)) {420TOCSymbol = Sym;421return Error::success();422}423}424425assert(TOCSymbol == nullptr &&426"TOCSymbol should not be defined at this point");427428for (Symbol *Sym : G.external_symbols()) {429if (Sym->getName() == ELFTOCSymbolName) {430TOCSymbol = Sym;431break;432}433}434435if (Section *TOCSection = G.findSectionByName(436ppc64::TOCTableManager<Endianness>::getSectionName())) {437assert(!TOCSection->empty() && "TOC section should have reserved an "438"entry for containing the TOC base");439440SectionRange SR(*TOCSection);441orc::ExecutorAddr TOCBaseAddr(SR.getFirstBlock()->getAddress() +442ELFTOCBaseOffset);443assert(TOCSymbol && TOCSymbol->isExternal() &&444".TOC. should be a external symbol at this point");445G.makeAbsolute(*TOCSymbol, TOCBaseAddr);446// Create an alias of .TOC. so that rtdyld checker can recognize.447G.addAbsoluteSymbol(TOCSymbolAliasIdent, TOCSymbol->getAddress(),448TOCSymbol->getSize(), TOCSymbol->getLinkage(),449TOCSymbol->getScope(), TOCSymbol->isLive());450return Error::success();451}452453// If TOC section doesn't exist, which means no TOC relocation is found, we454// don't need a TOCSymbol.455return Error::success();456}457458Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {459return ppc64::applyFixup<Endianness>(G, B, E, TOCSymbol);460}461};462463template <llvm::endianness Endianness>464Expected<std::unique_ptr<LinkGraph>>465createLinkGraphFromELFObject_ppc64(MemoryBufferRef ObjectBuffer) {466LLVM_DEBUG({467dbgs() << "Building jitlink graph for new input "468<< ObjectBuffer.getBufferIdentifier() << "...\n";469});470471auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);472if (!ELFObj)473return ELFObj.takeError();474475auto Features = (*ELFObj)->getFeatures();476if (!Features)477return Features.takeError();478479using ELFT = object::ELFType<Endianness, true>;480auto &ELFObjFile = cast<object::ELFObjectFile<ELFT>>(**ELFObj);481return ELFLinkGraphBuilder_ppc64<Endianness>(482(*ELFObj)->getFileName(), ELFObjFile.getELFFile(),483(*ELFObj)->makeTriple(), std::move(*Features))484.buildGraph();485}486487template <llvm::endianness Endianness>488void link_ELF_ppc64(std::unique_ptr<LinkGraph> G,489std::unique_ptr<JITLinkContext> Ctx) {490PassConfiguration Config;491492if (Ctx->shouldAddDefaultTargetPasses(G->getTargetTriple())) {493// Construct a JITLinker and run the link function.494495// Add eh-frame passes.496Config.PrePrunePasses.push_back(DWARFRecordSectionSplitter(".eh_frame"));497Config.PrePrunePasses.push_back(EHFrameEdgeFixer(498".eh_frame", G->getPointerSize(), ppc64::Pointer32, ppc64::Pointer64,499ppc64::Delta32, ppc64::Delta64, ppc64::NegDelta32));500Config.PrePrunePasses.push_back(EHFrameNullTerminator(".eh_frame"));501502// Add a mark-live pass.503if (auto MarkLive = Ctx->getMarkLivePass(G->getTargetTriple()))504Config.PrePrunePasses.push_back(std::move(MarkLive));505else506Config.PrePrunePasses.push_back(markAllSymbolsLive);507}508509Config.PostPrunePasses.push_back(buildTables_ELF_ppc64<Endianness>);510511if (auto Err = Ctx->modifyPassConfig(*G, Config))512return Ctx->notifyFailed(std::move(Err));513514ELFJITLinker_ppc64<Endianness>::link(std::move(Ctx), std::move(G),515std::move(Config));516}517518Expected<std::unique_ptr<LinkGraph>>519createLinkGraphFromELFObject_ppc64(MemoryBufferRef ObjectBuffer) {520return createLinkGraphFromELFObject_ppc64<llvm::endianness::big>(521std::move(ObjectBuffer));522}523524Expected<std::unique_ptr<LinkGraph>>525createLinkGraphFromELFObject_ppc64le(MemoryBufferRef ObjectBuffer) {526return createLinkGraphFromELFObject_ppc64<llvm::endianness::little>(527std::move(ObjectBuffer));528}529530/// jit-link the given object buffer, which must be a ELF ppc64 object file.531void link_ELF_ppc64(std::unique_ptr<LinkGraph> G,532std::unique_ptr<JITLinkContext> Ctx) {533return link_ELF_ppc64<llvm::endianness::big>(std::move(G), std::move(Ctx));534}535536/// jit-link the given object buffer, which must be a ELF ppc64le object file.537void link_ELF_ppc64le(std::unique_ptr<LinkGraph> G,538std::unique_ptr<JITLinkContext> Ctx) {539return link_ELF_ppc64<llvm::endianness::little>(std::move(G), std::move(Ctx));540}541542} // end namespace llvm::jitlink543544545