Path: blob/main/contrib/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFX86_64.h
35294 views
//===-- RuntimeDyldCOFFX86_64.h --- COFF/X86_64 specific code ---*- 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// COFF x86_x64 support for MC-JIT runtime dynamic linker.9//10//===----------------------------------------------------------------------===//1112#ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDCOFF86_64_H13#define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDCOFF86_64_H1415#include "../RuntimeDyldCOFF.h"16#include "llvm/BinaryFormat/COFF.h"17#include "llvm/Object/COFF.h"1819#define DEBUG_TYPE "dyld"2021namespace llvm {2223class RuntimeDyldCOFFX86_64 : public RuntimeDyldCOFF {2425private:26// When a module is loaded we save the SectionID of the unwind27// sections in a table until we receive a request to register all28// unregisteredEH frame sections with the memory manager.29SmallVector<SID, 2> UnregisteredEHFrameSections;30SmallVector<SID, 2> RegisteredEHFrameSections;31uint64_t ImageBase;3233// Fake an __ImageBase pointer by returning the section with the lowest adress34uint64_t getImageBase() {35if (!ImageBase) {36ImageBase = std::numeric_limits<uint64_t>::max();37for (const SectionEntry &Section : Sections)38// The Sections list may contain sections that weren't loaded for39// whatever reason: they may be debug sections, and ProcessAllSections40// is false, or they may be sections that contain 0 bytes. If the41// section isn't loaded, the load address will be 0, and it should not42// be included in the ImageBase calculation.43if (Section.getLoadAddress() != 0)44ImageBase = std::min(ImageBase, Section.getLoadAddress());45}46return ImageBase;47}4849void write32BitOffset(uint8_t *Target, int64_t Addend, uint64_t Delta) {50uint64_t Result = Addend + Delta;51assert(Result <= UINT32_MAX && "Relocation overflow");52writeBytesUnaligned(Result, Target, 4);53}5455public:56RuntimeDyldCOFFX86_64(RuntimeDyld::MemoryManager &MM,57JITSymbolResolver &Resolver)58: RuntimeDyldCOFF(MM, Resolver, 8, COFF::IMAGE_REL_AMD64_ADDR64),59ImageBase(0) {}6061Align getStubAlignment() override { return Align(1); }6263// 2-byte jmp instruction + 32-bit relative address + 64-bit absolute jump64unsigned getMaxStubSize() const override { return 14; }6566// The target location for the relocation is described by RE.SectionID and67// RE.Offset. RE.SectionID can be used to find the SectionEntry. Each68// SectionEntry has three members describing its location.69// SectionEntry::Address is the address at which the section has been loaded70// into memory in the current (host) process. SectionEntry::LoadAddress is71// the address that the section will have in the target process.72// SectionEntry::ObjAddress is the address of the bits for this section in the73// original emitted object image (also in the current address space).74//75// Relocations will be applied as if the section were loaded at76// SectionEntry::LoadAddress, but they will be applied at an address based77// on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer78// to Target memory contents if they are required for value calculations.79//80// The Value parameter here is the load address of the symbol for the81// relocation to be applied. For relocations which refer to symbols in the82// current object Value will be the LoadAddress of the section in which83// the symbol resides (RE.Addend provides additional information about the84// symbol location). For external symbols, Value will be the address of the85// symbol in the target address space.86void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override {87const SectionEntry &Section = Sections[RE.SectionID];88uint8_t *Target = Section.getAddressWithOffset(RE.Offset);8990switch (RE.RelType) {9192case COFF::IMAGE_REL_AMD64_REL32:93case COFF::IMAGE_REL_AMD64_REL32_1:94case COFF::IMAGE_REL_AMD64_REL32_2:95case COFF::IMAGE_REL_AMD64_REL32_3:96case COFF::IMAGE_REL_AMD64_REL32_4:97case COFF::IMAGE_REL_AMD64_REL32_5: {98uint64_t FinalAddress = Section.getLoadAddressWithOffset(RE.Offset);99// Delta is the distance from the start of the reloc to the end of the100// instruction with the reloc.101uint64_t Delta = 4 + (RE.RelType - COFF::IMAGE_REL_AMD64_REL32);102Value -= FinalAddress + Delta;103uint64_t Result = Value + RE.Addend;104assert(((int64_t)Result <= INT32_MAX) && "Relocation overflow");105assert(((int64_t)Result >= INT32_MIN) && "Relocation underflow");106writeBytesUnaligned(Result, Target, 4);107break;108}109110case COFF::IMAGE_REL_AMD64_ADDR32NB: {111// ADDR32NB requires an offset less than 2GB from 'ImageBase'.112// The MemoryManager can make sure this is always true by forcing the113// memory layout to be: CodeSection < ReadOnlySection < ReadWriteSection.114const uint64_t ImageBase = getImageBase();115if (Value < ImageBase || ((Value - ImageBase) > UINT32_MAX))116report_fatal_error("IMAGE_REL_AMD64_ADDR32NB relocation requires an "117"ordered section layout");118else {119write32BitOffset(Target, RE.Addend, Value - ImageBase);120}121break;122}123124case COFF::IMAGE_REL_AMD64_ADDR64: {125writeBytesUnaligned(Value + RE.Addend, Target, 8);126break;127}128129case COFF::IMAGE_REL_AMD64_SECREL: {130assert(static_cast<int64_t>(RE.Addend) <= INT32_MAX && "Relocation overflow");131assert(static_cast<int64_t>(RE.Addend) >= INT32_MIN && "Relocation underflow");132writeBytesUnaligned(RE.Addend, Target, 4);133break;134}135136case COFF::IMAGE_REL_AMD64_SECTION: {137assert(static_cast<int16_t>(RE.SectionID) <= INT16_MAX && "Relocation overflow");138assert(static_cast<int16_t>(RE.SectionID) >= INT16_MIN && "Relocation underflow");139writeBytesUnaligned(RE.SectionID, Target, 2);140break;141}142143default:144llvm_unreachable("Relocation type not implemented yet!");145break;146}147}148149std::tuple<uint64_t, uint64_t, uint64_t>150generateRelocationStub(unsigned SectionID, StringRef TargetName,151uint64_t Offset, uint64_t RelType, uint64_t Addend,152StubMap &Stubs) {153uintptr_t StubOffset;154SectionEntry &Section = Sections[SectionID];155156RelocationValueRef OriginalRelValueRef;157OriginalRelValueRef.SectionID = SectionID;158OriginalRelValueRef.Offset = Offset;159OriginalRelValueRef.Addend = Addend;160OriginalRelValueRef.SymbolName = TargetName.data();161162auto Stub = Stubs.find(OriginalRelValueRef);163if (Stub == Stubs.end()) {164LLVM_DEBUG(dbgs() << " Create a new stub function for "165<< TargetName.data() << "\n");166167StubOffset = Section.getStubOffset();168Stubs[OriginalRelValueRef] = StubOffset;169createStubFunction(Section.getAddressWithOffset(StubOffset));170Section.advanceStubOffset(getMaxStubSize());171} else {172LLVM_DEBUG(dbgs() << " Stub function found for " << TargetName.data()173<< "\n");174StubOffset = Stub->second;175}176177// FIXME: If RelType == COFF::IMAGE_REL_AMD64_ADDR32NB we should be able178// to ignore the __ImageBase requirement and just forward to the stub179// directly as an offset of this section:180// write32BitOffset(Section.getAddressWithOffset(Offset), 0, StubOffset);181// .xdata exception handler's aren't having this though.182183// Resolve original relocation to stub function.184const RelocationEntry RE(SectionID, Offset, RelType, Addend);185resolveRelocation(RE, Section.getLoadAddressWithOffset(StubOffset));186187// adjust relocation info so resolution writes to the stub function188Addend = 0;189Offset = StubOffset + 6;190RelType = COFF::IMAGE_REL_AMD64_ADDR64;191192return std::make_tuple(Offset, RelType, Addend);193}194195Expected<object::relocation_iterator>196processRelocationRef(unsigned SectionID,197object::relocation_iterator RelI,198const object::ObjectFile &Obj,199ObjSectionToIDMap &ObjSectionToID,200StubMap &Stubs) override {201// If possible, find the symbol referred to in the relocation,202// and the section that contains it.203object::symbol_iterator Symbol = RelI->getSymbol();204if (Symbol == Obj.symbol_end())205report_fatal_error("Unknown symbol in relocation");206auto SectionOrError = Symbol->getSection();207if (!SectionOrError)208return SectionOrError.takeError();209object::section_iterator SecI = *SectionOrError;210// If there is no section, this must be an external reference.211bool IsExtern = SecI == Obj.section_end();212213// Determine the Addend used to adjust the relocation value.214uint64_t RelType = RelI->getType();215uint64_t Offset = RelI->getOffset();216uint64_t Addend = 0;217SectionEntry &Section = Sections[SectionID];218uintptr_t ObjTarget = Section.getObjAddress() + Offset;219220Expected<StringRef> TargetNameOrErr = Symbol->getName();221if (!TargetNameOrErr)222return TargetNameOrErr.takeError();223224StringRef TargetName = *TargetNameOrErr;225unsigned TargetSectionID = 0;226uint64_t TargetOffset = 0;227228if (TargetName.starts_with(getImportSymbolPrefix())) {229assert(IsExtern && "DLLImport not marked extern?");230TargetSectionID = SectionID;231TargetOffset = getDLLImportOffset(SectionID, Stubs, TargetName);232TargetName = StringRef();233IsExtern = false;234} else if (!IsExtern) {235if (auto TargetSectionIDOrErr =236findOrEmitSection(Obj, *SecI, SecI->isText(), ObjSectionToID))237TargetSectionID = *TargetSectionIDOrErr;238else239return TargetSectionIDOrErr.takeError();240TargetOffset = getSymbolOffset(*Symbol);241}242243switch (RelType) {244245case COFF::IMAGE_REL_AMD64_REL32:246case COFF::IMAGE_REL_AMD64_REL32_1:247case COFF::IMAGE_REL_AMD64_REL32_2:248case COFF::IMAGE_REL_AMD64_REL32_3:249case COFF::IMAGE_REL_AMD64_REL32_4:250case COFF::IMAGE_REL_AMD64_REL32_5:251case COFF::IMAGE_REL_AMD64_ADDR32NB: {252uint8_t *Displacement = (uint8_t *)ObjTarget;253Addend = readBytesUnaligned(Displacement, 4);254255if (IsExtern)256std::tie(Offset, RelType, Addend) = generateRelocationStub(257SectionID, TargetName, Offset, RelType, Addend, Stubs);258259break;260}261262case COFF::IMAGE_REL_AMD64_ADDR64: {263uint8_t *Displacement = (uint8_t *)ObjTarget;264Addend = readBytesUnaligned(Displacement, 8);265break;266}267268default:269break;270}271272LLVM_DEBUG(dbgs() << "\t\tIn Section " << SectionID << " Offset " << Offset273<< " RelType: " << RelType << " TargetName: "274<< TargetName << " Addend " << Addend << "\n");275276if (IsExtern) {277RelocationEntry RE(SectionID, Offset, RelType, Addend);278addRelocationForSymbol(RE, TargetName);279} else {280RelocationEntry RE(SectionID, Offset, RelType, TargetOffset + Addend);281addRelocationForSection(RE, TargetSectionID);282}283284return ++RelI;285}286287void registerEHFrames() override {288for (auto const &EHFrameSID : UnregisteredEHFrameSections) {289uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();290uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();291size_t EHFrameSize = Sections[EHFrameSID].getSize();292MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);293RegisteredEHFrameSections.push_back(EHFrameSID);294}295UnregisteredEHFrameSections.clear();296}297298Error finalizeLoad(const object::ObjectFile &Obj,299ObjSectionToIDMap &SectionMap) override {300// Look for and record the EH frame section IDs.301for (const auto &SectionPair : SectionMap) {302const object::SectionRef &Section = SectionPair.first;303Expected<StringRef> NameOrErr = Section.getName();304if (!NameOrErr)305return NameOrErr.takeError();306307// Note unwind info is stored in .pdata but often points to .xdata308// with an IMAGE_REL_AMD64_ADDR32NB relocation. Using a memory manager309// that keeps sections ordered in relation to __ImageBase is necessary.310if ((*NameOrErr) == ".pdata")311UnregisteredEHFrameSections.push_back(SectionPair.second);312}313return Error::success();314}315};316317} // end namespace llvm318319#undef DEBUG_TYPE320321#endif322323324