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 // On PPC ELF V2 abi, the dynamic section needs DT_PPC64_OPT (DT_LOPROC + 3)
176 // to be set to 0x2 if there can be multiple TOC's. Although we do not emit
177 // multiple TOC's, there can be a mix of TOC and NOTOC addressing which
178 // is functionally equivalent.
179 int ppc64DynamicSectionOpt = 0;
180
181 bool needsThunks = false;
182
183 // A 4-byte field corresponding to one or more trap instructions, used to pad
184 // executable OutputSections.
185 std::array<uint8_t, 4> trapInstr = {};
186
187 // Stores the NOP instructions of different sizes for the target and is used
188 // to pad sections that are relaxed.
189 std::optional<std::vector<std::vector<uint8_t>>> nopInstrs;
190
191 // If a target needs to rewrite calls to __morestack to instead call
192 // __morestack_non_split when a split-stack enabled caller calls a
193 // non-split-stack callee this will return true. Otherwise returns false.
194 bool needsMoreStackNonSplit = true;
195
196 virtual RelExpr adjustTlsExpr(RelType type, RelExpr expr) const;
197 virtual RelExpr adjustGotPcExpr(RelType type, int64_t addend,
198 const uint8_t *loc) const;
199
200protected:
201 // On FreeBSD x86_64 the first page cannot be mmaped.
202 // On Linux this is controlled by vm.mmap_min_addr. At least on some x86_64
203 // installs this is set to 65536, so the first 15 pages cannot be used.
204 // Given that, the smallest value that can be used in here is 0x10000.
205 uint64_t defaultImageBase = 0x10000;
206};
207
208void setAArch64TargetInfo(Ctx &);
209void setAMDGPUTargetInfo(Ctx &);
210void setARMTargetInfo(Ctx &);
211void setAVRTargetInfo(Ctx &);
212void setHexagonTargetInfo(Ctx &);
213void setLoongArchTargetInfo(Ctx &);
214void setMSP430TargetInfo(Ctx &);
215void setMipsTargetInfo(Ctx &);
216void setPPC64TargetInfo(Ctx &);
217void setPPCTargetInfo(Ctx &);
218void setRISCVTargetInfo(Ctx &);
219void setSPARCV9TargetInfo(Ctx &);
220void setSystemZTargetInfo(Ctx &);
221void setX86TargetInfo(Ctx &);
222void setX86_64TargetInfo(Ctx &);
223
224struct ErrorPlace {
225 InputSectionBase *isec;
226 std::string loc;
227 std::string srcLoc;
228};
229
230// Returns input section and corresponding source string for the given location.
231ErrorPlace getErrorPlace(Ctx &ctx, const uint8_t *loc);
232
233static inline std::string getErrorLoc(Ctx &ctx, const uint8_t *loc) {
234 return getErrorPlace(ctx, loc).loc;
235}
236
237void processArmCmseSymbols(Ctx &);
238
239template <class ELFT> uint32_t calcMipsEFlags(Ctx &);
240uint8_t getMipsFpAbiFlag(Ctx &, InputFile *file, uint8_t oldFlag,
241 uint8_t newFlag);
242uint64_t getMipsPageAddr(uint64_t addr);
243bool isMipsN32Abi(Ctx &, const InputFile &f);
244bool isMicroMips(Ctx &);
245bool isMipsR6(Ctx &);
246
247void writePPC32GlinkSection(Ctx &, uint8_t *buf, size_t numEntries);
248
249unsigned getPPCDFormOp(unsigned secondaryOp);
250unsigned getPPCDSFormOp(unsigned secondaryOp);
251
252// In the PowerPC64 Elf V2 abi a function can have 2 entry points. The first
253// is a global entry point (GEP) which typically is used to initialize the TOC
254// pointer in general purpose register 2. The second is a local entry
255// point (LEP) which bypasses the TOC pointer initialization code. The
256// offset between GEP and LEP is encoded in a function's st_other flags.
257// This function will return the offset (in bytes) from the global entry-point
258// to the local entry-point.
259unsigned getPPC64GlobalEntryToLocalEntryOffset(Ctx &, uint8_t stOther);
260
261// Write a prefixed instruction, which is a 4-byte prefix followed by a 4-byte
262// instruction (regardless of endianness). Therefore, the prefix is always in
263// lower memory than the instruction.
264void writePrefixedInst(Ctx &, uint8_t *loc, uint64_t insn);
265
266void addPPC64SaveRestore(Ctx &);
267uint64_t getPPC64TocBase(Ctx &ctx);
268uint64_t getAArch64Page(uint64_t expr);
269bool isAArch64BTILandingPad(Ctx &, Symbol &s, int64_t a);
270template <typename ELFT> void writeARMCmseImportLib(Ctx &);
271uint64_t getLoongArchPageDelta(uint64_t dest, uint64_t pc, RelType type);
272void riscvFinalizeRelax(int passes);
273void mergeRISCVAttributesSections(Ctx &);
274void mergeHexagonAttributesSections(Ctx &);
275void addArmInputSectionMappingSymbols(Ctx &);
276void addArmSyntheticSectionMappingSymbol(Defined *);
277void sortArmMappingSymbols(Ctx &);
278void convertArmInstructionstoBE8(Ctx &, InputSection *sec, uint8_t *buf);
279void createTaggedSymbols(Ctx &);
280void initSymbolAnchors(Ctx &);
281
282void setTarget(Ctx &);
283
284template <class ELFT> bool isMipsPIC(const Defined *sym);
285
286const ELFSyncStream &operator<<(const ELFSyncStream &, RelType);
287
288void reportRangeError(Ctx &, uint8_t *loc, const Relocation &rel,
289 const Twine &v, int64_t min, uint64_t max);
290void reportRangeError(Ctx &ctx, uint8_t *loc, int64_t v, int n,
291 const Symbol &sym, const Twine &msg);
292
293// Make sure that V can be represented as an N bit signed integer.
294inline void checkInt(Ctx &ctx, uint8_t *loc, int64_t v, int n,
295 const Relocation &rel) {
296 if (v != llvm::SignExtend64(X: v, B: n))
297 reportRangeError(ctx, loc, rel, v: Twine(v), min: llvm::minIntN(N: n),
298 max: llvm::maxIntN(N: n));
299}
300
301// Make sure that V can be represented as an N bit unsigned integer.
302inline void checkUInt(Ctx &ctx, uint8_t *loc, uint64_t v, int n,
303 const Relocation &rel) {
304 if ((v >> n) != 0)
305 reportRangeError(ctx, loc, rel, v: Twine(v), min: 0, max: llvm::maxUIntN(N: n));
306}
307
308// Make sure that V can be represented as an N bit signed or unsigned integer.
309inline void checkIntUInt(Ctx &ctx, uint8_t *loc, uint64_t v, int n,
310 const Relocation &rel) {
311 // For the error message we should cast V to a signed integer so that error
312 // messages show a small negative value rather than an extremely large one
313 if (v != (uint64_t)llvm::SignExtend64(X: v, B: n) && (v >> n) != 0)
314 reportRangeError(ctx, loc, rel, v: Twine((int64_t)v), min: llvm::minIntN(N: n),
315 max: llvm::maxUIntN(N: n));
316}
317
318inline void checkAlignment(Ctx &ctx, uint8_t *loc, uint64_t v, int n,
319 const Relocation &rel) {
320 if ((v & (n - 1)) != 0)
321 Err(ctx) << getErrorLoc(ctx, loc) << "improper alignment for relocation "
322 << rel.type << ": 0x" << llvm::utohexstr(X: v)
323 << " is not aligned to " << n << " bytes";
324}
325
326// Endianness-aware read/write.
327inline uint16_t read16(Ctx &ctx, const void *p) {
328 return llvm::support::endian::read16(P: p, E: ctx.arg.endianness);
329}
330
331inline uint32_t read32(Ctx &ctx, const void *p) {
332 return llvm::support::endian::read32(P: p, E: ctx.arg.endianness);
333}
334
335inline uint64_t read64(Ctx &ctx, const void *p) {
336 return llvm::support::endian::read64(P: p, E: ctx.arg.endianness);
337}
338
339inline void write16(Ctx &ctx, void *p, uint16_t v) {
340 llvm::support::endian::write16(P: p, V: v, E: ctx.arg.endianness);
341}
342
343inline void write32(Ctx &ctx, void *p, uint32_t v) {
344 llvm::support::endian::write32(P: p, V: v, E: ctx.arg.endianness);
345}
346
347inline void write64(Ctx &ctx, void *p, uint64_t v) {
348 llvm::support::endian::write64(P: p, V: v, E: ctx.arg.endianness);
349}
350
351} // namespace elf
352} // namespace lld
353
354#ifdef __clang__
355#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
356#endif
357#define invokeELFT(f, ...) \
358 do { \
359 switch (ctx.arg.ekind) { \
360 case lld::elf::ELF32LEKind: \
361 f<llvm::object::ELF32LE>(__VA_ARGS__); \
362 break; \
363 case lld::elf::ELF32BEKind: \
364 f<llvm::object::ELF32BE>(__VA_ARGS__); \
365 break; \
366 case lld::elf::ELF64LEKind: \
367 f<llvm::object::ELF64LE>(__VA_ARGS__); \
368 break; \
369 case lld::elf::ELF64BEKind: \
370 f<llvm::object::ELF64BE>(__VA_ARGS__); \
371 break; \
372 default: \
373 llvm_unreachable("unknown ctx.arg.ekind"); \
374 } \
375 } while (0)
376
377#endif
378