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