1 /*
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
37 #include <async_safe/log.h>
38
39 #include "linker.h"
40 #include "linker_config.h"
41 #include "linker_debug.h"
42 #include "linker_globals.h"
43 #include "linker_gnu_hash.h"
44 #include "linker_logger.h"
45 #include "linker_relocate.h"
46 #include "linker_utils.h"
47 #include "platform/bionic/mte.h"
48 #include "private/bionic_globals.h"
49
SymbolLookupList(soinfo * si)50 SymbolLookupList::SymbolLookupList(soinfo* si)
51 : sole_lib_(si->get_lookup_lib()), begin_(&sole_lib_), end_(&sole_lib_ + 1) {
52 CHECK(si != nullptr);
53 slow_path_count_ += !!g_linker_debug_config.lookup;
54 slow_path_count_ += sole_lib_.needs_sysv_lookup();
55 }
56
SymbolLookupList(const soinfo_list_t & global_group,const soinfo_list_t & local_group)57 SymbolLookupList::SymbolLookupList(const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
58 slow_path_count_ += !!g_linker_debug_config.lookup;
59 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 */
set_dt_symbolic_lib(soinfo * lib)89 void 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.)
check_symbol_version(const ElfW (Versym)* ver_table,uint32_t sym_idx,const ElfW (Versym)verneed)105 static 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
114 template <bool IsGeneral>
ElfW(Sym)115 __attribute__((noinline)) static const ElfW(Sym)*
116 soinfo_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) {
144 LD_DEBUG(lookup, "SEARCH %s in %s@%p (gnu)",
145 name, lib->si_->get_realpath(), reinterpret_cast<void*>(lib->si_->base));
146 }
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 }
159 }
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_;
181 return sym;
182 }
183 }
184 ++sym_idx;
185 } while ((chain_value & 1) == 0);
186 }
187 }
188
ElfW(Sym)189 const 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 }
195
soinfo(android_namespace_t * ns,const char * realpath,const struct stat * file_stat,off64_t file_offset,int rtld_flags)196 soinfo::soinfo(android_namespace_t* ns, const char* realpath, const struct stat* file_stat,
197 off64_t file_offset, int rtld_flags) {
198 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
~soinfo()215 soinfo::~soinfo() {
216 g_soinfo_handles_map.erase(handle_);
217 }
218
set_dt_runpath(const char * path)219 void 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());
229 // FIXME: add $PLATFORM.
230 std::vector<std::pair<std::string, std::string>> params = {
231 {"ORIGIN", origin},
232 {"LIB", kLibPath},
233 };
234 for (auto&& s : runpaths) {
235 format_string(&s, params);
236 }
237
238 resolve_paths(runpaths, &dt_runpath_);
239 }
240
ElfW(Versym)241 const ElfW(Versym)* soinfo::get_versym(size_t n) const {
242 auto table = get_versym_table();
243 return table ? table + n : nullptr;
244 }
245
ElfW(Addr)246 ElfW(Addr) soinfo::get_verneed_ptr() const {
247 if (has_min_version(2)) {
248 return verneed_ptr_;
249 }
250
251 return 0;
252 }
253
get_verneed_cnt() const254 size_t soinfo::get_verneed_cnt() const {
255 if (has_min_version(2)) {
256 return verneed_cnt_;
257 }
258
259 return 0;
260 }
261
ElfW(Addr)262 ElfW(Addr) soinfo::get_verdef_ptr() const {
263 if (has_min_version(2)) {
264 return verdef_ptr_;
265 }
266
267 return 0;
268 }
269
get_verdef_cnt() const270 size_t soinfo::get_verdef_cnt() const {
271 if (has_min_version(2)) {
272 return verdef_cnt_;
273 }
274
275 return 0;
276 }
277
get_lookup_lib()278 SymbolLookupLib 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;
286 }
287
288 result.gnu_maskwords_ = gnu_maskwords_;
289 result.gnu_shift2_ = gnu_shift2_;
290 result.gnu_bloom_filter_ = gnu_bloom_filter_;
291
292 result.strtab_ = strtab_;
293 result.strtab_size_ = strtab_size_;
294 result.symtab_ = symtab_;
295 result.versym_ = get_versym_table();
296
297 result.gnu_chain_ = gnu_chain_;
298 result.gnu_nbucket_ = gnu_nbucket_;
299 result.gnu_bucket_ = gnu_bucket_;
300
301 return result;
302 }
303
ElfW(Sym)304 const 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
ElfW(Addr)309 ElfW(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
ElfW(Sym)315 const ElfW(Sym)* soinfo::gnu_lookup(SymbolName& symbol_name, const version_info* vi) const {
316 const uint32_t hash = symbol_name.gnu_hash();
317
318 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;
323
324 LD_DEBUG(lookup, "SEARCH %s in %s@%p (gnu)",
325 symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
326
327 // test against bloom filter
328 if ((1 & (bloom_word >> h1) & (bloom_word >> h2)) == 0) {
329 return nullptr;
330 }
331
332 // bloom test says "probably yes"...
333 uint32_t n = gnu_bucket_[hash % gnu_nbucket_];
334
335 if (n == 0) {
336 return nullptr;
337 }
338
339 const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
340 const ElfW(Versym)* versym = get_versym_table();
341
342 do {
343 ElfW(Sym)* s = symtab_ + n;
344 if (((gnu_chain_[n] ^ hash) >> 1) == 0 &&
345 check_symbol_version(versym, n, verneed) &&
346 strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
347 is_symbol_global_and_defined(this, s)) {
348 return symtab_ + n;
349 }
350 } while ((gnu_chain_[n++] & 1) == 0);
351
352 return nullptr;
353 }
354
ElfW(Sym)355 const ElfW(Sym)* soinfo::elf_lookup(SymbolName& symbol_name, const version_info* vi) const {
356 uint32_t hash = symbol_name.elf_hash();
357
358 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_);
361
362 const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
363 const ElfW(Versym)* versym = get_versym_table();
364
365 for (uint32_t n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
366 ElfW(Sym)* s = symtab_ + n;
367
368 if (check_symbol_version(versym, n, verneed) &&
369 strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
370 is_symbol_global_and_defined(this, s)) {
371 return symtab_ + n;
372 }
373 }
374
375 return nullptr;
376 }
377
ElfW(Sym)378 ElfW(Sym)* soinfo::find_symbol_by_address(const void* addr) {
379 return is_gnu_hash() ? gnu_addr_lookup(addr) : elf_addr_lookup(addr);
380 }
381
symbol_matches_soaddr(const ElfW (Sym)* sym,ElfW (Addr)soaddr)382 static bool symbol_matches_soaddr(const ElfW(Sym)* sym, ElfW(Addr) soaddr) {
383 // 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.)
386 return sym->st_shndx != SHN_UNDEF &&
387 ELF_ST_TYPE(sym->st_info) != STT_TLS &&
388 soaddr >= sym->st_value &&
389 soaddr < sym->st_value + sym->st_size;
390 }
391
ElfW(Sym)392 ElfW(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
ElfW(Sym)413 ElfW(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
call_function(const char * function_name __unused,linker_ctor_function_t function,const char * realpath __unused)428 static 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
435 LD_DEBUG(calls, "[ Calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
436 function(g_argc, g_argv, g_envp);
437 LD_DEBUG(calls, "[ Done calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
438 }
439
call_function(const char * function_name __unused,linker_dtor_function_t function,const char * realpath __unused)440 static 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
447 LD_DEBUG(calls, "[ Calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
448 function();
449 LD_DEBUG(calls, "[ Done calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
450 }
451
452 template <typename F>
call_array(const char * array_name __unused,F * functions,size_t count,bool reverse,const char * realpath)453 static inline void call_array(const char* array_name __unused, F* functions, size_t count,
454 bool reverse, const char* realpath) {
455 if (functions == nullptr) {
456 return;
457 }
458
459 LD_DEBUG(calls, "[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, realpath);
460
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) {
466 LD_DEBUG(calls, "[ %s[%d] == %p ]", array_name, i, functions[i]);
467 call_function("function", functions[i], realpath);
468 }
469
470 LD_DEBUG(calls, "[ Done calling %s for '%s' ]", array_name, realpath);
471 }
472
call_pre_init_constructors()473 void 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
call_constructors()479 void soinfo::call_constructors() {
480 if (constructors_called) {
481 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.
498 DL_WARN("\"%s\": ignoring DT_PREINIT_ARRAY in shared library!", get_realpath());
499 }
500
501 get_children().for_each([] (soinfo* si) {
502 si->call_constructors();
503 });
504
505 if (!is_linker()) {
506 bionic_trace_begin((std::string("calling constructors: ") + get_realpath()).c_str());
507 }
508
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());
512
513 if (!is_linker()) {
514 bionic_trace_end();
515 }
516 }
517
call_destructors()518 void soinfo::call_destructors() {
519 if (!constructors_called) {
520 return;
521 }
522
523 ScopedTrace trace((std::string("calling destructors: ") + get_realpath()).c_str());
524
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
add_child(soinfo * child)532 void 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
remove_all_links()539 void 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
get_st_dev() const573 dev_t soinfo::get_st_dev() const {
574 if (has_min_version(0)) {
575 return st_dev_;
576 }
577
578 return 0;
579 };
580
get_st_ino() const581 ino_t soinfo::get_st_ino() const {
582 if (has_min_version(0)) {
583 return st_ino_;
584 }
585
586 return 0;
587 }
588
get_file_offset() const589 off64_t soinfo::get_file_offset() const {
590 if (has_min_version(1)) {
591 return file_offset_;
592 }
593
594 return 0;
595 }
596
get_rtld_flags() const597 uint32_t soinfo::get_rtld_flags() const {
598 if (has_min_version(1)) {
599 return rtld_flags_;
600 }
601
602 return 0;
603 }
604
get_dt_flags_1() const605 uint32_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
set_dt_flags_1(uint32_t dt_flags_1)613 void 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
set_nodelete()627 void soinfo::set_nodelete() {
628 rtld_flags_ |= RTLD_NODELETE;
629 }
630
set_realpath(const char * path)631 void 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
get_realpath() const641 const 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
set_soname(const char * soname)653 void soinfo::set_soname(const char* soname) {
654 #if defined(__work_around_b_24465209__)
655 if (has_min_version(2)) {
656 soname_ = soname;
657 }
658 strlcpy(old_name_, soname_.c_str(), sizeof(old_name_));
659 #else
660 soname_ = soname;
661 #endif
662 }
663
get_soname() const664 const char* soinfo::get_soname() const {
665 #if defined(__work_around_b_24465209__)
666 if (has_min_version(2)) {
667 return soname_.c_str();
668 } else {
669 return old_name_;
670 }
671 #else
672 return soname_.c_str();
673 #endif
674 }
675
676 // This is a return on get_children()/get_parents() if
677 // 'this->flags' does not have FLAG_NEW_SOINFO set.
678 static soinfo_list_t g_empty_list;
679
get_children()680 soinfo_list_t& soinfo::get_children() {
681 if (has_min_version(0)) {
682 return children_;
683 }
684
685 return g_empty_list;
686 }
687
get_children() const688 const 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
get_parents()696 soinfo_list_t& soinfo::get_parents() {
697 if (has_min_version(0)) {
698 return parents_;
699 }
700
701 return g_empty_list;
702 }
703
704 static std::vector<std::string> g_empty_runpath;
705
get_dt_runpath() const706 const 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
get_primary_namespace()714 android_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
add_secondary_namespace(android_namespace_t * secondary_ns)722 void soinfo::add_secondary_namespace(android_namespace_t* secondary_ns) {
723 CHECK(has_min_version(3));
724 secondary_namespaces_.push_back(secondary_ns);
725 }
726
get_secondary_namespaces()727 android_namespace_list_t& soinfo::get_secondary_namespaces() {
728 CHECK(has_min_version(3));
729 return secondary_namespaces_;
730 }
731
get_string(ElfW (Word)index) const732 const char* soinfo::get_string(ElfW(Word) index) const {
733 if (has_min_version(1) && (index >= strtab_size_)) {
734 async_safe_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
735 get_realpath(), strtab_size_, index);
736 }
737
738 return strtab_ + index;
739 }
740
is_gnu_hash() const741 bool soinfo::is_gnu_hash() const {
742 return (flags_ & FLAG_GNU_HASH) != 0;
743 }
744
can_unload() const745 bool soinfo::can_unload() const {
746 return !is_linked() ||
747 (
748 (get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0
749 );
750 }
751
is_linked() const752 bool soinfo::is_linked() const {
753 return (flags_ & FLAG_LINKED) != 0;
754 }
755
is_image_linked() const756 bool soinfo::is_image_linked() const {
757 return (flags_ & FLAG_IMAGE_LINKED) != 0;
758 }
759
is_main_executable() const760 bool soinfo::is_main_executable() const {
761 return (flags_ & FLAG_EXE) != 0;
762 }
763
is_linker() const764 bool soinfo::is_linker() const {
765 return (flags_ & FLAG_LINKER) != 0;
766 }
767
set_linked()768 void soinfo::set_linked() {
769 flags_ |= FLAG_LINKED;
770 }
771
set_image_linked()772 void soinfo::set_image_linked() {
773 flags_ |= FLAG_IMAGE_LINKED;
774 }
775
set_linker_flag()776 void soinfo::set_linker_flag() {
777 flags_ |= FLAG_LINKER;
778 }
779
set_main_executable()780 void soinfo::set_main_executable() {
781 flags_ |= FLAG_EXE;
782 }
783
increment_ref_count()784 size_t soinfo::increment_ref_count() {
785 return ++local_group_root_->ref_count_;
786 }
787
decrement_ref_count()788 size_t soinfo::decrement_ref_count() {
789 return --local_group_root_->ref_count_;
790 }
791
get_ref_count() const792 size_t soinfo::get_ref_count() const {
793 return local_group_root_->ref_count_;
794 }
795
get_local_group_root() const796 soinfo* soinfo::get_local_group_root() const {
797 return local_group_root_;
798 }
799
set_mapped_by_caller(bool mapped_by_caller)800 void 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
is_mapped_by_caller() const808 bool 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.
get_target_sdk_version() const815 int soinfo::get_target_sdk_version() const {
816 if (!has_min_version(2)) {
817 return __ANDROID_API__;
818 }
819
820 return local_group_root_->target_sdk_version_;
821 }
822
get_handle() const823 uintptr_t soinfo::get_handle() const {
824 CHECK(has_min_version(3));
825 CHECK(handle_ != 0);
826 return handle_;
827 }
828
to_handle()829 void* soinfo::to_handle() {
830 if (get_application_target_sdk_version() < 24 || !has_min_version(3)) {
831 return this;
832 }
833
834 return reinterpret_cast<void*>(get_handle());
835 }
836
generate_handle()837 void 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 {
844 if (!is_first_stage_init()) {
845 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 }
852 // 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) ||
858 g_soinfo_handles_map.contains(handle_));
859
860 g_soinfo_handles_map[handle_] = this;
861 }
862
set_gap_start(ElfW (Addr)gap_start)863 void soinfo::set_gap_start(ElfW(Addr) gap_start) {
864 CHECK(has_min_version(6));
865 gap_start_ = gap_start;
866 }
ElfW(Addr)867 ElfW(Addr) soinfo::get_gap_start() const {
868 CHECK(has_min_version(6));
869 return gap_start_;
870 }
871
set_gap_size(size_t gap_size)872 void soinfo::set_gap_size(size_t gap_size) {
873 CHECK(has_min_version(6));
874 gap_size_ = gap_size;
875 }
get_gap_size() const876 size_t soinfo::get_gap_size() const {
877 CHECK(has_min_version(6));
878 return gap_size_;
879 }
880
881 // TODO(dimitry): Move SymbolName methods to a separate file.
882
calculate_elf_hash(const char * name)883 uint32_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
elf_hash()897 uint32_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
gnu_hash()906 uint32_t SymbolName::gnu_hash() {
907 if (!has_gnu_hash_) {
908 gnu_hash_ = calculate_gnu_hash(name_).first;
909 has_gnu_hash_ = true;
910 }
911
912 return gnu_hash_;
913 }
914