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