Path: blob/main/contrib/llvm-project/lld/ELF/Target.h
34870 views
//===- Target.h -------------------------------------------------*- 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//===----------------------------------------------------------------------===//78#ifndef LLD_ELF_TARGET_H9#define LLD_ELF_TARGET_H1011#include "Config.h"12#include "InputSection.h"13#include "lld/Common/ErrorHandler.h"14#include "llvm/ADT/StringExtras.h"15#include "llvm/Object/ELF.h"16#include "llvm/Object/ELFTypes.h"17#include "llvm/Support/Compiler.h"18#include "llvm/Support/MathExtras.h"19#include <array>2021namespace lld {22std::string toString(elf::RelType type);2324namespace elf {25class Defined;26class InputFile;27class Symbol;2829class TargetInfo {30public:31virtual uint32_t calcEFlags() const { return 0; }32virtual RelExpr getRelExpr(RelType type, const Symbol &s,33const uint8_t *loc) const = 0;34virtual RelType getDynRel(RelType type) const { return 0; }35virtual void writeGotPltHeader(uint8_t *buf) const {}36virtual void writeGotHeader(uint8_t *buf) const {}37virtual void writeGotPlt(uint8_t *buf, const Symbol &s) const {};38virtual void writeIgotPlt(uint8_t *buf, const Symbol &s) const {}39virtual int64_t getImplicitAddend(const uint8_t *buf, RelType type) const;40virtual int getTlsGdRelaxSkip(RelType type) const { return 1; }4142// If lazy binding is supported, the first entry of the PLT has code43// to call the dynamic linker to resolve PLT entries the first time44// they are called. This function writes that code.45virtual void writePltHeader(uint8_t *buf) const {}4647virtual void writePlt(uint8_t *buf, const Symbol &sym,48uint64_t pltEntryAddr) const {}49virtual void writeIplt(uint8_t *buf, const Symbol &sym,50uint64_t pltEntryAddr) const {51// All but PPC32 and PPC64 use the same format for .plt and .iplt entries.52writePlt(buf, sym, pltEntryAddr);53}54virtual void writeIBTPlt(uint8_t *buf, size_t numEntries) const {}55virtual void addPltHeaderSymbols(InputSection &isec) const {}56virtual void addPltSymbols(InputSection &isec, uint64_t off) const {}5758// Returns true if a relocation only uses the low bits of a value such that59// all those bits are in the same page. For example, if the relocation60// only uses the low 12 bits in a system with 4k pages. If this is true, the61// bits will always have the same value at runtime and we don't have to emit62// a dynamic relocation.63virtual bool usesOnlyLowPageBits(RelType type) const;6465// Decide whether a Thunk is needed for the relocation from File66// targeting S.67virtual bool needsThunk(RelExpr expr, RelType relocType,68const InputFile *file, uint64_t branchAddr,69const Symbol &s, int64_t a) const;7071// On systems with range extensions we place collections of Thunks at72// regular spacings that enable the majority of branches reach the Thunks.73// a value of 0 means range extension thunks are not supported.74virtual uint32_t getThunkSectionSpacing() const { return 0; }7576// The function with a prologue starting at Loc was compiled with77// -fsplit-stack and it calls a function compiled without. Adjust the prologue78// to do the right thing. See https://gcc.gnu.org/wiki/SplitStacks.79// The symbols st_other flags are needed on PowerPC64 for determining the80// offset to the split-stack prologue.81virtual bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,82uint8_t stOther) const;8384// Return true if we can reach dst from src with RelType type.85virtual bool inBranchRange(RelType type, uint64_t src,86uint64_t dst) const;8788virtual void relocate(uint8_t *loc, const Relocation &rel,89uint64_t val) const = 0;90void relocateNoSym(uint8_t *loc, RelType type, uint64_t val) const {91relocate(loc, Relocation{R_NONE, type, 0, 0, nullptr}, val);92}93virtual void relocateAlloc(InputSectionBase &sec, uint8_t *buf) const;9495// Do a linker relaxation pass and return true if we changed something.96virtual bool relaxOnce(int pass) const { return false; }97// Do finalize relaxation after collecting relaxation infos.98virtual void finalizeRelax(int passes) const {}99100virtual void applyJumpInstrMod(uint8_t *loc, JumpModType type,101JumpModType val) const {}102103virtual ~TargetInfo();104105// This deletes a jump insn at the end of the section if it is a fall thru to106// the next section. Further, if there is a conditional jump and a direct107// jump consecutively, it tries to flip the conditional jump to convert the108// direct jump into a fall thru and delete it. Returns true if a jump109// instruction can be deleted.110virtual bool deleteFallThruJmpInsn(InputSection &is, InputFile *file,111InputSection *nextIS) const {112return false;113}114115unsigned defaultCommonPageSize = 4096;116unsigned defaultMaxPageSize = 4096;117118uint64_t getImageBase() const;119120// True if _GLOBAL_OFFSET_TABLE_ is relative to .got.plt, false if .got.121bool gotBaseSymInGotPlt = false;122123static constexpr RelType noneRel = 0;124RelType copyRel;125RelType gotRel;126RelType pltRel;127RelType relativeRel;128RelType iRelativeRel;129RelType symbolicRel;130RelType tlsDescRel;131RelType tlsGotRel;132RelType tlsModuleIndexRel;133RelType tlsOffsetRel;134unsigned gotEntrySize = config->wordsize;135unsigned pltEntrySize;136unsigned pltHeaderSize;137unsigned ipltEntrySize;138139// At least on x86_64 positions 1 and 2 are used by the first plt entry140// to support lazy loading.141unsigned gotPltHeaderEntriesNum = 3;142143// On PPC ELF V2 abi, the first entry in the .got is the .TOC.144unsigned gotHeaderEntriesNum = 0;145146// On PPC ELF V2 abi, the dynamic section needs DT_PPC64_OPT (DT_LOPROC + 3)147// to be set to 0x2 if there can be multiple TOC's. Although we do not emit148// multiple TOC's, there can be a mix of TOC and NOTOC addressing which149// is functionally equivalent.150int ppc64DynamicSectionOpt = 0;151152bool needsThunks = false;153154// A 4-byte field corresponding to one or more trap instructions, used to pad155// executable OutputSections.156std::array<uint8_t, 4> trapInstr;157158// Stores the NOP instructions of different sizes for the target and is used159// to pad sections that are relaxed.160std::optional<std::vector<std::vector<uint8_t>>> nopInstrs;161162// If a target needs to rewrite calls to __morestack to instead call163// __morestack_non_split when a split-stack enabled caller calls a164// non-split-stack callee this will return true. Otherwise returns false.165bool needsMoreStackNonSplit = true;166167virtual RelExpr adjustTlsExpr(RelType type, RelExpr expr) const;168virtual RelExpr adjustGotPcExpr(RelType type, int64_t addend,169const uint8_t *loc) const;170171protected:172// On FreeBSD x86_64 the first page cannot be mmaped.173// On Linux this is controlled by vm.mmap_min_addr. At least on some x86_64174// installs this is set to 65536, so the first 15 pages cannot be used.175// Given that, the smallest value that can be used in here is 0x10000.176uint64_t defaultImageBase = 0x10000;177};178179TargetInfo *getAArch64TargetInfo();180TargetInfo *getAMDGPUTargetInfo();181TargetInfo *getARMTargetInfo();182TargetInfo *getAVRTargetInfo();183TargetInfo *getHexagonTargetInfo();184TargetInfo *getLoongArchTargetInfo();185TargetInfo *getMSP430TargetInfo();186TargetInfo *getPPC64TargetInfo();187TargetInfo *getPPCTargetInfo();188TargetInfo *getRISCVTargetInfo();189TargetInfo *getSPARCV9TargetInfo();190TargetInfo *getSystemZTargetInfo();191TargetInfo *getX86TargetInfo();192TargetInfo *getX86_64TargetInfo();193template <class ELFT> TargetInfo *getMipsTargetInfo();194195struct ErrorPlace {196InputSectionBase *isec;197std::string loc;198std::string srcLoc;199};200201// Returns input section and corresponding source string for the given location.202ErrorPlace getErrorPlace(const uint8_t *loc);203204static inline std::string getErrorLocation(const uint8_t *loc) {205return getErrorPlace(loc).loc;206}207208void processArmCmseSymbols();209210void writePPC32GlinkSection(uint8_t *buf, size_t numEntries);211212unsigned getPPCDFormOp(unsigned secondaryOp);213unsigned getPPCDSFormOp(unsigned secondaryOp);214215// In the PowerPC64 Elf V2 abi a function can have 2 entry points. The first216// is a global entry point (GEP) which typically is used to initialize the TOC217// pointer in general purpose register 2. The second is a local entry218// point (LEP) which bypasses the TOC pointer initialization code. The219// offset between GEP and LEP is encoded in a function's st_other flags.220// This function will return the offset (in bytes) from the global entry-point221// to the local entry-point.222unsigned getPPC64GlobalEntryToLocalEntryOffset(uint8_t stOther);223224// Write a prefixed instruction, which is a 4-byte prefix followed by a 4-byte225// instruction (regardless of endianness). Therefore, the prefix is always in226// lower memory than the instruction.227void writePrefixedInstruction(uint8_t *loc, uint64_t insn);228229void addPPC64SaveRestore();230uint64_t getPPC64TocBase();231uint64_t getAArch64Page(uint64_t expr);232template <typename ELFT> void writeARMCmseImportLib();233uint64_t getLoongArchPageDelta(uint64_t dest, uint64_t pc, RelType type);234void riscvFinalizeRelax(int passes);235void mergeRISCVAttributesSections();236void addArmInputSectionMappingSymbols();237void addArmSyntheticSectionMappingSymbol(Defined *);238void sortArmMappingSymbols();239void convertArmInstructionstoBE8(InputSection *sec, uint8_t *buf);240void createTaggedSymbols(const SmallVector<ELFFileBase *, 0> &files);241void initSymbolAnchors();242243LLVM_LIBRARY_VISIBILITY extern const TargetInfo *target;244TargetInfo *getTarget();245246template <class ELFT> bool isMipsPIC(const Defined *sym);247248void reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v,249int64_t min, uint64_t max);250void reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym,251const Twine &msg);252253// Make sure that V can be represented as an N bit signed integer.254inline void checkInt(uint8_t *loc, int64_t v, int n, const Relocation &rel) {255if (v != llvm::SignExtend64(v, n))256reportRangeError(loc, rel, Twine(v), llvm::minIntN(n), llvm::maxIntN(n));257}258259// Make sure that V can be represented as an N bit unsigned integer.260inline void checkUInt(uint8_t *loc, uint64_t v, int n, const Relocation &rel) {261if ((v >> n) != 0)262reportRangeError(loc, rel, Twine(v), 0, llvm::maxUIntN(n));263}264265// Make sure that V can be represented as an N bit signed or unsigned integer.266inline void checkIntUInt(uint8_t *loc, uint64_t v, int n,267const Relocation &rel) {268// For the error message we should cast V to a signed integer so that error269// messages show a small negative value rather than an extremely large one270if (v != (uint64_t)llvm::SignExtend64(v, n) && (v >> n) != 0)271reportRangeError(loc, rel, Twine((int64_t)v), llvm::minIntN(n),272llvm::maxUIntN(n));273}274275inline void checkAlignment(uint8_t *loc, uint64_t v, int n,276const Relocation &rel) {277if ((v & (n - 1)) != 0)278error(getErrorLocation(loc) + "improper alignment for relocation " +279lld::toString(rel.type) + ": 0x" + llvm::utohexstr(v) +280" is not aligned to " + Twine(n) + " bytes");281}282283// Endianness-aware read/write.284inline uint16_t read16(const void *p) {285return llvm::support::endian::read16(p, config->endianness);286}287288inline uint32_t read32(const void *p) {289return llvm::support::endian::read32(p, config->endianness);290}291292inline uint64_t read64(const void *p) {293return llvm::support::endian::read64(p, config->endianness);294}295296inline void write16(void *p, uint16_t v) {297llvm::support::endian::write16(p, v, config->endianness);298}299300inline void write32(void *p, uint32_t v) {301llvm::support::endian::write32(p, v, config->endianness);302}303304inline void write64(void *p, uint64_t v) {305llvm::support::endian::write64(p, v, config->endianness);306}307308// Overwrite a ULEB128 value and keep the original length.309inline uint64_t overwriteULEB128(uint8_t *bufLoc, uint64_t val) {310while (*bufLoc & 0x80) {311*bufLoc++ = 0x80 | (val & 0x7f);312val >>= 7;313}314*bufLoc = val;315return val;316}317} // namespace elf318} // namespace lld319320#ifdef __clang__321#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"322#endif323#define invokeELFT(f, ...) \324switch (config->ekind) { \325case lld::elf::ELF32LEKind: \326f<llvm::object::ELF32LE>(__VA_ARGS__); \327break; \328case lld::elf::ELF32BEKind: \329f<llvm::object::ELF32BE>(__VA_ARGS__); \330break; \331case lld::elf::ELF64LEKind: \332f<llvm::object::ELF64LE>(__VA_ARGS__); \333break; \334case lld::elf::ELF64BEKind: \335f<llvm::object::ELF64BE>(__VA_ARGS__); \336break; \337default: \338llvm_unreachable("unknown config->ekind"); \339}340341#endif342343344