• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 (!is_lp64_or_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   return is_lp64_or_has_min_version(2)? verneed_ptr_ : 0;
248 }
249 
get_verneed_cnt() const250 size_t soinfo::get_verneed_cnt() const {
251   return is_lp64_or_has_min_version(2) ? verneed_cnt_ : 0;
252 }
253 
ElfW(Addr)254 ElfW(Addr) soinfo::get_verdef_ptr() const {
255   return is_lp64_or_has_min_version(2) ? verdef_ptr_ : 0;
256 }
257 
get_verdef_cnt() const258 size_t soinfo::get_verdef_cnt() const {
259   return is_lp64_or_has_min_version(2) ? verdef_cnt_ : 0;
260 }
261 
get_lookup_lib()262 SymbolLookupLib soinfo::get_lookup_lib() {
263   SymbolLookupLib result {};
264   result.si_ = this;
265 
266   // For libs that only have SysV hashes, leave the gnu_bloom_filter_ field NULL to signal that
267   // the fallback code path is needed.
268   if (!is_gnu_hash()) {
269     return result;
270   }
271 
272   result.gnu_maskwords_ = gnu_maskwords_;
273   result.gnu_shift2_ = gnu_shift2_;
274   result.gnu_bloom_filter_ = gnu_bloom_filter_;
275 
276   result.strtab_ = strtab_;
277   result.strtab_size_ = strtab_size_;
278   result.symtab_ = symtab_;
279   result.versym_ = get_versym_table();
280 
281   result.gnu_chain_ = gnu_chain_;
282   result.gnu_nbucket_ = gnu_nbucket_;
283   result.gnu_bucket_ = gnu_bucket_;
284 
285   return result;
286 }
287 
ElfW(Sym)288 const ElfW(Sym)* soinfo::find_symbol_by_name(SymbolName& symbol_name,
289                                              const version_info* vi) const {
290   return is_gnu_hash() ? gnu_lookup(symbol_name, vi) : elf_lookup(symbol_name, vi);
291 }
292 
ElfW(Addr)293 ElfW(Addr) soinfo::apply_memtag_if_mte_globals(ElfW(Addr) sym_addr) const {
294   if (!should_tag_memtag_globals()) return sym_addr;
295   if (sym_addr == 0) return sym_addr;  // Handle undefined weak symbols.
296   return reinterpret_cast<ElfW(Addr)>(get_tagged_address(reinterpret_cast<void*>(sym_addr)));
297 }
298 
ElfW(Sym)299 const ElfW(Sym)* soinfo::gnu_lookup(SymbolName& symbol_name, const version_info* vi) const {
300   const uint32_t hash = symbol_name.gnu_hash();
301 
302   constexpr uint32_t kBloomMaskBits = sizeof(ElfW(Addr)) * 8;
303   const uint32_t word_num = (hash / kBloomMaskBits) & gnu_maskwords_;
304   const ElfW(Addr) bloom_word = gnu_bloom_filter_[word_num];
305   const uint32_t h1 = hash % kBloomMaskBits;
306   const uint32_t h2 = (hash >> gnu_shift2_) % kBloomMaskBits;
307 
308   LD_DEBUG(lookup, "SEARCH %s in %s@%p (gnu)",
309            symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
310 
311   // test against bloom filter
312   if ((1 & (bloom_word >> h1) & (bloom_word >> h2)) == 0) {
313     return nullptr;
314   }
315 
316   // bloom test says "probably yes"...
317   uint32_t n = gnu_bucket_[hash % gnu_nbucket_];
318 
319   if (n == 0) {
320     return nullptr;
321   }
322 
323   const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
324   const ElfW(Versym)* versym = get_versym_table();
325 
326   do {
327     ElfW(Sym)* s = symtab_ + n;
328     if (((gnu_chain_[n] ^ hash) >> 1) == 0 &&
329         check_symbol_version(versym, n, verneed) &&
330         strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
331         is_symbol_global_and_defined(this, s)) {
332       return symtab_ + n;
333     }
334   } while ((gnu_chain_[n++] & 1) == 0);
335 
336   return nullptr;
337 }
338 
ElfW(Sym)339 const ElfW(Sym)* soinfo::elf_lookup(SymbolName& symbol_name, const version_info* vi) const {
340   uint32_t hash = symbol_name.elf_hash();
341 
342   LD_DEBUG(lookup, "SEARCH %s in %s@%p h=%x(elf) %zd",
343            symbol_name.get_name(), get_realpath(),
344            reinterpret_cast<void*>(base), hash, hash % nbucket_);
345 
346   const ElfW(Versym) verneed = find_verdef_version_index(this, vi);
347   const ElfW(Versym)* versym = get_versym_table();
348 
349   for (uint32_t n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
350     ElfW(Sym)* s = symtab_ + n;
351 
352     if (check_symbol_version(versym, n, verneed) &&
353         strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
354         is_symbol_global_and_defined(this, s)) {
355       return symtab_ + n;
356     }
357   }
358 
359   return nullptr;
360 }
361 
ElfW(Sym)362 ElfW(Sym)* soinfo::find_symbol_by_address(const void* addr) {
363   return is_gnu_hash() ? gnu_addr_lookup(addr) : elf_addr_lookup(addr);
364 }
365 
symbol_matches_soaddr(const ElfW (Sym)* sym,ElfW (Addr)soaddr)366 static bool symbol_matches_soaddr(const ElfW(Sym)* sym, ElfW(Addr) soaddr) {
367   // Skip TLS symbols. A TLS symbol's value is relative to the start of the TLS segment rather than
368   // to the start of the solib. The solib only reserves space for the initialized part of the TLS
369   // segment. (i.e. .tdata is followed by .tbss, and .tbss overlaps other sections.)
370   return sym->st_shndx != SHN_UNDEF &&
371       ELF_ST_TYPE(sym->st_info) != STT_TLS &&
372       soaddr >= sym->st_value &&
373       soaddr < sym->st_value + sym->st_size;
374 }
375 
ElfW(Sym)376 ElfW(Sym)* soinfo::gnu_addr_lookup(const void* addr) {
377   ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
378 
379   for (size_t i = 0; i < gnu_nbucket_; ++i) {
380     uint32_t n = gnu_bucket_[i];
381 
382     if (n == 0) {
383       continue;
384     }
385 
386     do {
387       ElfW(Sym)* sym = symtab_ + n;
388       if (symbol_matches_soaddr(sym, soaddr)) {
389         return sym;
390       }
391     } while ((gnu_chain_[n++] & 1) == 0);
392   }
393 
394   return nullptr;
395 }
396 
ElfW(Sym)397 ElfW(Sym)* soinfo::elf_addr_lookup(const void* addr) {
398   ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
399 
400   // Search the library's symbol table for any defined symbol which
401   // contains this address.
402   for (size_t i = 0; i < nchain_; ++i) {
403     ElfW(Sym)* sym = symtab_ + i;
404     if (symbol_matches_soaddr(sym, soaddr)) {
405       return sym;
406     }
407   }
408 
409   return nullptr;
410 }
411 
call_function(const char * function_name __unused,linker_ctor_function_t function,const char * realpath __unused)412 static void call_function(const char* function_name __unused,
413                           linker_ctor_function_t function,
414                           const char* realpath __unused) {
415   if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
416     return;
417   }
418 
419   LD_DEBUG(calls, "[ Calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
420   function(g_argc, g_argv, g_envp);
421   LD_DEBUG(calls, "[ Done calling c-tor %s @ %p for '%s' ]", function_name, function, realpath);
422 }
423 
call_function(const char * function_name __unused,linker_dtor_function_t function,const char * realpath __unused)424 static void call_function(const char* function_name __unused,
425                           linker_dtor_function_t function,
426                           const char* realpath __unused) {
427   if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
428     return;
429   }
430 
431   LD_DEBUG(calls, "[ Calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
432   function();
433   LD_DEBUG(calls, "[ Done calling d-tor %s @ %p for '%s' ]", function_name, function, realpath);
434 }
435 
436 template <typename F>
call_array(const char * array_name __unused,F * functions,size_t count,bool reverse,const char * realpath)437 static inline void call_array(const char* array_name __unused, F* functions, size_t count,
438                               bool reverse, const char* realpath) {
439   if (functions == nullptr) {
440     return;
441   }
442 
443   LD_DEBUG(calls, "[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, realpath);
444 
445   int begin = reverse ? (count - 1) : 0;
446   int end = reverse ? -1 : count;
447   int step = reverse ? -1 : 1;
448 
449   for (int i = begin; i != end; i += step) {
450     LD_DEBUG(calls, "[ %s[%d] == %p ]", array_name, i, functions[i]);
451     call_function("function", functions[i], realpath);
452   }
453 
454   LD_DEBUG(calls, "[ Done calling %s for '%s' ]", array_name, realpath);
455 }
456 
call_pre_init_constructors()457 void soinfo::call_pre_init_constructors() {
458   // DT_PREINIT_ARRAY functions are called before any other constructors for executables,
459   // but ignored in a shared library.
460   call_array("DT_PREINIT_ARRAY", preinit_array_, preinit_array_count_, false, get_realpath());
461 }
462 
call_constructors()463 void soinfo::call_constructors() {
464   if (constructors_called) {
465     return;
466   }
467 
468   // We set constructors_called before actually calling the constructors, otherwise it doesn't
469   // protect against recursive constructor calls. One simple example of constructor recursion
470   // is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so:
471   // 1. The program depends on libc, so libc's constructor is called here.
472   // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
473   // 3. dlopen() calls the constructors on the newly created
474   //    soinfo for libc_malloc_debug_leak.so.
475   // 4. The debug .so depends on libc, so CallConstructors is
476   //    called again with the libc soinfo. If it doesn't trigger the early-
477   //    out above, the libc constructor will be called again (recursively!).
478   constructors_called = true;
479 
480   if (!is_main_executable() && preinit_array_ != nullptr) {
481     // The GNU dynamic linker silently ignores these, but we warn the developer.
482     DL_WARN("\"%s\": ignoring DT_PREINIT_ARRAY in shared library!", get_realpath());
483   }
484 
485   get_children().for_each([] (soinfo* si) {
486     si->call_constructors();
487   });
488 
489   if (!is_linker()) {
490     bionic_trace_begin((std::string("calling constructors: ") + get_realpath()).c_str());
491   }
492 
493   // DT_INIT should be called before DT_INIT_ARRAY if both are present.
494   call_function("DT_INIT", init_func_, get_realpath());
495   call_array("DT_INIT_ARRAY", init_array_, init_array_count_, false, get_realpath());
496 
497   if (!is_linker()) {
498     bionic_trace_end();
499   }
500 }
501 
call_destructors()502 void soinfo::call_destructors() {
503   if (!constructors_called) {
504     return;
505   }
506 
507   ScopedTrace trace((std::string("calling destructors: ") + get_realpath()).c_str());
508 
509   // DT_FINI_ARRAY must be parsed in reverse order.
510   call_array("DT_FINI_ARRAY", fini_array_, fini_array_count_, true, get_realpath());
511 
512   // DT_FINI should be called after DT_FINI_ARRAY if both are present.
513   call_function("DT_FINI", fini_func_, get_realpath());
514 }
515 
add_child(soinfo * child)516 void soinfo::add_child(soinfo* child) {
517   if (is_lp64_or_has_min_version(0)) {
518     child->parents_.push_back(this);
519     this->children_.push_back(child);
520   }
521 }
522 
remove_all_links()523 void soinfo::remove_all_links() {
524   if (!is_lp64_or_has_min_version(0)) {
525     return;
526   }
527 
528   // 1. Untie connected soinfos from 'this'.
529   children_.for_each([&] (soinfo* child) {
530     child->parents_.remove_if([&] (const soinfo* parent) {
531       return parent == this;
532     });
533   });
534 
535   parents_.for_each([&] (soinfo* parent) {
536     parent->children_.remove_if([&] (const soinfo* child) {
537       return child == this;
538     });
539   });
540 
541   // 2. Remove from the primary namespace
542   primary_namespace_->remove_soinfo(this);
543   primary_namespace_ = nullptr;
544 
545   // 3. Remove from secondary namespaces
546   secondary_namespaces_.for_each([&](android_namespace_t* ns) {
547     ns->remove_soinfo(this);
548   });
549 
550 
551   // 4. Once everything untied - clear local lists.
552   parents_.clear();
553   children_.clear();
554   secondary_namespaces_.clear();
555 }
556 
get_st_dev() const557 dev_t soinfo::get_st_dev() const {
558   return is_lp64_or_has_min_version(0) ? st_dev_ : 0;
559 };
560 
get_st_ino() const561 ino_t soinfo::get_st_ino() const {
562   return is_lp64_or_has_min_version(0) ? st_ino_ : 0;
563 }
564 
get_file_offset() const565 off64_t soinfo::get_file_offset() const {
566   return is_lp64_or_has_min_version(1) ? file_offset_ : 0;
567 }
568 
get_rtld_flags() const569 uint32_t soinfo::get_rtld_flags() const {
570   return is_lp64_or_has_min_version(1) ? rtld_flags_ : 0;
571 }
572 
get_dt_flags_1() const573 uint32_t soinfo::get_dt_flags_1() const {
574   return is_lp64_or_has_min_version(1) ? dt_flags_1_ : 0;
575 }
576 
set_dt_flags_1(uint32_t dt_flags_1)577 void soinfo::set_dt_flags_1(uint32_t dt_flags_1) {
578   if (is_lp64_or_has_min_version(1)) {
579     if ((dt_flags_1 & DF_1_GLOBAL) != 0) {
580       rtld_flags_ |= RTLD_GLOBAL;
581     }
582 
583     if ((dt_flags_1 & DF_1_NODELETE) != 0) {
584       rtld_flags_ |= RTLD_NODELETE;
585     }
586 
587     dt_flags_1_ = dt_flags_1;
588   }
589 }
590 
set_nodelete()591 void soinfo::set_nodelete() {
592   rtld_flags_ |= RTLD_NODELETE;
593 }
594 
set_realpath(const char * path)595 void soinfo::set_realpath(const char* path) {
596   if (is_lp64_or_has_min_version(2)) {
597     realpath_ = path;
598   }
599 }
600 
get_realpath() const601 const char* soinfo::get_realpath() const {
602 #if defined(__LP64__)
603   return realpath_.c_str();
604 #else
605   return is_lp64_or_has_min_version(2) ? realpath_.c_str() : old_name_;
606 #endif
607 }
608 
set_soname(const char * soname)609 void soinfo::set_soname(const char* soname) {
610   if (is_lp64_or_has_min_version(2)) {
611     soname_ = soname;
612   }
613 #if !defined(__LP64__)
614   strlcpy(old_name_, soname_.c_str(), sizeof(old_name_));
615 #endif
616 }
617 
get_soname() const618 const char* soinfo::get_soname() const {
619 #if defined(__LP64__)
620   return soname_.c_str();
621 #else
622   return is_lp64_or_has_min_version(2) ? soname_.c_str() : old_name_;
623 #endif
624 }
625 
626 // This is a return on get_children()/get_parents() if
627 // 'this->flags' does not have FLAG_NEW_SOINFO set.
628 static soinfo_list_t g_empty_list;
629 
get_children()630 soinfo_list_t& soinfo::get_children() {
631   return is_lp64_or_has_min_version(0) ? children_ : g_empty_list;
632 }
633 
get_children() const634 const soinfo_list_t& soinfo::get_children() const {
635   return is_lp64_or_has_min_version(0) ? children_ : g_empty_list;
636 }
637 
get_parents()638 soinfo_list_t& soinfo::get_parents() {
639   return is_lp64_or_has_min_version(0) ? parents_ : g_empty_list;
640 }
641 
642 static std::vector<std::string> g_empty_runpath;
643 
get_dt_runpath() const644 const std::vector<std::string>& soinfo::get_dt_runpath() const {
645   return is_lp64_or_has_min_version(3) ? dt_runpath_ : g_empty_runpath;
646 }
647 
get_primary_namespace()648 android_namespace_t* soinfo::get_primary_namespace() {
649   return is_lp64_or_has_min_version(3) ? primary_namespace_ : &g_default_namespace;
650 }
651 
add_secondary_namespace(android_namespace_t * secondary_ns)652 void soinfo::add_secondary_namespace(android_namespace_t* secondary_ns) {
653   CHECK(is_lp64_or_has_min_version(3));
654   secondary_namespaces_.push_back(secondary_ns);
655 }
656 
get_secondary_namespaces()657 android_namespace_list_t& soinfo::get_secondary_namespaces() {
658   CHECK(is_lp64_or_has_min_version(3));
659   return secondary_namespaces_;
660 }
661 
get_string(ElfW (Word)index) const662 const char* soinfo::get_string(ElfW(Word) index) const {
663   if (is_lp64_or_has_min_version(1) && (index >= strtab_size_)) {
664     async_safe_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
665         get_realpath(), strtab_size_, index);
666   }
667 
668   return strtab_ + index;
669 }
670 
is_gnu_hash() const671 bool soinfo::is_gnu_hash() const {
672   return (flags_ & FLAG_GNU_HASH) != 0;
673 }
674 
can_unload() const675 bool soinfo::can_unload() const {
676   return !is_linked() ||
677          (
678              (get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0
679          );
680 }
681 
is_linked() const682 bool soinfo::is_linked() const {
683   return (flags_ & FLAG_LINKED) != 0;
684 }
685 
is_image_linked() const686 bool soinfo::is_image_linked() const {
687   return (flags_ & FLAG_IMAGE_LINKED) != 0;
688 }
689 
is_main_executable() const690 bool soinfo::is_main_executable() const {
691   return (flags_ & FLAG_EXE) != 0;
692 }
693 
is_linker() const694 bool soinfo::is_linker() const {
695   return (flags_ & FLAG_LINKER) != 0;
696 }
697 
set_linked()698 void soinfo::set_linked() {
699   flags_ |= FLAG_LINKED;
700 }
701 
set_image_linked()702 void soinfo::set_image_linked() {
703   flags_ |= FLAG_IMAGE_LINKED;
704 }
705 
set_linker_flag()706 void soinfo::set_linker_flag() {
707   flags_ |= FLAG_LINKER;
708 }
709 
set_main_executable()710 void soinfo::set_main_executable() {
711   flags_ |= FLAG_EXE;
712 }
713 
increment_ref_count()714 size_t soinfo::increment_ref_count() {
715   return ++local_group_root_->ref_count_;
716 }
717 
decrement_ref_count()718 size_t soinfo::decrement_ref_count() {
719   return --local_group_root_->ref_count_;
720 }
721 
get_ref_count() const722 size_t soinfo::get_ref_count() const {
723   return local_group_root_->ref_count_;
724 }
725 
get_local_group_root() const726 soinfo* soinfo::get_local_group_root() const {
727   return local_group_root_;
728 }
729 
set_mapped_by_caller(bool mapped_by_caller)730 void soinfo::set_mapped_by_caller(bool mapped_by_caller) {
731   if (mapped_by_caller) {
732     flags_ |= FLAG_MAPPED_BY_CALLER;
733   } else {
734     flags_ &= ~FLAG_MAPPED_BY_CALLER;
735   }
736 }
737 
is_mapped_by_caller() const738 bool soinfo::is_mapped_by_caller() const {
739   return (flags_ & FLAG_MAPPED_BY_CALLER) != 0;
740 }
741 
742 // This function returns api-level at the time of
743 // dlopen/load. Note that libraries opened by system
744 // will always have 'current' target sdk version.
get_target_sdk_version() const745 int soinfo::get_target_sdk_version() const {
746   if (!is_lp64_or_has_min_version(2)) {
747     return __ANDROID_API__;
748   }
749 
750   return local_group_root_->target_sdk_version_;
751 }
752 
get_handle() const753 uintptr_t soinfo::get_handle() const {
754   CHECK(is_lp64_or_has_min_version(3));
755   CHECK(handle_ != 0);
756   return handle_;
757 }
758 
to_handle()759 void* soinfo::to_handle() {
760   if (get_application_target_sdk_version() < 24 || !is_lp64_or_has_min_version(3)) {
761     return this;
762   }
763 
764   return reinterpret_cast<void*>(get_handle());
765 }
766 
generate_handle()767 void soinfo::generate_handle() {
768   CHECK(is_lp64_or_has_min_version(3));
769   CHECK(handle_ == 0); // Make sure this is the first call
770 
771   // Make sure the handle is unique and does not collide
772   // with special values which are RTLD_DEFAULT and RTLD_NEXT.
773   do {
774     if (!is_first_stage_init()) {
775       arc4random_buf(&handle_, sizeof(handle_));
776     } else {
777       // arc4random* is not available in init because /dev/urandom hasn't yet been
778       // created. So, when running with init, use the monotonically increasing
779       // numbers as handles
780       handle_ += 2;
781     }
782     // the least significant bit for the handle is always 1
783     // making it easy to test the type of handle passed to
784     // dl* functions.
785     handle_ = handle_ | 1;
786   } while (handle_ == reinterpret_cast<uintptr_t>(RTLD_DEFAULT) ||
787            handle_ == reinterpret_cast<uintptr_t>(RTLD_NEXT) ||
788            g_soinfo_handles_map.contains(handle_));
789 
790   g_soinfo_handles_map[handle_] = this;
791 }
792 
set_gap_start(ElfW (Addr)gap_start)793 void soinfo::set_gap_start(ElfW(Addr) gap_start) {
794   CHECK(is_lp64_or_has_min_version(6));
795   gap_start_ = gap_start;
796 }
ElfW(Addr)797 ElfW(Addr) soinfo::get_gap_start() const {
798   CHECK(is_lp64_or_has_min_version(6));
799   return gap_start_;
800 }
801 
set_gap_size(size_t gap_size)802 void soinfo::set_gap_size(size_t gap_size) {
803   CHECK(is_lp64_or_has_min_version(6));
804   gap_size_ = gap_size;
805 }
get_gap_size() const806 size_t soinfo::get_gap_size() const {
807   CHECK(is_lp64_or_has_min_version(6));
808   return gap_size_;
809 }
810 
811 // TODO(dimitry): Move SymbolName methods to a separate file.
812 
calculate_elf_hash(const char * name)813 uint32_t calculate_elf_hash(const char* name) {
814   const uint8_t* name_bytes = reinterpret_cast<const uint8_t*>(name);
815   uint32_t h = 0, g;
816 
817   while (*name_bytes) {
818     h = (h << 4) + *name_bytes++;
819     g = h & 0xf0000000;
820     h ^= g;
821     h ^= g >> 24;
822   }
823 
824   return h;
825 }
826 
elf_hash()827 uint32_t SymbolName::elf_hash() {
828   if (!has_elf_hash_) {
829     elf_hash_ = calculate_elf_hash(name_);
830     has_elf_hash_ = true;
831   }
832 
833   return elf_hash_;
834 }
835 
gnu_hash()836 uint32_t SymbolName::gnu_hash() {
837   if (!has_gnu_hash_) {
838     gnu_hash_ = calculate_gnu_hash(name_).first;
839     has_gnu_hash_ = true;
840   }
841 
842   return gnu_hash_;
843 }
844