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