blob: 0470f873c88ecfd20b3c6e7e2dbef52e173f0025 [file] [log] [blame]
Ryan Prichard339ecef2020-01-02 16:36:06 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include "linker_relocate.h"
30
31#include <elf.h>
32#include <link.h>
33
34#include <type_traits>
35
36#include "linker.h"
37#include "linker_debug.h"
38#include "linker_globals.h"
39#include "linker_gnu_hash.h"
40#include "linker_phdr.h"
41#include "linker_relocs.h"
42#include "linker_reloc_iterators.h"
43#include "linker_sleb128.h"
44#include "linker_soinfo.h"
45#include "private/bionic_globals.h"
46
47static bool is_tls_reloc(ElfW(Word) type) {
48 switch (type) {
49 case R_GENERIC_TLS_DTPMOD:
50 case R_GENERIC_TLS_DTPREL:
51 case R_GENERIC_TLS_TPREL:
Elliott Hughes43462702022-10-10 19:21:44 +000052#if defined(R_GENERIC_TLSDESC)
Ryan Prichard339ecef2020-01-02 16:36:06 -080053 case R_GENERIC_TLSDESC:
Elliott Hughes43462702022-10-10 19:21:44 +000054#endif
Ryan Prichard339ecef2020-01-02 16:36:06 -080055 return true;
56 default:
57 return false;
58 }
59}
60
61class Relocator {
62 public:
63 Relocator(const VersionTracker& version_tracker, const SymbolLookupList& lookup_list)
64 : version_tracker(version_tracker), lookup_list(lookup_list)
65 {}
66
67 soinfo* si = nullptr;
68 const char* si_strtab = nullptr;
69 size_t si_strtab_size = 0;
70 ElfW(Sym)* si_symtab = nullptr;
71
72 const VersionTracker& version_tracker;
73 const SymbolLookupList& lookup_list;
74
75 // Cache key
76 ElfW(Word) cache_sym_val = 0;
77 // Cache value
78 const ElfW(Sym)* cache_sym = nullptr;
79 soinfo* cache_si = nullptr;
80
81 std::vector<TlsDynamicResolverArg>* tlsdesc_args;
82 std::vector<std::pair<TlsDescriptor*, size_t>> deferred_tlsdesc_relocs;
83 size_t tls_tp_base = 0;
84
85 __attribute__((always_inline))
86 const char* get_string(ElfW(Word) index) {
87 if (__predict_false(index >= si_strtab_size)) {
88 async_safe_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
89 si->get_realpath(), si_strtab_size, index);
90 }
91 return si_strtab + index;
92 }
93};
94
95template <bool DoLogging>
96__attribute__((always_inline))
97static inline bool lookup_symbol(Relocator& relocator, uint32_t r_sym, const char* sym_name,
98 soinfo** found_in, const ElfW(Sym)** sym) {
99 if (r_sym == relocator.cache_sym_val) {
100 *found_in = relocator.cache_si;
101 *sym = relocator.cache_sym;
102 count_relocation_if<DoLogging>(kRelocSymbolCached);
103 } else {
104 const version_info* vi = nullptr;
105 if (!relocator.si->lookup_version_info(relocator.version_tracker, r_sym, sym_name, &vi)) {
106 return false;
107 }
108
109 soinfo* local_found_in = nullptr;
110 const ElfW(Sym)* local_sym = soinfo_do_lookup(sym_name, vi, &local_found_in, relocator.lookup_list);
111
112 relocator.cache_sym_val = r_sym;
113 relocator.cache_si = local_found_in;
114 relocator.cache_sym = local_sym;
115 *found_in = local_found_in;
116 *sym = local_sym;
117 }
118
119 if (*sym == nullptr) {
120 if (ELF_ST_BIND(relocator.si_symtab[r_sym].st_info) != STB_WEAK) {
121 DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, relocator.si->get_realpath());
122 return false;
123 }
124 }
125
126 count_relocation_if<DoLogging>(kRelocSymbol);
127 return true;
128}
129
130enum class RelocMode {
131 // Fast path for JUMP_SLOT relocations.
132 JumpTable,
133 // Fast path for typical relocations: ABSOLUTE, GLOB_DAT, or RELATIVE.
134 Typical,
135 // Handle all relocation types, relocations in text sections, and statistics/tracing.
136 General,
137};
138
139struct linker_stats_t {
140 int count[kRelocMax];
141};
142
143static linker_stats_t linker_stats;
144
145void count_relocation(RelocationKind kind) {
146 ++linker_stats.count[kind];
147}
148
149void print_linker_stats() {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400150 LD_DEBUG(statistics,
151 "RELO STATS: %s: %d abs, %d rel, %d symbol (%d cached)",
152 g_argv[0],
153 linker_stats.count[kRelocAbsolute],
154 linker_stats.count[kRelocRelative],
155 linker_stats.count[kRelocSymbol],
156 linker_stats.count[kRelocSymbolCached]);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800157}
158
159static bool process_relocation_general(Relocator& relocator, const rel_t& reloc);
160
161template <RelocMode Mode>
162__attribute__((always_inline))
163static bool process_relocation_impl(Relocator& relocator, const rel_t& reloc) {
164 constexpr bool IsGeneral = Mode == RelocMode::General;
165
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000166 void* const rel_target = reinterpret_cast<void*>(reloc.r_offset + relocator.si->load_bias);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800167 const uint32_t r_type = ELFW(R_TYPE)(reloc.r_info);
168 const uint32_t r_sym = ELFW(R_SYM)(reloc.r_info);
169
170 soinfo* found_in = nullptr;
171 const ElfW(Sym)* sym = nullptr;
172 const char* sym_name = nullptr;
173 ElfW(Addr) sym_addr = 0;
174
175 if (r_sym != 0) {
176 sym_name = relocator.get_string(relocator.si_symtab[r_sym].st_name);
177 }
178
179 // While relocating a DSO with text relocations (obsolete and 32-bit only), the .text segment is
180 // writable (but not executable). To call an ifunc, temporarily remap the segment as executable
181 // (but not writable). Then switch it back to continue applying relocations in the segment.
182#if defined(__LP64__)
183 const bool handle_text_relocs = false;
184 auto protect_segments = []() { return true; };
185 auto unprotect_segments = []() { return true; };
186#else
187 const bool handle_text_relocs = IsGeneral && relocator.si->has_text_relocations;
188 auto protect_segments = [&]() {
189 // Make .text executable.
190 if (phdr_table_protect_segments(relocator.si->phdr, relocator.si->phnum,
Kalesh Singhb23787f2024-09-05 08:22:06 +0000191 relocator.si->load_bias, relocator.si->should_pad_segments(),
192 relocator.si->should_use_16kib_app_compat()) < 0) {
Elliott Hughesf5e21d92024-07-26 11:48:19 +0000193 DL_ERR("can't protect segments for \"%s\": %m", relocator.si->get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800194 return false;
195 }
196 return true;
197 };
198 auto unprotect_segments = [&]() {
199 // Make .text writable.
200 if (phdr_table_unprotect_segments(relocator.si->phdr, relocator.si->phnum,
Kalesh Singhb23787f2024-09-05 08:22:06 +0000201 relocator.si->load_bias, relocator.si->should_pad_segments(),
202 relocator.si->should_use_16kib_app_compat()) < 0) {
Elliott Hughesf5e21d92024-07-26 11:48:19 +0000203 DL_ERR("can't unprotect loadable segments for \"%s\": %m",
204 relocator.si->get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800205 return false;
206 }
207 return true;
208 };
209#endif
210
Ryan Prichard4f140692020-01-15 14:44:31 -0800211 // Skip symbol lookup for R_GENERIC_NONE relocations.
212 if (__predict_false(r_type == R_GENERIC_NONE)) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400213 LD_DEBUG(reloc && IsGeneral, "RELO NONE");
Ryan Prichard4f140692020-01-15 14:44:31 -0800214 return true;
215 }
216
Ryan Prichard339ecef2020-01-02 16:36:06 -0800217#if defined(USE_RELA)
218 auto get_addend_rel = [&]() -> ElfW(Addr) { return reloc.r_addend; };
219 auto get_addend_norel = [&]() -> ElfW(Addr) { return reloc.r_addend; };
220#else
221 auto get_addend_rel = [&]() -> ElfW(Addr) { return *static_cast<ElfW(Addr)*>(rel_target); };
222 auto get_addend_norel = [&]() -> ElfW(Addr) { return 0; };
223#endif
224
Ryan Prichard8ea6af52022-03-24 21:14:27 -0700225 if (!IsGeneral && __predict_false(is_tls_reloc(r_type))) {
226 // Always process TLS relocations using the slow code path, so that STB_LOCAL symbols are
227 // diagnosed, and ifunc processing is skipped.
228 return process_relocation_general(relocator, reloc);
229 }
230
Ryan Prichard339ecef2020-01-02 16:36:06 -0800231 if (IsGeneral && is_tls_reloc(r_type)) {
232 if (r_sym == 0) {
233 // By convention in ld.bfd and lld, an omitted symbol on a TLS relocation
234 // is a reference to the current module.
235 found_in = relocator.si;
236 } else if (ELF_ST_BIND(relocator.si_symtab[r_sym].st_info) == STB_LOCAL) {
237 // In certain situations, the Gold linker accesses a TLS symbol using a
238 // relocation to an STB_LOCAL symbol in .dynsym of either STT_SECTION or
239 // STT_TLS type. Bionic doesn't support these relocations, so issue an
240 // error. References:
241 // - https://groups.google.com/d/topic/generic-abi/dJ4_Y78aQ2M/discussion
242 // - https://sourceware.org/bugzilla/show_bug.cgi?id=17699
243 sym = &relocator.si_symtab[r_sym];
Ryan Prichard8ea6af52022-03-24 21:14:27 -0700244 auto sym_type = ELF_ST_TYPE(sym->st_info);
245 if (sym_type == STT_SECTION) {
246 DL_ERR("unexpected TLS reference to local section in \"%s\": sym type %d, rel type %u",
247 relocator.si->get_realpath(), sym_type, r_type);
248 } else {
249 DL_ERR(
250 "unexpected TLS reference to local symbol \"%s\" in \"%s\": sym type %d, rel type %u",
251 sym_name, relocator.si->get_realpath(), sym_type, r_type);
252 }
Ryan Prichard339ecef2020-01-02 16:36:06 -0800253 return false;
254 } else if (!lookup_symbol<IsGeneral>(relocator, r_sym, sym_name, &found_in, &sym)) {
255 return false;
256 }
257 if (found_in != nullptr && found_in->get_tls() == nullptr) {
258 // sym_name can be nullptr if r_sym is 0. A linker should never output an ELF file like this.
259 DL_ERR("TLS relocation refers to symbol \"%s\" in solib \"%s\" with no TLS segment",
260 sym_name, found_in->get_realpath());
261 return false;
262 }
263 if (sym != nullptr) {
264 if (ELF_ST_TYPE(sym->st_info) != STT_TLS) {
265 // A toolchain should never output a relocation like this.
266 DL_ERR("reference to non-TLS symbol \"%s\" from TLS relocation in \"%s\"",
267 sym_name, relocator.si->get_realpath());
268 return false;
269 }
270 sym_addr = sym->st_value;
271 }
272 } else {
273 if (r_sym == 0) {
274 // Do nothing.
275 } else {
276 if (!lookup_symbol<IsGeneral>(relocator, r_sym, sym_name, &found_in, &sym)) return false;
277 if (sym != nullptr) {
278 const bool should_protect_segments = handle_text_relocs &&
279 found_in == relocator.si &&
280 ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC;
281 if (should_protect_segments && !protect_segments()) return false;
282 sym_addr = found_in->resolve_symbol_address(sym);
283 if (should_protect_segments && !unprotect_segments()) return false;
284 } else if constexpr (IsGeneral) {
285 // A weak reference to an undefined symbol. We typically use a zero symbol address, but
286 // use the relocation base for PC-relative relocations, so that the value written is zero.
287 switch (r_type) {
288#if defined(__x86_64__)
289 case R_X86_64_PC32:
290 sym_addr = reinterpret_cast<ElfW(Addr)>(rel_target);
291 break;
292#elif defined(__i386__)
293 case R_386_PC32:
294 sym_addr = reinterpret_cast<ElfW(Addr)>(rel_target);
295 break;
296#endif
297 }
298 }
299 }
300 }
301
302 if constexpr (IsGeneral || Mode == RelocMode::JumpTable) {
303 if (r_type == R_GENERIC_JUMP_SLOT) {
304 count_relocation_if<IsGeneral>(kRelocAbsolute);
305 const ElfW(Addr) result = sym_addr + get_addend_norel();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400306 LD_DEBUG(reloc && IsGeneral, "RELO JMP_SLOT %16p <- %16p %s",
307 rel_target, reinterpret_cast<void*>(result), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800308 *static_cast<ElfW(Addr)*>(rel_target) = result;
309 return true;
310 }
311 }
312
313 if constexpr (IsGeneral || Mode == RelocMode::Typical) {
314 // Almost all dynamic relocations are of one of these types, and most will be
315 // R_GENERIC_ABSOLUTE. The platform typically uses RELR instead, but R_GENERIC_RELATIVE is
316 // common in non-platform binaries.
317 if (r_type == R_GENERIC_ABSOLUTE) {
318 count_relocation_if<IsGeneral>(kRelocAbsolute);
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000319 const ElfW(Addr) result = sym_addr + get_addend_rel();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400320 LD_DEBUG(reloc && IsGeneral, "RELO ABSOLUTE %16p <- %16p %s",
321 rel_target, reinterpret_cast<void*>(result), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800322 *static_cast<ElfW(Addr)*>(rel_target) = result;
323 return true;
324 } else if (r_type == R_GENERIC_GLOB_DAT) {
325 // The i386 psABI specifies that R_386_GLOB_DAT doesn't have an addend. The ARM ELF ABI
326 // document (IHI0044F) specifies that R_ARM_GLOB_DAT has an addend, but Bionic isn't adding
327 // it.
328 count_relocation_if<IsGeneral>(kRelocAbsolute);
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000329 const ElfW(Addr) result = sym_addr + get_addend_norel();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400330 LD_DEBUG(reloc && IsGeneral, "RELO GLOB_DAT %16p <- %16p %s",
331 rel_target, reinterpret_cast<void*>(result), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800332 *static_cast<ElfW(Addr)*>(rel_target) = result;
333 return true;
334 } else if (r_type == R_GENERIC_RELATIVE) {
335 // In practice, r_sym is always zero, but if it weren't, the linker would still look up the
336 // referenced symbol (and abort if the symbol isn't found), even though it isn't used.
337 count_relocation_if<IsGeneral>(kRelocRelative);
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000338 const ElfW(Addr) result = relocator.si->load_bias + get_addend_rel();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400339 LD_DEBUG(reloc && IsGeneral, "RELO RELATIVE %16p <- %16p",
340 rel_target, reinterpret_cast<void*>(result));
Ryan Prichard339ecef2020-01-02 16:36:06 -0800341 *static_cast<ElfW(Addr)*>(rel_target) = result;
342 return true;
343 }
344 }
345
346 if constexpr (!IsGeneral) {
347 // Almost all relocations are handled above. Handle the remaining relocations below, in a
348 // separate function call. The symbol lookup will be repeated, but the result should be served
349 // from the 1-symbol lookup cache.
350 return process_relocation_general(relocator, reloc);
351 }
352
353 switch (r_type) {
354 case R_GENERIC_IRELATIVE:
355 // In the linker, ifuncs are called as soon as possible so that string functions work. We must
356 // not call them again. (e.g. On arm32, resolving an ifunc changes the meaning of the addend
357 // from a resolver function to the implementation.)
358 if (!relocator.si->is_linker()) {
359 count_relocation_if<IsGeneral>(kRelocRelative);
360 const ElfW(Addr) ifunc_addr = relocator.si->load_bias + get_addend_rel();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400361 LD_DEBUG(reloc && IsGeneral, "RELO IRELATIVE %16p <- %16p",
362 rel_target, reinterpret_cast<void*>(ifunc_addr));
Ryan Prichard339ecef2020-01-02 16:36:06 -0800363 if (handle_text_relocs && !protect_segments()) return false;
364 const ElfW(Addr) result = call_ifunc_resolver(ifunc_addr);
365 if (handle_text_relocs && !unprotect_segments()) return false;
366 *static_cast<ElfW(Addr)*>(rel_target) = result;
367 }
368 break;
369 case R_GENERIC_COPY:
370 // Copy relocations allow read-only data or code in a non-PIE executable to access a
371 // variable from a DSO. The executable reserves extra space in its .bss section, and the
372 // linker copies the variable into the extra space. The executable then exports its copy
373 // to interpose the copy in the DSO.
374 //
375 // Bionic only supports PIE executables, so copy relocations aren't supported. The ARM and
376 // AArch64 ABI documents only allow them for ET_EXEC (non-PIE) objects. See IHI0056B and
377 // IHI0044F.
378 DL_ERR("%s COPY relocations are not supported", relocator.si->get_realpath());
379 return false;
380 case R_GENERIC_TLS_TPREL:
381 count_relocation_if<IsGeneral>(kRelocRelative);
382 {
383 ElfW(Addr) tpoff = 0;
384 if (found_in == nullptr) {
385 // Unresolved weak relocation. Leave tpoff at 0 to resolve
386 // &weak_tls_symbol to __get_tls().
387 } else {
388 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
389 const TlsModule& mod = get_tls_module(found_in->get_tls()->module_id);
390 if (mod.static_offset != SIZE_MAX) {
391 tpoff += mod.static_offset - relocator.tls_tp_base;
392 } else {
393 DL_ERR("TLS symbol \"%s\" in dlopened \"%s\" referenced from \"%s\" using IE access model",
394 sym_name, found_in->get_realpath(), relocator.si->get_realpath());
395 return false;
396 }
397 }
398 tpoff += sym_addr + get_addend_rel();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400399 LD_DEBUG(reloc && IsGeneral, "RELO TLS_TPREL %16p <- %16p %s",
400 rel_target, reinterpret_cast<void*>(tpoff), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800401 *static_cast<ElfW(Addr)*>(rel_target) = tpoff;
402 }
403 break;
404 case R_GENERIC_TLS_DTPMOD:
405 count_relocation_if<IsGeneral>(kRelocRelative);
406 {
407 size_t module_id = 0;
408 if (found_in == nullptr) {
409 // Unresolved weak relocation. Evaluate the module ID to 0.
410 } else {
411 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
412 module_id = found_in->get_tls()->module_id;
Ryan Prichardb4937462024-03-13 23:07:15 -0700413 CHECK(module_id != kTlsUninitializedModuleId);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800414 }
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400415 LD_DEBUG(reloc && IsGeneral, "RELO TLS_DTPMOD %16p <- %zu %s",
416 rel_target, module_id, sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800417 *static_cast<ElfW(Addr)*>(rel_target) = module_id;
418 }
419 break;
420 case R_GENERIC_TLS_DTPREL:
421 count_relocation_if<IsGeneral>(kRelocRelative);
422 {
Elliott Hughes43462702022-10-10 19:21:44 +0000423 const ElfW(Addr) result = sym_addr + get_addend_rel() - TLS_DTV_OFFSET;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400424 LD_DEBUG(reloc && IsGeneral, "RELO TLS_DTPREL %16p <- %16p %s",
425 rel_target, reinterpret_cast<void*>(result), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800426 *static_cast<ElfW(Addr)*>(rel_target) = result;
427 }
428 break;
429
Paul Kirth4d437782024-01-30 23:03:14 +0000430#if defined(__aarch64__) || defined(__riscv)
431 // Bionic currently implements TLSDESC for arm64 and riscv64. This implementation should work
432 // with other architectures, as long as the resolver functions are implemented.
Ryan Prichard339ecef2020-01-02 16:36:06 -0800433 case R_GENERIC_TLSDESC:
434 count_relocation_if<IsGeneral>(kRelocRelative);
435 {
436 ElfW(Addr) addend = reloc.r_addend;
437 TlsDescriptor* desc = static_cast<TlsDescriptor*>(rel_target);
438 if (found_in == nullptr) {
439 // Unresolved weak relocation.
440 desc->func = tlsdesc_resolver_unresolved_weak;
441 desc->arg = addend;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400442 LD_DEBUG(reloc && IsGeneral, "RELO TLSDESC %16p <- unresolved weak, addend 0x%zx %s",
443 rel_target, static_cast<size_t>(addend), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800444 } else {
445 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
446 size_t module_id = found_in->get_tls()->module_id;
447 const TlsModule& mod = get_tls_module(module_id);
448 if (mod.static_offset != SIZE_MAX) {
449 desc->func = tlsdesc_resolver_static;
450 desc->arg = mod.static_offset - relocator.tls_tp_base + sym_addr + addend;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400451 LD_DEBUG(reloc && IsGeneral, "RELO TLSDESC %16p <- static (0x%zx - 0x%zx + 0x%zx + 0x%zx) %s",
452 rel_target, mod.static_offset, relocator.tls_tp_base,
453 static_cast<size_t>(sym_addr), static_cast<size_t>(addend),
454 sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800455 } else {
456 relocator.tlsdesc_args->push_back({
457 .generation = mod.first_generation,
458 .index.module_id = module_id,
459 .index.offset = sym_addr + addend,
460 });
461 // Defer the TLSDESC relocation until the address of the TlsDynamicResolverArg object
462 // is finalized.
463 relocator.deferred_tlsdesc_relocs.push_back({
464 desc, relocator.tlsdesc_args->size() - 1
465 });
466 const TlsDynamicResolverArg& desc_arg = relocator.tlsdesc_args->back();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400467 LD_DEBUG(reloc && IsGeneral, "RELO TLSDESC %16p <- dynamic (gen %zu, mod %zu, off %zu) %s",
468 rel_target, desc_arg.generation, desc_arg.index.module_id,
469 desc_arg.index.offset, sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800470 }
471 }
472 }
473 break;
Paul Kirth4d437782024-01-30 23:03:14 +0000474#endif // defined(__aarch64__) || defined(__riscv)
Ryan Prichard339ecef2020-01-02 16:36:06 -0800475
476#if defined(__x86_64__)
477 case R_X86_64_32:
478 count_relocation_if<IsGeneral>(kRelocAbsolute);
479 {
480 const Elf32_Addr result = sym_addr + reloc.r_addend;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400481 LD_DEBUG(reloc && IsGeneral, "RELO R_X86_64_32 %16p <- 0x%08x %s",
482 rel_target, result, sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800483 *static_cast<Elf32_Addr*>(rel_target) = result;
484 }
485 break;
486 case R_X86_64_PC32:
487 count_relocation_if<IsGeneral>(kRelocRelative);
488 {
489 const ElfW(Addr) target = sym_addr + reloc.r_addend;
490 const ElfW(Addr) base = reinterpret_cast<ElfW(Addr)>(rel_target);
491 const Elf32_Addr result = target - base;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400492 LD_DEBUG(reloc && IsGeneral, "RELO R_X86_64_PC32 %16p <- 0x%08x (%16p - %16p) %s",
493 rel_target, result, reinterpret_cast<void*>(target),
494 reinterpret_cast<void*>(base), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800495 *static_cast<Elf32_Addr*>(rel_target) = result;
496 }
497 break;
498#elif defined(__i386__)
499 case R_386_PC32:
500 count_relocation_if<IsGeneral>(kRelocRelative);
501 {
502 const ElfW(Addr) target = sym_addr + get_addend_rel();
503 const ElfW(Addr) base = reinterpret_cast<ElfW(Addr)>(rel_target);
504 const ElfW(Addr) result = target - base;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400505 LD_DEBUG(reloc && IsGeneral, "RELO R_386_PC32 %16p <- 0x%08x (%16p - %16p) %s",
506 rel_target, result, reinterpret_cast<void*>(target),
507 reinterpret_cast<void*>(base), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800508 *static_cast<ElfW(Addr)*>(rel_target) = result;
509 }
510 break;
511#endif
512 default:
513 DL_ERR("unknown reloc type %d in \"%s\"", r_type, relocator.si->get_realpath());
514 return false;
515 }
516 return true;
517}
518
519__attribute__((noinline))
520static bool process_relocation_general(Relocator& relocator, const rel_t& reloc) {
521 return process_relocation_impl<RelocMode::General>(relocator, reloc);
522}
523
524template <RelocMode Mode>
525__attribute__((always_inline))
526static inline bool process_relocation(Relocator& relocator, const rel_t& reloc) {
527 return Mode == RelocMode::General ?
528 process_relocation_general(relocator, reloc) :
529 process_relocation_impl<Mode>(relocator, reloc);
530}
531
532template <RelocMode Mode>
533__attribute__((noinline))
534static bool plain_relocate_impl(Relocator& relocator, rel_t* rels, size_t rel_count) {
535 for (size_t i = 0; i < rel_count; ++i) {
536 if (!process_relocation<Mode>(relocator, rels[i])) {
537 return false;
538 }
539 }
540 return true;
541}
542
543template <RelocMode Mode>
544__attribute__((noinline))
545static bool packed_relocate_impl(Relocator& relocator, sleb128_decoder decoder) {
546 return for_all_packed_relocs(decoder, [&](const rel_t& reloc) {
547 return process_relocation<Mode>(relocator, reloc);
548 });
549}
550
551static bool needs_slow_relocate_loop(const Relocator& relocator __unused) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800552#if !defined(__LP64__)
553 if (relocator.si->has_text_relocations) return true;
554#endif
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400555 // Both LD_DEBUG relocation logging and statistics need the slow path.
556 if (g_linker_debug_config.any || g_linker_debug_config.statistics) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800557 return true;
558 }
559 return false;
560}
561
562template <RelocMode OptMode, typename ...Args>
563static bool plain_relocate(Relocator& relocator, Args ...args) {
564 return needs_slow_relocate_loop(relocator) ?
565 plain_relocate_impl<RelocMode::General>(relocator, args...) :
566 plain_relocate_impl<OptMode>(relocator, args...);
567}
568
569template <RelocMode OptMode, typename ...Args>
570static bool packed_relocate(Relocator& relocator, Args ...args) {
571 return needs_slow_relocate_loop(relocator) ?
572 packed_relocate_impl<RelocMode::General>(relocator, args...) :
573 packed_relocate_impl<OptMode>(relocator, args...);
574}
575
576bool soinfo::relocate(const SymbolLookupList& lookup_list) {
Ryan Prichard32bb3672024-03-08 16:53:06 -0800577 // For ldd, don't apply relocations because TLS segments are not registered.
578 // We don't care whether ldd diagnoses unresolved symbols.
579 if (g_is_ldd) {
580 return true;
581 }
Ryan Prichard339ecef2020-01-02 16:36:06 -0800582
583 VersionTracker version_tracker;
584
585 if (!version_tracker.init(this)) {
586 return false;
587 }
588
589 Relocator relocator(version_tracker, lookup_list);
590 relocator.si = this;
591 relocator.si_strtab = strtab_;
592 relocator.si_strtab_size = has_min_version(1) ? strtab_size_ : SIZE_MAX;
593 relocator.si_symtab = symtab_;
594 relocator.tlsdesc_args = &tlsdesc_args_;
595 relocator.tls_tp_base = __libc_shared_globals()->static_tls_layout.offset_thread_pointer();
596
Ryan Prichard2a901e62024-04-04 03:05:35 -0700597 // The linker already applied its RELR relocations in an earlier pass, so
598 // skip the RELR relocations for the linker.
599 if (relr_ != nullptr && !is_linker()) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400600 LD_DEBUG(reloc, "[ relocating %s relr ]", get_realpath());
Ryan Prichard2a901e62024-04-04 03:05:35 -0700601 const ElfW(Relr)* begin = relr_;
602 const ElfW(Relr)* end = relr_ + relr_count_;
603 if (!relocate_relr(begin, end, load_bias)) {
Peter Collingbournee0ebca82024-03-26 15:39:42 -0700604 return false;
605 }
606 }
607
Ryan Prichard339ecef2020-01-02 16:36:06 -0800608 if (android_relocs_ != nullptr) {
609 // check signature
610 if (android_relocs_size_ > 3 &&
611 android_relocs_[0] == 'A' &&
612 android_relocs_[1] == 'P' &&
613 android_relocs_[2] == 'S' &&
614 android_relocs_[3] == '2') {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400615 LD_DEBUG(reloc, "[ relocating %s android rel/rela ]", get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800616
617 const uint8_t* packed_relocs = android_relocs_ + 4;
618 const size_t packed_relocs_size = android_relocs_size_ - 4;
619
620 if (!packed_relocate<RelocMode::Typical>(relocator, sleb128_decoder(packed_relocs, packed_relocs_size))) {
621 return false;
622 }
623 } else {
624 DL_ERR("bad android relocation header.");
625 return false;
626 }
627 }
628
Ryan Prichard339ecef2020-01-02 16:36:06 -0800629#if defined(USE_RELA)
630 if (rela_ != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400631 LD_DEBUG(reloc, "[ relocating %s rela ]", get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800632
633 if (!plain_relocate<RelocMode::Typical>(relocator, rela_, rela_count_)) {
634 return false;
635 }
636 }
637 if (plt_rela_ != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400638 LD_DEBUG(reloc, "[ relocating %s plt rela ]", get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800639 if (!plain_relocate<RelocMode::JumpTable>(relocator, plt_rela_, plt_rela_count_)) {
640 return false;
641 }
642 }
643#else
644 if (rel_ != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400645 LD_DEBUG(reloc, "[ relocating %s rel ]", get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800646 if (!plain_relocate<RelocMode::Typical>(relocator, rel_, rel_count_)) {
647 return false;
648 }
649 }
650 if (plt_rel_ != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400651 LD_DEBUG(reloc, "[ relocating %s plt rel ]", get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800652 if (!plain_relocate<RelocMode::JumpTable>(relocator, plt_rel_, plt_rel_count_)) {
653 return false;
654 }
655 }
656#endif
657
Ryan Prichard339ecef2020-01-02 16:36:06 -0800658 // Once the tlsdesc_args_ vector's size is finalized, we can write the addresses of its elements
659 // into the TLSDESC relocations.
Paul Kirth4d437782024-01-30 23:03:14 +0000660#if defined(__aarch64__) || defined(__riscv)
661 // Bionic currently only implements TLSDESC for arm64 and riscv64.
Ryan Prichard339ecef2020-01-02 16:36:06 -0800662 for (const std::pair<TlsDescriptor*, size_t>& pair : relocator.deferred_tlsdesc_relocs) {
663 TlsDescriptor* desc = pair.first;
664 desc->func = tlsdesc_resolver_dynamic;
665 desc->arg = reinterpret_cast<size_t>(&tlsdesc_args_[pair.second]);
666 }
Paul Kirth4d437782024-01-30 23:03:14 +0000667#endif // defined(__aarch64__) || defined(__riscv)
Ryan Prichard339ecef2020-01-02 16:36:06 -0800668
669 return true;
670}