blob: b2170d868931975fd15bdef1a5eaf7a0e3fb1501 [file] [log] [blame]
Dimitry Ivanov48ec2882016-08-04 11:50:36 -07001/*
2 * Copyright (C) 2016 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_soinfo.h"
30
31#include <dlfcn.h>
32#include <elf.h>
33#include <string.h>
34#include <sys/stat.h>
35#include <unistd.h>
36
Christopher Ferris7a3681e2017-04-24 17:48:32 -070037#include <async_safe/log.h>
38
Ryan Prichard0e12cce2020-01-02 14:59:11 -080039#include "linker.h"
Ryan Prichard4d4087d2019-12-02 16:55:48 -080040#include "linker_config.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070041#include "linker_debug.h"
42#include "linker_globals.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080043#include "linker_gnu_hash.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070044#include "linker_logger.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080045#include "linker_relocate.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070046#include "linker_utils.h"
47
Ryan Prichard339ecef2020-01-02 16:36:06 -080048// Enable the slow lookup path if symbol lookups should be logged.
49static bool is_lookup_tracing_enabled() {
50 return g_ld_debug_verbosity > LINKER_VERBOSITY_TRACE && DO_TRACE_LOOKUP;
51}
52
53SymbolLookupList::SymbolLookupList(soinfo* si)
54 : sole_lib_(si->get_lookup_lib()), begin_(&sole_lib_), end_(&sole_lib_ + 1) {
55 CHECK(si != nullptr);
56 slow_path_count_ += is_lookup_tracing_enabled();
57 slow_path_count_ += sole_lib_.needs_sysv_lookup();
58}
59
60SymbolLookupList::SymbolLookupList(const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
61 slow_path_count_ += is_lookup_tracing_enabled();
62 libs_.reserve(1 + global_group.size() + local_group.size());
63
64 // Reserve a space in front for DT_SYMBOLIC lookup.
65 libs_.push_back(SymbolLookupLib {});
66
67 global_group.for_each([this](soinfo* si) {
68 libs_.push_back(si->get_lookup_lib());
69 slow_path_count_ += libs_.back().needs_sysv_lookup();
70 });
71
72 local_group.for_each([this](soinfo* si) {
73 libs_.push_back(si->get_lookup_lib());
74 slow_path_count_ += libs_.back().needs_sysv_lookup();
75 });
76
77 begin_ = &libs_[1];
78 end_ = &libs_[0] + libs_.size();
79}
80
81/* "This element's presence in a shared object library alters the dynamic linker's
82 * symbol resolution algorithm for references within the library. Instead of starting
83 * a symbol search with the executable file, the dynamic linker starts from the shared
84 * object itself. If the shared object fails to supply the referenced symbol, the
85 * dynamic linker then searches the executable file and other shared objects as usual."
86 *
87 * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
88 *
89 * Note that this is unlikely since static linker avoids generating
90 * relocations for -Bsymbolic linked dynamic executables.
91 */
92void SymbolLookupList::set_dt_symbolic_lib(soinfo* lib) {
93 CHECK(!libs_.empty());
94 slow_path_count_ -= libs_[0].needs_sysv_lookup();
95 libs_[0] = lib ? lib->get_lookup_lib() : SymbolLookupLib();
96 slow_path_count_ += libs_[0].needs_sysv_lookup();
97 begin_ = lib ? &libs_[0] : &libs_[1];
98}
99
100// Check whether a requested version matches the version on a symbol definition. There are a few
101// special cases:
102// - If the defining DSO has no version info at all, then any version matches.
103// - If no version is requested (vi==nullptr, verneed==kVersymNotNeeded), then any non-hidden
104// version matches.
105// - If the requested version is not defined by the DSO, then verneed is kVersymGlobal, and only
106// global symbol definitions match. (This special case is handled as part of the ordinary case
107// where the version must match exactly.)
108static inline bool check_symbol_version(const ElfW(Versym)* ver_table, uint32_t sym_idx,
109 const ElfW(Versym) verneed) {
110 if (ver_table == nullptr) return true;
111 const uint32_t verdef = ver_table[sym_idx];
112 return (verneed == kVersymNotNeeded) ?
113 !(verdef & kVersymHiddenBit) :
114 verneed == (verdef & ~kVersymHiddenBit);
115}
116
117template <bool IsGeneral>
118__attribute__((noinline)) static const ElfW(Sym)*
119soinfo_do_lookup_impl(const char* name, const version_info* vi,
120 soinfo** si_found_in, const SymbolLookupList& lookup_list) {
121 const auto [ hash, name_len ] = calculate_gnu_hash(name);
122 constexpr uint32_t kBloomMaskBits = sizeof(ElfW(Addr)) * 8;
123 SymbolName elf_symbol_name(name);
124
125 const SymbolLookupLib* end = lookup_list.end();
126 const SymbolLookupLib* it = lookup_list.begin();
127
128 while (true) {
129 const SymbolLookupLib* lib;
130 uint32_t sym_idx;
131
132 // Iterate over libraries until we find one whose Bloom filter matches the symbol we're
133 // searching for.
134 while (true) {
135 if (it == end) return nullptr;
136 lib = it++;
137
138 if (IsGeneral && lib->needs_sysv_lookup()) {
139 if (const ElfW(Sym)* sym = lib->si_->find_symbol_by_name(elf_symbol_name, vi)) {
140 *si_found_in = lib->si_;
141 return sym;
142 }
143 continue;
144 }
145
146 if (IsGeneral) {
147 TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p (gnu)",
148 name, lib->si_->get_realpath(), reinterpret_cast<void*>(lib->si_->base));
149 }
150
151 const uint32_t word_num = (hash / kBloomMaskBits) & lib->gnu_maskwords_;
152 const ElfW(Addr) bloom_word = lib->gnu_bloom_filter_[word_num];
153 const uint32_t h1 = hash % kBloomMaskBits;
154 const uint32_t h2 = (hash >> lib->gnu_shift2_) % kBloomMaskBits;
155
156 if ((1 & (bloom_word >> h1) & (bloom_word >> h2)) == 1) {
157 sym_idx = lib->gnu_bucket_[hash % lib->gnu_nbucket_];
158 if (sym_idx != 0) {
159 break;
160 }
161 }
Ryan Prichard339ecef2020-01-02 16:36:06 -0800162 }
163
164 // Search the library's hash table chain.
165 ElfW(Versym) verneed = kVersymNotNeeded;
166 bool calculated_verneed = false;
167
168 uint32_t chain_value = 0;
169 const ElfW(Sym)* sym = nullptr;
170
171 do {
172 sym = lib->symtab_ + sym_idx;
173 chain_value = lib->gnu_chain_[sym_idx];
174 if ((chain_value >> 1) == (hash >> 1)) {
175 if (vi != nullptr && !calculated_verneed) {
176 calculated_verneed = true;
177 verneed = find_verdef_version_index(lib->si_, vi);
178 }
179 if (check_symbol_version(lib->versym_, sym_idx, verneed) &&
180 static_cast<size_t>(sym->st_name) + name_len + 1 <= lib->strtab_size_ &&
181 memcmp(lib->strtab_ + sym->st_name, name, name_len + 1) == 0 &&
182 is_symbol_global_and_defined(lib->si_, sym)) {
183 *si_found_in = lib->si_;
Ryan Prichard339ecef2020-01-02 16:36:06 -0800184 return sym;
185 }
186 }
187 ++sym_idx;
188 } while ((chain_value & 1) == 0);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800189 }
190}
191
192const ElfW(Sym)* soinfo_do_lookup(const char* name, const version_info* vi,
193 soinfo** si_found_in, const SymbolLookupList& lookup_list) {
194 return lookup_list.needs_slow_path() ?
195 soinfo_do_lookup_impl<true>(name, vi, si_found_in, lookup_list) :
196 soinfo_do_lookup_impl<false>(name, vi, si_found_in, lookup_list);
197}
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700198
Elliott Hughesb003e102023-09-29 17:07:27 +0000199soinfo::soinfo(android_namespace_t* ns, const char* realpath, const struct stat* file_stat,
200 off64_t file_offset, int rtld_flags) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700201 if (realpath != nullptr) {
202 realpath_ = realpath;
203 }
204
205 flags_ = FLAG_NEW_SOINFO;
206 version_ = SOINFO_VERSION;
207
208 if (file_stat != nullptr) {
209 this->st_dev_ = file_stat->st_dev;
210 this->st_ino_ = file_stat->st_ino;
211 this->file_offset_ = file_offset;
212 }
213
214 this->rtld_flags_ = rtld_flags;
215 this->primary_namespace_ = ns;
216}
217
218soinfo::~soinfo() {
219 g_soinfo_handles_map.erase(handle_);
220}
221
222void soinfo::set_dt_runpath(const char* path) {
223 if (!has_min_version(3)) {
224 return;
225 }
226
227 std::vector<std::string> runpaths;
228
229 split_path(path, ":", &runpaths);
230
231 std::string origin = dirname(get_realpath());
Jiyong Park57b9d1e2019-01-17 03:14:45 +0900232 // FIXME: add $PLATFORM.
233 std::vector<std::pair<std::string, std::string>> params = {
234 {"ORIGIN", origin},
Ryan Prichard4d4087d2019-12-02 16:55:48 -0800235 {"LIB", kLibPath},
Jiyong Park57b9d1e2019-01-17 03:14:45 +0900236 };
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700237 for (auto&& s : runpaths) {
Dimitry Ivanov2a6d9b22017-03-11 14:35:38 -0800238 format_string(&s, params);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700239 }
240
241 resolve_paths(runpaths, &dt_runpath_);
242}
243
244const ElfW(Versym)* soinfo::get_versym(size_t n) const {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800245 auto table = get_versym_table();
246 return table ? table + n : nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700247}
248
249ElfW(Addr) soinfo::get_verneed_ptr() const {
250 if (has_min_version(2)) {
251 return verneed_ptr_;
252 }
253
254 return 0;
255}
256
257size_t soinfo::get_verneed_cnt() const {
258 if (has_min_version(2)) {
259 return verneed_cnt_;
260 }
261
262 return 0;
263}
264
265ElfW(Addr) soinfo::get_verdef_ptr() const {
266 if (has_min_version(2)) {
267 return verdef_ptr_;
268 }
269
270 return 0;
271}
272
273size_t soinfo::get_verdef_cnt() const {
274 if (has_min_version(2)) {
275 return verdef_cnt_;
276 }
277
278 return 0;
279}
280
Ryan Prichard339ecef2020-01-02 16:36:06 -0800281SymbolLookupLib soinfo::get_lookup_lib() {
282 SymbolLookupLib result {};
283 result.si_ = this;
284
285 // For libs that only have SysV hashes, leave the gnu_bloom_filter_ field NULL to signal that
286 // the fallback code path is needed.
287 if (!is_gnu_hash()) {
288 return result;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700289 }
290
Ryan Prichard339ecef2020-01-02 16:36:06 -0800291 result.gnu_maskwords_ = gnu_maskwords_;
292 result.gnu_shift2_ = gnu_shift2_;
293 result.gnu_bloom_filter_ = gnu_bloom_filter_;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700294
Ryan Prichard339ecef2020-01-02 16:36:06 -0800295 result.strtab_ = strtab_;
296 result.strtab_size_ = strtab_size_;
297 result.symtab_ = symtab_;
298 result.versym_ = get_versym_table();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700299
Ryan Prichard339ecef2020-01-02 16:36:06 -0800300 result.gnu_chain_ = gnu_chain_;
301 result.gnu_nbucket_ = gnu_nbucket_;
302 result.gnu_bucket_ = gnu_bucket_;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700303
Ryan Prichard339ecef2020-01-02 16:36:06 -0800304 return result;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700305}
306
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800307const ElfW(Sym)* soinfo::find_symbol_by_name(SymbolName& symbol_name,
308 const version_info* vi) const {
309 return is_gnu_hash() ? gnu_lookup(symbol_name, vi) : elf_lookup(symbol_name, vi);
310}
311
312const ElfW(Sym)* soinfo::gnu_lookup(SymbolName& symbol_name, const version_info* vi) const {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800313 const uint32_t hash = symbol_name.gnu_hash();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700314
Ryan Prichard339ecef2020-01-02 16:36:06 -0800315 constexpr uint32_t kBloomMaskBits = sizeof(ElfW(Addr)) * 8;
316 const uint32_t word_num = (hash / kBloomMaskBits) & gnu_maskwords_;
317 const ElfW(Addr) bloom_word = gnu_bloom_filter_[word_num];
318 const uint32_t h1 = hash % kBloomMaskBits;
319 const uint32_t h2 = (hash >> gnu_shift2_) % kBloomMaskBits;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700320
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700321 TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p (gnu)",
322 symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
323
324 // test against bloom filter
Ryan Prichard339ecef2020-01-02 16:36:06 -0800325 if ((1 & (bloom_word >> h1) & (bloom_word >> h2)) == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800326 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700327 }
328
329 // bloom test says "probably yes"...
330 uint32_t n = gnu_bucket_[hash % gnu_nbucket_];
331
332 if (n == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800333 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700334 }
335
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800336 const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800337 const ElfW(Versym)* versym = get_versym_table();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700338
339 do {
340 ElfW(Sym)* s = symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700341 if (((gnu_chain_[n] ^ hash) >> 1) == 0 &&
Ryan Prichard339ecef2020-01-02 16:36:06 -0800342 check_symbol_version(versym, n, verneed) &&
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700343 strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
344 is_symbol_global_and_defined(this, s)) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800345 return symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700346 }
347 } while ((gnu_chain_[n++] & 1) == 0);
348
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800349 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700350}
351
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800352const ElfW(Sym)* soinfo::elf_lookup(SymbolName& symbol_name, const version_info* vi) const {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700353 uint32_t hash = symbol_name.elf_hash();
354
355 TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p h=%x(elf) %zd",
356 symbol_name.get_name(), get_realpath(),
357 reinterpret_cast<void*>(base), hash, hash % nbucket_);
358
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800359 const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800360 const ElfW(Versym)* versym = get_versym_table();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700361
362 for (uint32_t n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
363 ElfW(Sym)* s = symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700364
Ryan Prichard339ecef2020-01-02 16:36:06 -0800365 if (check_symbol_version(versym, n, verneed) &&
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700366 strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
367 is_symbol_global_and_defined(this, s)) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800368 return symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700369 }
370 }
371
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800372 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700373}
374
375ElfW(Sym)* soinfo::find_symbol_by_address(const void* addr) {
376 return is_gnu_hash() ? gnu_addr_lookup(addr) : elf_addr_lookup(addr);
377}
378
379static bool symbol_matches_soaddr(const ElfW(Sym)* sym, ElfW(Addr) soaddr) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -0700380 // Skip TLS symbols. A TLS symbol's value is relative to the start of the TLS segment rather than
381 // to the start of the solib. The solib only reserves space for the initialized part of the TLS
382 // segment. (i.e. .tdata is followed by .tbss, and .tbss overlaps other sections.)
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700383 return sym->st_shndx != SHN_UNDEF &&
Ryan Pricharde4d620b2019-04-01 17:42:14 -0700384 ELF_ST_TYPE(sym->st_info) != STT_TLS &&
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700385 soaddr >= sym->st_value &&
386 soaddr < sym->st_value + sym->st_size;
387}
388
389ElfW(Sym)* soinfo::gnu_addr_lookup(const void* addr) {
390 ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
391
392 for (size_t i = 0; i < gnu_nbucket_; ++i) {
393 uint32_t n = gnu_bucket_[i];
394
395 if (n == 0) {
396 continue;
397 }
398
399 do {
400 ElfW(Sym)* sym = symtab_ + n;
401 if (symbol_matches_soaddr(sym, soaddr)) {
402 return sym;
403 }
404 } while ((gnu_chain_[n++] & 1) == 0);
405 }
406
407 return nullptr;
408}
409
410ElfW(Sym)* soinfo::elf_addr_lookup(const void* addr) {
411 ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
412
413 // Search the library's symbol table for any defined symbol which
414 // contains this address.
415 for (size_t i = 0; i < nchain_; ++i) {
416 ElfW(Sym)* sym = symtab_ + i;
417 if (symbol_matches_soaddr(sym, soaddr)) {
418 return sym;
419 }
420 }
421
422 return nullptr;
423}
424
425static void call_function(const char* function_name __unused,
426 linker_ctor_function_t function,
427 const char* realpath __unused) {
428 if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
429 return;
430 }
431
432 TRACE("[ Calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
433 function(g_argc, g_argv, g_envp);
434 TRACE("[ Done calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
435}
436
437static void call_function(const char* function_name __unused,
438 linker_dtor_function_t function,
439 const char* realpath __unused) {
440 if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
441 return;
442 }
443
444 TRACE("[ Calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
445 function();
446 TRACE("[ Done calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
447}
448
449template <typename F>
Elliott Hughes01be44d2021-01-19 09:41:23 -0800450static inline void call_array(const char* array_name __unused, F* functions, size_t count,
451 bool reverse, const char* realpath) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700452 if (functions == nullptr) {
453 return;
454 }
455
456 TRACE("[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, realpath);
457
458 int begin = reverse ? (count - 1) : 0;
459 int end = reverse ? -1 : count;
460 int step = reverse ? -1 : 1;
461
462 for (int i = begin; i != end; i += step) {
463 TRACE("[ %s[%d] == %p ]", array_name, i, functions[i]);
464 call_function("function", functions[i], realpath);
465 }
466
467 TRACE("[ Done calling %s for '%s' ]", array_name, realpath);
468}
469
470void soinfo::call_pre_init_constructors() {
471 // DT_PREINIT_ARRAY functions are called before any other constructors for executables,
472 // but ignored in a shared library.
473 call_array("DT_PREINIT_ARRAY", preinit_array_, preinit_array_count_, false, get_realpath());
474}
475
476void soinfo::call_constructors() {
Ryan Prichard32bb3672024-03-08 16:53:06 -0800477 if (constructors_called) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700478 return;
479 }
480
481 // We set constructors_called before actually calling the constructors, otherwise it doesn't
482 // protect against recursive constructor calls. One simple example of constructor recursion
483 // is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so:
484 // 1. The program depends on libc, so libc's constructor is called here.
485 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
486 // 3. dlopen() calls the constructors on the newly created
487 // soinfo for libc_malloc_debug_leak.so.
488 // 4. The debug .so depends on libc, so CallConstructors is
489 // called again with the libc soinfo. If it doesn't trigger the early-
490 // out above, the libc constructor will be called again (recursively!).
491 constructors_called = true;
492
493 if (!is_main_executable() && preinit_array_ != nullptr) {
494 // The GNU dynamic linker silently ignores these, but we warn the developer.
495 PRINT("\"%s\": ignoring DT_PREINIT_ARRAY in shared library!", get_realpath());
496 }
497
498 get_children().for_each([] (soinfo* si) {
499 si->call_constructors();
500 });
501
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -0700502 if (!is_linker()) {
503 bionic_trace_begin((std::string("calling constructors: ") + get_realpath()).c_str());
504 }
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700505
506 // DT_INIT should be called before DT_INIT_ARRAY if both are present.
507 call_function("DT_INIT", init_func_, get_realpath());
508 call_array("DT_INIT_ARRAY", init_array_, init_array_count_, false, get_realpath());
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -0700509
510 if (!is_linker()) {
511 bionic_trace_end();
512 }
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700513}
514
515void soinfo::call_destructors() {
516 if (!constructors_called) {
517 return;
518 }
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -0700519
520 ScopedTrace trace((std::string("calling destructors: ") + get_realpath()).c_str());
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700521
522 // DT_FINI_ARRAY must be parsed in reverse order.
523 call_array("DT_FINI_ARRAY", fini_array_, fini_array_count_, true, get_realpath());
524
525 // DT_FINI should be called after DT_FINI_ARRAY if both are present.
526 call_function("DT_FINI", fini_func_, get_realpath());
527}
528
529void soinfo::add_child(soinfo* child) {
530 if (has_min_version(0)) {
531 child->parents_.push_back(this);
532 this->children_.push_back(child);
533 }
534}
535
536void soinfo::remove_all_links() {
537 if (!has_min_version(0)) {
538 return;
539 }
540
541 // 1. Untie connected soinfos from 'this'.
542 children_.for_each([&] (soinfo* child) {
543 child->parents_.remove_if([&] (const soinfo* parent) {
544 return parent == this;
545 });
546 });
547
548 parents_.for_each([&] (soinfo* parent) {
549 parent->children_.remove_if([&] (const soinfo* child) {
550 return child == this;
551 });
552 });
553
554 // 2. Remove from the primary namespace
555 primary_namespace_->remove_soinfo(this);
556 primary_namespace_ = nullptr;
557
558 // 3. Remove from secondary namespaces
559 secondary_namespaces_.for_each([&](android_namespace_t* ns) {
560 ns->remove_soinfo(this);
561 });
562
563
564 // 4. Once everything untied - clear local lists.
565 parents_.clear();
566 children_.clear();
567 secondary_namespaces_.clear();
568}
569
570dev_t soinfo::get_st_dev() const {
571 if (has_min_version(0)) {
572 return st_dev_;
573 }
574
575 return 0;
576};
577
578ino_t soinfo::get_st_ino() const {
579 if (has_min_version(0)) {
580 return st_ino_;
581 }
582
583 return 0;
584}
585
586off64_t soinfo::get_file_offset() const {
587 if (has_min_version(1)) {
588 return file_offset_;
589 }
590
591 return 0;
592}
593
594uint32_t soinfo::get_rtld_flags() const {
595 if (has_min_version(1)) {
596 return rtld_flags_;
597 }
598
599 return 0;
600}
601
602uint32_t soinfo::get_dt_flags_1() const {
603 if (has_min_version(1)) {
604 return dt_flags_1_;
605 }
606
607 return 0;
608}
609
610void soinfo::set_dt_flags_1(uint32_t dt_flags_1) {
611 if (has_min_version(1)) {
612 if ((dt_flags_1 & DF_1_GLOBAL) != 0) {
613 rtld_flags_ |= RTLD_GLOBAL;
614 }
615
616 if ((dt_flags_1 & DF_1_NODELETE) != 0) {
617 rtld_flags_ |= RTLD_NODELETE;
618 }
619
620 dt_flags_1_ = dt_flags_1;
621 }
622}
623
624void soinfo::set_nodelete() {
625 rtld_flags_ |= RTLD_NODELETE;
626}
627
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700628void soinfo::set_realpath(const char* path) {
629#if defined(__work_around_b_24465209__)
630 if (has_min_version(2)) {
631 realpath_ = path;
632 }
633#else
634 realpath_ = path;
635#endif
636}
637
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700638const char* soinfo::get_realpath() const {
639#if defined(__work_around_b_24465209__)
640 if (has_min_version(2)) {
641 return realpath_.c_str();
642 } else {
643 return old_name_;
644 }
645#else
646 return realpath_.c_str();
647#endif
648}
649
650void soinfo::set_soname(const char* soname) {
651#if defined(__work_around_b_24465209__)
652 if (has_min_version(2)) {
653 soname_ = soname;
654 }
Elliott Hughesf9dd1a72021-01-11 09:04:58 -0800655 strlcpy(old_name_, soname_.c_str(), sizeof(old_name_));
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700656#else
657 soname_ = soname;
658#endif
659}
660
661const char* soinfo::get_soname() const {
662#if defined(__work_around_b_24465209__)
663 if (has_min_version(2)) {
Elliott Hughesf9dd1a72021-01-11 09:04:58 -0800664 return soname_.c_str();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700665 } else {
666 return old_name_;
667 }
668#else
Elliott Hughesf9dd1a72021-01-11 09:04:58 -0800669 return soname_.c_str();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700670#endif
671}
672
673// This is a return on get_children()/get_parents() if
674// 'this->flags' does not have FLAG_NEW_SOINFO set.
675static soinfo_list_t g_empty_list;
676
677soinfo_list_t& soinfo::get_children() {
678 if (has_min_version(0)) {
679 return children_;
680 }
681
682 return g_empty_list;
683}
684
685const soinfo_list_t& soinfo::get_children() const {
686 if (has_min_version(0)) {
687 return children_;
688 }
689
690 return g_empty_list;
691}
692
693soinfo_list_t& soinfo::get_parents() {
694 if (has_min_version(0)) {
695 return parents_;
696 }
697
698 return g_empty_list;
699}
700
701static std::vector<std::string> g_empty_runpath;
702
703const std::vector<std::string>& soinfo::get_dt_runpath() const {
704 if (has_min_version(3)) {
705 return dt_runpath_;
706 }
707
708 return g_empty_runpath;
709}
710
711android_namespace_t* soinfo::get_primary_namespace() {
712 if (has_min_version(3)) {
713 return primary_namespace_;
714 }
715
716 return &g_default_namespace;
717}
718
719void soinfo::add_secondary_namespace(android_namespace_t* secondary_ns) {
720 CHECK(has_min_version(3));
721 secondary_namespaces_.push_back(secondary_ns);
722}
723
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800724android_namespace_list_t& soinfo::get_secondary_namespaces() {
725 CHECK(has_min_version(3));
726 return secondary_namespaces_;
727}
728
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700729const char* soinfo::get_string(ElfW(Word) index) const {
730 if (has_min_version(1) && (index >= strtab_size_)) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700731 async_safe_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700732 get_realpath(), strtab_size_, index);
733 }
734
735 return strtab_ + index;
736}
737
738bool soinfo::is_gnu_hash() const {
739 return (flags_ & FLAG_GNU_HASH) != 0;
740}
741
742bool soinfo::can_unload() const {
dimitry06016f22018-01-05 11:39:28 +0100743 return !is_linked() ||
744 (
dimitry55547db2018-05-25 14:17:37 +0200745 (get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0
dimitry06016f22018-01-05 11:39:28 +0100746 );
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700747}
748
749bool soinfo::is_linked() const {
750 return (flags_ & FLAG_LINKED) != 0;
751}
752
dimitry965d06d2017-11-28 16:03:07 +0100753bool soinfo::is_image_linked() const {
754 return (flags_ & FLAG_IMAGE_LINKED) != 0;
755}
756
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700757bool soinfo::is_main_executable() const {
758 return (flags_ & FLAG_EXE) != 0;
759}
760
761bool soinfo::is_linker() const {
762 return (flags_ & FLAG_LINKER) != 0;
763}
764
765void soinfo::set_linked() {
766 flags_ |= FLAG_LINKED;
767}
768
dimitry965d06d2017-11-28 16:03:07 +0100769void soinfo::set_image_linked() {
770 flags_ |= FLAG_IMAGE_LINKED;
771}
772
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700773void soinfo::set_linker_flag() {
774 flags_ |= FLAG_LINKER;
775}
776
777void soinfo::set_main_executable() {
778 flags_ |= FLAG_EXE;
779}
780
dimitry965d06d2017-11-28 16:03:07 +0100781size_t soinfo::increment_ref_count() {
782 return ++local_group_root_->ref_count_;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700783}
784
785size_t soinfo::decrement_ref_count() {
786 return --local_group_root_->ref_count_;
787}
788
dimitry06016f22018-01-05 11:39:28 +0100789size_t soinfo::get_ref_count() const {
790 return local_group_root_->ref_count_;
791}
792
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700793soinfo* soinfo::get_local_group_root() const {
794 return local_group_root_;
795}
796
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700797void soinfo::set_mapped_by_caller(bool mapped_by_caller) {
798 if (mapped_by_caller) {
799 flags_ |= FLAG_MAPPED_BY_CALLER;
800 } else {
801 flags_ &= ~FLAG_MAPPED_BY_CALLER;
802 }
803}
804
805bool soinfo::is_mapped_by_caller() const {
806 return (flags_ & FLAG_MAPPED_BY_CALLER) != 0;
807}
808
809// This function returns api-level at the time of
810// dlopen/load. Note that libraries opened by system
811// will always have 'current' api level.
Elliott Hughesff1428a2018-11-12 16:01:37 -0800812int soinfo::get_target_sdk_version() const {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700813 if (!has_min_version(2)) {
814 return __ANDROID_API__;
815 }
816
817 return local_group_root_->target_sdk_version_;
818}
819
820uintptr_t soinfo::get_handle() const {
821 CHECK(has_min_version(3));
822 CHECK(handle_ != 0);
823 return handle_;
824}
825
826void* soinfo::to_handle() {
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800827 if (get_application_target_sdk_version() < 24 || !has_min_version(3)) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700828 return this;
829 }
830
831 return reinterpret_cast<void*>(get_handle());
832}
833
834void soinfo::generate_handle() {
835 CHECK(has_min_version(3));
836 CHECK(handle_ == 0); // Make sure this is the first call
837
838 // Make sure the handle is unique and does not collide
839 // with special values which are RTLD_DEFAULT and RTLD_NEXT.
840 do {
Tom Cherry66bc4282018-11-08 13:40:52 -0800841 if (!is_first_stage_init()) {
Jiyong Park31cd08f2018-06-01 19:18:56 +0900842 arc4random_buf(&handle_, sizeof(handle_));
843 } else {
844 // arc4random* is not available in init because /dev/urandom hasn't yet been
845 // created. So, when running with init, use the monotonically increasing
846 // numbers as handles
847 handle_ += 2;
848 }
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700849 // the least significant bit for the handle is always 1
850 // making it easy to test the type of handle passed to
851 // dl* functions.
852 handle_ = handle_ | 1;
853 } while (handle_ == reinterpret_cast<uintptr_t>(RTLD_DEFAULT) ||
854 handle_ == reinterpret_cast<uintptr_t>(RTLD_NEXT) ||
Elliott Hughes192f3cf2024-06-25 11:21:41 +0000855 g_soinfo_handles_map.contains(handle_));
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700856
857 g_soinfo_handles_map[handle_] = this;
858}
859
Evgenii Stepanove0848bb2020-07-14 16:44:57 -0700860void soinfo::set_gap_start(ElfW(Addr) gap_start) {
861 CHECK(has_min_version(6));
862 gap_start_ = gap_start;
863}
864ElfW(Addr) soinfo::get_gap_start() const {
865 CHECK(has_min_version(6));
866 return gap_start_;
867}
868
869void soinfo::set_gap_size(size_t gap_size) {
870 CHECK(has_min_version(6));
871 gap_size_ = gap_size;
872}
873size_t soinfo::get_gap_size() const {
874 CHECK(has_min_version(6));
875 return gap_size_;
876}
877
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700878// TODO(dimitry): Move SymbolName methods to a separate file.
879
880uint32_t calculate_elf_hash(const char* name) {
881 const uint8_t* name_bytes = reinterpret_cast<const uint8_t*>(name);
882 uint32_t h = 0, g;
883
884 while (*name_bytes) {
885 h = (h << 4) + *name_bytes++;
886 g = h & 0xf0000000;
887 h ^= g;
888 h ^= g >> 24;
889 }
890
891 return h;
892}
893
894uint32_t SymbolName::elf_hash() {
895 if (!has_elf_hash_) {
896 elf_hash_ = calculate_elf_hash(name_);
897 has_elf_hash_ = true;
898 }
899
900 return elf_hash_;
901}
902
903uint32_t SymbolName::gnu_hash() {
904 if (!has_gnu_hash_) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800905 gnu_hash_ = calculate_gnu_hash(name_).first;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700906 has_gnu_hash_ = true;
907 }
908
909 return gnu_hash_;
910}