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