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/Object/ELF.h"
16 #include "llvm/Support/Compiler.h"
17 #include "llvm/Support/MathExtras.h"
18 #include <array>
19
20 namespace lld {
21 std::string toString(elf::RelType type);
22
23 namespace elf {
24 class Defined;
25 class InputFile;
26 class Symbol;
27
28 class TargetInfo {
29 public:
calcEFlags()30 virtual uint32_t calcEFlags() const { return 0; }
31 virtual RelExpr getRelExpr(RelType type, const Symbol &s,
32 const uint8_t *loc) const = 0;
getDynRel(RelType type)33 virtual RelType getDynRel(RelType type) const { return 0; }
writeGotPltHeader(uint8_t * buf)34 virtual void writeGotPltHeader(uint8_t *buf) const {}
writeGotHeader(uint8_t * buf)35 virtual void writeGotHeader(uint8_t *buf) const {}
writeGotPlt(uint8_t * buf,const Symbol & s)36 virtual void writeGotPlt(uint8_t *buf, const Symbol &s) const {};
writeIgotPlt(uint8_t * buf,const Symbol & s)37 virtual void writeIgotPlt(uint8_t *buf, const Symbol &s) const {}
38 virtual int64_t getImplicitAddend(const uint8_t *buf, RelType type) const;
getTlsGdRelaxSkip(RelType type)39 virtual int getTlsGdRelaxSkip(RelType type) const { return 1; }
40
41 // If lazy binding is supported, the first entry of the PLT has code
42 // to call the dynamic linker to resolve PLT entries the first time
43 // they are called. This function writes that code.
writePltHeader(uint8_t * buf)44 virtual void writePltHeader(uint8_t *buf) const {}
45
writePlt(uint8_t * buf,const Symbol & sym,uint64_t pltEntryAddr)46 virtual void writePlt(uint8_t *buf, const Symbol &sym,
47 uint64_t pltEntryAddr) const {}
writeIplt(uint8_t * buf,const Symbol & sym,uint64_t pltEntryAddr)48 virtual void writeIplt(uint8_t *buf, const Symbol &sym,
49 uint64_t pltEntryAddr) const {
50 // All but PPC32 and PPC64 use the same format for .plt and .iplt entries.
51 writePlt(buf, sym, pltEntryAddr);
52 }
writeIBTPlt(uint8_t * buf,size_t numEntries)53 virtual void writeIBTPlt(uint8_t *buf, size_t numEntries) const {}
addPltHeaderSymbols(InputSection & isec)54 virtual void addPltHeaderSymbols(InputSection &isec) const {}
addPltSymbols(InputSection & isec,uint64_t off)55 virtual void addPltSymbols(InputSection &isec, uint64_t off) const {}
56
57 // Returns true if a relocation only uses the low bits of a value such that
58 // all those bits are in the same page. For example, if the relocation
59 // only uses the low 12 bits in a system with 4k pages. If this is true, the
60 // bits will always have the same value at runtime and we don't have to emit
61 // a dynamic relocation.
62 virtual bool usesOnlyLowPageBits(RelType type) const;
63
64 // Decide whether a Thunk is needed for the relocation from File
65 // targeting S.
66 virtual bool needsThunk(RelExpr expr, RelType relocType,
67 const InputFile *file, uint64_t branchAddr,
68 const Symbol &s, int64_t a) const;
69
70 // On systems with range extensions we place collections of Thunks at
71 // regular spacings that enable the majority of branches reach the Thunks.
72 // a value of 0 means range extension thunks are not supported.
getThunkSectionSpacing()73 virtual uint32_t getThunkSectionSpacing() const { return 0; }
74
75 // The function with a prologue starting at Loc was compiled with
76 // -fsplit-stack and it calls a function compiled without. Adjust the prologue
77 // to do the right thing. See https://gcc.gnu.org/wiki/SplitStacks.
78 // The symbols st_other flags are needed on PowerPC64 for determining the
79 // offset to the split-stack prologue.
80 virtual bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
81 uint8_t stOther) const;
82
83 // Return true if we can reach dst from src with RelType type.
84 virtual bool inBranchRange(RelType type, uint64_t src,
85 uint64_t dst) const;
86
87 virtual void relocate(uint8_t *loc, const Relocation &rel,
88 uint64_t val) const = 0;
relocateNoSym(uint8_t * loc,RelType type,uint64_t val)89 void relocateNoSym(uint8_t *loc, RelType type, uint64_t val) const {
90 relocate(loc, Relocation{R_NONE, type, 0, 0, nullptr}, val);
91 }
92 virtual void relocateAlloc(InputSectionBase &sec, uint8_t *buf) const;
93
94 // Do a linker relaxation pass and return true if we changed something.
relaxOnce(int pass)95 virtual bool relaxOnce(int pass) const { return false; }
96
applyJumpInstrMod(uint8_t * loc,JumpModType type,JumpModType val)97 virtual void applyJumpInstrMod(uint8_t *loc, JumpModType type,
98 JumpModType val) const {}
99
100 virtual ~TargetInfo();
101
102 // This deletes a jump insn at the end of the section if it is a fall thru to
103 // the next section. Further, if there is a conditional jump and a direct
104 // jump consecutively, it tries to flip the conditional jump to convert the
105 // direct jump into a fall thru and delete it. Returns true if a jump
106 // instruction can be deleted.
deleteFallThruJmpInsn(InputSection & is,InputFile * file,InputSection * nextIS)107 virtual bool deleteFallThruJmpInsn(InputSection &is, InputFile *file,
108 InputSection *nextIS) const {
109 return false;
110 }
111
112 unsigned defaultCommonPageSize = 4096;
113 unsigned defaultMaxPageSize = 4096;
114
115 uint64_t getImageBase() const;
116
117 // True if _GLOBAL_OFFSET_TABLE_ is relative to .got.plt, false if .got.
118 bool gotBaseSymInGotPlt = false;
119
120 static constexpr RelType noneRel = 0;
121 RelType copyRel;
122 RelType gotRel;
123 RelType pltRel;
124 RelType relativeRel;
125 RelType iRelativeRel;
126 RelType symbolicRel;
127 RelType tlsDescRel;
128 RelType tlsGotRel;
129 RelType tlsModuleIndexRel;
130 RelType tlsOffsetRel;
131 unsigned gotEntrySize = config->wordsize;
132 unsigned pltEntrySize;
133 unsigned pltHeaderSize;
134 unsigned ipltEntrySize;
135
136 // At least on x86_64 positions 1 and 2 are used by the first plt entry
137 // to support lazy loading.
138 unsigned gotPltHeaderEntriesNum = 3;
139
140 // On PPC ELF V2 abi, the first entry in the .got is the .TOC.
141 unsigned gotHeaderEntriesNum = 0;
142
143 bool needsThunks = false;
144
145 // A 4-byte field corresponding to one or more trap instructions, used to pad
146 // executable OutputSections.
147 std::array<uint8_t, 4> trapInstr;
148
149 // Stores the NOP instructions of different sizes for the target and is used
150 // to pad sections that are relaxed.
151 std::optional<std::vector<std::vector<uint8_t>>> nopInstrs;
152
153 // If a target needs to rewrite calls to __morestack to instead call
154 // __morestack_non_split when a split-stack enabled caller calls a
155 // non-split-stack callee this will return true. Otherwise returns false.
156 bool needsMoreStackNonSplit = true;
157
158 virtual RelExpr adjustTlsExpr(RelType type, RelExpr expr) const;
159 virtual RelExpr adjustGotPcExpr(RelType type, int64_t addend,
160 const uint8_t *loc) const;
161
162 protected:
163 // On FreeBSD x86_64 the first page cannot be mmaped.
164 // On Linux this is controlled by vm.mmap_min_addr. At least on some x86_64
165 // installs this is set to 65536, so the first 15 pages cannot be used.
166 // Given that, the smallest value that can be used in here is 0x10000.
167 uint64_t defaultImageBase = 0x10000;
168 };
169
170 TargetInfo *getAArch64TargetInfo();
171 TargetInfo *getAMDGPUTargetInfo();
172 TargetInfo *getARMTargetInfo();
173 TargetInfo *getAVRTargetInfo();
174 TargetInfo *getHexagonTargetInfo();
175 TargetInfo *getMSP430TargetInfo();
176 TargetInfo *getPPC64TargetInfo();
177 TargetInfo *getPPCTargetInfo();
178 TargetInfo *getRISCVTargetInfo();
179 TargetInfo *getSPARCV9TargetInfo();
180 TargetInfo *getX86TargetInfo();
181 TargetInfo *getX86_64TargetInfo();
182 template <class ELFT> TargetInfo *getMipsTargetInfo();
183
184 struct ErrorPlace {
185 InputSectionBase *isec;
186 std::string loc;
187 std::string srcLoc;
188 };
189
190 // Returns input section and corresponding source string for the given location.
191 ErrorPlace getErrorPlace(const uint8_t *loc);
192
getErrorLocation(const uint8_t * loc)193 static inline std::string getErrorLocation(const uint8_t *loc) {
194 return getErrorPlace(loc).loc;
195 }
196
197 void writePPC32GlinkSection(uint8_t *buf, size_t numEntries);
198
199 unsigned getPPCDFormOp(unsigned secondaryOp);
200
201 // In the PowerPC64 Elf V2 abi a function can have 2 entry points. The first
202 // is a global entry point (GEP) which typically is used to initialize the TOC
203 // pointer in general purpose register 2. The second is a local entry
204 // point (LEP) which bypasses the TOC pointer initialization code. The
205 // offset between GEP and LEP is encoded in a function's st_other flags.
206 // This function will return the offset (in bytes) from the global entry-point
207 // to the local entry-point.
208 unsigned getPPC64GlobalEntryToLocalEntryOffset(uint8_t stOther);
209
210 // Write a prefixed instruction, which is a 4-byte prefix followed by a 4-byte
211 // instruction (regardless of endianness). Therefore, the prefix is always in
212 // lower memory than the instruction.
213 void writePrefixedInstruction(uint8_t *loc, uint64_t insn);
214
215 void addPPC64SaveRestore();
216 uint64_t getPPC64TocBase();
217 uint64_t getAArch64Page(uint64_t expr);
218 void riscvFinalizeRelax(int passes);
219 void mergeRISCVAttributesSections();
220
221 LLVM_LIBRARY_VISIBILITY extern const TargetInfo *target;
222 TargetInfo *getTarget();
223
224 template <class ELFT> bool isMipsPIC(const Defined *sym);
225
226 void reportRangeError(uint8_t *loc, const Relocation &rel, const Twine &v,
227 int64_t min, uint64_t max);
228 void reportRangeError(uint8_t *loc, int64_t v, int n, const Symbol &sym,
229 const Twine &msg);
230
231 // Make sure that V can be represented as an N bit signed integer.
checkInt(uint8_t * loc,int64_t v,int n,const Relocation & rel)232 inline void checkInt(uint8_t *loc, int64_t v, int n, const Relocation &rel) {
233 if (v != llvm::SignExtend64(v, n))
234 reportRangeError(loc, rel, Twine(v), llvm::minIntN(n), llvm::maxIntN(n));
235 }
236
237 // Make sure that V can be represented as an N bit unsigned integer.
checkUInt(uint8_t * loc,uint64_t v,int n,const Relocation & rel)238 inline void checkUInt(uint8_t *loc, uint64_t v, int n, const Relocation &rel) {
239 if ((v >> n) != 0)
240 reportRangeError(loc, rel, Twine(v), 0, llvm::maxUIntN(n));
241 }
242
243 // Make sure that V can be represented as an N bit signed or unsigned integer.
checkIntUInt(uint8_t * loc,uint64_t v,int n,const Relocation & rel)244 inline void checkIntUInt(uint8_t *loc, uint64_t v, int n,
245 const Relocation &rel) {
246 // For the error message we should cast V to a signed integer so that error
247 // messages show a small negative value rather than an extremely large one
248 if (v != (uint64_t)llvm::SignExtend64(v, n) && (v >> n) != 0)
249 reportRangeError(loc, rel, Twine((int64_t)v), llvm::minIntN(n),
250 llvm::maxUIntN(n));
251 }
252
checkAlignment(uint8_t * loc,uint64_t v,int n,const Relocation & rel)253 inline void checkAlignment(uint8_t *loc, uint64_t v, int n,
254 const Relocation &rel) {
255 if ((v & (n - 1)) != 0)
256 error(getErrorLocation(loc) + "improper alignment for relocation " +
257 lld::toString(rel.type) + ": 0x" + llvm::utohexstr(v) +
258 " is not aligned to " + Twine(n) + " bytes");
259 }
260
261 // Endianness-aware read/write.
read16(const void * p)262 inline uint16_t read16(const void *p) {
263 return llvm::support::endian::read16(p, config->endianness);
264 }
265
read32(const void * p)266 inline uint32_t read32(const void *p) {
267 return llvm::support::endian::read32(p, config->endianness);
268 }
269
read64(const void * p)270 inline uint64_t read64(const void *p) {
271 return llvm::support::endian::read64(p, config->endianness);
272 }
273
write16(void * p,uint16_t v)274 inline void write16(void *p, uint16_t v) {
275 llvm::support::endian::write16(p, v, config->endianness);
276 }
277
write32(void * p,uint32_t v)278 inline void write32(void *p, uint32_t v) {
279 llvm::support::endian::write32(p, v, config->endianness);
280 }
281
write64(void * p,uint64_t v)282 inline void write64(void *p, uint64_t v) {
283 llvm::support::endian::write64(p, v, config->endianness);
284 }
285 } // namespace elf
286 } // namespace lld
287
288 #ifdef __clang__
289 #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
290 #endif
291 #define invokeELFT(f, ...) \
292 switch (config->ekind) { \
293 case ELF32LEKind: \
294 f<ELF32LE>(__VA_ARGS__); \
295 break; \
296 case ELF32BEKind: \
297 f<ELF32BE>(__VA_ARGS__); \
298 break; \
299 case ELF64LEKind: \
300 f<ELF64LE>(__VA_ARGS__); \
301 break; \
302 case ELF64BEKind: \
303 f<ELF64BE>(__VA_ARGS__); \
304 break; \
305 default: \
306 llvm_unreachable("unknown config->ekind"); \
307 }
308
309 #endif
310