blob: 8f85871333dc75f2808fe6e1e47edd341a2e96fd [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() {
150 PRINT("RELO STATS: %s: %d abs, %d rel, %d symbol (%d cached)",
151 g_argv[0],
152 linker_stats.count[kRelocAbsolute],
153 linker_stats.count[kRelocRelative],
154 linker_stats.count[kRelocSymbol],
155 linker_stats.count[kRelocSymbolCached]);
156}
157
158static bool process_relocation_general(Relocator& relocator, const rel_t& reloc);
159
160template <RelocMode Mode>
161__attribute__((always_inline))
162static bool process_relocation_impl(Relocator& relocator, const rel_t& reloc) {
163 constexpr bool IsGeneral = Mode == RelocMode::General;
164
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000165 void* const rel_target = reinterpret_cast<void*>(reloc.r_offset + relocator.si->load_bias);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800166 const uint32_t r_type = ELFW(R_TYPE)(reloc.r_info);
167 const uint32_t r_sym = ELFW(R_SYM)(reloc.r_info);
168
169 soinfo* found_in = nullptr;
170 const ElfW(Sym)* sym = nullptr;
171 const char* sym_name = nullptr;
172 ElfW(Addr) sym_addr = 0;
173
174 if (r_sym != 0) {
175 sym_name = relocator.get_string(relocator.si_symtab[r_sym].st_name);
176 }
177
178 // While relocating a DSO with text relocations (obsolete and 32-bit only), the .text segment is
179 // writable (but not executable). To call an ifunc, temporarily remap the segment as executable
180 // (but not writable). Then switch it back to continue applying relocations in the segment.
181#if defined(__LP64__)
182 const bool handle_text_relocs = false;
183 auto protect_segments = []() { return true; };
184 auto unprotect_segments = []() { return true; };
185#else
186 const bool handle_text_relocs = IsGeneral && relocator.si->has_text_relocations;
187 auto protect_segments = [&]() {
188 // Make .text executable.
189 if (phdr_table_protect_segments(relocator.si->phdr, relocator.si->phnum,
Kalesh Singh4084b552024-03-13 13:35:49 -0700190 relocator.si->load_bias,
191 relocator.si->should_pad_segments()) < 0) {
Elliott Hughesf5e21d92024-07-26 11:48:19 +0000192 DL_ERR("can't protect segments for \"%s\": %m", relocator.si->get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800193 return false;
194 }
195 return true;
196 };
197 auto unprotect_segments = [&]() {
198 // Make .text writable.
199 if (phdr_table_unprotect_segments(relocator.si->phdr, relocator.si->phnum,
Kalesh Singh4084b552024-03-13 13:35:49 -0700200 relocator.si->load_bias,
201 relocator.si->should_pad_segments()) < 0) {
Elliott Hughesf5e21d92024-07-26 11:48:19 +0000202 DL_ERR("can't unprotect loadable segments for \"%s\": %m",
203 relocator.si->get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800204 return false;
205 }
206 return true;
207 };
208#endif
209
210 auto trace_reloc = [](const char* fmt, ...) __printflike(2, 3) {
211 if (IsGeneral &&
212 g_ld_debug_verbosity > LINKER_VERBOSITY_TRACE &&
213 DO_TRACE_RELO) {
214 va_list ap;
215 va_start(ap, fmt);
216 linker_log_va_list(LINKER_VERBOSITY_TRACE, fmt, ap);
217 va_end(ap);
218 }
219 };
220
Ryan Prichard4f140692020-01-15 14:44:31 -0800221 // Skip symbol lookup for R_GENERIC_NONE relocations.
222 if (__predict_false(r_type == R_GENERIC_NONE)) {
223 trace_reloc("RELO NONE");
224 return true;
225 }
226
Ryan Prichard339ecef2020-01-02 16:36:06 -0800227#if defined(USE_RELA)
228 auto get_addend_rel = [&]() -> ElfW(Addr) { return reloc.r_addend; };
229 auto get_addend_norel = [&]() -> ElfW(Addr) { return reloc.r_addend; };
230#else
231 auto get_addend_rel = [&]() -> ElfW(Addr) { return *static_cast<ElfW(Addr)*>(rel_target); };
232 auto get_addend_norel = [&]() -> ElfW(Addr) { return 0; };
233#endif
234
Ryan Prichard8ea6af52022-03-24 21:14:27 -0700235 if (!IsGeneral && __predict_false(is_tls_reloc(r_type))) {
236 // Always process TLS relocations using the slow code path, so that STB_LOCAL symbols are
237 // diagnosed, and ifunc processing is skipped.
238 return process_relocation_general(relocator, reloc);
239 }
240
Ryan Prichard339ecef2020-01-02 16:36:06 -0800241 if (IsGeneral && is_tls_reloc(r_type)) {
242 if (r_sym == 0) {
243 // By convention in ld.bfd and lld, an omitted symbol on a TLS relocation
244 // is a reference to the current module.
245 found_in = relocator.si;
246 } else if (ELF_ST_BIND(relocator.si_symtab[r_sym].st_info) == STB_LOCAL) {
247 // In certain situations, the Gold linker accesses a TLS symbol using a
248 // relocation to an STB_LOCAL symbol in .dynsym of either STT_SECTION or
249 // STT_TLS type. Bionic doesn't support these relocations, so issue an
250 // error. References:
251 // - https://groups.google.com/d/topic/generic-abi/dJ4_Y78aQ2M/discussion
252 // - https://sourceware.org/bugzilla/show_bug.cgi?id=17699
253 sym = &relocator.si_symtab[r_sym];
Ryan Prichard8ea6af52022-03-24 21:14:27 -0700254 auto sym_type = ELF_ST_TYPE(sym->st_info);
255 if (sym_type == STT_SECTION) {
256 DL_ERR("unexpected TLS reference to local section in \"%s\": sym type %d, rel type %u",
257 relocator.si->get_realpath(), sym_type, r_type);
258 } else {
259 DL_ERR(
260 "unexpected TLS reference to local symbol \"%s\" in \"%s\": sym type %d, rel type %u",
261 sym_name, relocator.si->get_realpath(), sym_type, r_type);
262 }
Ryan Prichard339ecef2020-01-02 16:36:06 -0800263 return false;
264 } else if (!lookup_symbol<IsGeneral>(relocator, r_sym, sym_name, &found_in, &sym)) {
265 return false;
266 }
267 if (found_in != nullptr && found_in->get_tls() == nullptr) {
268 // sym_name can be nullptr if r_sym is 0. A linker should never output an ELF file like this.
269 DL_ERR("TLS relocation refers to symbol \"%s\" in solib \"%s\" with no TLS segment",
270 sym_name, found_in->get_realpath());
271 return false;
272 }
273 if (sym != nullptr) {
274 if (ELF_ST_TYPE(sym->st_info) != STT_TLS) {
275 // A toolchain should never output a relocation like this.
276 DL_ERR("reference to non-TLS symbol \"%s\" from TLS relocation in \"%s\"",
277 sym_name, relocator.si->get_realpath());
278 return false;
279 }
280 sym_addr = sym->st_value;
281 }
282 } else {
283 if (r_sym == 0) {
284 // Do nothing.
285 } else {
286 if (!lookup_symbol<IsGeneral>(relocator, r_sym, sym_name, &found_in, &sym)) return false;
287 if (sym != nullptr) {
288 const bool should_protect_segments = handle_text_relocs &&
289 found_in == relocator.si &&
290 ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC;
291 if (should_protect_segments && !protect_segments()) return false;
292 sym_addr = found_in->resolve_symbol_address(sym);
293 if (should_protect_segments && !unprotect_segments()) return false;
294 } else if constexpr (IsGeneral) {
295 // A weak reference to an undefined symbol. We typically use a zero symbol address, but
296 // use the relocation base for PC-relative relocations, so that the value written is zero.
297 switch (r_type) {
298#if defined(__x86_64__)
299 case R_X86_64_PC32:
300 sym_addr = reinterpret_cast<ElfW(Addr)>(rel_target);
301 break;
302#elif defined(__i386__)
303 case R_386_PC32:
304 sym_addr = reinterpret_cast<ElfW(Addr)>(rel_target);
305 break;
306#endif
307 }
308 }
309 }
310 }
311
312 if constexpr (IsGeneral || Mode == RelocMode::JumpTable) {
313 if (r_type == R_GENERIC_JUMP_SLOT) {
314 count_relocation_if<IsGeneral>(kRelocAbsolute);
315 const ElfW(Addr) result = sym_addr + get_addend_norel();
316 trace_reloc("RELO JMP_SLOT %16p <- %16p %s",
317 rel_target, reinterpret_cast<void*>(result), sym_name);
318 *static_cast<ElfW(Addr)*>(rel_target) = result;
319 return true;
320 }
321 }
322
323 if constexpr (IsGeneral || Mode == RelocMode::Typical) {
324 // Almost all dynamic relocations are of one of these types, and most will be
325 // R_GENERIC_ABSOLUTE. The platform typically uses RELR instead, but R_GENERIC_RELATIVE is
326 // common in non-platform binaries.
327 if (r_type == R_GENERIC_ABSOLUTE) {
328 count_relocation_if<IsGeneral>(kRelocAbsolute);
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000329 const ElfW(Addr) result = sym_addr + get_addend_rel();
Ryan Prichard339ecef2020-01-02 16:36:06 -0800330 trace_reloc("RELO ABSOLUTE %16p <- %16p %s",
331 rel_target, reinterpret_cast<void*>(result), sym_name);
332 *static_cast<ElfW(Addr)*>(rel_target) = result;
333 return true;
334 } else if (r_type == R_GENERIC_GLOB_DAT) {
335 // The i386 psABI specifies that R_386_GLOB_DAT doesn't have an addend. The ARM ELF ABI
336 // document (IHI0044F) specifies that R_ARM_GLOB_DAT has an addend, but Bionic isn't adding
337 // it.
338 count_relocation_if<IsGeneral>(kRelocAbsolute);
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000339 const ElfW(Addr) result = sym_addr + get_addend_norel();
340 trace_reloc("RELO GLOB_DAT %16p <- %16p %s",
341 rel_target, reinterpret_cast<void*>(result), sym_name);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800342 *static_cast<ElfW(Addr)*>(rel_target) = result;
343 return true;
344 } else if (r_type == R_GENERIC_RELATIVE) {
345 // In practice, r_sym is always zero, but if it weren't, the linker would still look up the
346 // referenced symbol (and abort if the symbol isn't found), even though it isn't used.
347 count_relocation_if<IsGeneral>(kRelocRelative);
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000348 const ElfW(Addr) result = relocator.si->load_bias + get_addend_rel();
Ryan Prichard339ecef2020-01-02 16:36:06 -0800349 trace_reloc("RELO RELATIVE %16p <- %16p",
350 rel_target, reinterpret_cast<void*>(result));
351 *static_cast<ElfW(Addr)*>(rel_target) = result;
352 return true;
353 }
354 }
355
356 if constexpr (!IsGeneral) {
357 // Almost all relocations are handled above. Handle the remaining relocations below, in a
358 // separate function call. The symbol lookup will be repeated, but the result should be served
359 // from the 1-symbol lookup cache.
360 return process_relocation_general(relocator, reloc);
361 }
362
363 switch (r_type) {
364 case R_GENERIC_IRELATIVE:
365 // In the linker, ifuncs are called as soon as possible so that string functions work. We must
366 // not call them again. (e.g. On arm32, resolving an ifunc changes the meaning of the addend
367 // from a resolver function to the implementation.)
368 if (!relocator.si->is_linker()) {
369 count_relocation_if<IsGeneral>(kRelocRelative);
370 const ElfW(Addr) ifunc_addr = relocator.si->load_bias + get_addend_rel();
371 trace_reloc("RELO IRELATIVE %16p <- %16p",
372 rel_target, reinterpret_cast<void*>(ifunc_addr));
373 if (handle_text_relocs && !protect_segments()) return false;
374 const ElfW(Addr) result = call_ifunc_resolver(ifunc_addr);
375 if (handle_text_relocs && !unprotect_segments()) return false;
376 *static_cast<ElfW(Addr)*>(rel_target) = result;
377 }
378 break;
379 case R_GENERIC_COPY:
380 // Copy relocations allow read-only data or code in a non-PIE executable to access a
381 // variable from a DSO. The executable reserves extra space in its .bss section, and the
382 // linker copies the variable into the extra space. The executable then exports its copy
383 // to interpose the copy in the DSO.
384 //
385 // Bionic only supports PIE executables, so copy relocations aren't supported. The ARM and
386 // AArch64 ABI documents only allow them for ET_EXEC (non-PIE) objects. See IHI0056B and
387 // IHI0044F.
388 DL_ERR("%s COPY relocations are not supported", relocator.si->get_realpath());
389 return false;
390 case R_GENERIC_TLS_TPREL:
391 count_relocation_if<IsGeneral>(kRelocRelative);
392 {
393 ElfW(Addr) tpoff = 0;
394 if (found_in == nullptr) {
395 // Unresolved weak relocation. Leave tpoff at 0 to resolve
396 // &weak_tls_symbol to __get_tls().
397 } else {
398 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
399 const TlsModule& mod = get_tls_module(found_in->get_tls()->module_id);
400 if (mod.static_offset != SIZE_MAX) {
401 tpoff += mod.static_offset - relocator.tls_tp_base;
402 } else {
403 DL_ERR("TLS symbol \"%s\" in dlopened \"%s\" referenced from \"%s\" using IE access model",
404 sym_name, found_in->get_realpath(), relocator.si->get_realpath());
405 return false;
406 }
407 }
408 tpoff += sym_addr + get_addend_rel();
409 trace_reloc("RELO TLS_TPREL %16p <- %16p %s",
410 rel_target, reinterpret_cast<void*>(tpoff), sym_name);
411 *static_cast<ElfW(Addr)*>(rel_target) = tpoff;
412 }
413 break;
414 case R_GENERIC_TLS_DTPMOD:
415 count_relocation_if<IsGeneral>(kRelocRelative);
416 {
417 size_t module_id = 0;
418 if (found_in == nullptr) {
419 // Unresolved weak relocation. Evaluate the module ID to 0.
420 } else {
421 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
422 module_id = found_in->get_tls()->module_id;
Ryan Prichardb4937462024-03-13 23:07:15 -0700423 CHECK(module_id != kTlsUninitializedModuleId);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800424 }
425 trace_reloc("RELO TLS_DTPMOD %16p <- %zu %s",
426 rel_target, module_id, sym_name);
427 *static_cast<ElfW(Addr)*>(rel_target) = module_id;
428 }
429 break;
430 case R_GENERIC_TLS_DTPREL:
431 count_relocation_if<IsGeneral>(kRelocRelative);
432 {
Elliott Hughes43462702022-10-10 19:21:44 +0000433 const ElfW(Addr) result = sym_addr + get_addend_rel() - TLS_DTV_OFFSET;
Ryan Prichard339ecef2020-01-02 16:36:06 -0800434 trace_reloc("RELO TLS_DTPREL %16p <- %16p %s",
435 rel_target, reinterpret_cast<void*>(result), sym_name);
436 *static_cast<ElfW(Addr)*>(rel_target) = result;
437 }
438 break;
439
Paul Kirth4d437782024-01-30 23:03:14 +0000440#if defined(__aarch64__) || defined(__riscv)
441 // Bionic currently implements TLSDESC for arm64 and riscv64. This implementation should work
442 // with other architectures, as long as the resolver functions are implemented.
Ryan Prichard339ecef2020-01-02 16:36:06 -0800443 case R_GENERIC_TLSDESC:
444 count_relocation_if<IsGeneral>(kRelocRelative);
445 {
446 ElfW(Addr) addend = reloc.r_addend;
447 TlsDescriptor* desc = static_cast<TlsDescriptor*>(rel_target);
448 if (found_in == nullptr) {
449 // Unresolved weak relocation.
450 desc->func = tlsdesc_resolver_unresolved_weak;
451 desc->arg = addend;
452 trace_reloc("RELO TLSDESC %16p <- unresolved weak, addend 0x%zx %s",
453 rel_target, static_cast<size_t>(addend), sym_name);
454 } else {
455 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
456 size_t module_id = found_in->get_tls()->module_id;
457 const TlsModule& mod = get_tls_module(module_id);
458 if (mod.static_offset != SIZE_MAX) {
459 desc->func = tlsdesc_resolver_static;
460 desc->arg = mod.static_offset - relocator.tls_tp_base + sym_addr + addend;
461 trace_reloc("RELO TLSDESC %16p <- static (0x%zx - 0x%zx + 0x%zx + 0x%zx) %s",
462 rel_target, mod.static_offset, relocator.tls_tp_base,
463 static_cast<size_t>(sym_addr), static_cast<size_t>(addend),
464 sym_name);
465 } else {
466 relocator.tlsdesc_args->push_back({
467 .generation = mod.first_generation,
468 .index.module_id = module_id,
469 .index.offset = sym_addr + addend,
470 });
471 // Defer the TLSDESC relocation until the address of the TlsDynamicResolverArg object
472 // is finalized.
473 relocator.deferred_tlsdesc_relocs.push_back({
474 desc, relocator.tlsdesc_args->size() - 1
475 });
476 const TlsDynamicResolverArg& desc_arg = relocator.tlsdesc_args->back();
477 trace_reloc("RELO TLSDESC %16p <- dynamic (gen %zu, mod %zu, off %zu) %s",
478 rel_target, desc_arg.generation, desc_arg.index.module_id,
479 desc_arg.index.offset, sym_name);
480 }
481 }
482 }
483 break;
Paul Kirth4d437782024-01-30 23:03:14 +0000484#endif // defined(__aarch64__) || defined(__riscv)
Ryan Prichard339ecef2020-01-02 16:36:06 -0800485
486#if defined(__x86_64__)
487 case R_X86_64_32:
488 count_relocation_if<IsGeneral>(kRelocAbsolute);
489 {
490 const Elf32_Addr result = sym_addr + reloc.r_addend;
491 trace_reloc("RELO R_X86_64_32 %16p <- 0x%08x %s",
492 rel_target, result, sym_name);
493 *static_cast<Elf32_Addr*>(rel_target) = result;
494 }
495 break;
496 case R_X86_64_PC32:
497 count_relocation_if<IsGeneral>(kRelocRelative);
498 {
499 const ElfW(Addr) target = sym_addr + reloc.r_addend;
500 const ElfW(Addr) base = reinterpret_cast<ElfW(Addr)>(rel_target);
501 const Elf32_Addr result = target - base;
502 trace_reloc("RELO R_X86_64_PC32 %16p <- 0x%08x (%16p - %16p) %s",
503 rel_target, result, reinterpret_cast<void*>(target),
504 reinterpret_cast<void*>(base), sym_name);
505 *static_cast<Elf32_Addr*>(rel_target) = result;
506 }
507 break;
508#elif defined(__i386__)
509 case R_386_PC32:
510 count_relocation_if<IsGeneral>(kRelocRelative);
511 {
512 const ElfW(Addr) target = sym_addr + get_addend_rel();
513 const ElfW(Addr) base = reinterpret_cast<ElfW(Addr)>(rel_target);
514 const ElfW(Addr) result = target - base;
515 trace_reloc("RELO R_386_PC32 %16p <- 0x%08x (%16p - %16p) %s",
516 rel_target, result, reinterpret_cast<void*>(target),
517 reinterpret_cast<void*>(base), sym_name);
518 *static_cast<ElfW(Addr)*>(rel_target) = result;
519 }
520 break;
521#endif
522 default:
523 DL_ERR("unknown reloc type %d in \"%s\"", r_type, relocator.si->get_realpath());
524 return false;
525 }
526 return true;
527}
528
529__attribute__((noinline))
530static bool process_relocation_general(Relocator& relocator, const rel_t& reloc) {
531 return process_relocation_impl<RelocMode::General>(relocator, reloc);
532}
533
534template <RelocMode Mode>
535__attribute__((always_inline))
536static inline bool process_relocation(Relocator& relocator, const rel_t& reloc) {
537 return Mode == RelocMode::General ?
538 process_relocation_general(relocator, reloc) :
539 process_relocation_impl<Mode>(relocator, reloc);
540}
541
542template <RelocMode Mode>
543__attribute__((noinline))
544static bool plain_relocate_impl(Relocator& relocator, rel_t* rels, size_t rel_count) {
545 for (size_t i = 0; i < rel_count; ++i) {
546 if (!process_relocation<Mode>(relocator, rels[i])) {
547 return false;
548 }
549 }
550 return true;
551}
552
553template <RelocMode Mode>
554__attribute__((noinline))
555static bool packed_relocate_impl(Relocator& relocator, sleb128_decoder decoder) {
556 return for_all_packed_relocs(decoder, [&](const rel_t& reloc) {
557 return process_relocation<Mode>(relocator, reloc);
558 });
559}
560
561static bool needs_slow_relocate_loop(const Relocator& relocator __unused) {
562#if STATS
563 // TODO: This could become a run-time flag.
564 return true;
565#endif
566#if !defined(__LP64__)
567 if (relocator.si->has_text_relocations) return true;
568#endif
569 if (g_ld_debug_verbosity > LINKER_VERBOSITY_TRACE) {
570 // If linker TRACE() is enabled, then each relocation is logged.
571 return true;
572 }
573 return false;
574}
575
576template <RelocMode OptMode, typename ...Args>
577static bool plain_relocate(Relocator& relocator, Args ...args) {
578 return needs_slow_relocate_loop(relocator) ?
579 plain_relocate_impl<RelocMode::General>(relocator, args...) :
580 plain_relocate_impl<OptMode>(relocator, args...);
581}
582
583template <RelocMode OptMode, typename ...Args>
584static bool packed_relocate(Relocator& relocator, Args ...args) {
585 return needs_slow_relocate_loop(relocator) ?
586 packed_relocate_impl<RelocMode::General>(relocator, args...) :
587 packed_relocate_impl<OptMode>(relocator, args...);
588}
589
590bool soinfo::relocate(const SymbolLookupList& lookup_list) {
Ryan Prichard32bb3672024-03-08 16:53:06 -0800591 // For ldd, don't apply relocations because TLS segments are not registered.
592 // We don't care whether ldd diagnoses unresolved symbols.
593 if (g_is_ldd) {
594 return true;
595 }
Ryan Prichard339ecef2020-01-02 16:36:06 -0800596
597 VersionTracker version_tracker;
598
599 if (!version_tracker.init(this)) {
600 return false;
601 }
602
603 Relocator relocator(version_tracker, lookup_list);
604 relocator.si = this;
605 relocator.si_strtab = strtab_;
606 relocator.si_strtab_size = has_min_version(1) ? strtab_size_ : SIZE_MAX;
607 relocator.si_symtab = symtab_;
608 relocator.tlsdesc_args = &tlsdesc_args_;
609 relocator.tls_tp_base = __libc_shared_globals()->static_tls_layout.offset_thread_pointer();
610
Ryan Prichard2a901e62024-04-04 03:05:35 -0700611 // The linker already applied its RELR relocations in an earlier pass, so
612 // skip the RELR relocations for the linker.
613 if (relr_ != nullptr && !is_linker()) {
Peter Collingbournee0ebca82024-03-26 15:39:42 -0700614 DEBUG("[ relocating %s relr ]", get_realpath());
Ryan Prichard2a901e62024-04-04 03:05:35 -0700615 const ElfW(Relr)* begin = relr_;
616 const ElfW(Relr)* end = relr_ + relr_count_;
617 if (!relocate_relr(begin, end, load_bias)) {
Peter Collingbournee0ebca82024-03-26 15:39:42 -0700618 return false;
619 }
620 }
621
Ryan Prichard339ecef2020-01-02 16:36:06 -0800622 if (android_relocs_ != nullptr) {
623 // check signature
624 if (android_relocs_size_ > 3 &&
625 android_relocs_[0] == 'A' &&
626 android_relocs_[1] == 'P' &&
627 android_relocs_[2] == 'S' &&
628 android_relocs_[3] == '2') {
Elliott Hughes1f18d022024-07-16 15:44:32 +0000629 DEBUG("[ relocating %s android rel/rela ]", get_realpath());
Ryan Prichard339ecef2020-01-02 16:36:06 -0800630
631 const uint8_t* packed_relocs = android_relocs_ + 4;
632 const size_t packed_relocs_size = android_relocs_size_ - 4;
633
634 if (!packed_relocate<RelocMode::Typical>(relocator, sleb128_decoder(packed_relocs, packed_relocs_size))) {
635 return false;
636 }
637 } else {
638 DL_ERR("bad android relocation header.");
639 return false;
640 }
641 }
642
Ryan Prichard339ecef2020-01-02 16:36:06 -0800643#if defined(USE_RELA)
644 if (rela_ != nullptr) {
645 DEBUG("[ relocating %s rela ]", get_realpath());
646
647 if (!plain_relocate<RelocMode::Typical>(relocator, rela_, rela_count_)) {
648 return false;
649 }
650 }
651 if (plt_rela_ != nullptr) {
652 DEBUG("[ relocating %s plt rela ]", get_realpath());
653 if (!plain_relocate<RelocMode::JumpTable>(relocator, plt_rela_, plt_rela_count_)) {
654 return false;
655 }
656 }
657#else
658 if (rel_ != nullptr) {
659 DEBUG("[ relocating %s rel ]", get_realpath());
660 if (!plain_relocate<RelocMode::Typical>(relocator, rel_, rel_count_)) {
661 return false;
662 }
663 }
664 if (plt_rel_ != nullptr) {
665 DEBUG("[ relocating %s plt rel ]", get_realpath());
666 if (!plain_relocate<RelocMode::JumpTable>(relocator, plt_rel_, plt_rel_count_)) {
667 return false;
668 }
669 }
670#endif
671
Ryan Prichard339ecef2020-01-02 16:36:06 -0800672 // Once the tlsdesc_args_ vector's size is finalized, we can write the addresses of its elements
673 // into the TLSDESC relocations.
Paul Kirth4d437782024-01-30 23:03:14 +0000674#if defined(__aarch64__) || defined(__riscv)
675 // Bionic currently only implements TLSDESC for arm64 and riscv64.
Ryan Prichard339ecef2020-01-02 16:36:06 -0800676 for (const std::pair<TlsDescriptor*, size_t>& pair : relocator.deferred_tlsdesc_relocs) {
677 TlsDescriptor* desc = pair.first;
678 desc->func = tlsdesc_resolver_dynamic;
679 desc->arg = reinterpret_cast<size_t>(&tlsdesc_args_[pair.second]);
680 }
Paul Kirth4d437782024-01-30 23:03:14 +0000681#endif // defined(__aarch64__) || defined(__riscv)
Ryan Prichard339ecef2020-01-02 16:36:06 -0800682
683 return true;
684}