brintos

brintos / llvm-project-archived public Read only

0
0
Text · 14.9 KiB · 8da0b5c Raw
368 lines · c
1//===- Target.h -------------------------------------------------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLD_ELF_TARGET_H10#define LLD_ELF_TARGET_H11 12#include "Config.h"13#include "InputSection.h"14#include "lld/Common/ErrorHandler.h"15#include "llvm/ADT/StringExtras.h"16#include "llvm/Object/ELF.h"17#include "llvm/Object/ELFTypes.h"18#include "llvm/Support/Compiler.h"19#include "llvm/Support/MathExtras.h"20#include <array>21 22namespace lld {23namespace elf {24class Defined;25class InputFile;26class Symbol;27template <class RelTy> struct Relocs;28 29std::string toStr(Ctx &, RelType type);30 31class TargetInfo {32public:33  TargetInfo(Ctx &ctx) : ctx(ctx) {}34  virtual uint32_t calcEFlags() const { return 0; }35  virtual RelExpr getRelExpr(RelType type, const Symbol &s,36                             const uint8_t *loc) const = 0;37  virtual RelType getDynRel(RelType type) const { return 0; }38  virtual void writeGotPltHeader(uint8_t *buf) const {}39  virtual void writeGotHeader(uint8_t *buf) const {}40  virtual void writeGotPlt(uint8_t *buf, const Symbol &s) const {};41  virtual void writeIgotPlt(uint8_t *buf, const Symbol &s) const {}42  virtual int64_t getImplicitAddend(const uint8_t *buf, RelType type) const;43  virtual int getTlsGdRelaxSkip(RelType type) const { return 1; }44 45  // If lazy binding is supported, the first entry of the PLT has code46  // to call the dynamic linker to resolve PLT entries the first time47  // they are called. This function writes that code.48  virtual void writePltHeader(uint8_t *buf) const {}49 50  virtual void writePlt(uint8_t *buf, const Symbol &sym,51                        uint64_t pltEntryAddr) const {}52  virtual void writeIplt(uint8_t *buf, const Symbol &sym,53                         uint64_t pltEntryAddr) const {54    // All but PPC32 and PPC64 use the same format for .plt and .iplt entries.55    writePlt(buf, sym, pltEntryAddr);56  }57  virtual void writeIBTPlt(uint8_t *buf, size_t numEntries) const {}58  virtual void addPltHeaderSymbols(InputSection &isec) const {}59  virtual void addPltSymbols(InputSection &isec, uint64_t off) const {}60 61  // Returns true if a relocation only uses the low bits of a value such that62  // all those bits are in the same page. For example, if the relocation63  // only uses the low 12 bits in a system with 4k pages. If this is true, the64  // bits will always have the same value at runtime and we don't have to emit65  // a dynamic relocation.66  virtual bool usesOnlyLowPageBits(RelType type) const;67 68  // Decide whether a Thunk is needed for the relocation from File69  // targeting S.70  virtual bool needsThunk(RelExpr expr, RelType relocType,71                          const InputFile *file, uint64_t branchAddr,72                          const Symbol &s, int64_t a) const;73 74  // On systems with range extensions we place collections of Thunks at75  // regular spacings that enable the majority of branches reach the Thunks.76  // a value of 0 means range extension thunks are not supported.77  virtual uint32_t getThunkSectionSpacing() const { return 0; }78 79  // The function with a prologue starting at Loc was compiled with80  // -fsplit-stack and it calls a function compiled without. Adjust the prologue81  // to do the right thing. See https://gcc.gnu.org/wiki/SplitStacks.82  // The symbols st_other flags are needed on PowerPC64 for determining the83  // offset to the split-stack prologue.84  virtual bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,85                                                uint8_t stOther) const;86 87  // Return true if we can reach dst from src with RelType type.88  virtual bool inBranchRange(RelType type, uint64_t src,89                             uint64_t dst) const;90 91  // Function for scanning relocation. Typically overridden by targets that92  // require special type or addend adjustment.93  virtual void scanSection(InputSectionBase &);94  // Called by scanSection as a default implementation for specific ELF95  // relocation types.96  template <class ELFT> void scanSection1(InputSectionBase &);97  template <class ELFT, class RelTy>98  void scanSectionImpl(InputSectionBase &, Relocs<RelTy>);99 100  virtual void relocate(uint8_t *loc, const Relocation &rel,101                        uint64_t val) const = 0;102  void relocateNoSym(uint8_t *loc, RelType type, uint64_t val) const {103    relocate(loc, Relocation{R_NONE, type, 0, 0, nullptr}, val);104  }105  virtual void relocateAlloc(InputSection &sec, uint8_t *buf) const;106  void relocateEh(EhInputSection &sec, uint8_t *buf) const;107 108  // Do a linker relaxation pass and return true if we changed something.109  virtual bool relaxOnce(int pass) const { return false; }110  virtual bool synthesizeAlign(uint64_t &dot, InputSection *sec) {111    return false;112  }113  // Do finalize relaxation after collecting relaxation infos.114  virtual void finalizeRelax(int passes) const {}115 116  virtual void applyJumpInstrMod(uint8_t *loc, JumpModType type,117                                 JumpModType val) const {}118  virtual void applyBranchToBranchOpt() const {}119 120  virtual ~TargetInfo();121 122  // This deletes a jump insn at the end of the section if it is a fall thru to123  // the next section.  Further, if there is a conditional jump and a direct124  // jump consecutively, it tries to flip the conditional jump to convert the125  // direct jump into a fall thru and delete it.  Returns true if a jump126  // instruction can be deleted.127  virtual bool deleteFallThruJmpInsn(InputSection &is, InputFile *file,128                                     InputSection *nextIS) const {129    return false;130  }131 132  Ctx &ctx;133  unsigned defaultCommonPageSize = 4096;134  unsigned defaultMaxPageSize = 4096;135 136  uint64_t getImageBase() const;137 138  // True if _GLOBAL_OFFSET_TABLE_ is relative to .got.plt, false if .got.139  bool gotBaseSymInGotPlt = false;140 141  static constexpr RelType noneRel = 0;142  RelType copyRel = 0;143  RelType gotRel = 0;144  RelType pltRel = 0;145  RelType relativeRel = 0;146  RelType iRelativeRel = 0;147  RelType symbolicRel = 0;148  RelType iRelSymbolicRel = 0;149  RelType tlsDescRel = 0;150  RelType tlsGotRel = 0;151  RelType tlsModuleIndexRel = 0;152  RelType tlsOffsetRel = 0;153  unsigned gotEntrySize = ctx.arg.wordsize;154  unsigned pltEntrySize = 0;155  unsigned pltHeaderSize = 0;156  unsigned ipltEntrySize = 0;157 158  // At least on x86_64 positions 1 and 2 are used by the first plt entry159  // to support lazy loading.160  unsigned gotPltHeaderEntriesNum = 3;161 162  // On PPC ELF V2 abi, the first entry in the .got is the .TOC.163  unsigned gotHeaderEntriesNum = 0;164 165  // On PPC ELF V2 abi, the dynamic section needs DT_PPC64_OPT (DT_LOPROC + 3)166  // to be set to 0x2 if there can be multiple TOC's. Although we do not emit167  // multiple TOC's, there can be a mix of TOC and NOTOC addressing which168  // is functionally equivalent.169  int ppc64DynamicSectionOpt = 0;170 171  bool needsThunks = false;172 173  // A 4-byte field corresponding to one or more trap instructions, used to pad174  // executable OutputSections.175  std::array<uint8_t, 4> trapInstr = {};176 177  // Stores the NOP instructions of different sizes for the target and is used178  // to pad sections that are relaxed.179  std::optional<std::vector<std::vector<uint8_t>>> nopInstrs;180 181  // If a target needs to rewrite calls to __morestack to instead call182  // __morestack_non_split when a split-stack enabled caller calls a183  // non-split-stack callee this will return true. Otherwise returns false.184  bool needsMoreStackNonSplit = true;185 186  virtual RelExpr adjustTlsExpr(RelType type, RelExpr expr) const;187  virtual RelExpr adjustGotPcExpr(RelType type, int64_t addend,188                                  const uint8_t *loc) const;189 190protected:191  // On FreeBSD x86_64 the first page cannot be mmaped.192  // On Linux this is controlled by vm.mmap_min_addr. At least on some x86_64193  // installs this is set to 65536, so the first 15 pages cannot be used.194  // Given that, the smallest value that can be used in here is 0x10000.195  uint64_t defaultImageBase = 0x10000;196};197 198void setAArch64TargetInfo(Ctx &);199void setAMDGPUTargetInfo(Ctx &);200void setARMTargetInfo(Ctx &);201void setAVRTargetInfo(Ctx &);202void setHexagonTargetInfo(Ctx &);203void setLoongArchTargetInfo(Ctx &);204void setMSP430TargetInfo(Ctx &);205void setMipsTargetInfo(Ctx &);206void setPPC64TargetInfo(Ctx &);207void setPPCTargetInfo(Ctx &);208void setRISCVTargetInfo(Ctx &);209void setSPARCV9TargetInfo(Ctx &);210void setSystemZTargetInfo(Ctx &);211void setX86TargetInfo(Ctx &);212void setX86_64TargetInfo(Ctx &);213 214struct ErrorPlace {215  InputSectionBase *isec;216  std::string loc;217  std::string srcLoc;218};219 220// Returns input section and corresponding source string for the given location.221ErrorPlace getErrorPlace(Ctx &ctx, const uint8_t *loc);222 223static inline std::string getErrorLoc(Ctx &ctx, const uint8_t *loc) {224  return getErrorPlace(ctx, loc).loc;225}226 227void processArmCmseSymbols(Ctx &);228 229template <class ELFT> uint32_t calcMipsEFlags(Ctx &);230uint8_t getMipsFpAbiFlag(Ctx &, InputFile *file, uint8_t oldFlag,231                         uint8_t newFlag);232uint64_t getMipsPageAddr(uint64_t addr);233bool isMipsN32Abi(Ctx &, const InputFile &f);234bool isMicroMips(Ctx &);235bool isMipsR6(Ctx &);236 237void writePPC32GlinkSection(Ctx &, uint8_t *buf, size_t numEntries);238 239unsigned getPPCDFormOp(unsigned secondaryOp);240unsigned getPPCDSFormOp(unsigned secondaryOp);241 242// In the PowerPC64 Elf V2 abi a function can have 2 entry points.  The first243// is a global entry point (GEP) which typically is used to initialize the TOC244// pointer in general purpose register 2.  The second is a local entry245// point (LEP) which bypasses the TOC pointer initialization code. The246// offset between GEP and LEP is encoded in a function's st_other flags.247// This function will return the offset (in bytes) from the global entry-point248// to the local entry-point.249unsigned getPPC64GlobalEntryToLocalEntryOffset(Ctx &, uint8_t stOther);250 251// Write a prefixed instruction, which is a 4-byte prefix followed by a 4-byte252// instruction (regardless of endianness). Therefore, the prefix is always in253// lower memory than the instruction.254void writePrefixedInst(Ctx &, uint8_t *loc, uint64_t insn);255 256void addPPC64SaveRestore(Ctx &);257uint64_t getPPC64TocBase(Ctx &ctx);258uint64_t getAArch64Page(uint64_t expr);259bool isAArch64BTILandingPad(Ctx &, Symbol &s, int64_t a);260template <typename ELFT> void writeARMCmseImportLib(Ctx &);261uint64_t getLoongArchPageDelta(uint64_t dest, uint64_t pc, RelType type);262void riscvFinalizeRelax(int passes);263void mergeRISCVAttributesSections(Ctx &);264void mergeHexagonAttributesSections(Ctx &);265void addArmInputSectionMappingSymbols(Ctx &);266void addArmSyntheticSectionMappingSymbol(Defined *);267void sortArmMappingSymbols(Ctx &);268void convertArmInstructionstoBE8(Ctx &, InputSection *sec, uint8_t *buf);269void createTaggedSymbols(Ctx &);270void initSymbolAnchors(Ctx &);271 272void setTarget(Ctx &);273 274template <class ELFT> bool isMipsPIC(const Defined *sym);275 276const ELFSyncStream &operator<<(const ELFSyncStream &, RelType);277 278void reportRangeError(Ctx &, uint8_t *loc, const Relocation &rel,279                      const Twine &v, int64_t min, uint64_t max);280void reportRangeError(Ctx &ctx, uint8_t *loc, int64_t v, int n,281                      const Symbol &sym, const Twine &msg);282 283// Make sure that V can be represented as an N bit signed integer.284inline void checkInt(Ctx &ctx, uint8_t *loc, int64_t v, int n,285                     const Relocation &rel) {286  if (v != llvm::SignExtend64(v, n))287    reportRangeError(ctx, loc, rel, Twine(v), llvm::minIntN(n),288                     llvm::maxIntN(n));289}290 291// Make sure that V can be represented as an N bit unsigned integer.292inline void checkUInt(Ctx &ctx, uint8_t *loc, uint64_t v, int n,293                      const Relocation &rel) {294  if ((v >> n) != 0)295    reportRangeError(ctx, loc, rel, Twine(v), 0, llvm::maxUIntN(n));296}297 298// Make sure that V can be represented as an N bit signed or unsigned integer.299inline void checkIntUInt(Ctx &ctx, uint8_t *loc, uint64_t v, int n,300                         const Relocation &rel) {301  // For the error message we should cast V to a signed integer so that error302  // messages show a small negative value rather than an extremely large one303  if (v != (uint64_t)llvm::SignExtend64(v, n) && (v >> n) != 0)304    reportRangeError(ctx, loc, rel, Twine((int64_t)v), llvm::minIntN(n),305                     llvm::maxUIntN(n));306}307 308inline void checkAlignment(Ctx &ctx, uint8_t *loc, uint64_t v, int n,309                           const Relocation &rel) {310  if ((v & (n - 1)) != 0)311    Err(ctx) << getErrorLoc(ctx, loc) << "improper alignment for relocation "312             << rel.type << ": 0x" << llvm::utohexstr(v)313             << " is not aligned to " << n << " bytes";314}315 316// Endianness-aware read/write.317inline uint16_t read16(Ctx &ctx, const void *p) {318  return llvm::support::endian::read16(p, ctx.arg.endianness);319}320 321inline uint32_t read32(Ctx &ctx, const void *p) {322  return llvm::support::endian::read32(p, ctx.arg.endianness);323}324 325inline uint64_t read64(Ctx &ctx, const void *p) {326  return llvm::support::endian::read64(p, ctx.arg.endianness);327}328 329inline void write16(Ctx &ctx, void *p, uint16_t v) {330  llvm::support::endian::write16(p, v, ctx.arg.endianness);331}332 333inline void write32(Ctx &ctx, void *p, uint32_t v) {334  llvm::support::endian::write32(p, v, ctx.arg.endianness);335}336 337inline void write64(Ctx &ctx, void *p, uint64_t v) {338  llvm::support::endian::write64(p, v, ctx.arg.endianness);339}340 341} // namespace elf342} // namespace lld343 344#ifdef __clang__345#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"346#endif347#define invokeELFT(f, ...)                                                     \348  do {                                                                         \349    switch (ctx.arg.ekind) {                                                   \350    case lld::elf::ELF32LEKind:                                                \351      f<llvm::object::ELF32LE>(__VA_ARGS__);                                   \352      break;                                                                   \353    case lld::elf::ELF32BEKind:                                                \354      f<llvm::object::ELF32BE>(__VA_ARGS__);                                   \355      break;                                                                   \356    case lld::elf::ELF64LEKind:                                                \357      f<llvm::object::ELF64LE>(__VA_ARGS__);                                   \358      break;                                                                   \359    case lld::elf::ELF64BEKind:                                                \360      f<llvm::object::ELF64BE>(__VA_ARGS__);                                   \361      break;                                                                   \362    default:                                                                   \363      llvm_unreachable("unknown ctx.arg.ekind");                               \364    }                                                                          \365  } while (0)366 367#endif368