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