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-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLD_ELF_TARGET_H
10#define LLD_ELF_TARGET_H
11
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 // Create target-specific synthetic sections, defined in Arch/ files.
36 virtual void initTargetSpecificSections() {}
37 virtual RelExpr getRelExpr(RelType type, const Symbol &s,
38 const uint8_t *loc) const = 0;
39 virtual RelType getDynRel(RelType type) const { return 0; }
40 virtual void writeGotPltHeader(uint8_t *buf) const {}
41 virtual void writeGotHeader(uint8_t *buf) const {}
42 virtual void writeGotPlt(uint8_t *buf, const Symbol &s) const {}
43 virtual void writeIgotPlt(uint8_t *buf, const Symbol &s) const {}
44 virtual int64_t getImplicitAddend(const uint8_t *buf, RelType type) const;
45
46 // If lazy binding is supported, the first entry of the PLT has code
47 // to call the dynamic linker to resolve PLT entries the first time
48 // they are called. This function writes that code.
49 virtual void writePltHeader(uint8_t *buf) const {}
50
51 virtual void writePlt(uint8_t *buf, const Symbol &sym,
52 uint64_t pltEntryAddr) const {}
53 virtual void writeIplt(uint8_t *buf, const Symbol &sym,
54 uint64_t pltEntryAddr) const {
55 // All but PPC32 and PPC64 use the same format for .plt and .iplt entries.
56 writePlt(buf, sym, pltEntryAddr);
57 }
58 virtual void writeIBTPlt(uint8_t *buf, size_t numEntries) const {}
59 virtual void addPltHeaderSymbols(InputSection &isec) const {}
60 virtual void addPltSymbols(InputSection &isec, uint64_t off) const {}
61
62 // Returns true if a relocation only uses the low bits of a value such that
63 // all those bits are in the same page. For example, if the relocation
64 // only uses the low 12 bits in a system with 4k pages. If this is true, the
65 // bits will always have the same value at runtime and we don't have to emit
66 // a dynamic relocation.
67 virtual bool usesOnlyLowPageBits(RelType type) const;
68
69 // Decide whether a Thunk is needed for the relocation from File
70 // targeting S.
71 virtual bool needsThunk(RelExpr expr, RelType relocType,
72 const InputFile *file, uint64_t branchAddr,
73 const Symbol &s, int64_t a) const;
74
75 // On systems with range extensions we place collections of Thunks at
76 // regular spacings that enable the majority of branches reach the Thunks.
77 // a value of 0 means range extension thunks are not supported.
78 virtual uint32_t getThunkSectionSpacing() const { return 0; }
79
80 // The function with a prologue starting at Loc was compiled with
81 // -fsplit-stack and it calls a function compiled without. Adjust the prologue
82 // to do the right thing. See https://gcc.gnu.org/wiki/SplitStacks.
83 // The symbols st_other flags are needed on PowerPC64 for determining the
84 // offset to the split-stack prologue.
85 virtual bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
86 uint8_t stOther) const;
87
88 // Return true if we can reach dst from src with RelType type.
89 virtual bool inBranchRange(RelType type, uint64_t src,
90 uint64_t dst) const;
91
92 // Function for scanning relocation. Typically overridden by targets that
93 // require special type or addend adjustment. `shard` selects the `relocsVec`
94 // shard that discovered dynamic relocations are appended to.
95 virtual void scanSection(InputSectionBase &, unsigned shard);
96 template <class RelTy>
97 void scanSectionImpl(InputSectionBase &, Relocs<RelTy>, unsigned shard);
98
99 // Called after parallel relocation scanning is complete but before
100 // postScanRelocations processes symbol flags. Targets may override this to
101 // perform single-threaded fixups that cannot run during parallel scanning
102 // (e.g. symbol table modifications).
103 virtual void finalizeRelocScan() {}
104
105 virtual void relocate(uint8_t *loc, const Relocation &rel,
106 uint64_t val) const = 0;
107 void relocateNoSym(uint8_t *loc, RelType type, uint64_t val) const {
108 relocate(loc, rel: Relocation{.expr: R_NONE, .type: type, .offset: 0, .addend: 0, .sym: nullptr}, val);
109 }
110 virtual void relocateAlloc(InputSection &sec, uint8_t *buf) const;
111 void relocateEh(EhInputSection &sec, uint8_t *buf) const;
112
113 // Do a linker relaxation pass and return true if we changed something.
114 virtual bool relaxOnce(int pass) const { return false; }
115 // Relax CFI jump tables if implemented by target.
116 virtual void relaxCFIJumpTables() const {}
117 virtual bool synthesizeAlign(uint64_t &dot, InputSection *sec) {
118 return false;
119 }
120 // Do finalize relaxation after collecting relaxation infos.
121 virtual void finalizeRelax(int passes) const {}
122
123 virtual void applyJumpInstrMod(uint8_t *loc, JumpModType type,
124 JumpModType val) const {}
125 virtual void applyBranchToBranchOpt() const {}
126
127 virtual ~TargetInfo();
128
129 // This deletes a jump insn at the end of the section if it is a fall thru to
130 // the next section. Further, if there is a conditional jump and a direct
131 // jump consecutively, it tries to flip the conditional jump to convert the
132 // direct jump into a fall thru and delete it. Returns true if a jump
133 // instruction can be deleted.
134 virtual bool deleteFallThruJmpInsn(InputSection &is,
135 InputSection *nextIS) const {
136 return false;
137 }
138
139 Ctx &ctx;
140 unsigned defaultCommonPageSize = 4096;
141 unsigned defaultMaxPageSize = 4096;
142
143 uint64_t getImageBase() const;
144
145 // True if _GLOBAL_OFFSET_TABLE_ is relative to .got.plt, false if .got.
146 bool gotBaseSymInGotPlt = false;
147
148 static constexpr RelType noneRel = 0;
149 RelType copyRel = 0;
150 RelType gotRel = 0;
151 RelType pltRel = 0;
152 RelType relativeRel = 0;
153 RelType iRelativeRel = 0;
154 RelType symbolicRel = 0;
155 RelType iRelSymbolicRel = 0;
156 RelType tlsDescRel = 0;
157 RelType tlsGotRel = 0;
158 RelType tlsModuleIndexRel = 0;
159 RelType tlsOffsetRel = 0;
160 unsigned gotEntrySize = ctx.arg.wordsize;
161 unsigned pltEntrySize = 0;
162 unsigned pltHeaderSize = 0;
163 unsigned ipltEntrySize = 0;
164
165 // At least on x86_64 positions 1 and 2 are used by the first plt entry
166 // to support lazy loading.
167 unsigned gotPltHeaderEntriesNum = 3;
168
169 // On PPC ELF V2 abi, the first entry in the .got is the .TOC.
170 unsigned gotHeaderEntriesNum = 0;
171
172 // True if the dynamic linker resolves a PLT entry by writing the target
173 // address to a GotPltSection slot (named .plt on PPC). SPARC instead has it
174 // rewrite the PLT entry's instructions, so pltRel applies to .plt.
175 bool usesGotPlt = true;
176
177 // On PPC ELF V2 abi, the dynamic section needs DT_PPC64_OPT (DT_LOPROC + 3)
178 // to be set to 0x2 if there can be multiple TOC's. Although we do not emit
179 // multiple TOC's, there can be a mix of TOC and NOTOC addressing which
180 // is functionally equivalent.
181 int ppc64DynamicSectionOpt = 0;
182
183 bool needsThunks = false;
184
185 // A 4-byte field corresponding to one or more trap instructions, used to pad
186 // executable OutputSections.
187 std::array<uint8_t, 4> trapInstr = {};
188
189 // Stores the NOP instructions of different sizes for the target and is used
190 // to pad sections that are relaxed.
191 std::optional<std::vector<std::vector<uint8_t>>> nopInstrs;
192
193 // If a target needs to rewrite calls to __morestack to instead call
194 // __morestack_non_split when a split-stack enabled caller calls a
195 // non-split-stack callee this will return true. Otherwise returns false.
196 bool needsMoreStackNonSplit = true;
197
198 virtual RelExpr adjustGotPcExpr(RelType type, int64_t addend,
199 const uint8_t *loc) const;
200
201protected:
202 // On FreeBSD x86_64 the first page cannot be mmaped.
203 // On Linux this is controlled by vm.mmap_min_addr. At least on some x86_64
204 // installs this is set to 65536, so the first 15 pages cannot be used.
205 // Given that, the smallest value that can be used in here is 0x10000.
206 uint64_t defaultImageBase = 0x10000;
207};
208
209void setAArch64TargetInfo(Ctx &);
210void setAMDGPUTargetInfo(Ctx &);
211void setARMTargetInfo(Ctx &);
212void setAVRTargetInfo(Ctx &);
213void setHexagonTargetInfo(Ctx &);
214void setLoongArchTargetInfo(Ctx &);
215void setMSP430TargetInfo(Ctx &);
216void setMipsTargetInfo(Ctx &);
217void setPPC64TargetInfo(Ctx &);
218void setPPCTargetInfo(Ctx &);
219void setRISCVTargetInfo(Ctx &);
220void setSPARCV9TargetInfo(Ctx &);
221void setSystemZTargetInfo(Ctx &);
222void setX86TargetInfo(Ctx &);
223void setX86_64TargetInfo(Ctx &);
224
225struct ErrorPlace {
226 InputSectionBase *isec;
227 std::string loc;
228 std::string srcLoc;
229};
230
231// Returns input section and corresponding source string for the given location.
232ErrorPlace getErrorPlace(Ctx &ctx, const uint8_t *loc);
233
234static inline std::string getErrorLoc(Ctx &ctx, const uint8_t *loc) {
235 return getErrorPlace(ctx, loc).loc;
236}
237
238void processArmCmseSymbols(Ctx &);
239
240template <class ELFT> uint32_t calcMipsEFlags(Ctx &);
241uint8_t getMipsFpAbiFlag(Ctx &, InputFile *file, uint8_t oldFlag,
242 uint8_t newFlag);
243uint64_t getMipsPageAddr(uint64_t addr);
244bool isMipsN32Abi(Ctx &, const InputFile &f);
245bool isMicroMips(Ctx &);
246bool isMipsR6(Ctx &);
247
248void writePPC32GlinkSection(Ctx &, uint8_t *buf, size_t numEntries);
249
250unsigned getPPCDFormOp(unsigned secondaryOp);
251unsigned getPPCDSFormOp(unsigned secondaryOp);
252
253// In the PowerPC64 Elf V2 abi a function can have 2 entry points. The first
254// is a global entry point (GEP) which typically is used to initialize the TOC
255// pointer in general purpose register 2. The second is a local entry
256// point (LEP) which bypasses the TOC pointer initialization code. The
257// offset between GEP and LEP is encoded in a function's st_other flags.
258// This function will return the offset (in bytes) from the global entry-point
259// to the local entry-point.
260unsigned getPPC64GlobalEntryToLocalEntryOffset(Ctx &, uint8_t stOther);
261
262// Write a prefixed instruction, which is a 4-byte prefix followed by a 4-byte
263// instruction (regardless of endianness). Therefore, the prefix is always in
264// lower memory than the instruction.
265void writePrefixedInst(Ctx &, uint8_t *loc, uint64_t insn);
266
267void addPPC64SaveRestore(Ctx &);
268uint64_t getPPC64TocBase(Ctx &ctx);
269uint64_t getAArch64Page(uint64_t expr);
270bool isAArch64BTILandingPad(Ctx &, Symbol &s, int64_t a);
271template <typename ELFT> void writeARMCmseImportLib(Ctx &);
272uint64_t getLoongArchPageDelta(uint64_t dest, uint64_t pc, RelType type);
273void riscvFinalizeRelax(int passes);
274void mergeRISCVAttributesSections(Ctx &);
275void mergeHexagonAttributesSections(Ctx &);
276void addArmInputSectionMappingSymbols(Ctx &);
277void addArmSyntheticSectionMappingSymbol(Defined *);
278void sortArmMappingSymbols(Ctx &);
279void convertArmInstructionstoBE8(Ctx &, InputSection *sec, uint8_t *buf);
280void createTaggedSymbols(Ctx &);
281void initSymbolAnchors(Ctx &);
282
283void setTarget(Ctx &);
284
285template <class ELFT> bool isMipsPIC(const Defined *sym);
286
287const ELFSyncStream &operator<<(const ELFSyncStream &, RelType);
288
289void reportRangeError(Ctx &, uint8_t *loc, const Relocation &rel,
290 const Twine &v, int64_t min, uint64_t max);
291void reportRangeError(Ctx &ctx, uint8_t *loc, int64_t v, int n,
292 const Symbol &sym, const Twine &msg);
293
294// Make sure that V can be represented as an N bit signed integer.
295inline void checkInt(Ctx &ctx, uint8_t *loc, int64_t v, int n,
296 const Relocation &rel) {
297 if (v != llvm::SignExtend64(X: v, B: n))
298 reportRangeError(ctx, loc, rel, v: Twine(v), min: llvm::minIntN(N: n),
299 max: llvm::maxIntN(N: n));
300}
301
302// Make sure that V can be represented as an N bit unsigned integer.
303inline void checkUInt(Ctx &ctx, uint8_t *loc, uint64_t v, int n,
304 const Relocation &rel) {
305 if ((v >> n) != 0)
306 reportRangeError(ctx, loc, rel, v: Twine(v), min: 0, max: llvm::maxUIntN(N: n));
307}
308
309// Make sure that V can be represented as an N bit signed or unsigned integer.
310inline void checkIntUInt(Ctx &ctx, uint8_t *loc, uint64_t v, int n,
311 const Relocation &rel) {
312 // For the error message we should cast V to a signed integer so that error
313 // messages show a small negative value rather than an extremely large one
314 if (v != (uint64_t)llvm::SignExtend64(X: v, B: n) && (v >> n) != 0)
315 reportRangeError(ctx, loc, rel, v: Twine((int64_t)v), min: llvm::minIntN(N: n),
316 max: llvm::maxUIntN(N: n));
317}
318
319inline void checkAlignment(Ctx &ctx, uint8_t *loc, uint64_t v, int n,
320 const Relocation &rel) {
321 if ((v & (n - 1)) != 0)
322 Err(ctx) << getErrorLoc(ctx, loc) << "improper alignment for relocation "
323 << rel.type << ": 0x" << llvm::utohexstr(X: v)
324 << " is not aligned to " << n << " bytes";
325}
326
327// Endianness-aware read/write.
328inline uint16_t read16(Ctx &ctx, const void *p) {
329 return llvm::support::endian::read16(P: p, E: ctx.arg.endianness);
330}
331
332inline uint32_t read32(Ctx &ctx, const void *p) {
333 return llvm::support::endian::read32(P: p, E: ctx.arg.endianness);
334}
335
336inline uint64_t read64(Ctx &ctx, const void *p) {
337 return llvm::support::endian::read64(P: p, E: ctx.arg.endianness);
338}
339
340inline void write16(Ctx &ctx, void *p, uint16_t v) {
341 llvm::support::endian::write16(P: p, V: v, E: ctx.arg.endianness);
342}
343
344inline void write32(Ctx &ctx, void *p, uint32_t v) {
345 llvm::support::endian::write32(P: p, V: v, E: ctx.arg.endianness);
346}
347
348inline void write64(Ctx &ctx, void *p, uint64_t v) {
349 llvm::support::endian::write64(P: p, V: v, E: ctx.arg.endianness);
350}
351
352} // namespace elf
353} // namespace lld
354
355#ifdef __clang__
356#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
357#endif
358#define invokeELFT(f, ...) \
359 do { \
360 switch (ctx.arg.ekind) { \
361 case lld::elf::ELF32LEKind: \
362 f<llvm::object::ELF32LE>(__VA_ARGS__); \
363 break; \
364 case lld::elf::ELF32BEKind: \
365 f<llvm::object::ELF32BE>(__VA_ARGS__); \
366 break; \
367 case lld::elf::ELF64LEKind: \
368 f<llvm::object::ELF64LE>(__VA_ARGS__); \
369 break; \
370 case lld::elf::ELF64BEKind: \
371 f<llvm::object::ELF64BE>(__VA_ARGS__); \
372 break; \
373 default: \
374 llvm_unreachable("unknown ctx.arg.ekind"); \
375 } \
376 } while (0)
377
378#endif
379