blob: 7bf12d364d6bb48408ea1c644da86bee2ade6c6e [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:
52 case R_GENERIC_TLSDESC:
53 return true;
54 default:
55 return false;
56 }
57}
58
59class Relocator {
60 public:
61 Relocator(const VersionTracker& version_tracker, const SymbolLookupList& lookup_list)
62 : version_tracker(version_tracker), lookup_list(lookup_list)
63 {}
64
65 soinfo* si = nullptr;
66 const char* si_strtab = nullptr;
67 size_t si_strtab_size = 0;
68 ElfW(Sym)* si_symtab = nullptr;
69
70 const VersionTracker& version_tracker;
71 const SymbolLookupList& lookup_list;
72
73 // Cache key
74 ElfW(Word) cache_sym_val = 0;
75 // Cache value
76 const ElfW(Sym)* cache_sym = nullptr;
77 soinfo* cache_si = nullptr;
78
79 std::vector<TlsDynamicResolverArg>* tlsdesc_args;
80 std::vector<std::pair<TlsDescriptor*, size_t>> deferred_tlsdesc_relocs;
81 size_t tls_tp_base = 0;
82
83 __attribute__((always_inline))
84 const char* get_string(ElfW(Word) index) {
85 if (__predict_false(index >= si_strtab_size)) {
86 async_safe_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
87 si->get_realpath(), si_strtab_size, index);
88 }
89 return si_strtab + index;
90 }
91};
92
93template <bool DoLogging>
94__attribute__((always_inline))
95static inline bool lookup_symbol(Relocator& relocator, uint32_t r_sym, const char* sym_name,
96 soinfo** found_in, const ElfW(Sym)** sym) {
97 if (r_sym == relocator.cache_sym_val) {
98 *found_in = relocator.cache_si;
99 *sym = relocator.cache_sym;
100 count_relocation_if<DoLogging>(kRelocSymbolCached);
101 } else {
102 const version_info* vi = nullptr;
103 if (!relocator.si->lookup_version_info(relocator.version_tracker, r_sym, sym_name, &vi)) {
104 return false;
105 }
106
107 soinfo* local_found_in = nullptr;
108 const ElfW(Sym)* local_sym = soinfo_do_lookup(sym_name, vi, &local_found_in, relocator.lookup_list);
109
110 relocator.cache_sym_val = r_sym;
111 relocator.cache_si = local_found_in;
112 relocator.cache_sym = local_sym;
113 *found_in = local_found_in;
114 *sym = local_sym;
115 }
116
117 if (*sym == nullptr) {
118 if (ELF_ST_BIND(relocator.si_symtab[r_sym].st_info) != STB_WEAK) {
119 DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, relocator.si->get_realpath());
120 return false;
121 }
122 }
123
124 count_relocation_if<DoLogging>(kRelocSymbol);
125 return true;
126}
127
128enum class RelocMode {
129 // Fast path for JUMP_SLOT relocations.
130 JumpTable,
131 // Fast path for typical relocations: ABSOLUTE, GLOB_DAT, or RELATIVE.
132 Typical,
133 // Handle all relocation types, relocations in text sections, and statistics/tracing.
134 General,
135};
136
137struct linker_stats_t {
138 int count[kRelocMax];
139};
140
141static linker_stats_t linker_stats;
142
143void count_relocation(RelocationKind kind) {
144 ++linker_stats.count[kind];
145}
146
147void print_linker_stats() {
148 PRINT("RELO STATS: %s: %d abs, %d rel, %d symbol (%d cached)",
149 g_argv[0],
150 linker_stats.count[kRelocAbsolute],
151 linker_stats.count[kRelocRelative],
152 linker_stats.count[kRelocSymbol],
153 linker_stats.count[kRelocSymbolCached]);
154}
155
156static bool process_relocation_general(Relocator& relocator, const rel_t& reloc);
157
158template <RelocMode Mode>
159__attribute__((always_inline))
160static bool process_relocation_impl(Relocator& relocator, const rel_t& reloc) {
161 constexpr bool IsGeneral = Mode == RelocMode::General;
162
163 void* const rel_target = reinterpret_cast<void*>(reloc.r_offset + relocator.si->load_bias);
164 const uint32_t r_type = ELFW(R_TYPE)(reloc.r_info);
165 const uint32_t r_sym = ELFW(R_SYM)(reloc.r_info);
166
167 soinfo* found_in = nullptr;
168 const ElfW(Sym)* sym = nullptr;
169 const char* sym_name = nullptr;
170 ElfW(Addr) sym_addr = 0;
171
172 if (r_sym != 0) {
173 sym_name = relocator.get_string(relocator.si_symtab[r_sym].st_name);
174 }
175
176 // While relocating a DSO with text relocations (obsolete and 32-bit only), the .text segment is
177 // writable (but not executable). To call an ifunc, temporarily remap the segment as executable
178 // (but not writable). Then switch it back to continue applying relocations in the segment.
179#if defined(__LP64__)
180 const bool handle_text_relocs = false;
181 auto protect_segments = []() { return true; };
182 auto unprotect_segments = []() { return true; };
183#else
184 const bool handle_text_relocs = IsGeneral && relocator.si->has_text_relocations;
185 auto protect_segments = [&]() {
186 // Make .text executable.
187 if (phdr_table_protect_segments(relocator.si->phdr, relocator.si->phnum,
188 relocator.si->load_bias) < 0) {
189 DL_ERR("can't protect segments for \"%s\": %s",
190 relocator.si->get_realpath(), strerror(errno));
191 return false;
192 }
193 return true;
194 };
195 auto unprotect_segments = [&]() {
196 // Make .text writable.
197 if (phdr_table_unprotect_segments(relocator.si->phdr, relocator.si->phnum,
198 relocator.si->load_bias) < 0) {
199 DL_ERR("can't unprotect loadable segments for \"%s\": %s",
200 relocator.si->get_realpath(), strerror(errno));
201 return false;
202 }
203 return true;
204 };
205#endif
206
207 auto trace_reloc = [](const char* fmt, ...) __printflike(2, 3) {
208 if (IsGeneral &&
209 g_ld_debug_verbosity > LINKER_VERBOSITY_TRACE &&
210 DO_TRACE_RELO) {
211 va_list ap;
212 va_start(ap, fmt);
213 linker_log_va_list(LINKER_VERBOSITY_TRACE, fmt, ap);
214 va_end(ap);
215 }
216 };
217
218#if defined(USE_RELA)
219 auto get_addend_rel = [&]() -> ElfW(Addr) { return reloc.r_addend; };
220 auto get_addend_norel = [&]() -> ElfW(Addr) { return reloc.r_addend; };
221#else
222 auto get_addend_rel = [&]() -> ElfW(Addr) { return *static_cast<ElfW(Addr)*>(rel_target); };
223 auto get_addend_norel = [&]() -> ElfW(Addr) { return 0; };
224#endif
225
226 if (IsGeneral && is_tls_reloc(r_type)) {
227 if (r_sym == 0) {
228 // By convention in ld.bfd and lld, an omitted symbol on a TLS relocation
229 // is a reference to the current module.
230 found_in = relocator.si;
231 } else if (ELF_ST_BIND(relocator.si_symtab[r_sym].st_info) == STB_LOCAL) {
232 // In certain situations, the Gold linker accesses a TLS symbol using a
233 // relocation to an STB_LOCAL symbol in .dynsym of either STT_SECTION or
234 // STT_TLS type. Bionic doesn't support these relocations, so issue an
235 // error. References:
236 // - https://groups.google.com/d/topic/generic-abi/dJ4_Y78aQ2M/discussion
237 // - https://sourceware.org/bugzilla/show_bug.cgi?id=17699
238 sym = &relocator.si_symtab[r_sym];
239 DL_ERR("unexpected TLS reference to local symbol \"%s\" in \"%s\": sym type %d, rel type %u",
240 sym_name, relocator.si->get_realpath(), ELF_ST_TYPE(sym->st_info), r_type);
241 return false;
242 } else if (!lookup_symbol<IsGeneral>(relocator, r_sym, sym_name, &found_in, &sym)) {
243 return false;
244 }
245 if (found_in != nullptr && found_in->get_tls() == nullptr) {
246 // sym_name can be nullptr if r_sym is 0. A linker should never output an ELF file like this.
247 DL_ERR("TLS relocation refers to symbol \"%s\" in solib \"%s\" with no TLS segment",
248 sym_name, found_in->get_realpath());
249 return false;
250 }
251 if (sym != nullptr) {
252 if (ELF_ST_TYPE(sym->st_info) != STT_TLS) {
253 // A toolchain should never output a relocation like this.
254 DL_ERR("reference to non-TLS symbol \"%s\" from TLS relocation in \"%s\"",
255 sym_name, relocator.si->get_realpath());
256 return false;
257 }
258 sym_addr = sym->st_value;
259 }
260 } else {
261 if (r_sym == 0) {
262 // Do nothing.
263 } else {
264 if (!lookup_symbol<IsGeneral>(relocator, r_sym, sym_name, &found_in, &sym)) return false;
265 if (sym != nullptr) {
266 const bool should_protect_segments = handle_text_relocs &&
267 found_in == relocator.si &&
268 ELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC;
269 if (should_protect_segments && !protect_segments()) return false;
270 sym_addr = found_in->resolve_symbol_address(sym);
271 if (should_protect_segments && !unprotect_segments()) return false;
272 } else if constexpr (IsGeneral) {
273 // A weak reference to an undefined symbol. We typically use a zero symbol address, but
274 // use the relocation base for PC-relative relocations, so that the value written is zero.
275 switch (r_type) {
276#if defined(__x86_64__)
277 case R_X86_64_PC32:
278 sym_addr = reinterpret_cast<ElfW(Addr)>(rel_target);
279 break;
280#elif defined(__i386__)
281 case R_386_PC32:
282 sym_addr = reinterpret_cast<ElfW(Addr)>(rel_target);
283 break;
284#endif
285 }
286 }
287 }
288 }
289
290 if constexpr (IsGeneral || Mode == RelocMode::JumpTable) {
291 if (r_type == R_GENERIC_JUMP_SLOT) {
292 count_relocation_if<IsGeneral>(kRelocAbsolute);
293 const ElfW(Addr) result = sym_addr + get_addend_norel();
294 trace_reloc("RELO JMP_SLOT %16p <- %16p %s",
295 rel_target, reinterpret_cast<void*>(result), sym_name);
296 *static_cast<ElfW(Addr)*>(rel_target) = result;
297 return true;
298 }
299 }
300
301 if constexpr (IsGeneral || Mode == RelocMode::Typical) {
302 // Almost all dynamic relocations are of one of these types, and most will be
303 // R_GENERIC_ABSOLUTE. The platform typically uses RELR instead, but R_GENERIC_RELATIVE is
304 // common in non-platform binaries.
305 if (r_type == R_GENERIC_ABSOLUTE) {
306 count_relocation_if<IsGeneral>(kRelocAbsolute);
307 const ElfW(Addr) result = sym_addr + get_addend_rel();
308 trace_reloc("RELO ABSOLUTE %16p <- %16p %s",
309 rel_target, reinterpret_cast<void*>(result), sym_name);
310 *static_cast<ElfW(Addr)*>(rel_target) = result;
311 return true;
312 } else if (r_type == R_GENERIC_GLOB_DAT) {
313 // The i386 psABI specifies that R_386_GLOB_DAT doesn't have an addend. The ARM ELF ABI
314 // document (IHI0044F) specifies that R_ARM_GLOB_DAT has an addend, but Bionic isn't adding
315 // it.
316 count_relocation_if<IsGeneral>(kRelocAbsolute);
317 const ElfW(Addr) result = sym_addr + get_addend_norel();
318 trace_reloc("RELO GLOB_DAT %16p <- %16p %s",
319 rel_target, reinterpret_cast<void*>(result), sym_name);
320 *static_cast<ElfW(Addr)*>(rel_target) = result;
321 return true;
322 } else if (r_type == R_GENERIC_RELATIVE) {
323 // In practice, r_sym is always zero, but if it weren't, the linker would still look up the
324 // referenced symbol (and abort if the symbol isn't found), even though it isn't used.
325 count_relocation_if<IsGeneral>(kRelocRelative);
326 const ElfW(Addr) result = relocator.si->load_bias + get_addend_rel();
327 trace_reloc("RELO RELATIVE %16p <- %16p",
328 rel_target, reinterpret_cast<void*>(result));
329 *static_cast<ElfW(Addr)*>(rel_target) = result;
330 return true;
331 }
332 }
333
334 if constexpr (!IsGeneral) {
335 // Almost all relocations are handled above. Handle the remaining relocations below, in a
336 // separate function call. The symbol lookup will be repeated, but the result should be served
337 // from the 1-symbol lookup cache.
338 return process_relocation_general(relocator, reloc);
339 }
340
341 switch (r_type) {
342 case R_GENERIC_IRELATIVE:
343 // In the linker, ifuncs are called as soon as possible so that string functions work. We must
344 // not call them again. (e.g. On arm32, resolving an ifunc changes the meaning of the addend
345 // from a resolver function to the implementation.)
346 if (!relocator.si->is_linker()) {
347 count_relocation_if<IsGeneral>(kRelocRelative);
348 const ElfW(Addr) ifunc_addr = relocator.si->load_bias + get_addend_rel();
349 trace_reloc("RELO IRELATIVE %16p <- %16p",
350 rel_target, reinterpret_cast<void*>(ifunc_addr));
351 if (handle_text_relocs && !protect_segments()) return false;
352 const ElfW(Addr) result = call_ifunc_resolver(ifunc_addr);
353 if (handle_text_relocs && !unprotect_segments()) return false;
354 *static_cast<ElfW(Addr)*>(rel_target) = result;
355 }
356 break;
357 case R_GENERIC_COPY:
358 // Copy relocations allow read-only data or code in a non-PIE executable to access a
359 // variable from a DSO. The executable reserves extra space in its .bss section, and the
360 // linker copies the variable into the extra space. The executable then exports its copy
361 // to interpose the copy in the DSO.
362 //
363 // Bionic only supports PIE executables, so copy relocations aren't supported. The ARM and
364 // AArch64 ABI documents only allow them for ET_EXEC (non-PIE) objects. See IHI0056B and
365 // IHI0044F.
366 DL_ERR("%s COPY relocations are not supported", relocator.si->get_realpath());
367 return false;
368 case R_GENERIC_TLS_TPREL:
369 count_relocation_if<IsGeneral>(kRelocRelative);
370 {
371 ElfW(Addr) tpoff = 0;
372 if (found_in == nullptr) {
373 // Unresolved weak relocation. Leave tpoff at 0 to resolve
374 // &weak_tls_symbol to __get_tls().
375 } else {
376 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
377 const TlsModule& mod = get_tls_module(found_in->get_tls()->module_id);
378 if (mod.static_offset != SIZE_MAX) {
379 tpoff += mod.static_offset - relocator.tls_tp_base;
380 } else {
381 DL_ERR("TLS symbol \"%s\" in dlopened \"%s\" referenced from \"%s\" using IE access model",
382 sym_name, found_in->get_realpath(), relocator.si->get_realpath());
383 return false;
384 }
385 }
386 tpoff += sym_addr + get_addend_rel();
387 trace_reloc("RELO TLS_TPREL %16p <- %16p %s",
388 rel_target, reinterpret_cast<void*>(tpoff), sym_name);
389 *static_cast<ElfW(Addr)*>(rel_target) = tpoff;
390 }
391 break;
392 case R_GENERIC_TLS_DTPMOD:
393 count_relocation_if<IsGeneral>(kRelocRelative);
394 {
395 size_t module_id = 0;
396 if (found_in == nullptr) {
397 // Unresolved weak relocation. Evaluate the module ID to 0.
398 } else {
399 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
400 module_id = found_in->get_tls()->module_id;
401 }
402 trace_reloc("RELO TLS_DTPMOD %16p <- %zu %s",
403 rel_target, module_id, sym_name);
404 *static_cast<ElfW(Addr)*>(rel_target) = module_id;
405 }
406 break;
407 case R_GENERIC_TLS_DTPREL:
408 count_relocation_if<IsGeneral>(kRelocRelative);
409 {
410 const ElfW(Addr) result = sym_addr + get_addend_rel();
411 trace_reloc("RELO TLS_DTPREL %16p <- %16p %s",
412 rel_target, reinterpret_cast<void*>(result), sym_name);
413 *static_cast<ElfW(Addr)*>(rel_target) = result;
414 }
415 break;
416
417#if defined(__aarch64__)
418 // Bionic currently only implements TLSDESC for arm64. This implementation should work with
419 // other architectures, as long as the resolver functions are implemented.
420 case R_GENERIC_TLSDESC:
421 count_relocation_if<IsGeneral>(kRelocRelative);
422 {
423 ElfW(Addr) addend = reloc.r_addend;
424 TlsDescriptor* desc = static_cast<TlsDescriptor*>(rel_target);
425 if (found_in == nullptr) {
426 // Unresolved weak relocation.
427 desc->func = tlsdesc_resolver_unresolved_weak;
428 desc->arg = addend;
429 trace_reloc("RELO TLSDESC %16p <- unresolved weak, addend 0x%zx %s",
430 rel_target, static_cast<size_t>(addend), sym_name);
431 } else {
432 CHECK(found_in->get_tls() != nullptr); // We rejected a missing TLS segment above.
433 size_t module_id = found_in->get_tls()->module_id;
434 const TlsModule& mod = get_tls_module(module_id);
435 if (mod.static_offset != SIZE_MAX) {
436 desc->func = tlsdesc_resolver_static;
437 desc->arg = mod.static_offset - relocator.tls_tp_base + sym_addr + addend;
438 trace_reloc("RELO TLSDESC %16p <- static (0x%zx - 0x%zx + 0x%zx + 0x%zx) %s",
439 rel_target, mod.static_offset, relocator.tls_tp_base,
440 static_cast<size_t>(sym_addr), static_cast<size_t>(addend),
441 sym_name);
442 } else {
443 relocator.tlsdesc_args->push_back({
444 .generation = mod.first_generation,
445 .index.module_id = module_id,
446 .index.offset = sym_addr + addend,
447 });
448 // Defer the TLSDESC relocation until the address of the TlsDynamicResolverArg object
449 // is finalized.
450 relocator.deferred_tlsdesc_relocs.push_back({
451 desc, relocator.tlsdesc_args->size() - 1
452 });
453 const TlsDynamicResolverArg& desc_arg = relocator.tlsdesc_args->back();
454 trace_reloc("RELO TLSDESC %16p <- dynamic (gen %zu, mod %zu, off %zu) %s",
455 rel_target, desc_arg.generation, desc_arg.index.module_id,
456 desc_arg.index.offset, sym_name);
457 }
458 }
459 }
460 break;
461#endif // defined(__aarch64__)
462
463#if defined(__x86_64__)
464 case R_X86_64_32:
465 count_relocation_if<IsGeneral>(kRelocAbsolute);
466 {
467 const Elf32_Addr result = sym_addr + reloc.r_addend;
468 trace_reloc("RELO R_X86_64_32 %16p <- 0x%08x %s",
469 rel_target, result, sym_name);
470 *static_cast<Elf32_Addr*>(rel_target) = result;
471 }
472 break;
473 case R_X86_64_PC32:
474 count_relocation_if<IsGeneral>(kRelocRelative);
475 {
476 const ElfW(Addr) target = sym_addr + reloc.r_addend;
477 const ElfW(Addr) base = reinterpret_cast<ElfW(Addr)>(rel_target);
478 const Elf32_Addr result = target - base;
479 trace_reloc("RELO R_X86_64_PC32 %16p <- 0x%08x (%16p - %16p) %s",
480 rel_target, result, reinterpret_cast<void*>(target),
481 reinterpret_cast<void*>(base), sym_name);
482 *static_cast<Elf32_Addr*>(rel_target) = result;
483 }
484 break;
485#elif defined(__i386__)
486 case R_386_PC32:
487 count_relocation_if<IsGeneral>(kRelocRelative);
488 {
489 const ElfW(Addr) target = sym_addr + get_addend_rel();
490 const ElfW(Addr) base = reinterpret_cast<ElfW(Addr)>(rel_target);
491 const ElfW(Addr) result = target - base;
492 trace_reloc("RELO R_386_PC32 %16p <- 0x%08x (%16p - %16p) %s",
493 rel_target, result, reinterpret_cast<void*>(target),
494 reinterpret_cast<void*>(base), sym_name);
495 *static_cast<ElfW(Addr)*>(rel_target) = result;
496 }
497 break;
498#endif
499 default:
500 DL_ERR("unknown reloc type %d in \"%s\"", r_type, relocator.si->get_realpath());
501 return false;
502 }
503 return true;
504}
505
506__attribute__((noinline))
507static bool process_relocation_general(Relocator& relocator, const rel_t& reloc) {
508 return process_relocation_impl<RelocMode::General>(relocator, reloc);
509}
510
511template <RelocMode Mode>
512__attribute__((always_inline))
513static inline bool process_relocation(Relocator& relocator, const rel_t& reloc) {
514 return Mode == RelocMode::General ?
515 process_relocation_general(relocator, reloc) :
516 process_relocation_impl<Mode>(relocator, reloc);
517}
518
519template <RelocMode Mode>
520__attribute__((noinline))
521static bool plain_relocate_impl(Relocator& relocator, rel_t* rels, size_t rel_count) {
522 for (size_t i = 0; i < rel_count; ++i) {
523 if (!process_relocation<Mode>(relocator, rels[i])) {
524 return false;
525 }
526 }
527 return true;
528}
529
530template <RelocMode Mode>
531__attribute__((noinline))
532static bool packed_relocate_impl(Relocator& relocator, sleb128_decoder decoder) {
533 return for_all_packed_relocs(decoder, [&](const rel_t& reloc) {
534 return process_relocation<Mode>(relocator, reloc);
535 });
536}
537
538static bool needs_slow_relocate_loop(const Relocator& relocator __unused) {
539#if STATS
540 // TODO: This could become a run-time flag.
541 return true;
542#endif
543#if !defined(__LP64__)
544 if (relocator.si->has_text_relocations) return true;
545#endif
546 if (g_ld_debug_verbosity > LINKER_VERBOSITY_TRACE) {
547 // If linker TRACE() is enabled, then each relocation is logged.
548 return true;
549 }
550 return false;
551}
552
553template <RelocMode OptMode, typename ...Args>
554static bool plain_relocate(Relocator& relocator, Args ...args) {
555 return needs_slow_relocate_loop(relocator) ?
556 plain_relocate_impl<RelocMode::General>(relocator, args...) :
557 plain_relocate_impl<OptMode>(relocator, args...);
558}
559
560template <RelocMode OptMode, typename ...Args>
561static bool packed_relocate(Relocator& relocator, Args ...args) {
562 return needs_slow_relocate_loop(relocator) ?
563 packed_relocate_impl<RelocMode::General>(relocator, args...) :
564 packed_relocate_impl<OptMode>(relocator, args...);
565}
566
567bool soinfo::relocate(const SymbolLookupList& lookup_list) {
568
569 VersionTracker version_tracker;
570
571 if (!version_tracker.init(this)) {
572 return false;
573 }
574
575 Relocator relocator(version_tracker, lookup_list);
576 relocator.si = this;
577 relocator.si_strtab = strtab_;
578 relocator.si_strtab_size = has_min_version(1) ? strtab_size_ : SIZE_MAX;
579 relocator.si_symtab = symtab_;
580 relocator.tlsdesc_args = &tlsdesc_args_;
581 relocator.tls_tp_base = __libc_shared_globals()->static_tls_layout.offset_thread_pointer();
582
583 if (android_relocs_ != nullptr) {
584 // check signature
585 if (android_relocs_size_ > 3 &&
586 android_relocs_[0] == 'A' &&
587 android_relocs_[1] == 'P' &&
588 android_relocs_[2] == 'S' &&
589 android_relocs_[3] == '2') {
590 DEBUG("[ android relocating %s ]", get_realpath());
591
592 const uint8_t* packed_relocs = android_relocs_ + 4;
593 const size_t packed_relocs_size = android_relocs_size_ - 4;
594
595 if (!packed_relocate<RelocMode::Typical>(relocator, sleb128_decoder(packed_relocs, packed_relocs_size))) {
596 return false;
597 }
598 } else {
599 DL_ERR("bad android relocation header.");
600 return false;
601 }
602 }
603
604 if (relr_ != nullptr) {
605 DEBUG("[ relocating %s relr ]", get_realpath());
606 if (!relocate_relr()) {
607 return false;
608 }
609 }
610
611#if defined(USE_RELA)
612 if (rela_ != nullptr) {
613 DEBUG("[ relocating %s rela ]", get_realpath());
614
615 if (!plain_relocate<RelocMode::Typical>(relocator, rela_, rela_count_)) {
616 return false;
617 }
618 }
619 if (plt_rela_ != nullptr) {
620 DEBUG("[ relocating %s plt rela ]", get_realpath());
621 if (!plain_relocate<RelocMode::JumpTable>(relocator, plt_rela_, plt_rela_count_)) {
622 return false;
623 }
624 }
625#else
626 if (rel_ != nullptr) {
627 DEBUG("[ relocating %s rel ]", get_realpath());
628 if (!plain_relocate<RelocMode::Typical>(relocator, rel_, rel_count_)) {
629 return false;
630 }
631 }
632 if (plt_rel_ != nullptr) {
633 DEBUG("[ relocating %s plt rel ]", get_realpath());
634 if (!plain_relocate<RelocMode::JumpTable>(relocator, plt_rel_, plt_rel_count_)) {
635 return false;
636 }
637 }
638#endif
639
640#if defined(__mips__)
641 if (!mips_relocate_got(version_tracker, global_group, local_group)) {
642 return false;
643 }
644#endif
645
646 // Once the tlsdesc_args_ vector's size is finalized, we can write the addresses of its elements
647 // into the TLSDESC relocations.
648#if defined(__aarch64__)
649 // Bionic currently only implements TLSDESC for arm64.
650 for (const std::pair<TlsDescriptor*, size_t>& pair : relocator.deferred_tlsdesc_relocs) {
651 TlsDescriptor* desc = pair.first;
652 desc->func = tlsdesc_resolver_dynamic;
653 desc->arg = reinterpret_cast<size_t>(&tlsdesc_args_[pair.second]);
654 }
655#endif
656
657 return true;
658}