blob: 176c133349410eb865df823ce13a7a255c48628a [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"
Florian Mayer4edc20d2024-10-30 14:24:26 -070047#include "platform/bionic/mte.h"
48#include "private/bionic_globals.h"
Dimitry Ivanov48ec2882016-08-04 11:50:36 -070049
Ryan Prichard339ecef2020-01-02 16:36:06 -080050SymbolLookupList::SymbolLookupList(soinfo* si)
51 : sole_lib_(si->get_lookup_lib()), begin_(&sole_lib_), end_(&sole_lib_ + 1) {
52 CHECK(si != nullptr);
Elliott Hughesf08d0eb2024-09-03 17:31:29 -040053 slow_path_count_ += !!g_linker_debug_config.lookup;
Ryan Prichard339ecef2020-01-02 16:36:06 -080054 slow_path_count_ += sole_lib_.needs_sysv_lookup();
55}
56
57SymbolLookupList::SymbolLookupList(const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -040058 slow_path_count_ += !!g_linker_debug_config.lookup;
Ryan Prichard339ecef2020-01-02 16:36:06 -080059 libs_.reserve(1 + global_group.size() + local_group.size());
60
61 // Reserve a space in front for DT_SYMBOLIC lookup.
62 libs_.push_back(SymbolLookupLib {});
63
64 global_group.for_each([this](soinfo* si) {
65 libs_.push_back(si->get_lookup_lib());
66 slow_path_count_ += libs_.back().needs_sysv_lookup();
67 });
68
69 local_group.for_each([this](soinfo* si) {
70 libs_.push_back(si->get_lookup_lib());
71 slow_path_count_ += libs_.back().needs_sysv_lookup();
72 });
73
74 begin_ = &libs_[1];
75 end_ = &libs_[0] + libs_.size();
76}
77
78/* "This element's presence in a shared object library alters the dynamic linker's
79 * symbol resolution algorithm for references within the library. Instead of starting
80 * a symbol search with the executable file, the dynamic linker starts from the shared
81 * object itself. If the shared object fails to supply the referenced symbol, the
82 * dynamic linker then searches the executable file and other shared objects as usual."
83 *
84 * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
85 *
86 * Note that this is unlikely since static linker avoids generating
87 * relocations for -Bsymbolic linked dynamic executables.
88 */
89void SymbolLookupList::set_dt_symbolic_lib(soinfo* lib) {
90 CHECK(!libs_.empty());
91 slow_path_count_ -= libs_[0].needs_sysv_lookup();
92 libs_[0] = lib ? lib->get_lookup_lib() : SymbolLookupLib();
93 slow_path_count_ += libs_[0].needs_sysv_lookup();
94 begin_ = lib ? &libs_[0] : &libs_[1];
95}
96
97// Check whether a requested version matches the version on a symbol definition. There are a few
98// special cases:
99// - If the defining DSO has no version info at all, then any version matches.
100// - If no version is requested (vi==nullptr, verneed==kVersymNotNeeded), then any non-hidden
101// version matches.
102// - If the requested version is not defined by the DSO, then verneed is kVersymGlobal, and only
103// global symbol definitions match. (This special case is handled as part of the ordinary case
104// where the version must match exactly.)
105static inline bool check_symbol_version(const ElfW(Versym)* ver_table, uint32_t sym_idx,
106 const ElfW(Versym) verneed) {
107 if (ver_table == nullptr) return true;
108 const uint32_t verdef = ver_table[sym_idx];
109 return (verneed == kVersymNotNeeded) ?
110 !(verdef & kVersymHiddenBit) :
111 verneed == (verdef & ~kVersymHiddenBit);
112}
113
114template <bool IsGeneral>
115__attribute__((noinline)) static const ElfW(Sym)*
116soinfo_do_lookup_impl(const char* name, const version_info* vi,
117 soinfo** si_found_in, const SymbolLookupList& lookup_list) {
118 const auto [ hash, name_len ] = calculate_gnu_hash(name);
119 constexpr uint32_t kBloomMaskBits = sizeof(ElfW(Addr)) * 8;
120 SymbolName elf_symbol_name(name);
121
122 const SymbolLookupLib* end = lookup_list.end();
123 const SymbolLookupLib* it = lookup_list.begin();
124
125 while (true) {
126 const SymbolLookupLib* lib;
127 uint32_t sym_idx;
128
129 // Iterate over libraries until we find one whose Bloom filter matches the symbol we're
130 // searching for.
131 while (true) {
132 if (it == end) return nullptr;
133 lib = it++;
134
135 if (IsGeneral && lib->needs_sysv_lookup()) {
136 if (const ElfW(Sym)* sym = lib->si_->find_symbol_by_name(elf_symbol_name, vi)) {
137 *si_found_in = lib->si_;
138 return sym;
139 }
140 continue;
141 }
142
143 if (IsGeneral) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400144 LD_DEBUG(lookup, "SEARCH %s in %s@%p (gnu)",
145 name, lib->si_->get_realpath(), reinterpret_cast<void*>(lib->si_->base));
Ryan Prichard339ecef2020-01-02 16:36:06 -0800146 }
147
148 const uint32_t word_num = (hash / kBloomMaskBits) & lib->gnu_maskwords_;
149 const ElfW(Addr) bloom_word = lib->gnu_bloom_filter_[word_num];
150 const uint32_t h1 = hash % kBloomMaskBits;
151 const uint32_t h2 = (hash >> lib->gnu_shift2_) % kBloomMaskBits;
152
153 if ((1 & (bloom_word >> h1) & (bloom_word >> h2)) == 1) {
154 sym_idx = lib->gnu_bucket_[hash % lib->gnu_nbucket_];
155 if (sym_idx != 0) {
156 break;
157 }
158 }
Ryan Prichard339ecef2020-01-02 16:36:06 -0800159 }
160
161 // Search the library's hash table chain.
162 ElfW(Versym) verneed = kVersymNotNeeded;
163 bool calculated_verneed = false;
164
165 uint32_t chain_value = 0;
166 const ElfW(Sym)* sym = nullptr;
167
168 do {
169 sym = lib->symtab_ + sym_idx;
170 chain_value = lib->gnu_chain_[sym_idx];
171 if ((chain_value >> 1) == (hash >> 1)) {
172 if (vi != nullptr && !calculated_verneed) {
173 calculated_verneed = true;
174 verneed = find_verdef_version_index(lib->si_, vi);
175 }
176 if (check_symbol_version(lib->versym_, sym_idx, verneed) &&
177 static_cast<size_t>(sym->st_name) + name_len + 1 <= lib->strtab_size_ &&
178 memcmp(lib->strtab_ + sym->st_name, name, name_len + 1) == 0 &&
179 is_symbol_global_and_defined(lib->si_, sym)) {
180 *si_found_in = lib->si_;
Ryan Prichard339ecef2020-01-02 16:36:06 -0800181 return sym;
182 }
183 }
184 ++sym_idx;
185 } while ((chain_value & 1) == 0);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800186 }
187}
188
189const ElfW(Sym)* soinfo_do_lookup(const char* name, const version_info* vi,
190 soinfo** si_found_in, const SymbolLookupList& lookup_list) {
191 return lookup_list.needs_slow_path() ?
192 soinfo_do_lookup_impl<true>(name, vi, si_found_in, lookup_list) :
193 soinfo_do_lookup_impl<false>(name, vi, si_found_in, lookup_list);
194}
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700195
Elliott Hughesb003e102023-09-29 17:07:27 +0000196soinfo::soinfo(android_namespace_t* ns, const char* realpath, const struct stat* file_stat,
197 off64_t file_offset, int rtld_flags) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700198 if (realpath != nullptr) {
199 realpath_ = realpath;
200 }
201
202 flags_ = FLAG_NEW_SOINFO;
203 version_ = SOINFO_VERSION;
204
205 if (file_stat != nullptr) {
206 this->st_dev_ = file_stat->st_dev;
207 this->st_ino_ = file_stat->st_ino;
208 this->file_offset_ = file_offset;
209 }
210
211 this->rtld_flags_ = rtld_flags;
212 this->primary_namespace_ = ns;
213}
214
215soinfo::~soinfo() {
216 g_soinfo_handles_map.erase(handle_);
217}
218
219void soinfo::set_dt_runpath(const char* path) {
220 if (!has_min_version(3)) {
221 return;
222 }
223
224 std::vector<std::string> runpaths;
225
226 split_path(path, ":", &runpaths);
227
228 std::string origin = dirname(get_realpath());
Jiyong Park57b9d1e2019-01-17 03:14:45 +0900229 // FIXME: add $PLATFORM.
230 std::vector<std::pair<std::string, std::string>> params = {
231 {"ORIGIN", origin},
Ryan Prichard4d4087d2019-12-02 16:55:48 -0800232 {"LIB", kLibPath},
Jiyong Park57b9d1e2019-01-17 03:14:45 +0900233 };
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700234 for (auto&& s : runpaths) {
Dimitry Ivanov2a6d9b22017-03-11 14:35:38 -0800235 format_string(&s, params);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700236 }
237
238 resolve_paths(runpaths, &dt_runpath_);
239}
240
241const ElfW(Versym)* soinfo::get_versym(size_t n) const {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800242 auto table = get_versym_table();
243 return table ? table + n : nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700244}
245
246ElfW(Addr) soinfo::get_verneed_ptr() const {
247 if (has_min_version(2)) {
248 return verneed_ptr_;
249 }
250
251 return 0;
252}
253
254size_t soinfo::get_verneed_cnt() const {
255 if (has_min_version(2)) {
256 return verneed_cnt_;
257 }
258
259 return 0;
260}
261
262ElfW(Addr) soinfo::get_verdef_ptr() const {
263 if (has_min_version(2)) {
264 return verdef_ptr_;
265 }
266
267 return 0;
268}
269
270size_t soinfo::get_verdef_cnt() const {
271 if (has_min_version(2)) {
272 return verdef_cnt_;
273 }
274
275 return 0;
276}
277
Ryan Prichard339ecef2020-01-02 16:36:06 -0800278SymbolLookupLib soinfo::get_lookup_lib() {
279 SymbolLookupLib result {};
280 result.si_ = this;
281
282 // For libs that only have SysV hashes, leave the gnu_bloom_filter_ field NULL to signal that
283 // the fallback code path is needed.
284 if (!is_gnu_hash()) {
285 return result;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700286 }
287
Ryan Prichard339ecef2020-01-02 16:36:06 -0800288 result.gnu_maskwords_ = gnu_maskwords_;
289 result.gnu_shift2_ = gnu_shift2_;
290 result.gnu_bloom_filter_ = gnu_bloom_filter_;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700291
Ryan Prichard339ecef2020-01-02 16:36:06 -0800292 result.strtab_ = strtab_;
293 result.strtab_size_ = strtab_size_;
294 result.symtab_ = symtab_;
295 result.versym_ = get_versym_table();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700296
Ryan Prichard339ecef2020-01-02 16:36:06 -0800297 result.gnu_chain_ = gnu_chain_;
298 result.gnu_nbucket_ = gnu_nbucket_;
299 result.gnu_bucket_ = gnu_bucket_;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700300
Ryan Prichard339ecef2020-01-02 16:36:06 -0800301 return result;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700302}
303
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800304const ElfW(Sym)* soinfo::find_symbol_by_name(SymbolName& symbol_name,
305 const version_info* vi) const {
306 return is_gnu_hash() ? gnu_lookup(symbol_name, vi) : elf_lookup(symbol_name, vi);
307}
308
Florian Mayer4edc20d2024-10-30 14:24:26 -0700309ElfW(Addr) soinfo::apply_memtag_if_mte_globals(ElfW(Addr) sym_addr) const {
310 if (!should_tag_memtag_globals()) return sym_addr;
311 if (sym_addr == 0) return sym_addr; // Handle undefined weak symbols.
312 return reinterpret_cast<ElfW(Addr)>(get_tagged_address(reinterpret_cast<void*>(sym_addr)));
313}
314
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800315const ElfW(Sym)* soinfo::gnu_lookup(SymbolName& symbol_name, const version_info* vi) const {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800316 const uint32_t hash = symbol_name.gnu_hash();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700317
Ryan Prichard339ecef2020-01-02 16:36:06 -0800318 constexpr uint32_t kBloomMaskBits = sizeof(ElfW(Addr)) * 8;
319 const uint32_t word_num = (hash / kBloomMaskBits) & gnu_maskwords_;
320 const ElfW(Addr) bloom_word = gnu_bloom_filter_[word_num];
321 const uint32_t h1 = hash % kBloomMaskBits;
322 const uint32_t h2 = (hash >> gnu_shift2_) % kBloomMaskBits;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700323
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400324 LD_DEBUG(lookup, "SEARCH %s in %s@%p (gnu)",
325 symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700326
327 // test against bloom filter
Ryan Prichard339ecef2020-01-02 16:36:06 -0800328 if ((1 & (bloom_word >> h1) & (bloom_word >> h2)) == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800329 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700330 }
331
332 // bloom test says "probably yes"...
333 uint32_t n = gnu_bucket_[hash % gnu_nbucket_];
334
335 if (n == 0) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800336 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700337 }
338
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800339 const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800340 const ElfW(Versym)* versym = get_versym_table();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700341
342 do {
343 ElfW(Sym)* s = symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700344 if (((gnu_chain_[n] ^ hash) >> 1) == 0 &&
Ryan Prichard339ecef2020-01-02 16:36:06 -0800345 check_symbol_version(versym, n, verneed) &&
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700346 strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
347 is_symbol_global_and_defined(this, s)) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800348 return symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700349 }
350 } while ((gnu_chain_[n++] & 1) == 0);
351
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800352 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700353}
354
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800355const ElfW(Sym)* soinfo::elf_lookup(SymbolName& symbol_name, const version_info* vi) const {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700356 uint32_t hash = symbol_name.elf_hash();
357
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400358 LD_DEBUG(lookup, "SEARCH %s in %s@%p h=%x(elf) %zd",
359 symbol_name.get_name(), get_realpath(),
360 reinterpret_cast<void*>(base), hash, hash % nbucket_);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700361
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800362 const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800363 const ElfW(Versym)* versym = get_versym_table();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700364
365 for (uint32_t n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
366 ElfW(Sym)* s = symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700367
Ryan Prichard339ecef2020-01-02 16:36:06 -0800368 if (check_symbol_version(versym, n, verneed) &&
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700369 strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
370 is_symbol_global_and_defined(this, s)) {
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800371 return symtab_ + n;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700372 }
373 }
374
Ryan Prichard0e12cce2020-01-02 14:59:11 -0800375 return nullptr;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700376}
377
378ElfW(Sym)* soinfo::find_symbol_by_address(const void* addr) {
379 return is_gnu_hash() ? gnu_addr_lookup(addr) : elf_addr_lookup(addr);
380}
381
382static bool symbol_matches_soaddr(const ElfW(Sym)* sym, ElfW(Addr) soaddr) {
Ryan Pricharde4d620b2019-04-01 17:42:14 -0700383 // Skip TLS symbols. A TLS symbol's value is relative to the start of the TLS segment rather than
384 // to the start of the solib. The solib only reserves space for the initialized part of the TLS
385 // segment. (i.e. .tdata is followed by .tbss, and .tbss overlaps other sections.)
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700386 return sym->st_shndx != SHN_UNDEF &&
Ryan Pricharde4d620b2019-04-01 17:42:14 -0700387 ELF_ST_TYPE(sym->st_info) != STT_TLS &&
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700388 soaddr >= sym->st_value &&
389 soaddr < sym->st_value + sym->st_size;
390}
391
392ElfW(Sym)* soinfo::gnu_addr_lookup(const void* addr) {
393 ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
394
395 for (size_t i = 0; i < gnu_nbucket_; ++i) {
396 uint32_t n = gnu_bucket_[i];
397
398 if (n == 0) {
399 continue;
400 }
401
402 do {
403 ElfW(Sym)* sym = symtab_ + n;
404 if (symbol_matches_soaddr(sym, soaddr)) {
405 return sym;
406 }
407 } while ((gnu_chain_[n++] & 1) == 0);
408 }
409
410 return nullptr;
411}
412
413ElfW(Sym)* soinfo::elf_addr_lookup(const void* addr) {
414 ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
415
416 // Search the library's symbol table for any defined symbol which
417 // contains this address.
418 for (size_t i = 0; i < nchain_; ++i) {
419 ElfW(Sym)* sym = symtab_ + i;
420 if (symbol_matches_soaddr(sym, soaddr)) {
421 return sym;
422 }
423 }
424
425 return nullptr;
426}
427
428static void call_function(const char* function_name __unused,
429 linker_ctor_function_t function,
430 const char* realpath __unused) {
431 if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
432 return;
433 }
434
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400435 LD_DEBUG(calls, "[ Calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700436 function(g_argc, g_argv, g_envp);
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400437 LD_DEBUG(calls, "[ Done calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700438}
439
440static void call_function(const char* function_name __unused,
441 linker_dtor_function_t function,
442 const char* realpath __unused) {
443 if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
444 return;
445 }
446
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400447 LD_DEBUG(calls, "[ Calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700448 function();
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400449 LD_DEBUG(calls, "[ Done calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700450}
451
452template <typename F>
Elliott Hughes01be44d2021-01-19 09:41:23 -0800453static inline void call_array(const char* array_name __unused, F* functions, size_t count,
454 bool reverse, const char* realpath) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700455 if (functions == nullptr) {
456 return;
457 }
458
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400459 LD_DEBUG(calls, "[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, realpath);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700460
461 int begin = reverse ? (count - 1) : 0;
462 int end = reverse ? -1 : count;
463 int step = reverse ? -1 : 1;
464
465 for (int i = begin; i != end; i += step) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400466 LD_DEBUG(calls, "[ %s[%d] == %p ]", array_name, i, functions[i]);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700467 call_function("function", functions[i], realpath);
468 }
469
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400470 LD_DEBUG(calls, "[ Done calling %s for '%s' ]", array_name, realpath);
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700471}
472
473void soinfo::call_pre_init_constructors() {
474 // DT_PREINIT_ARRAY functions are called before any other constructors for executables,
475 // but ignored in a shared library.
476 call_array("DT_PREINIT_ARRAY", preinit_array_, preinit_array_count_, false, get_realpath());
477}
478
479void soinfo::call_constructors() {
Ryan Prichard32bb3672024-03-08 16:53:06 -0800480 if (constructors_called) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700481 return;
482 }
483
484 // We set constructors_called before actually calling the constructors, otherwise it doesn't
485 // protect against recursive constructor calls. One simple example of constructor recursion
486 // is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so:
487 // 1. The program depends on libc, so libc's constructor is called here.
488 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
489 // 3. dlopen() calls the constructors on the newly created
490 // soinfo for libc_malloc_debug_leak.so.
491 // 4. The debug .so depends on libc, so CallConstructors is
492 // called again with the libc soinfo. If it doesn't trigger the early-
493 // out above, the libc constructor will be called again (recursively!).
494 constructors_called = true;
495
496 if (!is_main_executable() && preinit_array_ != nullptr) {
497 // The GNU dynamic linker silently ignores these, but we warn the developer.
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400498 DL_WARN("\"%s\": ignoring DT_PREINIT_ARRAY in shared library!", get_realpath());
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700499 }
500
501 get_children().for_each([] (soinfo* si) {
502 si->call_constructors();
503 });
504
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -0700505 if (!is_linker()) {
506 bionic_trace_begin((std::string("calling constructors: ") + get_realpath()).c_str());
507 }
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700508
509 // DT_INIT should be called before DT_INIT_ARRAY if both are present.
510 call_function("DT_INIT", init_func_, get_realpath());
511 call_array("DT_INIT_ARRAY", init_array_, init_array_count_, false, get_realpath());
Dimitry Ivanov5c4a5802017-03-17 16:41:34 -0700512
513 if (!is_linker()) {
514 bionic_trace_end();
515 }
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700516}
517
518void soinfo::call_destructors() {
519 if (!constructors_called) {
520 return;
521 }
Dimitry Ivanov6705e8c2017-03-21 10:29:06 -0700522
523 ScopedTrace trace((std::string("calling destructors: ") + get_realpath()).c_str());
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700524
525 // DT_FINI_ARRAY must be parsed in reverse order.
526 call_array("DT_FINI_ARRAY", fini_array_, fini_array_count_, true, get_realpath());
527
528 // DT_FINI should be called after DT_FINI_ARRAY if both are present.
529 call_function("DT_FINI", fini_func_, get_realpath());
530}
531
532void soinfo::add_child(soinfo* child) {
533 if (has_min_version(0)) {
534 child->parents_.push_back(this);
535 this->children_.push_back(child);
536 }
537}
538
539void soinfo::remove_all_links() {
540 if (!has_min_version(0)) {
541 return;
542 }
543
544 // 1. Untie connected soinfos from 'this'.
545 children_.for_each([&] (soinfo* child) {
546 child->parents_.remove_if([&] (const soinfo* parent) {
547 return parent == this;
548 });
549 });
550
551 parents_.for_each([&] (soinfo* parent) {
552 parent->children_.remove_if([&] (const soinfo* child) {
553 return child == this;
554 });
555 });
556
557 // 2. Remove from the primary namespace
558 primary_namespace_->remove_soinfo(this);
559 primary_namespace_ = nullptr;
560
561 // 3. Remove from secondary namespaces
562 secondary_namespaces_.for_each([&](android_namespace_t* ns) {
563 ns->remove_soinfo(this);
564 });
565
566
567 // 4. Once everything untied - clear local lists.
568 parents_.clear();
569 children_.clear();
570 secondary_namespaces_.clear();
571}
572
573dev_t soinfo::get_st_dev() const {
574 if (has_min_version(0)) {
575 return st_dev_;
576 }
577
578 return 0;
579};
580
581ino_t soinfo::get_st_ino() const {
582 if (has_min_version(0)) {
583 return st_ino_;
584 }
585
586 return 0;
587}
588
589off64_t soinfo::get_file_offset() const {
590 if (has_min_version(1)) {
591 return file_offset_;
592 }
593
594 return 0;
595}
596
597uint32_t soinfo::get_rtld_flags() const {
598 if (has_min_version(1)) {
599 return rtld_flags_;
600 }
601
602 return 0;
603}
604
605uint32_t soinfo::get_dt_flags_1() const {
606 if (has_min_version(1)) {
607 return dt_flags_1_;
608 }
609
610 return 0;
611}
612
613void soinfo::set_dt_flags_1(uint32_t dt_flags_1) {
614 if (has_min_version(1)) {
615 if ((dt_flags_1 & DF_1_GLOBAL) != 0) {
616 rtld_flags_ |= RTLD_GLOBAL;
617 }
618
619 if ((dt_flags_1 & DF_1_NODELETE) != 0) {
620 rtld_flags_ |= RTLD_NODELETE;
621 }
622
623 dt_flags_1_ = dt_flags_1;
624 }
625}
626
627void soinfo::set_nodelete() {
628 rtld_flags_ |= RTLD_NODELETE;
629}
630
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700631void soinfo::set_realpath(const char* path) {
632#if defined(__work_around_b_24465209__)
633 if (has_min_version(2)) {
634 realpath_ = path;
635 }
636#else
637 realpath_ = path;
638#endif
639}
640
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700641const char* soinfo::get_realpath() const {
642#if defined(__work_around_b_24465209__)
643 if (has_min_version(2)) {
644 return realpath_.c_str();
645 } else {
646 return old_name_;
647 }
648#else
649 return realpath_.c_str();
650#endif
651}
652
653void soinfo::set_soname(const char* soname) {
654#if defined(__work_around_b_24465209__)
655 if (has_min_version(2)) {
656 soname_ = soname;
657 }
Elliott Hughesf9dd1a72021-01-11 09:04:58 -0800658 strlcpy(old_name_, soname_.c_str(), sizeof(old_name_));
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700659#else
660 soname_ = soname;
661#endif
662}
663
664const char* soinfo::get_soname() const {
665#if defined(__work_around_b_24465209__)
666 if (has_min_version(2)) {
Elliott Hughesf9dd1a72021-01-11 09:04:58 -0800667 return soname_.c_str();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700668 } else {
669 return old_name_;
670 }
671#else
Elliott Hughesf9dd1a72021-01-11 09:04:58 -0800672 return soname_.c_str();
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700673#endif
674}
675
676// This is a return on get_children()/get_parents() if
677// 'this->flags' does not have FLAG_NEW_SOINFO set.
678static soinfo_list_t g_empty_list;
679
680soinfo_list_t& soinfo::get_children() {
681 if (has_min_version(0)) {
682 return children_;
683 }
684
685 return g_empty_list;
686}
687
688const soinfo_list_t& soinfo::get_children() const {
689 if (has_min_version(0)) {
690 return children_;
691 }
692
693 return g_empty_list;
694}
695
696soinfo_list_t& soinfo::get_parents() {
697 if (has_min_version(0)) {
698 return parents_;
699 }
700
701 return g_empty_list;
702}
703
704static std::vector<std::string> g_empty_runpath;
705
706const std::vector<std::string>& soinfo::get_dt_runpath() const {
707 if (has_min_version(3)) {
708 return dt_runpath_;
709 }
710
711 return g_empty_runpath;
712}
713
714android_namespace_t* soinfo::get_primary_namespace() {
715 if (has_min_version(3)) {
716 return primary_namespace_;
717 }
718
719 return &g_default_namespace;
720}
721
722void soinfo::add_secondary_namespace(android_namespace_t* secondary_ns) {
723 CHECK(has_min_version(3));
724 secondary_namespaces_.push_back(secondary_ns);
725}
726
Dimitry Ivanov7a34b9d2017-02-03 14:07:34 -0800727android_namespace_list_t& soinfo::get_secondary_namespaces() {
728 CHECK(has_min_version(3));
729 return secondary_namespaces_;
730}
731
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700732const char* soinfo::get_string(ElfW(Word) index) const {
733 if (has_min_version(1) && (index >= strtab_size_)) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700734 async_safe_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700735 get_realpath(), strtab_size_, index);
736 }
737
738 return strtab_ + index;
739}
740
741bool soinfo::is_gnu_hash() const {
742 return (flags_ & FLAG_GNU_HASH) != 0;
743}
744
745bool soinfo::can_unload() const {
dimitry06016f22018-01-05 11:39:28 +0100746 return !is_linked() ||
747 (
dimitry55547db2018-05-25 14:17:37 +0200748 (get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0
dimitry06016f22018-01-05 11:39:28 +0100749 );
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700750}
751
752bool soinfo::is_linked() const {
753 return (flags_ & FLAG_LINKED) != 0;
754}
755
dimitry965d06d2017-11-28 16:03:07 +0100756bool soinfo::is_image_linked() const {
757 return (flags_ & FLAG_IMAGE_LINKED) != 0;
758}
759
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700760bool soinfo::is_main_executable() const {
761 return (flags_ & FLAG_EXE) != 0;
762}
763
764bool soinfo::is_linker() const {
765 return (flags_ & FLAG_LINKER) != 0;
766}
767
768void soinfo::set_linked() {
769 flags_ |= FLAG_LINKED;
770}
771
dimitry965d06d2017-11-28 16:03:07 +0100772void soinfo::set_image_linked() {
773 flags_ |= FLAG_IMAGE_LINKED;
774}
775
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700776void soinfo::set_linker_flag() {
777 flags_ |= FLAG_LINKER;
778}
779
780void soinfo::set_main_executable() {
781 flags_ |= FLAG_EXE;
782}
783
dimitry965d06d2017-11-28 16:03:07 +0100784size_t soinfo::increment_ref_count() {
785 return ++local_group_root_->ref_count_;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700786}
787
788size_t soinfo::decrement_ref_count() {
789 return --local_group_root_->ref_count_;
790}
791
dimitry06016f22018-01-05 11:39:28 +0100792size_t soinfo::get_ref_count() const {
793 return local_group_root_->ref_count_;
794}
795
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700796soinfo* soinfo::get_local_group_root() const {
797 return local_group_root_;
798}
799
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700800void soinfo::set_mapped_by_caller(bool mapped_by_caller) {
801 if (mapped_by_caller) {
802 flags_ |= FLAG_MAPPED_BY_CALLER;
803 } else {
804 flags_ &= ~FLAG_MAPPED_BY_CALLER;
805 }
806}
807
808bool soinfo::is_mapped_by_caller() const {
809 return (flags_ & FLAG_MAPPED_BY_CALLER) != 0;
810}
811
812// This function returns api-level at the time of
813// dlopen/load. Note that libraries opened by system
814// will always have 'current' api level.
Elliott Hughesff1428a2018-11-12 16:01:37 -0800815int soinfo::get_target_sdk_version() const {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700816 if (!has_min_version(2)) {
817 return __ANDROID_API__;
818 }
819
820 return local_group_root_->target_sdk_version_;
821}
822
823uintptr_t soinfo::get_handle() const {
824 CHECK(has_min_version(3));
825 CHECK(handle_ != 0);
826 return handle_;
827}
828
829void* soinfo::to_handle() {
Elliott Hughes95c6cd72019-12-20 13:26:14 -0800830 if (get_application_target_sdk_version() < 24 || !has_min_version(3)) {
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700831 return this;
832 }
833
834 return reinterpret_cast<void*>(get_handle());
835}
836
837void soinfo::generate_handle() {
838 CHECK(has_min_version(3));
839 CHECK(handle_ == 0); // Make sure this is the first call
840
841 // Make sure the handle is unique and does not collide
842 // with special values which are RTLD_DEFAULT and RTLD_NEXT.
843 do {
Tom Cherry66bc4282018-11-08 13:40:52 -0800844 if (!is_first_stage_init()) {
Jiyong Park31cd08f2018-06-01 19:18:56 +0900845 arc4random_buf(&handle_, sizeof(handle_));
846 } else {
847 // arc4random* is not available in init because /dev/urandom hasn't yet been
848 // created. So, when running with init, use the monotonically increasing
849 // numbers as handles
850 handle_ += 2;
851 }
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700852 // the least significant bit for the handle is always 1
853 // making it easy to test the type of handle passed to
854 // dl* functions.
855 handle_ = handle_ | 1;
856 } while (handle_ == reinterpret_cast<uintptr_t>(RTLD_DEFAULT) ||
857 handle_ == reinterpret_cast<uintptr_t>(RTLD_NEXT) ||
Elliott Hughes192f3cf2024-06-25 11:21:41 +0000858 g_soinfo_handles_map.contains(handle_));
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700859
860 g_soinfo_handles_map[handle_] = this;
861}
862
Evgenii Stepanove0848bb2020-07-14 16:44:57 -0700863void soinfo::set_gap_start(ElfW(Addr) gap_start) {
864 CHECK(has_min_version(6));
865 gap_start_ = gap_start;
866}
867ElfW(Addr) soinfo::get_gap_start() const {
868 CHECK(has_min_version(6));
869 return gap_start_;
870}
871
872void soinfo::set_gap_size(size_t gap_size) {
873 CHECK(has_min_version(6));
874 gap_size_ = gap_size;
875}
876size_t soinfo::get_gap_size() const {
877 CHECK(has_min_version(6));
878 return gap_size_;
879}
880
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700881// TODO(dimitry): Move SymbolName methods to a separate file.
882
883uint32_t calculate_elf_hash(const char* name) {
884 const uint8_t* name_bytes = reinterpret_cast<const uint8_t*>(name);
885 uint32_t h = 0, g;
886
887 while (*name_bytes) {
888 h = (h << 4) + *name_bytes++;
889 g = h & 0xf0000000;
890 h ^= g;
891 h ^= g >> 24;
892 }
893
894 return h;
895}
896
897uint32_t SymbolName::elf_hash() {
898 if (!has_elf_hash_) {
899 elf_hash_ = calculate_elf_hash(name_);
900 has_elf_hash_ = true;
901 }
902
903 return elf_hash_;
904}
905
906uint32_t SymbolName::gnu_hash() {
907 if (!has_gnu_hash_) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800908 gnu_hash_ = calculate_gnu_hash(name_).first;
Dimitry Ivanov48ec2882016-08-04 11:50:36 -0700909 has_gnu_hash_ = true;
910 }
911
912 return gnu_hash_;
913}