1//===- Relocations.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_RELOCATIONS_H
10#define LLD_ELF_RELOCATIONS_H
11
12#include "lld/Common/LLVM.h"
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/Object/ELFTypes.h"
16#include <vector>
17
18namespace lld::elf {
19struct Ctx;
20struct ELFSyncStream;
21class Defined;
22class Undefined;
23class Symbol;
24class InputSection;
25class InputSectionBase;
26class OutputSection;
27class RelocationBaseSection;
28class SectionBase;
29
30// Represents a relocation type, such as R_X86_64_PC32 or R_ARM_THM_CALL.
31struct RelType {
32 uint32_t v = 0;
33 /*implicit*/ constexpr RelType(uint32_t v = 0) : v(v) {}
34 /*implicit*/ operator uint32_t() const { return v; }
35};
36
37using JumpModType = uint32_t;
38
39// List of target-independent relocation types. Relocations read
40// from files are converted to these types so that the main code
41// doesn't have to know about architecture-specific details.
42enum RelExpr {
43 R_ABS,
44 R_ADDEND,
45 R_ADDEND_NEG,
46 R_DTPREL,
47 R_GOT,
48 R_GOT_OFF,
49 R_GOT_PC,
50 R_GOTONLY_PC,
51 R_GOTPLTONLY_PC,
52 R_GOTPLT,
53 R_GOTPLTREL,
54 R_GOTREL,
55 R_GOTPLT_GOTREL,
56 R_GOTPLT_PC,
57 R_NONE,
58 R_PC,
59 R_PLT,
60 R_PLT_PC,
61 R_PLT_GOTPLT,
62 R_PLT_GOTREL,
63 R_RELAX_HINT,
64 R_RELAX_GOT_PC,
65 R_RELAX_GOT_PC_NOPIC,
66 R_RELAX_TLS_GD_TO_IE,
67 R_RELAX_TLS_GD_TO_IE_ABS,
68 R_RELAX_TLS_GD_TO_IE_GOT_OFF,
69 R_RELAX_TLS_GD_TO_IE_GOTPLT,
70 R_RELAX_TLS_GD_TO_LE,
71 R_RELAX_TLS_GD_TO_LE_NEG,
72 R_RELAX_TLS_IE_TO_LE,
73 R_RELAX_TLS_LD_TO_LE,
74 R_SIZE,
75 R_TPREL,
76 R_TPREL_NEG,
77 R_TLSDESC,
78 R_TLSDESC_CALL,
79 R_TLSDESC_PC,
80 R_TLSDESC_GOTPLT,
81 R_TLSGD_GOT,
82 R_TLSGD_GOTPLT,
83 R_TLSGD_PC,
84 R_TLSIE_HINT,
85 R_TLSLD_GOT,
86 R_TLSLD_GOTPLT,
87 R_TLSLD_GOT_OFF,
88 R_TLSLD_HINT,
89 R_TLSLD_PC,
90
91 // The following is abstract relocation types used for only one target.
92 //
93 // Even though RelExpr is intended to be a target-neutral representation
94 // of a relocation type, there are some relocations whose semantics are
95 // unique to a target. Such relocation are marked with RE_<TARGET_NAME>.
96 RE_AARCH64_GOT_PAGE_PC,
97 RE_AARCH64_GOT_PAGE,
98 RE_AARCH64_PAGE_PC,
99 RE_AARCH64_TLSDESC_PAGE,
100 RE_AARCH64_AUTH,
101 RE_ARM_PCA,
102 RE_ARM_SBREL,
103 RE_MIPS_GOTREL,
104 RE_MIPS_GOT_GP,
105 RE_MIPS_GOT_GP_PC,
106 RE_MIPS_GOT_LOCAL_PAGE,
107 RE_MIPS_GOT_OFF,
108 RE_MIPS_GOT_OFF32,
109 RE_MIPS_OSEC_LOCAL_PAGE,
110 RE_MIPS_TLSGD,
111 RE_MIPS_TLSLD,
112 RE_PPC32_PLTREL,
113 RE_PPC64_CALL,
114 RE_PPC64_CALL_PLT,
115 RE_PPC64_TOCBASE,
116 RE_RISCV_ADD,
117 RE_RISCV_LEB128,
118 RE_RISCV_PC_INDIRECT,
119 // Same as R_PC but with page-aligned semantics.
120 RE_LOONGARCH_PAGE_PC,
121 // Same as R_PLT_PC but with page-aligned semantics.
122 RE_LOONGARCH_PLT_PAGE_PC,
123 // In addition to having page-aligned semantics, LoongArch GOT relocs are
124 // also reused for TLS, making the semantics differ from other architectures.
125 RE_LOONGARCH_GOT,
126 RE_LOONGARCH_GOT_PAGE_PC,
127 RE_LOONGARCH_PC_INDIRECT,
128 RE_LOONGARCH_TLSGD_PAGE_PC,
129 RE_LOONGARCH_TLSDESC_PAGE_PC,
130 RE_LOONGARCH_RELAX_TLS_GD_TO_IE_PAGE_PC,
131};
132
133// Architecture-neutral representation of relocation.
134struct Relocation {
135 RelExpr expr;
136 RelType type;
137 uint64_t offset;
138 int64_t addend;
139 Symbol *sym;
140};
141
142// Manipulate jump instructions with these modifiers. These are used to relax
143// jump instruction opcodes at basic block boundaries and are particularly
144// useful when basic block sections are enabled.
145struct JumpInstrMod {
146 uint64_t offset;
147 JumpModType original;
148 unsigned size;
149};
150
151void printLocation(ELFSyncStream &s, InputSectionBase &sec, const Symbol &sym,
152 uint64_t off);
153
154// This function writes undefined symbol diagnostics to an internal buffer.
155// Call reportUndefinedSymbols() after calling scanRelocations() to emit
156// the diagnostics.
157template <class ELFT> void scanRelocations(Ctx &ctx);
158template <class ELFT> void checkNoCrossRefs(Ctx &ctx);
159void reportUndefinedSymbols(Ctx &);
160bool maybeReportUndefined(Ctx &, Undefined &sym, InputSectionBase &sec,
161 uint64_t offset);
162void postScanRelocations(Ctx &ctx);
163void addGotEntry(Ctx &ctx, Symbol &sym);
164
165void hexagonTLSSymbolUpdate(Ctx &ctx);
166bool hexagonNeedsTLSSymbol(ArrayRef<OutputSection *> outputSections);
167
168bool isAbsolute(const Symbol &sym);
169
170class ThunkSection;
171class Thunk;
172class InputSectionDescription;
173
174class ThunkCreator {
175public:
176 // Thunk may be incomplete. Avoid inline ctor/dtor.
177 ThunkCreator(Ctx &ctx);
178 ~ThunkCreator();
179 // Return true if Thunks have been added to OutputSections
180 bool createThunks(uint32_t pass, ArrayRef<OutputSection *> outputSections);
181
182private:
183 void mergeThunks(ArrayRef<OutputSection *> outputSections);
184
185 ThunkSection *getISDThunkSec(OutputSection *os, InputSection *isec,
186 InputSectionDescription *isd,
187 const Relocation &rel, uint64_t src);
188
189 ThunkSection *getISThunkSec(InputSection *isec);
190
191 void createInitialThunkSections(ArrayRef<OutputSection *> outputSections);
192
193 std::pair<Thunk *, bool> getThunk(InputSection *isec, Relocation &rel,
194 uint64_t src);
195
196 std::pair<Thunk *, bool> getSyntheticLandingPad(Defined &d, int64_t a);
197
198 ThunkSection *addThunkSection(OutputSection *os, InputSectionDescription *,
199 uint64_t off, bool isPrefix = false);
200
201 bool normalizeExistingThunk(Relocation &rel, uint64_t src);
202
203 bool addSyntheticLandingPads();
204
205 Ctx &ctx;
206
207 // Record all the available Thunks for a (Symbol, addend) pair, where Symbol
208 // is represented as a (section, offset) pair. There may be multiple
209 // relocations sharing the same (section, offset + addend) pair. We may revert
210 // a relocation back to its original non-Thunk target, and restore the
211 // original addend, so we cannot fold offset + addend. A nested pair is used
212 // because DenseMapInfo is not specialized for std::tuple.
213 llvm::DenseMap<std::pair<std::pair<SectionBase *, uint64_t>, int64_t>,
214 SmallVector<std::unique_ptr<Thunk>, 0>>
215 thunkedSymbolsBySectionAndAddend;
216 llvm::DenseMap<std::pair<Symbol *, int64_t>,
217 SmallVector<std::unique_ptr<Thunk>, 0>>
218 thunkedSymbols;
219
220 // Find a Thunk from the Thunks symbol definition, we can use this to find
221 // the Thunk from a relocation to the Thunks symbol definition.
222 llvm::DenseMap<Symbol *, Thunk *> thunks;
223
224 // Track InputSections that have an inline ThunkSection placed in front
225 // an inline ThunkSection may have control fall through to the section below
226 // so we need to make sure that there is only one of them.
227 // The Mips LA25 Thunk is an example of an inline ThunkSection, as is
228 // the AArch64BTLandingPadThunk.
229 llvm::DenseMap<InputSection *, ThunkSection *> thunkedSections;
230
231 // Record landing pads, generated for a section + offset destination.
232 // Landling pads are alternative entry points for destinations that need
233 // to be reached via thunks that use indirect branches. A destination
234 // needs at most one landing pad as that can be reused by all callers.
235 llvm::DenseMap<std::pair<std::pair<SectionBase *, uint64_t>, int64_t>,
236 std::unique_ptr<Thunk>>
237 landingPadsBySectionAndAddend;
238
239 // All the nonLandingPad thunks that have been created, in order of creation.
240 std::vector<Thunk *> allThunks;
241
242 // The number of completed passes of createThunks this permits us
243 // to do one time initialization on Pass 0 and put a limit on the
244 // number of times it can be called to prevent infinite loops.
245 uint32_t pass = 0;
246};
247
248// Decode LEB128 without error checking. Only used by performance critical code
249// like RelocsCrel.
250inline uint64_t readLEB128(const uint8_t *&p, uint64_t leb) {
251 uint64_t acc = 0, shift = 0, byte;
252 do {
253 byte = *p++;
254 acc |= (byte - 128 * (byte >= leb)) << shift;
255 shift += 7;
256 } while (byte >= 128);
257 return acc;
258}
259inline uint64_t readULEB128(const uint8_t *&p) { return readLEB128(p, leb: 128); }
260inline int64_t readSLEB128(const uint8_t *&p) { return readLEB128(p, leb: 64); }
261
262// This class implements a CREL iterator that does not allocate extra memory.
263template <bool is64> struct RelocsCrel {
264 using uint = std::conditional_t<is64, uint64_t, uint32_t>;
265 struct const_iterator {
266 using iterator_category = std::forward_iterator_tag;
267 using value_type = llvm::object::Elf_Crel_Impl<is64>;
268 using difference_type = ptrdiff_t;
269 using pointer = value_type *;
270 using reference = const value_type &;
271 uint32_t count;
272 uint8_t flagBits, shift;
273 const uint8_t *p;
274 llvm::object::Elf_Crel_Impl<is64> crel{};
275 const_iterator(size_t hdr, const uint8_t *p)
276 : count(hdr / 8), flagBits(hdr & 4 ? 3 : 2), shift(hdr % 4), p(p) {
277 if (count)
278 step();
279 }
280 void step() {
281 // See object::decodeCrel.
282 const uint8_t b = *p++;
283 crel.r_offset += b >> flagBits << shift;
284 if (b >= 0x80)
285 crel.r_offset +=
286 ((readULEB128(p) << (7 - flagBits)) - (0x80 >> flagBits)) << shift;
287 if (b & 1)
288 crel.r_symidx += readSLEB128(p);
289 if (b & 2)
290 crel.r_type += readSLEB128(p);
291 if (b & 4 && flagBits == 3)
292 crel.r_addend += static_cast<uint>(readSLEB128(p));
293 }
294 llvm::object::Elf_Crel_Impl<is64> operator*() const { return crel; };
295 const llvm::object::Elf_Crel_Impl<is64> *operator->() const {
296 return &crel;
297 }
298 // For llvm::enumerate.
299 bool operator==(const const_iterator &r) const { return count == r.count; }
300 bool operator!=(const const_iterator &r) const { return count != r.count; }
301 const_iterator &operator++() {
302 if (--count)
303 step();
304 return *this;
305 }
306 // For RelocScan::scan when TLS relocations consume multiple entries.
307 void operator+=(size_t n) {
308 for (; n; --n)
309 operator++();
310 }
311 };
312
313 size_t hdr = 0;
314 const uint8_t *p = nullptr;
315
316 constexpr RelocsCrel() = default;
317 RelocsCrel(const uint8_t *p) : hdr(readULEB128(p)) { this->p = p; }
318 size_t size() const { return hdr / 8; }
319 const_iterator begin() const { return {hdr, p}; }
320 const_iterator end() const { return {0, nullptr}; }
321};
322
323template <class RelTy> struct Relocs : ArrayRef<RelTy> {
324 Relocs() = default;
325 Relocs(ArrayRef<RelTy> a) : ArrayRef<RelTy>(a) {}
326};
327
328template <bool is64>
329struct Relocs<llvm::object::Elf_Crel_Impl<is64>> : RelocsCrel<is64> {
330 using RelocsCrel<is64>::RelocsCrel;
331};
332
333// Return a int64_t to make sure we get the sign extension out of the way as
334// early as possible.
335template <class ELFT>
336static inline int64_t getAddend(const typename ELFT::Rel &rel) {
337 return 0;
338}
339template <class ELFT>
340static inline int64_t getAddend(const typename ELFT::Rela &rel) {
341 return rel.r_addend;
342}
343template <class ELFT>
344static inline int64_t getAddend(const typename ELFT::Crel &rel) {
345 return rel.r_addend;
346}
347
348RelocationBaseSection &getIRelativeSection(Ctx &ctx);
349
350// Returns true if Expr refers a GOT entry. Note that this function returns
351// false for TLS variables even though they need GOT, because TLS variables uses
352// GOT differently than the regular variables.
353bool needsGot(RelExpr expr);
354} // namespace lld::elf
355
356#endif
357