1 /*
2  * Copyright (C) 2008 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 <android/api-level.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <inttypes.h>
33 #include <pthread.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <sys/mman.h>
38 #include <sys/param.h>
39 #include <sys/vfs.h>
40 #include <unistd.h>
41 
42 #include <new>
43 #include <string>
44 #include <unordered_map>
45 #include <vector>
46 
47 #include <android-base/properties.h>
48 #include <android-base/scopeguard.h>
49 #include <async_safe/log.h>
50 #include <bionic/pthread_internal.h>
51 
52 // Private C library headers.
53 
54 #include "linker.h"
55 #include "linker_block_allocator.h"
56 #include "linker_cfi.h"
57 #include "linker_config.h"
58 #include "linker_gdb_support.h"
59 #include "linker_globals.h"
60 #include "linker_debug.h"
61 #include "linker_dlwarning.h"
62 #include "linker_main.h"
63 #include "linker_namespaces.h"
64 #include "linker_sleb128.h"
65 #include "linker_phdr.h"
66 #include "linker_relocate.h"
67 #include "linker_tls.h"
68 #include "linker_translate_path.h"
69 #include "linker_utils.h"
70 
71 #include "private/bionic_call_ifunc_resolver.h"
72 #include "private/bionic_globals.h"
73 #include "android-base/macros.h"
74 #include "android-base/strings.h"
75 #include "android-base/stringprintf.h"
76 #include "ziparchive/zip_archive.h"
77 
78 static std::unordered_map<void*, size_t> g_dso_handle_counters;
79 
80 static bool g_anonymous_namespace_set = false;
81 static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
82 static std::unordered_map<std::string, android_namespace_t*> g_exported_namespaces;
83 
84 static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
85 static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
86 
87 static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
88 static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
89 
90 static uint64_t g_module_load_counter = 0;
91 static uint64_t g_module_unload_counter = 0;
92 
93 static const char* const kLdConfigArchFilePath = "/system/etc/ld.config." ABI_STRING ".txt";
94 
95 static const char* const kLdConfigFilePath = "/system/etc/ld.config.txt";
96 static const char* const kLdConfigVndkLiteFilePath = "/system/etc/ld.config.vndk_lite.txt";
97 
98 static const char* const kLdGeneratedConfigFilePath = "/linkerconfig/ld.config.txt";
99 
100 #if defined(__LP64__)
101 static const char* const kSystemLibDir        = "/system/lib64";
102 static const char* const kOdmLibDir           = "/odm/lib64";
103 static const char* const kVendorLibDir        = "/vendor/lib64";
104 static const char* const kAsanSystemLibDir    = "/data/asan/system/lib64";
105 static const char* const kAsanOdmLibDir       = "/data/asan/odm/lib64";
106 static const char* const kAsanVendorLibDir    = "/data/asan/vendor/lib64";
107 #else
108 static const char* const kSystemLibDir        = "/system/lib";
109 static const char* const kOdmLibDir           = "/odm/lib";
110 static const char* const kVendorLibDir        = "/vendor/lib";
111 static const char* const kAsanSystemLibDir    = "/data/asan/system/lib";
112 static const char* const kAsanOdmLibDir       = "/data/asan/odm/lib";
113 static const char* const kAsanVendorLibDir    = "/data/asan/vendor/lib";
114 #endif
115 
116 static const char* const kAsanLibDirPrefix = "/data/asan";
117 
118 static const char* const kDefaultLdPaths[] = {
119   kSystemLibDir,
120   kOdmLibDir,
121   kVendorLibDir,
122   nullptr
123 };
124 
125 static const char* const kAsanDefaultLdPaths[] = {
126   kAsanSystemLibDir,
127   kSystemLibDir,
128   kAsanOdmLibDir,
129   kOdmLibDir,
130   kAsanVendorLibDir,
131   kVendorLibDir,
132   nullptr
133 };
134 
135 // Is ASAN enabled?
136 static bool g_is_asan = false;
137 
138 static CFIShadowWriter g_cfi_shadow;
139 
get_cfi_shadow()140 CFIShadowWriter* get_cfi_shadow() {
141   return &g_cfi_shadow;
142 }
143 
is_system_library(const std::string & realpath)144 static bool is_system_library(const std::string& realpath) {
145   for (const auto& dir : g_default_namespace.get_default_library_paths()) {
146     if (file_is_in_dir(realpath, dir)) {
147       return true;
148     }
149   }
150   return false;
151 }
152 
153 // Checks if the file exists and not a directory.
file_exists(const char * path)154 static bool file_exists(const char* path) {
155   struct stat s;
156 
157   if (stat(path, &s) != 0) {
158     return false;
159   }
160 
161   return S_ISREG(s.st_mode);
162 }
163 
resolve_soname(const std::string & name)164 static std::string resolve_soname(const std::string& name) {
165   // We assume that soname equals to basename here
166 
167   // TODO(dimitry): consider having honest absolute-path -> soname resolution
168   // note that since we might end up refusing to load this library because
169   // it is not in shared libs list we need to get the soname without actually loading
170   // the library.
171   //
172   // On the other hand there are several places where we already assume that
173   // soname == basename in particular for any not-loaded library mentioned
174   // in DT_NEEDED list.
175   return basename(name.c_str());
176 }
177 
maybe_accessible_via_namespace_links(android_namespace_t * ns,const char * name)178 static bool maybe_accessible_via_namespace_links(android_namespace_t* ns, const char* name) {
179   std::string soname = resolve_soname(name);
180   for (auto& ns_link : ns->linked_namespaces()) {
181     if (ns_link.is_accessible(soname.c_str())) {
182       return true;
183     }
184   }
185 
186   return false;
187 }
188 
189 // TODO(dimitry): The exempt-list is a workaround for http://b/26394120 ---
190 // gradually remove libraries from this list until it is gone.
is_exempt_lib(android_namespace_t * ns,const char * name,const soinfo * needed_by)191 static bool is_exempt_lib(android_namespace_t* ns, const char* name, const soinfo* needed_by) {
192   static const char* const kLibraryExemptList[] = {
193     "libandroid_runtime.so",
194     "libbinder.so",
195     "libcrypto.so",
196     "libcutils.so",
197     "libexpat.so",
198     "libgui.so",
199     "libmedia.so",
200     "libnativehelper.so",
201     "libssl.so",
202     "libstagefright.so",
203     "libsqlite.so",
204     "libui.so",
205     "libutils.so",
206     nullptr
207   };
208 
209   // If you're targeting N, you don't get the exempt-list.
210   if (get_application_target_sdk_version() >= 24) {
211     return false;
212   }
213 
214   // if the library needed by a system library - implicitly assume it
215   // is exempt unless it is in the list of shared libraries for one or
216   // more linked namespaces
217   if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
218     return !maybe_accessible_via_namespace_links(ns, name);
219   }
220 
221   // if this is an absolute path - make sure it points to /system/lib(64)
222   if (name[0] == '/' && dirname(name) == kSystemLibDir) {
223     // and reduce the path to basename
224     name = basename(name);
225   }
226 
227   for (size_t i = 0; kLibraryExemptList[i] != nullptr; ++i) {
228     if (strcmp(name, kLibraryExemptList[i]) == 0) {
229       return true;
230     }
231   }
232 
233   return false;
234 }
235 // END OF WORKAROUND
236 
237 static std::vector<std::string> g_ld_preload_names;
238 
notify_gdb_of_load(soinfo * info)239 static void notify_gdb_of_load(soinfo* info) {
240   if (info->is_linker() || info->is_main_executable()) {
241     // gdb already knows about the linker and the main executable.
242     return;
243   }
244 
245   link_map* map = &(info->link_map_head);
246 
247   map->l_addr = info->load_bias;
248   // link_map l_name field is not const.
249   map->l_name = const_cast<char*>(info->get_realpath());
250   map->l_ld = info->dynamic;
251 
252   CHECK(map->l_name != nullptr);
253   CHECK(map->l_name[0] != '\0');
254 
255   notify_gdb_of_load(map);
256 }
257 
notify_gdb_of_unload(soinfo * info)258 static void notify_gdb_of_unload(soinfo* info) {
259   notify_gdb_of_unload(&(info->link_map_head));
260 }
261 
alloc()262 LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
263   return g_soinfo_links_allocator.alloc();
264 }
265 
free(LinkedListEntry<soinfo> * entry)266 void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
267   g_soinfo_links_allocator.free(entry);
268 }
269 
alloc()270 LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
271   return g_namespace_list_allocator.alloc();
272 }
273 
free(LinkedListEntry<android_namespace_t> * entry)274 void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
275   g_namespace_list_allocator.free(entry);
276 }
277 
soinfo_alloc(android_namespace_t * ns,const char * name,const struct stat * file_stat,off64_t file_offset,uint32_t rtld_flags)278 soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
279                      const struct stat* file_stat, off64_t file_offset,
280                      uint32_t rtld_flags) {
281   if (strlen(name) >= PATH_MAX) {
282     async_safe_fatal("library name \"%s\" too long", name);
283   }
284 
285   TRACE("name %s: allocating soinfo for ns=%p", name, ns);
286 
287   soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
288                                                        file_offset, rtld_flags);
289 
290   solist_add_soinfo(si);
291 
292   si->generate_handle();
293   ns->add_soinfo(si);
294 
295   TRACE("name %s: allocated soinfo @ %p", name, si);
296   return si;
297 }
298 
soinfo_free(soinfo * si)299 static void soinfo_free(soinfo* si) {
300   if (si == nullptr) {
301     return;
302   }
303 
304   if (si->base != 0 && si->size != 0) {
305     if (!si->is_mapped_by_caller()) {
306       munmap(reinterpret_cast<void*>(si->base), si->size);
307     } else {
308       // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
309       mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
310            MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
311     }
312   }
313 
314   if (si->has_min_version(6) && si->get_gap_size()) {
315     munmap(reinterpret_cast<void*>(si->get_gap_start()), si->get_gap_size());
316   }
317 
318   TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
319 
320   if (!solist_remove_soinfo(si)) {
321     async_safe_fatal("soinfo=%p is not in soinfo_list (double unload?)", si);
322   }
323 
324   // clear links to/from si
325   si->remove_all_links();
326 
327   si->~soinfo();
328   g_soinfo_allocator.free(si);
329 }
330 
parse_path(const char * path,const char * delimiters,std::vector<std::string> * resolved_paths)331 static void parse_path(const char* path, const char* delimiters,
332                        std::vector<std::string>* resolved_paths) {
333   std::vector<std::string> paths;
334   split_path(path, delimiters, &paths);
335   resolve_paths(paths, resolved_paths);
336 }
337 
parse_LD_LIBRARY_PATH(const char * path)338 static void parse_LD_LIBRARY_PATH(const char* path) {
339   std::vector<std::string> ld_libary_paths;
340   parse_path(path, ":", &ld_libary_paths);
341   g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
342 }
343 
realpath_fd(int fd,std::string * realpath)344 static bool realpath_fd(int fd, std::string* realpath) {
345   // proc_self_fd needs to be large enough to hold "/proc/self/fd/" plus an
346   // integer, plus the NULL terminator.
347   char proc_self_fd[32];
348   // We want to statically allocate this large buffer so that we don't grow
349   // the stack by too much.
350   static char buf[PATH_MAX];
351 
352   async_safe_format_buffer(proc_self_fd, sizeof(proc_self_fd), "/proc/self/fd/%d", fd);
353   auto length = readlink(proc_self_fd, buf, sizeof(buf));
354   if (length == -1) {
355     if (!is_first_stage_init()) {
356       PRINT("readlink(\"%s\") failed: %s [fd=%d]", proc_self_fd, strerror(errno), fd);
357     }
358     return false;
359   }
360 
361   realpath->assign(buf, length);
362   return true;
363 }
364 
365 // Returns the address of the current thread's copy of a TLS module. If the current thread doesn't
366 // have a copy yet, allocate one on-demand if should_alloc is true, and return nullptr otherwise.
get_tls_block_for_this_thread(const soinfo_tls * si_tls,bool should_alloc)367 static inline void* get_tls_block_for_this_thread(const soinfo_tls* si_tls, bool should_alloc) {
368   const TlsModule& tls_mod = get_tls_module(si_tls->module_id);
369   if (tls_mod.static_offset != SIZE_MAX) {
370     const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
371     char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb();
372     return static_tls + tls_mod.static_offset;
373   } else if (should_alloc) {
374     const TlsIndex ti { si_tls->module_id, 0 };
375     return TLS_GET_ADDR(&ti);
376   } else {
377     TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
378     if (dtv->generation < tls_mod.first_generation) return nullptr;
379     return dtv->modules[__tls_module_id_to_idx(si_tls->module_id)];
380   }
381 }
382 
383 #if defined(__arm__)
384 
385 // For a given PC, find the .so that it belongs to.
386 // Returns the base address of the .ARM.exidx section
387 // for that .so, and the number of 8-byte entries
388 // in that section (via *pcount).
389 //
390 // Intended to be called by libc's __gnu_Unwind_Find_exidx().
do_dl_unwind_find_exidx(_Unwind_Ptr pc,int * pcount)391 _Unwind_Ptr do_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
392   if (soinfo* si = find_containing_library(reinterpret_cast<void*>(pc))) {
393     *pcount = si->ARM_exidx_count;
394     return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
395   }
396   *pcount = 0;
397   return 0;
398 }
399 
400 #endif
401 
402 // Here, we only have to provide a callback to iterate across all the
403 // loaded libraries. gcc_eh does the rest.
do_dl_iterate_phdr(int (* cb)(dl_phdr_info * info,size_t size,void * data),void * data)404 int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
405   int rv = 0;
406   for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
407     dl_phdr_info dl_info;
408     dl_info.dlpi_addr = si->link_map_head.l_addr;
409     dl_info.dlpi_name = si->link_map_head.l_name;
410     dl_info.dlpi_phdr = si->phdr;
411     dl_info.dlpi_phnum = si->phnum;
412     dl_info.dlpi_adds = g_module_load_counter;
413     dl_info.dlpi_subs = g_module_unload_counter;
414     if (soinfo_tls* tls_module = si->get_tls()) {
415       dl_info.dlpi_tls_modid = tls_module->module_id;
416       dl_info.dlpi_tls_data = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/false);
417     } else {
418       dl_info.dlpi_tls_modid = 0;
419       dl_info.dlpi_tls_data = nullptr;
420     }
421 
422     rv = cb(&dl_info, sizeof(dl_phdr_info), data);
423     if (rv != 0) {
424       break;
425     }
426   }
427   return rv;
428 }
429 
ProtectedDataGuard()430 ProtectedDataGuard::ProtectedDataGuard() {
431   if (ref_count_++ == 0) {
432     protect_data(PROT_READ | PROT_WRITE);
433   }
434 
435   if (ref_count_ == 0) { // overflow
436     async_safe_fatal("Too many nested calls to dlopen()");
437   }
438 }
439 
~ProtectedDataGuard()440 ProtectedDataGuard::~ProtectedDataGuard() {
441   if (--ref_count_ == 0) {
442     protect_data(PROT_READ);
443   }
444 }
445 
protect_data(int protection)446 void ProtectedDataGuard::protect_data(int protection) {
447   g_soinfo_allocator.protect_all(protection);
448   g_soinfo_links_allocator.protect_all(protection);
449   g_namespace_allocator.protect_all(protection);
450   g_namespace_list_allocator.protect_all(protection);
451 }
452 
453 size_t ProtectedDataGuard::ref_count_ = 0;
454 
455 // Each size has it's own allocator.
456 template<size_t size>
457 class SizeBasedAllocator {
458  public:
alloc()459   static void* alloc() {
460     return allocator_.alloc();
461   }
462 
free(void * ptr)463   static void free(void* ptr) {
464     allocator_.free(ptr);
465   }
466 
purge()467   static void purge() {
468     allocator_.purge();
469   }
470 
471  private:
472   static LinkerBlockAllocator allocator_;
473 };
474 
475 template<size_t size>
476 LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
477 
478 template<typename T>
479 class TypeBasedAllocator {
480  public:
alloc()481   static T* alloc() {
482     return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
483   }
484 
free(T * ptr)485   static void free(T* ptr) {
486     SizeBasedAllocator<sizeof(T)>::free(ptr);
487   }
488 
purge()489   static void purge() {
490     SizeBasedAllocator<sizeof(T)>::purge();
491   }
492 };
493 
494 class LoadTask {
495  public:
496   struct deleter_t {
operator ()LoadTask::deleter_t497     void operator()(LoadTask* t) {
498       t->~LoadTask();
499       TypeBasedAllocator<LoadTask>::free(t);
500     }
501   };
502 
503   static deleter_t deleter;
504 
505   // needed_by is NULL iff dlopen is called from memory that isn't part of any known soinfo.
create(const char * _Nonnull name,soinfo * _Nullable needed_by,android_namespace_t * _Nonnull start_from,std::unordered_map<const soinfo *,ElfReader> * _Nonnull readers_map)506   static LoadTask* create(const char* _Nonnull name, soinfo* _Nullable needed_by,
507                           android_namespace_t* _Nonnull start_from,
508                           std::unordered_map<const soinfo*, ElfReader>* _Nonnull readers_map) {
509     LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
510     return new (ptr) LoadTask(name, needed_by, start_from, readers_map);
511   }
512 
get_name() const513   const char* get_name() const {
514     return name_;
515   }
516 
get_needed_by() const517   soinfo* get_needed_by() const {
518     return needed_by_;
519   }
520 
get_soinfo() const521   soinfo* get_soinfo() const {
522     return si_;
523   }
524 
set_soinfo(soinfo * si)525   void set_soinfo(soinfo* si) {
526     si_ = si;
527   }
528 
get_file_offset() const529   off64_t get_file_offset() const {
530     return file_offset_;
531   }
532 
set_file_offset(off64_t offset)533   void set_file_offset(off64_t offset) {
534     file_offset_ = offset;
535   }
536 
get_fd() const537   int get_fd() const {
538     return fd_;
539   }
540 
set_fd(int fd,bool assume_ownership)541   void set_fd(int fd, bool assume_ownership) {
542     if (fd_ != -1 && close_fd_) {
543       close(fd_);
544     }
545     fd_ = fd;
546     close_fd_ = assume_ownership;
547   }
548 
get_extinfo() const549   const android_dlextinfo* get_extinfo() const {
550     return extinfo_;
551   }
552 
set_extinfo(const android_dlextinfo * extinfo)553   void set_extinfo(const android_dlextinfo* extinfo) {
554     extinfo_ = extinfo;
555   }
556 
is_dt_needed() const557   bool is_dt_needed() const {
558     return is_dt_needed_;
559   }
560 
set_dt_needed(bool is_dt_needed)561   void set_dt_needed(bool is_dt_needed) {
562     is_dt_needed_ = is_dt_needed;
563   }
564 
565   // returns the namespace from where we need to start loading this.
get_start_from() const566   const android_namespace_t* get_start_from() const {
567     return start_from_;
568   }
569 
remove_cached_elf_reader()570   void remove_cached_elf_reader() {
571     CHECK(si_ != nullptr);
572     (*elf_readers_map_).erase(si_);
573   }
574 
get_elf_reader() const575   const ElfReader& get_elf_reader() const {
576     CHECK(si_ != nullptr);
577     return (*elf_readers_map_)[si_];
578   }
579 
get_elf_reader()580   ElfReader& get_elf_reader() {
581     CHECK(si_ != nullptr);
582     return (*elf_readers_map_)[si_];
583   }
584 
get_readers_map()585   std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
586     return elf_readers_map_;
587   }
588 
read(const char * realpath,off64_t file_size)589   bool read(const char* realpath, off64_t file_size) {
590     ElfReader& elf_reader = get_elf_reader();
591     return elf_reader.Read(realpath, fd_, file_offset_, file_size);
592   }
593 
load(address_space_params * address_space)594   bool load(address_space_params* address_space) {
595     ElfReader& elf_reader = get_elf_reader();
596     if (!elf_reader.Load(address_space)) {
597       return false;
598     }
599 
600     si_->base = elf_reader.load_start();
601     si_->size = elf_reader.load_size();
602     si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
603     si_->load_bias = elf_reader.load_bias();
604     si_->phnum = elf_reader.phdr_count();
605     si_->phdr = elf_reader.loaded_phdr();
606     si_->set_gap_start(elf_reader.gap_start());
607     si_->set_gap_size(elf_reader.gap_size());
608 
609     return true;
610   }
611 
612  private:
LoadTask(const char * name,soinfo * needed_by,android_namespace_t * start_from,std::unordered_map<const soinfo *,ElfReader> * readers_map)613   LoadTask(const char* name,
614            soinfo* needed_by,
615            android_namespace_t* start_from,
616            std::unordered_map<const soinfo*, ElfReader>* readers_map)
617     : name_(name), needed_by_(needed_by), si_(nullptr),
618       fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
619       is_dt_needed_(false), start_from_(start_from) {}
620 
~LoadTask()621   ~LoadTask() {
622     if (fd_ != -1 && close_fd_) {
623       close(fd_);
624     }
625   }
626 
627   const char* name_;
628   soinfo* needed_by_;
629   soinfo* si_;
630   const android_dlextinfo* extinfo_;
631   int fd_;
632   bool close_fd_;
633   off64_t file_offset_;
634   std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
635   // TODO(dimitry): needed by workaround for http://b/26394120 (the exempt-list)
636   bool is_dt_needed_;
637   // END OF WORKAROUND
638   const android_namespace_t* const start_from_;
639 
640   DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
641 };
642 
643 LoadTask::deleter_t LoadTask::deleter;
644 
645 template <typename T>
646 using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
647 
648 typedef linked_list_t<soinfo> SoinfoLinkedList;
649 typedef linked_list_t<const char> StringLinkedList;
650 typedef std::vector<LoadTask*> LoadTaskList;
651 
652 enum walk_action_result_t : uint32_t {
653   kWalkStop = 0,
654   kWalkContinue = 1,
655   kWalkSkip = 2
656 };
657 
658 // This function walks down the tree of soinfo dependencies
659 // in breadth-first order and
660 //   * calls action(soinfo* si) for each node, and
661 //   * terminates walk if action returns kWalkStop
662 //   * skips children of the node if action
663 //     return kWalkSkip
664 //
665 // walk_dependencies_tree returns false if walk was terminated
666 // by the action and true otherwise.
667 template<typename F>
walk_dependencies_tree(soinfo * root_soinfo,F action)668 static bool walk_dependencies_tree(soinfo* root_soinfo, F action) {
669   SoinfoLinkedList visit_list;
670   SoinfoLinkedList visited;
671 
672   visit_list.push_back(root_soinfo);
673 
674   soinfo* si;
675   while ((si = visit_list.pop_front()) != nullptr) {
676     if (visited.contains(si)) {
677       continue;
678     }
679 
680     walk_action_result_t result = action(si);
681 
682     if (result == kWalkStop) {
683       return false;
684     }
685 
686     visited.push_back(si);
687 
688     if (result != kWalkSkip) {
689       si->get_children().for_each([&](soinfo* child) {
690         visit_list.push_back(child);
691       });
692     }
693   }
694 
695   return true;
696 }
697 
698 
ElfW(Sym)699 static const ElfW(Sym)* dlsym_handle_lookup_impl(android_namespace_t* ns,
700                                                  soinfo* root,
701                                                  soinfo* skip_until,
702                                                  soinfo** found,
703                                                  SymbolName& symbol_name,
704                                                  const version_info* vi) {
705   const ElfW(Sym)* result = nullptr;
706   bool skip_lookup = skip_until != nullptr;
707 
708   walk_dependencies_tree(root, [&](soinfo* current_soinfo) {
709     if (skip_lookup) {
710       skip_lookup = current_soinfo != skip_until;
711       return kWalkContinue;
712     }
713 
714     if (!ns->is_accessible(current_soinfo)) {
715       return kWalkSkip;
716     }
717 
718     result = current_soinfo->find_symbol_by_name(symbol_name, vi);
719     if (result != nullptr) {
720       *found = current_soinfo;
721       return kWalkStop;
722     }
723 
724     return kWalkContinue;
725   });
726 
727   return result;
728 }
729 
730 /* This is used by dlsym(3) to performs a global symbol lookup. If the
731    start value is null (for RTLD_DEFAULT), the search starts at the
732    beginning of the global solist. Otherwise the search starts at the
733    specified soinfo (for RTLD_NEXT).
734  */
ElfW(Sym)735 static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
736                                             const char* name,
737                                             const version_info* vi,
738                                             soinfo** found,
739                                             soinfo* caller,
740                                             void* handle) {
741   SymbolName symbol_name(name);
742 
743   auto& soinfo_list = ns->soinfo_list();
744   auto start = soinfo_list.begin();
745 
746   if (handle == RTLD_NEXT) {
747     if (caller == nullptr) {
748       return nullptr;
749     } else {
750       auto it = soinfo_list.find(caller);
751       CHECK (it != soinfo_list.end());
752       start = ++it;
753     }
754   }
755 
756   const ElfW(Sym)* s = nullptr;
757   for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
758     soinfo* si = *it;
759     // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
760     // if the library is opened by application with target api level < M.
761     // See http://b/21565766
762     if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() >= 23) {
763       continue;
764     }
765 
766     s = si->find_symbol_by_name(symbol_name, vi);
767     if (s != nullptr) {
768       *found = si;
769       break;
770     }
771   }
772 
773   // If not found - use dlsym_handle_lookup_impl for caller's local_group
774   if (s == nullptr && caller != nullptr) {
775     soinfo* local_group_root = caller->get_local_group_root();
776 
777     return dlsym_handle_lookup_impl(local_group_root->get_primary_namespace(),
778                                     local_group_root,
779                                     (handle == RTLD_NEXT) ? caller : nullptr,
780                                     found,
781                                     symbol_name,
782                                     vi);
783   }
784 
785   if (s != nullptr) {
786     TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
787                name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
788   }
789 
790   return s;
791 }
792 
793 // This is used by dlsym(3).  It performs symbol lookup only within the
794 // specified soinfo object and its dependencies in breadth first order.
ElfW(Sym)795 static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si,
796                                             soinfo** found,
797                                             const char* name,
798                                             const version_info* vi) {
799   // According to man dlopen(3) and posix docs in the case when si is handle
800   // of the main executable we need to search not only in the executable and its
801   // dependencies but also in all libraries loaded with RTLD_GLOBAL.
802   //
803   // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
804   // libraries and they are loaded in breath-first (correct) order we can just execute
805   // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
806   if (si == solist_get_somain()) {
807     return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
808   }
809 
810   SymbolName symbol_name(name);
811   // note that the namespace is not the namespace associated with caller_addr
812   // we use ns associated with root si intentionally here. Using caller_ns
813   // causes problems when user uses dlopen_ext to open a library in the separate
814   // namespace and then calls dlsym() on the handle.
815   return dlsym_handle_lookup_impl(si->get_primary_namespace(), si, nullptr, found, symbol_name, vi);
816 }
817 
find_containing_library(const void * p)818 soinfo* find_containing_library(const void* p) {
819   // Addresses within a library may be tagged if they point to globals. Untag
820   // them so that the bounds check succeeds.
821   ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(untag_address(p));
822   for (soinfo* si = solist_get_head(); si != nullptr; si = si->next) {
823     if (address < si->base || address - si->base >= si->size) {
824       continue;
825     }
826     ElfW(Addr) vaddr = address - si->load_bias;
827     for (size_t i = 0; i != si->phnum; ++i) {
828       const ElfW(Phdr)* phdr = &si->phdr[i];
829       if (phdr->p_type != PT_LOAD) {
830         continue;
831       }
832       if (vaddr >= phdr->p_vaddr && vaddr < phdr->p_vaddr + phdr->p_memsz) {
833         return si;
834       }
835     }
836   }
837   return nullptr;
838 }
839 
840 class ZipArchiveCache {
841  public:
ZipArchiveCache()842   ZipArchiveCache() {}
843   ~ZipArchiveCache();
844 
845   bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
846  private:
847   DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
848 
849   std::unordered_map<std::string, ZipArchiveHandle> cache_;
850 };
851 
get_or_open(const char * zip_path,ZipArchiveHandle * handle)852 bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
853   std::string key(zip_path);
854 
855   auto it = cache_.find(key);
856   if (it != cache_.end()) {
857     *handle = it->second;
858     return true;
859   }
860 
861   int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
862   if (fd == -1) {
863     return false;
864   }
865 
866   if (OpenArchiveFd(fd, "", handle) != 0) {
867     // invalid zip-file (?)
868     CloseArchive(*handle);
869     return false;
870   }
871 
872   cache_[key] = *handle;
873   return true;
874 }
875 
~ZipArchiveCache()876 ZipArchiveCache::~ZipArchiveCache() {
877   for (const auto& it : cache_) {
878     CloseArchive(it.second);
879   }
880 }
881 
open_library_in_zipfile(ZipArchiveCache * zip_archive_cache,const char * const input_path,off64_t * file_offset,std::string * realpath)882 static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
883                                    const char* const input_path,
884                                    off64_t* file_offset, std::string* realpath) {
885   std::string normalized_path;
886   if (!normalize_path(input_path, &normalized_path)) {
887     return -1;
888   }
889 
890   const char* const path = normalized_path.c_str();
891   TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
892 
893   // Treat an '!/' separator inside a path as the separator between the name
894   // of the zip file on disk and the subdirectory to search within it.
895   // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
896   // "bar/bas/x.so" within "foo.zip".
897   const char* const separator = strstr(path, kZipFileSeparator);
898   if (separator == nullptr) {
899     return -1;
900   }
901 
902   char buf[512];
903   if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
904     PRINT("Warning: ignoring very long library path: %s", path);
905     return -1;
906   }
907 
908   buf[separator - path] = '\0';
909 
910   const char* zip_path = buf;
911   const char* file_path = &buf[separator - path + 2];
912   int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
913   if (fd == -1) {
914     return -1;
915   }
916 
917   ZipArchiveHandle handle;
918   if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
919     // invalid zip-file (?)
920     close(fd);
921     return -1;
922   }
923 
924   ZipEntry entry;
925 
926   if (FindEntry(handle, file_path, &entry) != 0) {
927     // Entry was not found.
928     close(fd);
929     return -1;
930   }
931 
932   // Check if it is properly stored
933   if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
934     close(fd);
935     return -1;
936   }
937 
938   *file_offset = entry.offset;
939 
940   if (realpath_fd(fd, realpath)) {
941     *realpath += separator;
942   } else {
943     if (!is_first_stage_init()) {
944       PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
945             normalized_path.c_str());
946     }
947     *realpath = normalized_path;
948   }
949 
950   return fd;
951 }
952 
format_path(char * buf,size_t buf_size,const char * path,const char * name)953 static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
954   int n = async_safe_format_buffer(buf, buf_size, "%s/%s", path, name);
955   if (n < 0 || n >= static_cast<int>(buf_size)) {
956     PRINT("Warning: ignoring very long library path: %s/%s", path, name);
957     return false;
958   }
959 
960   return true;
961 }
962 
open_library_at_path(ZipArchiveCache * zip_archive_cache,const char * path,off64_t * file_offset,std::string * realpath)963 static int open_library_at_path(ZipArchiveCache* zip_archive_cache,
964                                 const char* path, off64_t* file_offset,
965                                 std::string* realpath) {
966   int fd = -1;
967   if (strstr(path, kZipFileSeparator) != nullptr) {
968     fd = open_library_in_zipfile(zip_archive_cache, path, file_offset, realpath);
969   }
970 
971   if (fd == -1) {
972     fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
973     if (fd != -1) {
974       *file_offset = 0;
975       if (!realpath_fd(fd, realpath)) {
976         if (!is_first_stage_init()) {
977           PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
978                 path);
979         }
980         *realpath = path;
981       }
982     }
983   }
984 
985   return fd;
986 }
987 
open_library_on_paths(ZipArchiveCache * zip_archive_cache,const char * name,off64_t * file_offset,const std::vector<std::string> & paths,std::string * realpath)988 static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
989                                  const char* name, off64_t* file_offset,
990                                  const std::vector<std::string>& paths,
991                                  std::string* realpath) {
992   for (const auto& path : paths) {
993     char buf[512];
994     if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
995       continue;
996     }
997 
998     int fd = open_library_at_path(zip_archive_cache, buf, file_offset, realpath);
999     if (fd != -1) {
1000       return fd;
1001     }
1002   }
1003 
1004   return -1;
1005 }
1006 
open_library(android_namespace_t * ns,ZipArchiveCache * zip_archive_cache,const char * name,soinfo * needed_by,off64_t * file_offset,std::string * realpath)1007 static int open_library(android_namespace_t* ns,
1008                         ZipArchiveCache* zip_archive_cache,
1009                         const char* name, soinfo *needed_by,
1010                         off64_t* file_offset, std::string* realpath) {
1011   TRACE("[ opening %s from namespace %s ]", name, ns->get_name());
1012 
1013   // If the name contains a slash, we should attempt to open it directly and not search the paths.
1014   if (strchr(name, '/') != nullptr) {
1015     return open_library_at_path(zip_archive_cache, name, file_offset, realpath);
1016   }
1017 
1018   // LD_LIBRARY_PATH has the highest priority. We don't have to check accessibility when searching
1019   // the namespace's path lists, because anything found on a namespace path list should always be
1020   // accessible.
1021   int fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_ld_library_paths(), realpath);
1022 
1023   // Try the DT_RUNPATH, and verify that the library is accessible.
1024   if (fd == -1 && needed_by != nullptr) {
1025     fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
1026     if (fd != -1 && !ns->is_accessible(*realpath)) {
1027       close(fd);
1028       fd = -1;
1029     }
1030   }
1031 
1032   // Finally search the namespace's main search path list.
1033   if (fd == -1) {
1034     fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
1035   }
1036 
1037   return fd;
1038 }
1039 
open_executable(const char * path,off64_t * file_offset,std::string * realpath)1040 int open_executable(const char* path, off64_t* file_offset, std::string* realpath) {
1041   ZipArchiveCache zip_archive_cache;
1042   return open_library_at_path(&zip_archive_cache, path, file_offset, realpath);
1043 }
1044 
fix_dt_needed(const char * dt_needed,const char * sopath __unused)1045 const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
1046 #if !defined(__LP64__)
1047   // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
1048   int app_target_api_level = get_application_target_sdk_version();
1049   if (app_target_api_level < 23) {
1050     const char* bname = basename(dt_needed);
1051     if (bname != dt_needed) {
1052       DL_WARN_documented_change(23,
1053                                 "invalid-dt_needed-entries-enforced-for-api-level-23",
1054                                 "library \"%s\" has invalid DT_NEEDED entry \"%s\"",
1055                                 sopath, dt_needed, app_target_api_level);
1056       add_dlwarning(sopath, "invalid DT_NEEDED entry",  dt_needed);
1057     }
1058 
1059     return bname;
1060   }
1061 #endif
1062   return dt_needed;
1063 }
1064 
1065 template<typename F>
for_each_dt_needed(const ElfReader & elf_reader,F action)1066 static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1067   for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1068     if (d->d_tag == DT_NEEDED) {
1069       action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1070     }
1071   }
1072 }
1073 
find_loaded_library_by_inode(android_namespace_t * ns,const struct stat & file_stat,off64_t file_offset,bool search_linked_namespaces,soinfo ** candidate)1074 static bool find_loaded_library_by_inode(android_namespace_t* ns,
1075                                          const struct stat& file_stat,
1076                                          off64_t file_offset,
1077                                          bool search_linked_namespaces,
1078                                          soinfo** candidate) {
1079   if (file_stat.st_dev == 0 || file_stat.st_ino == 0) {
1080     *candidate = nullptr;
1081     return false;
1082   }
1083 
1084   auto predicate = [&](soinfo* si) {
1085     return si->get_st_ino() == file_stat.st_ino &&
1086            si->get_st_dev() == file_stat.st_dev &&
1087            si->get_file_offset() == file_offset;
1088   };
1089 
1090   *candidate = ns->soinfo_list().find_if(predicate);
1091 
1092   if (*candidate == nullptr && search_linked_namespaces) {
1093     for (auto& link : ns->linked_namespaces()) {
1094       android_namespace_t* linked_ns = link.linked_namespace();
1095       soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1096 
1097       if (si != nullptr && link.is_accessible(si->get_soname())) {
1098         *candidate = si;
1099         return true;
1100       }
1101     }
1102   }
1103 
1104   return *candidate != nullptr;
1105 }
1106 
find_loaded_library_by_realpath(android_namespace_t * ns,const char * realpath,bool search_linked_namespaces,soinfo ** candidate)1107 static bool find_loaded_library_by_realpath(android_namespace_t* ns, const char* realpath,
1108                                             bool search_linked_namespaces, soinfo** candidate) {
1109   auto predicate = [&](soinfo* si) { return strcmp(realpath, si->get_realpath()) == 0; };
1110 
1111   *candidate = ns->soinfo_list().find_if(predicate);
1112 
1113   if (*candidate == nullptr && search_linked_namespaces) {
1114     for (auto& link : ns->linked_namespaces()) {
1115       android_namespace_t* linked_ns = link.linked_namespace();
1116       soinfo* si = linked_ns->soinfo_list().find_if(predicate);
1117 
1118       if (si != nullptr && link.is_accessible(si->get_soname())) {
1119         *candidate = si;
1120         return true;
1121       }
1122     }
1123   }
1124 
1125   return *candidate != nullptr;
1126 }
1127 
load_library(android_namespace_t * ns,LoadTask * task,LoadTaskList * load_tasks,int rtld_flags,const std::string & realpath,bool search_linked_namespaces)1128 static bool load_library(android_namespace_t* ns,
1129                          LoadTask* task,
1130                          LoadTaskList* load_tasks,
1131                          int rtld_flags,
1132                          const std::string& realpath,
1133                          bool search_linked_namespaces) {
1134   off64_t file_offset = task->get_file_offset();
1135   const char* name = task->get_name();
1136   const android_dlextinfo* extinfo = task->get_extinfo();
1137 
1138   LD_LOG(kLogDlopen,
1139          "load_library(ns=%s, task=%s, flags=0x%x, realpath=%s, search_linked_namespaces=%d)",
1140          ns->get_name(), name, rtld_flags, realpath.c_str(), search_linked_namespaces);
1141 
1142   if ((file_offset % PAGE_SIZE) != 0) {
1143     DL_OPEN_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
1144     return false;
1145   }
1146   if (file_offset < 0) {
1147     DL_OPEN_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
1148     return false;
1149   }
1150 
1151   struct stat file_stat;
1152   if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
1153     DL_OPEN_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
1154     return false;
1155   }
1156   if (file_offset >= file_stat.st_size) {
1157     DL_OPEN_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
1158         name, file_offset, file_stat.st_size);
1159     return false;
1160   }
1161 
1162   // Check for symlink and other situations where
1163   // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1164   if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
1165     soinfo* si = nullptr;
1166     if (find_loaded_library_by_inode(ns, file_stat, file_offset, search_linked_namespaces, &si)) {
1167       LD_LOG(kLogDlopen,
1168              "load_library(ns=%s, task=%s): Already loaded under different name/path \"%s\" - "
1169              "will return existing soinfo",
1170              ns->get_name(), name, si->get_realpath());
1171       task->set_soinfo(si);
1172       return true;
1173     }
1174   }
1175 
1176   if ((rtld_flags & RTLD_NOLOAD) != 0) {
1177     DL_OPEN_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
1178     return false;
1179   }
1180 
1181   struct statfs fs_stat;
1182   if (TEMP_FAILURE_RETRY(fstatfs(task->get_fd(), &fs_stat)) != 0) {
1183     DL_OPEN_ERR("unable to fstatfs file for the library \"%s\": %s", name, strerror(errno));
1184     return false;
1185   }
1186 
1187   // do not check accessibility using realpath if fd is located on tmpfs
1188   // this enables use of memfd_create() for apps
1189   if ((fs_stat.f_type != TMPFS_MAGIC) && (!ns->is_accessible(realpath))) {
1190     // TODO(dimitry): workaround for http://b/26394120 - the exempt-list
1191 
1192     // TODO(dimitry) before O release: add a namespace attribute to have this enabled
1193     // only for classloader-namespaces
1194     const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
1195     if (is_exempt_lib(ns, name, needed_by)) {
1196       // print warning only if needed by non-system library
1197       if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1198         const soinfo* needed_or_dlopened_by = task->get_needed_by();
1199         const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1200                                                       needed_or_dlopened_by->get_realpath();
1201         DL_WARN_documented_change(24,
1202                                   "private-api-enforced-for-api-level-24",
1203                                   "library \"%s\" (\"%s\") needed or dlopened by \"%s\" "
1204                                   "is not accessible by namespace \"%s\"",
1205                                   name, realpath.c_str(), sopath, ns->get_name());
1206         add_dlwarning(sopath, "unauthorized access to",  name);
1207       }
1208     } else {
1209       // do not load libraries if they are not accessible for the specified namespace.
1210       const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1211                                           "(unknown)" :
1212                                           task->get_needed_by()->get_realpath();
1213 
1214       DL_OPEN_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
1215              name, needed_or_dlopened_by, ns->get_name());
1216 
1217       // do not print this if a library is in the list of shared libraries for linked namespaces
1218       if (!maybe_accessible_via_namespace_links(ns, name)) {
1219         PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1220               " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1221               " permitted_paths=\"%s\"]",
1222               name, realpath.c_str(),
1223               needed_or_dlopened_by,
1224               ns->get_name(),
1225               android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1226               android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1227               android::base::Join(ns->get_permitted_paths(), ':').c_str());
1228       }
1229       return false;
1230     }
1231   }
1232 
1233   soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
1234 
1235   task->set_soinfo(si);
1236 
1237   // Read the ELF header and some of the segments.
1238   if (!task->read(realpath.c_str(), file_stat.st_size)) {
1239     task->remove_cached_elf_reader();
1240     task->set_soinfo(nullptr);
1241     soinfo_free(si);
1242     return false;
1243   }
1244 
1245   // Find and set DT_RUNPATH, DT_SONAME, and DT_FLAGS_1.
1246   // Note that these field values are temporary and are
1247   // going to be overwritten on soinfo::prelink_image
1248   // with values from PT_LOAD segments.
1249   const ElfReader& elf_reader = task->get_elf_reader();
1250   for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1251     if (d->d_tag == DT_RUNPATH) {
1252       si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1253     }
1254     if (d->d_tag == DT_SONAME) {
1255       si->set_soname(elf_reader.get_string(d->d_un.d_val));
1256     }
1257     // We need to identify a DF_1_GLOBAL library early so we can link it to namespaces.
1258     if (d->d_tag == DT_FLAGS_1) {
1259       si->set_dt_flags_1(d->d_un.d_val);
1260     }
1261   }
1262 
1263 #if !defined(__ANDROID__)
1264   // Bionic on the host currently uses some Android prebuilts, which don't set
1265   // DT_RUNPATH with any relative paths, so they can't find their dependencies.
1266   // b/118058804
1267   if (si->get_dt_runpath().empty()) {
1268     si->set_dt_runpath("$ORIGIN/../lib64:$ORIGIN/lib64");
1269   }
1270 #endif
1271 
1272   for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
1273     LD_LOG(kLogDlopen, "load_library(ns=%s, task=%s): Adding DT_NEEDED task: %s",
1274            ns->get_name(), task->get_name(), name);
1275     load_tasks->push_back(LoadTask::create(name, si, ns, task->get_readers_map()));
1276   });
1277 
1278   return true;
1279 }
1280 
load_library(android_namespace_t * ns,LoadTask * task,ZipArchiveCache * zip_archive_cache,LoadTaskList * load_tasks,int rtld_flags,bool search_linked_namespaces)1281 static bool load_library(android_namespace_t* ns,
1282                          LoadTask* task,
1283                          ZipArchiveCache* zip_archive_cache,
1284                          LoadTaskList* load_tasks,
1285                          int rtld_flags,
1286                          bool search_linked_namespaces) {
1287   const char* name = task->get_name();
1288   soinfo* needed_by = task->get_needed_by();
1289   const android_dlextinfo* extinfo = task->get_extinfo();
1290 
1291   if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
1292     off64_t file_offset = 0;
1293     if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1294       file_offset = extinfo->library_fd_offset;
1295     }
1296 
1297     std::string realpath;
1298     if (!realpath_fd(extinfo->library_fd, &realpath)) {
1299       if (!is_first_stage_init()) {
1300         PRINT(
1301             "warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1302             "Will use given name.",
1303             name);
1304       }
1305       realpath = name;
1306     }
1307 
1308     task->set_fd(extinfo->library_fd, false);
1309     task->set_file_offset(file_offset);
1310     return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
1311   }
1312 
1313   LD_LOG(kLogDlopen,
1314          "load_library(ns=%s, task=%s, flags=0x%x, search_linked_namespaces=%d): calling "
1315          "open_library",
1316          ns->get_name(), name, rtld_flags, search_linked_namespaces);
1317 
1318   // Open the file.
1319   off64_t file_offset;
1320   std::string realpath;
1321   int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
1322   if (fd == -1) {
1323     if (task->is_dt_needed()) {
1324       if (needed_by->is_main_executable()) {
1325         DL_OPEN_ERR("library \"%s\" not found: needed by main executable", name);
1326       } else {
1327         DL_OPEN_ERR("library \"%s\" not found: needed by %s in namespace %s", name,
1328                     needed_by->get_realpath(), task->get_start_from()->get_name());
1329       }
1330     } else {
1331       DL_OPEN_ERR("library \"%s\" not found", name);
1332     }
1333     return false;
1334   }
1335 
1336   task->set_fd(fd, true);
1337   task->set_file_offset(file_offset);
1338 
1339   return load_library(ns, task, load_tasks, rtld_flags, realpath, search_linked_namespaces);
1340 }
1341 
find_loaded_library_by_soname(android_namespace_t * ns,const char * name,soinfo ** candidate)1342 static bool find_loaded_library_by_soname(android_namespace_t* ns,
1343                                           const char* name,
1344                                           soinfo** candidate) {
1345   return !ns->soinfo_list().visit([&](soinfo* si) {
1346     if (strcmp(name, si->get_soname()) == 0) {
1347       *candidate = si;
1348       return false;
1349     }
1350 
1351     return true;
1352   });
1353 }
1354 
1355 // Returns true if library was found and false otherwise
find_loaded_library_by_soname(android_namespace_t * ns,const char * name,bool search_linked_namespaces,soinfo ** candidate)1356 static bool find_loaded_library_by_soname(android_namespace_t* ns,
1357                                          const char* name,
1358                                          bool search_linked_namespaces,
1359                                          soinfo** candidate) {
1360   *candidate = nullptr;
1361 
1362   // Ignore filename with path.
1363   if (strchr(name, '/') != nullptr) {
1364     return false;
1365   }
1366 
1367   bool found = find_loaded_library_by_soname(ns, name, candidate);
1368 
1369   if (!found && search_linked_namespaces) {
1370     // if a library was not found - look into linked namespaces
1371     for (auto& link : ns->linked_namespaces()) {
1372       if (!link.is_accessible(name)) {
1373         continue;
1374       }
1375 
1376       android_namespace_t* linked_ns = link.linked_namespace();
1377 
1378       if (find_loaded_library_by_soname(linked_ns, name, candidate)) {
1379         return true;
1380       }
1381     }
1382   }
1383 
1384   return found;
1385 }
1386 
find_library_in_linked_namespace(const android_namespace_link_t & namespace_link,LoadTask * task)1387 static bool find_library_in_linked_namespace(const android_namespace_link_t& namespace_link,
1388                                              LoadTask* task) {
1389   android_namespace_t* ns = namespace_link.linked_namespace();
1390 
1391   soinfo* candidate;
1392   bool loaded = false;
1393 
1394   std::string soname;
1395   if (find_loaded_library_by_soname(ns, task->get_name(), false, &candidate)) {
1396     loaded = true;
1397     soname = candidate->get_soname();
1398   } else {
1399     soname = resolve_soname(task->get_name());
1400   }
1401 
1402   if (!namespace_link.is_accessible(soname.c_str())) {
1403     // the library is not accessible via namespace_link
1404     LD_LOG(kLogDlopen,
1405            "find_library_in_linked_namespace(ns=%s, task=%s): Not accessible (soname=%s)",
1406            ns->get_name(), task->get_name(), soname.c_str());
1407     return false;
1408   }
1409 
1410   // if library is already loaded - return it
1411   if (loaded) {
1412     LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Already loaded",
1413            ns->get_name(), task->get_name());
1414     task->set_soinfo(candidate);
1415     return true;
1416   }
1417 
1418   // returning true with empty soinfo means that the library is okay to be
1419   // loaded in the namespace but has not yet been loaded there before.
1420   LD_LOG(kLogDlopen, "find_library_in_linked_namespace(ns=%s, task=%s): Ok to load", ns->get_name(),
1421          task->get_name());
1422   task->set_soinfo(nullptr);
1423   return true;
1424 }
1425 
find_library_internal(android_namespace_t * ns,LoadTask * task,ZipArchiveCache * zip_archive_cache,LoadTaskList * load_tasks,int rtld_flags)1426 static bool find_library_internal(android_namespace_t* ns,
1427                                   LoadTask* task,
1428                                   ZipArchiveCache* zip_archive_cache,
1429                                   LoadTaskList* load_tasks,
1430                                   int rtld_flags) {
1431   soinfo* candidate;
1432 
1433   if (find_loaded_library_by_soname(ns, task->get_name(), true /* search_linked_namespaces */,
1434                                     &candidate)) {
1435     LD_LOG(kLogDlopen,
1436            "find_library_internal(ns=%s, task=%s): Already loaded (by soname): %s",
1437            ns->get_name(), task->get_name(), candidate->get_realpath());
1438     task->set_soinfo(candidate);
1439     return true;
1440   }
1441 
1442   // Library might still be loaded, the accurate detection
1443   // of this fact is done by load_library.
1444   TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder... ]",
1445         task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
1446 
1447   if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1448                    true /* search_linked_namespaces */)) {
1449     return true;
1450   }
1451 
1452   // TODO(dimitry): workaround for http://b/26394120 (the exempt-list)
1453   if (ns->is_exempt_list_enabled() && is_exempt_lib(ns, task->get_name(), task->get_needed_by())) {
1454     // For the libs in the exempt-list, switch to the default namespace and then
1455     // try the load again from there. The library could be loaded from the
1456     // default namespace or from another namespace (e.g. runtime) that is linked
1457     // from the default namespace.
1458     LD_LOG(kLogDlopen,
1459            "find_library_internal(ns=%s, task=%s): Exempt system library - trying namespace %s",
1460            ns->get_name(), task->get_name(), g_default_namespace.get_name());
1461     ns = &g_default_namespace;
1462     if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags,
1463                      true /* search_linked_namespaces */)) {
1464       return true;
1465     }
1466   }
1467   // END OF WORKAROUND
1468 
1469   // if a library was not found - look into linked namespaces
1470   // preserve current dlerror in the case it fails.
1471   DlErrorRestorer dlerror_restorer;
1472   LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Trying %zu linked namespaces",
1473          ns->get_name(), task->get_name(), ns->linked_namespaces().size());
1474   for (auto& linked_namespace : ns->linked_namespaces()) {
1475     if (find_library_in_linked_namespace(linked_namespace, task)) {
1476       // Library is already loaded.
1477       if (task->get_soinfo() != nullptr) {
1478         // n.b. This code path runs when find_library_in_linked_namespace found an already-loaded
1479         // library by soname. That should only be possible with a exempt-list lookup, where we
1480         // switch the namespace, because otherwise, find_library_in_linked_namespace is duplicating
1481         // the soname scan done in this function's first call to find_loaded_library_by_soname.
1482         return true;
1483       }
1484 
1485       if (load_library(linked_namespace.linked_namespace(), task, zip_archive_cache, load_tasks,
1486                        rtld_flags, false /* search_linked_namespaces */)) {
1487         LD_LOG(kLogDlopen, "find_library_internal(ns=%s, task=%s): Found in linked namespace %s",
1488                ns->get_name(), task->get_name(), linked_namespace.linked_namespace()->get_name());
1489         return true;
1490       }
1491     }
1492   }
1493 
1494   return false;
1495 }
1496 
1497 static void soinfo_unload(soinfo* si);
1498 
shuffle(std::vector<LoadTask * > * v)1499 static void shuffle(std::vector<LoadTask*>* v) {
1500   if (is_first_stage_init()) {
1501     // arc4random* is not available in first stage init because /dev/random
1502     // hasn't yet been created.
1503     return;
1504   }
1505   for (size_t i = 0, size = v->size(); i < size; ++i) {
1506     size_t n = size - i;
1507     size_t r = arc4random_uniform(n);
1508     std::swap((*v)[n-1], (*v)[r]);
1509   }
1510 }
1511 
1512 // add_as_children - add first-level loaded libraries (i.e. library_names[], but
1513 // not their transitive dependencies) as children of the start_with library.
1514 // This is false when find_libraries is called for dlopen(), when newly loaded
1515 // libraries must form a disjoint tree.
find_libraries(android_namespace_t * ns,soinfo * start_with,const char * const library_names[],size_t library_names_count,soinfo * soinfos[],std::vector<soinfo * > * ld_preloads,size_t ld_preloads_count,int rtld_flags,const android_dlextinfo * extinfo,bool add_as_children,std::vector<android_namespace_t * > * namespaces)1516 bool find_libraries(android_namespace_t* ns,
1517                     soinfo* start_with,
1518                     const char* const library_names[],
1519                     size_t library_names_count,
1520                     soinfo* soinfos[],
1521                     std::vector<soinfo*>* ld_preloads,
1522                     size_t ld_preloads_count,
1523                     int rtld_flags,
1524                     const android_dlextinfo* extinfo,
1525                     bool add_as_children,
1526                     std::vector<android_namespace_t*>* namespaces) {
1527   // Step 0: prepare.
1528   std::unordered_map<const soinfo*, ElfReader> readers_map;
1529   LoadTaskList load_tasks;
1530 
1531   for (size_t i = 0; i < library_names_count; ++i) {
1532     const char* name = library_names[i];
1533     load_tasks.push_back(LoadTask::create(name, start_with, ns, &readers_map));
1534   }
1535 
1536   // If soinfos array is null allocate one on stack.
1537   // The array is needed in case of failure; for example
1538   // when library_names[] = {libone.so, libtwo.so} and libone.so
1539   // is loaded correctly but libtwo.so failed for some reason.
1540   // In this case libone.so should be unloaded on return.
1541   // See also implementation of failure_guard below.
1542 
1543   if (soinfos == nullptr) {
1544     size_t soinfos_size = sizeof(soinfo*)*library_names_count;
1545     soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
1546     memset(soinfos, 0, soinfos_size);
1547   }
1548 
1549   // list of libraries to link - see step 2.
1550   size_t soinfos_count = 0;
1551 
1552   auto scope_guard = android::base::make_scope_guard([&]() {
1553     for (LoadTask* t : load_tasks) {
1554       LoadTask::deleter(t);
1555     }
1556   });
1557 
1558   ZipArchiveCache zip_archive_cache;
1559   soinfo_list_t new_global_group_members;
1560 
1561   // Step 1: expand the list of load_tasks to include
1562   // all DT_NEEDED libraries (do not load them just yet)
1563   for (size_t i = 0; i<load_tasks.size(); ++i) {
1564     LoadTask* task = load_tasks[i];
1565     soinfo* needed_by = task->get_needed_by();
1566 
1567     bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1568     task->set_extinfo(is_dt_needed ? nullptr : extinfo);
1569     task->set_dt_needed(is_dt_needed);
1570 
1571     LD_LOG(kLogDlopen, "find_libraries(ns=%s): task=%s, is_dt_needed=%d", ns->get_name(),
1572            task->get_name(), is_dt_needed);
1573 
1574     // Note: start from the namespace that is stored in the LoadTask. This namespace
1575     // is different from the current namespace when the LoadTask is for a transitive
1576     // dependency and the lib that created the LoadTask is not found in the
1577     // current namespace but in one of the linked namespace.
1578     if (!find_library_internal(const_cast<android_namespace_t*>(task->get_start_from()),
1579                                task,
1580                                &zip_archive_cache,
1581                                &load_tasks,
1582                                rtld_flags)) {
1583       return false;
1584     }
1585 
1586     soinfo* si = task->get_soinfo();
1587 
1588     if (is_dt_needed) {
1589       needed_by->add_child(si);
1590     }
1591 
1592     // When ld_preloads is not null, the first
1593     // ld_preloads_count libs are in fact ld_preloads.
1594     bool is_ld_preload = false;
1595     if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
1596       ld_preloads->push_back(si);
1597       is_ld_preload = true;
1598     }
1599 
1600     if (soinfos_count < library_names_count) {
1601       soinfos[soinfos_count++] = si;
1602     }
1603 
1604     // Add the new global group members to all initial namespaces. Do this secondary namespace setup
1605     // at the same time that libraries are added to their primary namespace so that the order of
1606     // global group members is the same in the every namespace. Only add a library to a namespace
1607     // once, even if it appears multiple times in the dependency graph.
1608     if (is_ld_preload || (si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1609       if (!si->is_linked() && namespaces != nullptr && !new_global_group_members.contains(si)) {
1610         new_global_group_members.push_back(si);
1611         for (auto linked_ns : *namespaces) {
1612           if (si->get_primary_namespace() != linked_ns) {
1613             linked_ns->add_soinfo(si);
1614             si->add_secondary_namespace(linked_ns);
1615           }
1616         }
1617       }
1618     }
1619   }
1620 
1621   // Step 2: Load libraries in random order (see b/24047022)
1622   LoadTaskList load_list;
1623   for (auto&& task : load_tasks) {
1624     soinfo* si = task->get_soinfo();
1625     auto pred = [&](const LoadTask* t) {
1626       return t->get_soinfo() == si;
1627     };
1628 
1629     if (!si->is_linked() &&
1630         std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
1631       load_list.push_back(task);
1632     }
1633   }
1634   bool reserved_address_recursive = false;
1635   if (extinfo) {
1636     reserved_address_recursive = extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_RECURSIVE;
1637   }
1638   if (!reserved_address_recursive) {
1639     // Shuffle the load order in the normal case, but not if we are loading all
1640     // the libraries to a reserved address range.
1641     shuffle(&load_list);
1642   }
1643 
1644   // Set up address space parameters.
1645   address_space_params extinfo_params, default_params;
1646   size_t relro_fd_offset = 0;
1647   if (extinfo) {
1648     if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS) {
1649       extinfo_params.start_addr = extinfo->reserved_addr;
1650       extinfo_params.reserved_size = extinfo->reserved_size;
1651       extinfo_params.must_use_address = true;
1652     } else if (extinfo->flags & ANDROID_DLEXT_RESERVED_ADDRESS_HINT) {
1653       extinfo_params.start_addr = extinfo->reserved_addr;
1654       extinfo_params.reserved_size = extinfo->reserved_size;
1655     }
1656   }
1657 
1658   for (auto&& task : load_list) {
1659     address_space_params* address_space =
1660         (reserved_address_recursive || !task->is_dt_needed()) ? &extinfo_params : &default_params;
1661     if (!task->load(address_space)) {
1662       return false;
1663     }
1664   }
1665 
1666   // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
1667   for (auto&& task : load_tasks) {
1668     soinfo* si = task->get_soinfo();
1669     if (!si->is_linked() && !si->prelink_image()) {
1670       return false;
1671     }
1672     register_soinfo_tls(si);
1673   }
1674 
1675   // Step 4: Construct the global group. DF_1_GLOBAL bit is force set for LD_PRELOADed libs because
1676   // they must be added to the global group. Note: The DF_1_GLOBAL bit for a library is normally set
1677   // in step 3.
1678   if (ld_preloads != nullptr) {
1679     for (auto&& si : *ld_preloads) {
1680       si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
1681     }
1682   }
1683 
1684   // Step 5: Collect roots of local_groups.
1685   // Whenever needed_by->si link crosses a namespace boundary it forms its own local_group.
1686   // Here we collect new roots to link them separately later on. Note that we need to avoid
1687   // collecting duplicates. Also the order is important. They need to be linked in the same
1688   // BFS order we link individual libraries.
1689   std::vector<soinfo*> local_group_roots;
1690   if (start_with != nullptr && add_as_children) {
1691     local_group_roots.push_back(start_with);
1692   } else {
1693     CHECK(soinfos_count == 1);
1694     local_group_roots.push_back(soinfos[0]);
1695   }
1696 
1697   for (auto&& task : load_tasks) {
1698     soinfo* si = task->get_soinfo();
1699     soinfo* needed_by = task->get_needed_by();
1700     bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
1701     android_namespace_t* needed_by_ns =
1702         is_dt_needed ? needed_by->get_primary_namespace() : ns;
1703 
1704     if (!si->is_linked() && si->get_primary_namespace() != needed_by_ns) {
1705       auto it = std::find(local_group_roots.begin(), local_group_roots.end(), si);
1706       LD_LOG(kLogDlopen,
1707              "Crossing namespace boundary (si=%s@%p, si_ns=%s@%p, needed_by=%s@%p, ns=%s@%p, needed_by_ns=%s@%p) adding to local_group_roots: %s",
1708              si->get_realpath(),
1709              si,
1710              si->get_primary_namespace()->get_name(),
1711              si->get_primary_namespace(),
1712              needed_by == nullptr ? "(nullptr)" : needed_by->get_realpath(),
1713              needed_by,
1714              ns->get_name(),
1715              ns,
1716              needed_by_ns->get_name(),
1717              needed_by_ns,
1718              it == local_group_roots.end() ? "yes" : "no");
1719 
1720       if (it == local_group_roots.end()) {
1721         local_group_roots.push_back(si);
1722       }
1723     }
1724   }
1725 
1726   // Step 6: Link all local groups
1727   for (auto root : local_group_roots) {
1728     soinfo_list_t local_group;
1729     android_namespace_t* local_group_ns = root->get_primary_namespace();
1730 
1731     walk_dependencies_tree(root,
1732       [&] (soinfo* si) {
1733         if (local_group_ns->is_accessible(si)) {
1734           local_group.push_back(si);
1735           return kWalkContinue;
1736         } else {
1737           return kWalkSkip;
1738         }
1739       });
1740 
1741     soinfo_list_t global_group = local_group_ns->get_global_group();
1742     SymbolLookupList lookup_list(global_group, local_group);
1743     soinfo* local_group_root = local_group.front();
1744 
1745     bool linked = local_group.visit([&](soinfo* si) {
1746       // Even though local group may contain accessible soinfos from other namespaces
1747       // we should avoid linking them (because if they are not linked -> they
1748       // are in the local_group_roots and will be linked later).
1749       if (!si->is_linked() && si->get_primary_namespace() == local_group_ns) {
1750         const android_dlextinfo* link_extinfo = nullptr;
1751         if (si == soinfos[0] || reserved_address_recursive) {
1752           // Only forward extinfo for the first library unless the recursive
1753           // flag is set.
1754           link_extinfo = extinfo;
1755         }
1756         if (__libc_shared_globals()->load_hook) {
1757           __libc_shared_globals()->load_hook(si->load_bias, si->phdr, si->phnum);
1758         }
1759         lookup_list.set_dt_symbolic_lib(si->has_DT_SYMBOLIC ? si : nullptr);
1760         if (!si->link_image(lookup_list, local_group_root, link_extinfo, &relro_fd_offset) ||
1761             !get_cfi_shadow()->AfterLoad(si, solist_get_head())) {
1762           return false;
1763         }
1764       }
1765 
1766       return true;
1767     });
1768 
1769     if (!linked) {
1770       return false;
1771     }
1772   }
1773 
1774   // Step 7: Mark all load_tasks as linked and increment refcounts
1775   // for references between load_groups (at this point it does not matter if
1776   // referenced load_groups were loaded by previous dlopen or as part of this
1777   // one on step 6)
1778   if (start_with != nullptr && add_as_children) {
1779     start_with->set_linked();
1780   }
1781 
1782   for (auto&& task : load_tasks) {
1783     soinfo* si = task->get_soinfo();
1784     si->set_linked();
1785   }
1786 
1787   for (auto&& task : load_tasks) {
1788     soinfo* si = task->get_soinfo();
1789     soinfo* needed_by = task->get_needed_by();
1790     if (needed_by != nullptr &&
1791         needed_by != start_with &&
1792         needed_by->get_local_group_root() != si->get_local_group_root()) {
1793       si->increment_ref_count();
1794     }
1795   }
1796 
1797 
1798   return true;
1799 }
1800 
find_library(android_namespace_t * ns,const char * name,int rtld_flags,const android_dlextinfo * extinfo,soinfo * needed_by)1801 static soinfo* find_library(android_namespace_t* ns,
1802                             const char* name, int rtld_flags,
1803                             const android_dlextinfo* extinfo,
1804                             soinfo* needed_by) {
1805   soinfo* si = nullptr;
1806 
1807   if (name == nullptr) {
1808     si = solist_get_somain();
1809   } else if (!find_libraries(ns,
1810                              needed_by,
1811                              &name,
1812                              1,
1813                              &si,
1814                              nullptr,
1815                              0,
1816                              rtld_flags,
1817                              extinfo,
1818                              false /* add_as_children */)) {
1819     if (si != nullptr) {
1820       soinfo_unload(si);
1821     }
1822     return nullptr;
1823   }
1824 
1825   si->increment_ref_count();
1826 
1827   return si;
1828 }
1829 
soinfo_unload_impl(soinfo * root)1830 static void soinfo_unload_impl(soinfo* root) {
1831   ScopedTrace trace((std::string("unload ") + root->get_realpath()).c_str());
1832   bool is_linked = root->is_linked();
1833 
1834   if (!root->can_unload()) {
1835     LD_LOG(kLogDlopen,
1836            "... dlclose(root=\"%s\"@%p) ... not unloading - the load group is flagged with NODELETE",
1837            root->get_realpath(),
1838            root);
1839     return;
1840   }
1841 
1842 
1843   soinfo_list_t unload_list;
1844   unload_list.push_back(root);
1845 
1846   soinfo_list_t local_unload_list;
1847   soinfo_list_t external_unload_list;
1848   soinfo* si = nullptr;
1849 
1850   while ((si = unload_list.pop_front()) != nullptr) {
1851     if (local_unload_list.contains(si)) {
1852       continue;
1853     }
1854 
1855     local_unload_list.push_back(si);
1856 
1857     if (si->has_min_version(0)) {
1858       soinfo* child = nullptr;
1859       while ((child = si->get_children().pop_front()) != nullptr) {
1860         TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
1861             child->get_realpath(), child);
1862 
1863         child->get_parents().remove(si);
1864 
1865         if (local_unload_list.contains(child)) {
1866           continue;
1867         } else if (child->is_linked() && child->get_local_group_root() != root) {
1868           external_unload_list.push_back(child);
1869         } else if (child->get_parents().empty()) {
1870           unload_list.push_back(child);
1871         }
1872       }
1873     } else {
1874       async_safe_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
1875     }
1876   }
1877 
1878   local_unload_list.for_each([](soinfo* si) {
1879     LD_LOG(kLogDlopen,
1880            "... dlclose: calling destructors for \"%s\"@%p ... ",
1881            si->get_realpath(),
1882            si);
1883     si->call_destructors();
1884     LD_LOG(kLogDlopen,
1885            "... dlclose: calling destructors for \"%s\"@%p ... done",
1886            si->get_realpath(),
1887            si);
1888   });
1889 
1890   while ((si = local_unload_list.pop_front()) != nullptr) {
1891     LD_LOG(kLogDlopen,
1892            "... dlclose: unloading \"%s\"@%p ...",
1893            si->get_realpath(),
1894            si);
1895     ++g_module_unload_counter;
1896     notify_gdb_of_unload(si);
1897     unregister_soinfo_tls(si);
1898     if (__libc_shared_globals()->unload_hook) {
1899       __libc_shared_globals()->unload_hook(si->load_bias, si->phdr, si->phnum);
1900     }
1901     get_cfi_shadow()->BeforeUnload(si);
1902     soinfo_free(si);
1903   }
1904 
1905   if (is_linked) {
1906     while ((si = external_unload_list.pop_front()) != nullptr) {
1907       LD_LOG(kLogDlopen,
1908              "... dlclose: unloading external reference \"%s\"@%p ...",
1909              si->get_realpath(),
1910              si);
1911       soinfo_unload(si);
1912     }
1913   } else {
1914       LD_LOG(kLogDlopen,
1915              "... dlclose: unload_si was not linked - not unloading external references ...");
1916   }
1917 }
1918 
soinfo_unload(soinfo * unload_si)1919 static void soinfo_unload(soinfo* unload_si) {
1920   // Note that the library can be loaded but not linked;
1921   // in which case there is no root but we still need
1922   // to walk the tree and unload soinfos involved.
1923   //
1924   // This happens on unsuccessful dlopen, when one of
1925   // the DT_NEEDED libraries could not be linked/found.
1926   bool is_linked = unload_si->is_linked();
1927   soinfo* root = is_linked ? unload_si->get_local_group_root() : unload_si;
1928 
1929   LD_LOG(kLogDlopen,
1930          "... dlclose(realpath=\"%s\"@%p) ... load group root is \"%s\"@%p",
1931          unload_si->get_realpath(),
1932          unload_si,
1933          root->get_realpath(),
1934          root);
1935 
1936 
1937   size_t ref_count = is_linked ? root->decrement_ref_count() : 0;
1938   if (ref_count > 0) {
1939     LD_LOG(kLogDlopen,
1940            "... dlclose(root=\"%s\"@%p) ... not unloading - decrementing ref_count to %zd",
1941            root->get_realpath(),
1942            root,
1943            ref_count);
1944     return;
1945   }
1946 
1947   soinfo_unload_impl(root);
1948 }
1949 
increment_dso_handle_reference_counter(void * dso_handle)1950 void increment_dso_handle_reference_counter(void* dso_handle) {
1951   if (dso_handle == nullptr) {
1952     return;
1953   }
1954 
1955   auto it = g_dso_handle_counters.find(dso_handle);
1956   if (it != g_dso_handle_counters.end()) {
1957     CHECK(++it->second != 0);
1958   } else {
1959     soinfo* si = find_containing_library(dso_handle);
1960     if (si != nullptr) {
1961       ProtectedDataGuard guard;
1962       si->increment_ref_count();
1963     } else {
1964       async_safe_fatal(
1965           "increment_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1966           dso_handle);
1967     }
1968     g_dso_handle_counters[dso_handle] = 1U;
1969   }
1970 }
1971 
decrement_dso_handle_reference_counter(void * dso_handle)1972 void decrement_dso_handle_reference_counter(void* dso_handle) {
1973   if (dso_handle == nullptr) {
1974     return;
1975   }
1976 
1977   auto it = g_dso_handle_counters.find(dso_handle);
1978   CHECK(it != g_dso_handle_counters.end());
1979   CHECK(it->second != 0);
1980 
1981   if (--it->second == 0) {
1982     soinfo* si = find_containing_library(dso_handle);
1983     if (si != nullptr) {
1984       ProtectedDataGuard guard;
1985       soinfo_unload(si);
1986     } else {
1987       async_safe_fatal(
1988           "decrement_dso_handle_reference_counter: Couldn't find soinfo by dso_handle=%p",
1989           dso_handle);
1990     }
1991     g_dso_handle_counters.erase(it);
1992   }
1993 }
1994 
symbol_display_name(const char * sym_name,const char * sym_ver)1995 static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
1996   if (sym_ver == nullptr) {
1997     return sym_name;
1998   }
1999 
2000   return std::string(sym_name) + ", version " + sym_ver;
2001 }
2002 
get_caller_namespace(soinfo * caller)2003 static android_namespace_t* get_caller_namespace(soinfo* caller) {
2004   return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2005 }
2006 
do_android_get_LD_LIBRARY_PATH(char * buffer,size_t buffer_size)2007 void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
2008   // Use basic string manipulation calls to avoid snprintf.
2009   // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2010   // When debug malloc is enabled, this call returns 0. This in turn causes
2011   // snprintf to do nothing, which causes libraries to fail to load.
2012   // See b/17302493 for further details.
2013   // Once the above bug is fixed, this code can be modified to use
2014   // snprintf again.
2015   const auto& default_ld_paths = g_default_namespace.get_default_library_paths();
2016 
2017   size_t required_size = 0;
2018   for (const auto& path : default_ld_paths) {
2019     required_size += path.size() + 1;
2020   }
2021 
2022   if (buffer_size < required_size) {
2023     async_safe_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2024                      "buffer len %zu, required len %zu", buffer_size, required_size);
2025   }
2026 
2027   char* end = buffer;
2028   for (size_t i = 0; i < default_ld_paths.size(); ++i) {
2029     if (i > 0) *end++ = ':';
2030     end = stpcpy(end, default_ld_paths[i].c_str());
2031   }
2032 }
2033 
do_android_update_LD_LIBRARY_PATH(const char * ld_library_path)2034 void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
2035   parse_LD_LIBRARY_PATH(ld_library_path);
2036 }
2037 
android_dlextinfo_to_string(const android_dlextinfo * info)2038 static std::string android_dlextinfo_to_string(const android_dlextinfo* info) {
2039   if (info == nullptr) {
2040     return "(null)";
2041   }
2042 
2043   return android::base::StringPrintf("[flags=0x%" PRIx64 ","
2044                                      " reserved_addr=%p,"
2045                                      " reserved_size=0x%zx,"
2046                                      " relro_fd=%d,"
2047                                      " library_fd=%d,"
2048                                      " library_fd_offset=0x%" PRIx64 ","
2049                                      " library_namespace=%s@%p]",
2050                                      info->flags,
2051                                      info->reserved_addr,
2052                                      info->reserved_size,
2053                                      info->relro_fd,
2054                                      info->library_fd,
2055                                      info->library_fd_offset,
2056                                      (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2057                                         (info->library_namespace != nullptr ?
2058                                           info->library_namespace->get_name() : "(null)") : "(n/a)",
2059                                      (info->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0 ?
2060                                         info->library_namespace : nullptr);
2061 }
2062 
do_dlopen(const char * name,int flags,const android_dlextinfo * extinfo,const void * caller_addr)2063 void* do_dlopen(const char* name, int flags,
2064                 const android_dlextinfo* extinfo,
2065                 const void* caller_addr) {
2066   std::string trace_prefix = std::string("dlopen: ") + (name == nullptr ? "(nullptr)" : name);
2067   ScopedTrace trace(trace_prefix.c_str());
2068   ScopedTrace loading_trace((trace_prefix + " - loading and linking").c_str());
2069   soinfo* const caller = find_containing_library(caller_addr);
2070   android_namespace_t* ns = get_caller_namespace(caller);
2071 
2072   LD_LOG(kLogDlopen,
2073          "dlopen(name=\"%s\", flags=0x%x, extinfo=%s, caller=\"%s\", caller_ns=%s@%p, targetSdkVersion=%i) ...",
2074          name,
2075          flags,
2076          android_dlextinfo_to_string(extinfo).c_str(),
2077          caller == nullptr ? "(null)" : caller->get_realpath(),
2078          ns == nullptr ? "(null)" : ns->get_name(),
2079          ns,
2080          get_application_target_sdk_version());
2081 
2082   auto purge_guard = android::base::make_scope_guard([&]() { purge_unused_memory(); });
2083 
2084   auto failure_guard = android::base::make_scope_guard(
2085       [&]() { LD_LOG(kLogDlopen, "... dlopen failed: %s", linker_get_error_buffer()); });
2086 
2087   if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
2088     DL_OPEN_ERR("invalid flags to dlopen: %x", flags);
2089     return nullptr;
2090   }
2091 
2092   if (extinfo != nullptr) {
2093     if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
2094       DL_OPEN_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
2095       return nullptr;
2096     }
2097 
2098     if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
2099         (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
2100       DL_OPEN_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
2101           "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
2102       return nullptr;
2103     }
2104 
2105     if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2106       if (extinfo->library_namespace == nullptr) {
2107         DL_OPEN_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
2108         return nullptr;
2109       }
2110       ns = extinfo->library_namespace;
2111     }
2112   }
2113 
2114   // Workaround for dlopen(/system/lib/<soname>) when .so is in /apex. http://b/121248172
2115   // The workaround works only when targetSdkVersion < Q.
2116   std::string name_to_apex;
2117   if (translateSystemPathToApexPath(name, &name_to_apex)) {
2118     const char* new_name = name_to_apex.c_str();
2119     LD_LOG(kLogDlopen, "dlopen considering translation from %s to APEX path %s",
2120            name,
2121            new_name);
2122     // Some APEXs could be optionally disabled. Only translate the path
2123     // when the old file is absent and the new file exists.
2124     // TODO(b/124218500): Re-enable it once app compat issue is resolved
2125     /*
2126     if (file_exists(name)) {
2127       LD_LOG(kLogDlopen, "dlopen %s exists, not translating", name);
2128     } else
2129     */
2130     if (!file_exists(new_name)) {
2131       LD_LOG(kLogDlopen, "dlopen %s does not exist, not translating",
2132              new_name);
2133     } else {
2134       LD_LOG(kLogDlopen, "dlopen translation accepted: using %s", new_name);
2135       name = new_name;
2136     }
2137   }
2138   // End Workaround for dlopen(/system/lib/<soname>) when .so is in /apex.
2139 
2140   std::string asan_name_holder;
2141 
2142   const char* translated_name = name;
2143   if (g_is_asan && translated_name != nullptr && translated_name[0] == '/') {
2144     char original_path[PATH_MAX];
2145     if (realpath(name, original_path) != nullptr) {
2146       asan_name_holder = std::string(kAsanLibDirPrefix) + original_path;
2147       if (file_exists(asan_name_holder.c_str())) {
2148         soinfo* si = nullptr;
2149         if (find_loaded_library_by_realpath(ns, original_path, true, &si)) {
2150           PRINT("linker_asan dlopen NOT translating \"%s\" -> \"%s\": library already loaded", name,
2151                 asan_name_holder.c_str());
2152         } else {
2153           PRINT("linker_asan dlopen translating \"%s\" -> \"%s\"", name, translated_name);
2154           translated_name = asan_name_holder.c_str();
2155         }
2156       }
2157     }
2158   }
2159 
2160   ProtectedDataGuard guard;
2161   soinfo* si = find_library(ns, translated_name, flags, extinfo, caller);
2162   loading_trace.End();
2163 
2164   if (si != nullptr) {
2165     void* handle = si->to_handle();
2166     LD_LOG(kLogDlopen,
2167            "... dlopen calling constructors: realpath=\"%s\", soname=\"%s\", handle=%p",
2168            si->get_realpath(), si->get_soname(), handle);
2169     si->call_constructors();
2170     failure_guard.Disable();
2171     LD_LOG(kLogDlopen,
2172            "... dlopen successful: realpath=\"%s\", soname=\"%s\", handle=%p",
2173            si->get_realpath(), si->get_soname(), handle);
2174     return handle;
2175   }
2176 
2177   return nullptr;
2178 }
2179 
do_dladdr(const void * addr,Dl_info * info)2180 int do_dladdr(const void* addr, Dl_info* info) {
2181   // Determine if this address can be found in any library currently mapped.
2182   soinfo* si = find_containing_library(addr);
2183   if (si == nullptr) {
2184     return 0;
2185   }
2186 
2187   memset(info, 0, sizeof(Dl_info));
2188 
2189   info->dli_fname = si->get_realpath();
2190   // Address at which the shared object is loaded.
2191   info->dli_fbase = reinterpret_cast<void*>(si->base);
2192 
2193   // Determine if any symbol in the library contains the specified address.
2194   ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2195   if (sym != nullptr) {
2196     info->dli_sname = si->get_string(sym->st_name);
2197     info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2198   }
2199 
2200   return 1;
2201 }
2202 
soinfo_from_handle(void * handle)2203 static soinfo* soinfo_from_handle(void* handle) {
2204   if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2205     auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2206     if (it == g_soinfo_handles_map.end()) {
2207       return nullptr;
2208     } else {
2209       return it->second;
2210     }
2211   }
2212 
2213   return static_cast<soinfo*>(handle);
2214 }
2215 
do_dlsym(void * handle,const char * sym_name,const char * sym_ver,const void * caller_addr,void ** symbol)2216 bool do_dlsym(void* handle,
2217               const char* sym_name,
2218               const char* sym_ver,
2219               const void* caller_addr,
2220               void** symbol) {
2221   ScopedTrace trace("dlsym");
2222 #if !defined(__LP64__)
2223   if (handle == nullptr) {
2224     DL_SYM_ERR("dlsym failed: library handle is null");
2225     return false;
2226   }
2227 #endif
2228 
2229   soinfo* found = nullptr;
2230   const ElfW(Sym)* sym = nullptr;
2231   soinfo* caller = find_containing_library(caller_addr);
2232   android_namespace_t* ns = get_caller_namespace(caller);
2233   soinfo* si = nullptr;
2234   if (handle != RTLD_DEFAULT && handle != RTLD_NEXT) {
2235     si = soinfo_from_handle(handle);
2236   }
2237 
2238   LD_LOG(kLogDlsym,
2239          "dlsym(handle=%p(\"%s\"), sym_name=\"%s\", sym_ver=\"%s\", caller=\"%s\", caller_ns=%s@%p) ...",
2240          handle,
2241          si != nullptr ? si->get_realpath() : "n/a",
2242          sym_name,
2243          sym_ver,
2244          caller == nullptr ? "(null)" : caller->get_realpath(),
2245          ns == nullptr ? "(null)" : ns->get_name(),
2246          ns);
2247 
2248   auto failure_guard = android::base::make_scope_guard(
2249       [&]() { LD_LOG(kLogDlsym, "... dlsym failed: %s", linker_get_error_buffer()); });
2250 
2251   if (sym_name == nullptr) {
2252     DL_SYM_ERR("dlsym failed: symbol name is null");
2253     return false;
2254   }
2255 
2256   version_info vi_instance;
2257   version_info* vi = nullptr;
2258 
2259   if (sym_ver != nullptr) {
2260     vi_instance.name = sym_ver;
2261     vi_instance.elf_hash = calculate_elf_hash(sym_ver);
2262     vi = &vi_instance;
2263   }
2264 
2265   if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2266     sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2267   } else {
2268     if (si == nullptr) {
2269       DL_SYM_ERR("dlsym failed: invalid handle: %p", handle);
2270       return false;
2271     }
2272     sym = dlsym_handle_lookup(si, &found, sym_name, vi);
2273   }
2274 
2275   if (sym != nullptr) {
2276     uint32_t bind = ELF_ST_BIND(sym->st_info);
2277     uint32_t type = ELF_ST_TYPE(sym->st_info);
2278 
2279     if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
2280       if (type == STT_TLS) {
2281         // For a TLS symbol, dlsym returns the address of the current thread's
2282         // copy of the symbol.
2283         const soinfo_tls* tls_module = found->get_tls();
2284         if (tls_module == nullptr) {
2285           DL_SYM_ERR("TLS symbol \"%s\" in solib \"%s\" with no TLS segment",
2286                      sym_name, found->get_realpath());
2287           return false;
2288         }
2289         void* tls_block = get_tls_block_for_this_thread(tls_module, /*should_alloc=*/true);
2290         *symbol = static_cast<char*>(tls_block) + sym->st_value;
2291       } else {
2292         *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2293       }
2294       failure_guard.Disable();
2295       LD_LOG(kLogDlsym,
2296              "... dlsym successful: sym_name=\"%s\", sym_ver=\"%s\", found in=\"%s\", address=%p",
2297              sym_name, sym_ver, found->get_soname(), *symbol);
2298       return true;
2299     }
2300 
2301     DL_SYM_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str());
2302     return false;
2303   }
2304 
2305   DL_SYM_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
2306   return false;
2307 }
2308 
do_dlclose(void * handle)2309 int do_dlclose(void* handle) {
2310   ScopedTrace trace("dlclose");
2311   ProtectedDataGuard guard;
2312   soinfo* si = soinfo_from_handle(handle);
2313   if (si == nullptr) {
2314     DL_OPEN_ERR("invalid handle: %p", handle);
2315     return -1;
2316   }
2317 
2318   LD_LOG(kLogDlopen,
2319          "dlclose(handle=%p, realpath=\"%s\"@%p) ...",
2320          handle,
2321          si->get_realpath(),
2322          si);
2323   soinfo_unload(si);
2324   LD_LOG(kLogDlopen,
2325          "dlclose(handle=%p) ... done",
2326          handle);
2327   return 0;
2328 }
2329 
2330 // Make ns as the anonymous namespace that is a namespace used when
2331 // we fail to determine the caller address (e.g., call from mono-jited code)
2332 // Since there can be multiple anonymous namespace in a process, subsequent
2333 // call to this function causes an error.
set_anonymous_namespace(android_namespace_t * ns)2334 static bool set_anonymous_namespace(android_namespace_t* ns) {
2335   if (!g_anonymous_namespace_set && ns != nullptr) {
2336     CHECK(ns->is_also_used_as_anonymous());
2337     g_anonymous_namespace = ns;
2338     g_anonymous_namespace_set = true;
2339     return true;
2340   }
2341   return false;
2342 }
2343 
2344 // TODO(b/130388701) remove this. Currently, this is used only for testing
2345 // where we don't have classloader namespace.
init_anonymous_namespace(const char * shared_lib_sonames,const char * library_search_path)2346 bool init_anonymous_namespace(const char* shared_lib_sonames, const char* library_search_path) {
2347   ProtectedDataGuard guard;
2348 
2349   // Test-only feature: we need to change the anonymous namespace multiple times
2350   // while the test is running.
2351   g_anonymous_namespace_set = false;
2352 
2353   // create anonymous namespace
2354   // When the caller is nullptr - create_namespace will take global group
2355   // from the anonymous namespace, which is fine because anonymous namespace
2356   // is still pointing to the default one.
2357   android_namespace_t* anon_ns =
2358       create_namespace(nullptr,
2359                        "(anonymous)",
2360                        nullptr,
2361                        library_search_path,
2362                        ANDROID_NAMESPACE_TYPE_ISOLATED |
2363                        ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS,
2364                        nullptr,
2365                        &g_default_namespace);
2366 
2367   CHECK(anon_ns != nullptr);
2368 
2369   if (!link_namespaces(anon_ns, &g_default_namespace, shared_lib_sonames)) {
2370     // TODO: delete anon_ns
2371     return false;
2372   }
2373 
2374   return true;
2375 }
2376 
add_soinfos_to_namespace(const soinfo_list_t & soinfos,android_namespace_t * ns)2377 static void add_soinfos_to_namespace(const soinfo_list_t& soinfos, android_namespace_t* ns) {
2378   ns->add_soinfos(soinfos);
2379   for (auto si : soinfos) {
2380     si->add_secondary_namespace(ns);
2381   }
2382 }
2383 
fix_lib_paths(std::vector<std::string> paths)2384 std::vector<std::string> fix_lib_paths(std::vector<std::string> paths) {
2385   // For the bootstrap linker, insert /system/${LIB}/bootstrap in front of /system/${LIB} in any
2386   // namespace search path. The bootstrap linker should prefer to use the bootstrap bionic libraries
2387   // (e.g. libc.so).
2388 #if !defined(__ANDROID_APEX__)
2389   for (size_t i = 0; i < paths.size(); ++i) {
2390     if (paths[i] == kSystemLibDir) {
2391       paths.insert(paths.begin() + i, std::string(kSystemLibDir) + "/bootstrap");
2392       ++i;
2393     }
2394   }
2395 #endif
2396   return paths;
2397 }
2398 
create_namespace(const void * caller_addr,const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,android_namespace_t * parent_namespace)2399 android_namespace_t* create_namespace(const void* caller_addr,
2400                                       const char* name,
2401                                       const char* ld_library_path,
2402                                       const char* default_library_path,
2403                                       uint64_t type,
2404                                       const char* permitted_when_isolated_path,
2405                                       android_namespace_t* parent_namespace) {
2406   if (parent_namespace == nullptr) {
2407     // if parent_namespace is nullptr -> set it to the caller namespace
2408     soinfo* caller_soinfo = find_containing_library(caller_addr);
2409 
2410     parent_namespace = caller_soinfo != nullptr ?
2411                        caller_soinfo->get_primary_namespace() :
2412                        g_anonymous_namespace;
2413   }
2414 
2415   ProtectedDataGuard guard;
2416   std::vector<std::string> ld_library_paths;
2417   std::vector<std::string> default_library_paths;
2418   std::vector<std::string> permitted_paths;
2419 
2420   parse_path(ld_library_path, ":", &ld_library_paths);
2421   parse_path(default_library_path, ":", &default_library_paths);
2422   parse_path(permitted_when_isolated_path, ":", &permitted_paths);
2423 
2424   android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2425   ns->set_name(name);
2426   ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
2427   ns->set_exempt_list_enabled((type & ANDROID_NAMESPACE_TYPE_EXEMPT_LIST_ENABLED) != 0);
2428   ns->set_also_used_as_anonymous((type & ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS) != 0);
2429 
2430   if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
2431     // append parent namespace paths.
2432     std::copy(parent_namespace->get_ld_library_paths().begin(),
2433               parent_namespace->get_ld_library_paths().end(),
2434               back_inserter(ld_library_paths));
2435 
2436     std::copy(parent_namespace->get_default_library_paths().begin(),
2437               parent_namespace->get_default_library_paths().end(),
2438               back_inserter(default_library_paths));
2439 
2440     std::copy(parent_namespace->get_permitted_paths().begin(),
2441               parent_namespace->get_permitted_paths().end(),
2442               back_inserter(permitted_paths));
2443 
2444     // If shared - clone the parent namespace
2445     add_soinfos_to_namespace(parent_namespace->soinfo_list(), ns);
2446     // and copy parent namespace links
2447     for (auto& link : parent_namespace->linked_namespaces()) {
2448       ns->add_linked_namespace(link.linked_namespace(), link.shared_lib_sonames(),
2449                                link.allow_all_shared_libs());
2450     }
2451   } else {
2452     // If not shared - copy only the shared group
2453     add_soinfos_to_namespace(parent_namespace->get_shared_group(), ns);
2454   }
2455 
2456   ns->set_ld_library_paths(std::move(ld_library_paths));
2457   ns->set_default_library_paths(std::move(default_library_paths));
2458   ns->set_permitted_paths(std::move(permitted_paths));
2459 
2460   if (ns->is_also_used_as_anonymous() && !set_anonymous_namespace(ns)) {
2461     DL_ERR("failed to set namespace: [name=\"%s\", ld_library_path=\"%s\", default_library_paths=\"%s\""
2462            " permitted_paths=\"%s\"] as the anonymous namespace",
2463            ns->get_name(),
2464            android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
2465            android::base::Join(ns->get_default_library_paths(), ':').c_str(),
2466            android::base::Join(ns->get_permitted_paths(), ':').c_str());
2467     return nullptr;
2468   }
2469 
2470   return ns;
2471 }
2472 
link_namespaces(android_namespace_t * namespace_from,android_namespace_t * namespace_to,const char * shared_lib_sonames)2473 bool link_namespaces(android_namespace_t* namespace_from,
2474                      android_namespace_t* namespace_to,
2475                      const char* shared_lib_sonames) {
2476   if (namespace_to == nullptr) {
2477     namespace_to = &g_default_namespace;
2478   }
2479 
2480   if (namespace_from == nullptr) {
2481     DL_ERR("error linking namespaces: namespace_from is null.");
2482     return false;
2483   }
2484 
2485   if (shared_lib_sonames == nullptr || shared_lib_sonames[0] == '\0') {
2486     DL_ERR("error linking namespaces \"%s\"->\"%s\": the list of shared libraries is empty.",
2487            namespace_from->get_name(), namespace_to->get_name());
2488     return false;
2489   }
2490 
2491   auto sonames = android::base::Split(shared_lib_sonames, ":");
2492   std::unordered_set<std::string> sonames_set(sonames.begin(), sonames.end());
2493 
2494   ProtectedDataGuard guard;
2495   namespace_from->add_linked_namespace(namespace_to, sonames_set, false);
2496 
2497   return true;
2498 }
2499 
link_namespaces_all_libs(android_namespace_t * namespace_from,android_namespace_t * namespace_to)2500 bool link_namespaces_all_libs(android_namespace_t* namespace_from,
2501                               android_namespace_t* namespace_to) {
2502   if (namespace_from == nullptr) {
2503     DL_ERR("error linking namespaces: namespace_from is null.");
2504     return false;
2505   }
2506 
2507   if (namespace_to == nullptr) {
2508     DL_ERR("error linking namespaces: namespace_to is null.");
2509     return false;
2510   }
2511 
2512   ProtectedDataGuard guard;
2513   namespace_from->add_linked_namespace(namespace_to, std::unordered_set<std::string>(), true);
2514 
2515   return true;
2516 }
2517 
call_ifunc_resolver(ElfW (Addr)resolver_addr)2518 ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
2519   if (g_is_ldd) return 0;
2520 
2521   ElfW(Addr) ifunc_addr = __bionic_call_ifunc_resolver(resolver_addr);
2522   TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
2523       reinterpret_cast<void *>(resolver_addr), reinterpret_cast<void*>(ifunc_addr));
2524 
2525   return ifunc_addr;
2526 }
2527 
get_version_info(ElfW (Versym)source_symver) const2528 const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2529   if (source_symver < 2 ||
2530       source_symver >= version_infos.size() ||
2531       version_infos[source_symver].name == nullptr) {
2532     return nullptr;
2533   }
2534 
2535   return &version_infos[source_symver];
2536 }
2537 
add_version_info(size_t source_index,ElfW (Word)elf_hash,const char * ver_name,const soinfo * target_si)2538 void VersionTracker::add_version_info(size_t source_index,
2539                                       ElfW(Word) elf_hash,
2540                                       const char* ver_name,
2541                                       const soinfo* target_si) {
2542   if (source_index >= version_infos.size()) {
2543     version_infos.resize(source_index+1);
2544   }
2545 
2546   version_infos[source_index].elf_hash = elf_hash;
2547   version_infos[source_index].name = ver_name;
2548   version_infos[source_index].target_si = target_si;
2549 }
2550 
init_verneed(const soinfo * si_from)2551 bool VersionTracker::init_verneed(const soinfo* si_from) {
2552   uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2553 
2554   if (verneed_ptr == 0) {
2555     return true;
2556   }
2557 
2558   size_t verneed_cnt = si_from->get_verneed_cnt();
2559 
2560   for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2561     const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2562     size_t vernaux_offset = offset + verneed->vn_aux;
2563     offset += verneed->vn_next;
2564 
2565     if (verneed->vn_version != 1) {
2566       DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2567       return false;
2568     }
2569 
2570     const char* target_soname = si_from->get_string(verneed->vn_file);
2571     // find it in dependencies
2572     soinfo* target_si = si_from->get_children().find_if(
2573         [&](const soinfo* si) { return strcmp(si->get_soname(), target_soname) == 0; });
2574 
2575     if (target_si == nullptr) {
2576       DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
2577           target_soname, i, si_from->get_realpath());
2578       return false;
2579     }
2580 
2581     for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2582       const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2583       vernaux_offset += vernaux->vna_next;
2584 
2585       const ElfW(Word) elf_hash = vernaux->vna_hash;
2586       const char* ver_name = si_from->get_string(vernaux->vna_name);
2587       ElfW(Half) source_index = vernaux->vna_other;
2588 
2589       add_version_info(source_index, elf_hash, ver_name, target_si);
2590     }
2591   }
2592 
2593   return true;
2594 }
2595 
2596 template <typename F>
for_each_verdef(const soinfo * si,F functor)2597 static bool for_each_verdef(const soinfo* si, F functor) {
2598   if (!si->has_min_version(2)) {
2599     return true;
2600   }
2601 
2602   uintptr_t verdef_ptr = si->get_verdef_ptr();
2603   if (verdef_ptr == 0) {
2604     return true;
2605   }
2606 
2607   size_t offset = 0;
2608 
2609   size_t verdef_cnt = si->get_verdef_cnt();
2610   for (size_t i = 0; i<verdef_cnt; ++i) {
2611     const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
2612     size_t verdaux_offset = offset + verdef->vd_aux;
2613     offset += verdef->vd_next;
2614 
2615     if (verdef->vd_version != 1) {
2616       DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
2617           i, verdef->vd_version, si->get_realpath());
2618       return false;
2619     }
2620 
2621     if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
2622       // "this is the version of the file itself.  It must not be used for
2623       //  matching a symbol. It can be used to match references."
2624       //
2625       // http://www.akkadia.org/drepper/symbol-versioning
2626       continue;
2627     }
2628 
2629     if (verdef->vd_cnt == 0) {
2630       DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
2631       return false;
2632     }
2633 
2634     const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
2635 
2636     if (functor(i, verdef, verdaux) == true) {
2637       break;
2638     }
2639   }
2640 
2641   return true;
2642 }
2643 
find_verdef_version_index(const soinfo * si,const version_info * vi)2644 ElfW(Versym) find_verdef_version_index(const soinfo* si, const version_info* vi) {
2645   if (vi == nullptr) {
2646     return kVersymNotNeeded;
2647   }
2648 
2649   ElfW(Versym) result = kVersymGlobal;
2650 
2651   if (!for_each_verdef(si,
2652     [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2653       if (verdef->vd_hash == vi->elf_hash &&
2654           strcmp(vi->name, si->get_string(verdaux->vda_name)) == 0) {
2655         result = verdef->vd_ndx;
2656         return true;
2657       }
2658 
2659       return false;
2660     }
2661   )) {
2662     // verdef should have already been validated in prelink_image.
2663     async_safe_fatal("invalid verdef after prelinking: %s, %s",
2664                      si->get_realpath(), linker_get_error_buffer());
2665   }
2666 
2667   return result;
2668 }
2669 
2670 // Validate the library's verdef section. On error, returns false and invokes DL_ERR.
validate_verdef_section(const soinfo * si)2671 bool validate_verdef_section(const soinfo* si) {
2672   return for_each_verdef(si,
2673     [&](size_t, const ElfW(Verdef)*, const ElfW(Verdaux)*) {
2674       return false;
2675     });
2676 }
2677 
init_verdef(const soinfo * si_from)2678 bool VersionTracker::init_verdef(const soinfo* si_from) {
2679   return for_each_verdef(si_from,
2680     [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2681       add_version_info(verdef->vd_ndx, verdef->vd_hash,
2682           si_from->get_string(verdaux->vda_name), si_from);
2683       return false;
2684     }
2685   );
2686 }
2687 
init(const soinfo * si_from)2688 bool VersionTracker::init(const soinfo* si_from) {
2689   if (!si_from->has_min_version(2)) {
2690     return true;
2691   }
2692 
2693   return init_verneed(si_from) && init_verdef(si_from);
2694 }
2695 
2696 // TODO (dimitry): Methods below need to be moved out of soinfo
2697 // and in more isolated file in order minimize dependencies on
2698 // unnecessary object in the linker binary. Consider making them
2699 // independent from soinfo (?).
lookup_version_info(const VersionTracker & version_tracker,ElfW (Word)sym,const char * sym_name,const version_info ** vi)2700 bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2701                                  const char* sym_name, const version_info** vi) {
2702   const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2703   ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2704 
2705   if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2706     *vi = version_tracker.get_version_info(sym_ver);
2707 
2708     if (*vi == nullptr) {
2709       DL_ERR("cannot find verneed/verdef for version index=%d "
2710           "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
2711       return false;
2712     }
2713   } else {
2714     // there is no version info
2715     *vi = nullptr;
2716   }
2717 
2718   return true;
2719 }
2720 
apply_relr_reloc(ElfW (Addr)offset)2721 void soinfo::apply_relr_reloc(ElfW(Addr) offset) {
2722   ElfW(Addr) address = offset + load_bias;
2723   *reinterpret_cast<ElfW(Addr)*>(address) += load_bias;
2724 }
2725 
2726 // Process relocations in SHT_RELR section (experimental).
2727 // Details of the encoding are described in this post:
2728 //   https://groups.google.com/d/msg/generic-abi/bX460iggiKg/Pi9aSwwABgAJ
relocate_relr()2729 bool soinfo::relocate_relr() {
2730   ElfW(Relr)* begin = relr_;
2731   ElfW(Relr)* end = relr_ + relr_count_;
2732   constexpr size_t wordsize = sizeof(ElfW(Addr));
2733 
2734   ElfW(Addr) base = 0;
2735   for (ElfW(Relr)* current = begin; current < end; ++current) {
2736     ElfW(Relr) entry = *current;
2737     ElfW(Addr) offset;
2738 
2739     if ((entry&1) == 0) {
2740       // Even entry: encodes the offset for next relocation.
2741       offset = static_cast<ElfW(Addr)>(entry);
2742       apply_relr_reloc(offset);
2743       // Set base offset for subsequent bitmap entries.
2744       base = offset + wordsize;
2745       continue;
2746     }
2747 
2748     // Odd entry: encodes bitmap for relocations starting at base.
2749     offset = base;
2750     while (entry != 0) {
2751       entry >>= 1;
2752       if ((entry&1) != 0) {
2753         apply_relr_reloc(offset);
2754       }
2755       offset += wordsize;
2756     }
2757 
2758     // Advance base offset by 63 words for 64-bit platforms,
2759     // or 31 words for 32-bit platforms.
2760     base += (8*wordsize - 1) * wordsize;
2761   }
2762   return true;
2763 }
2764 
2765 // An empty list of soinfos
2766 static soinfo_list_t g_empty_list;
2767 
prelink_image()2768 bool soinfo::prelink_image() {
2769   if (flags_ & FLAG_PRELINKED) return true;
2770   /* Extract dynamic section */
2771   ElfW(Word) dynamic_flags = 0;
2772   phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
2773 
2774   /* We can't log anything until the linker is relocated */
2775   bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
2776   if (!relocating_linker) {
2777     INFO("[ Linking \"%s\" ]", get_realpath());
2778     DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
2779   }
2780 
2781   if (dynamic == nullptr) {
2782     if (!relocating_linker) {
2783       DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
2784     }
2785     return false;
2786   } else {
2787     if (!relocating_linker) {
2788       DEBUG("dynamic = %p", dynamic);
2789     }
2790   }
2791 
2792 #if defined(__arm__)
2793   (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
2794                                   &ARM_exidx, &ARM_exidx_count);
2795 #endif
2796 
2797   TlsSegment tls_segment;
2798   if (__bionic_get_tls_segment(phdr, phnum, load_bias, &tls_segment)) {
2799     if (!__bionic_check_tls_alignment(&tls_segment.alignment)) {
2800       if (!relocating_linker) {
2801         DL_ERR("TLS segment alignment in \"%s\" is not a power of 2: %zu",
2802                get_realpath(), tls_segment.alignment);
2803       }
2804       return false;
2805     }
2806     tls_ = std::make_unique<soinfo_tls>();
2807     tls_->segment = tls_segment;
2808   }
2809 
2810   // Extract useful information from dynamic section.
2811   // Note that: "Except for the DT_NULL element at the end of the array,
2812   // and the relative order of DT_NEEDED elements, entries may appear in any order."
2813   //
2814   // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
2815   uint32_t needed_count = 0;
2816   for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
2817     DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
2818           d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
2819     switch (d->d_tag) {
2820       case DT_SONAME:
2821         // this is parsed after we have strtab initialized (see below).
2822         break;
2823 
2824       case DT_HASH:
2825         nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
2826         nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
2827         bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
2828         chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
2829         break;
2830 
2831       case DT_GNU_HASH:
2832         gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
2833         // skip symndx
2834         gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
2835         gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
2836 
2837         gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
2838         gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
2839         // amend chain for symndx = header[1]
2840         gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
2841             reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
2842 
2843         if (!powerof2(gnu_maskwords_)) {
2844           DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
2845               gnu_maskwords_, get_realpath());
2846           return false;
2847         }
2848         --gnu_maskwords_;
2849 
2850         flags_ |= FLAG_GNU_HASH;
2851         break;
2852 
2853       case DT_STRTAB:
2854         strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
2855         break;
2856 
2857       case DT_STRSZ:
2858         strtab_size_ = d->d_un.d_val;
2859         break;
2860 
2861       case DT_SYMTAB:
2862         symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
2863         break;
2864 
2865       case DT_SYMENT:
2866         if (d->d_un.d_val != sizeof(ElfW(Sym))) {
2867           DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
2868               static_cast<size_t>(d->d_un.d_val), get_realpath());
2869           return false;
2870         }
2871         break;
2872 
2873       case DT_PLTREL:
2874 #if defined(USE_RELA)
2875         if (d->d_un.d_val != DT_RELA) {
2876           DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
2877           return false;
2878         }
2879 #else
2880         if (d->d_un.d_val != DT_REL) {
2881           DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
2882           return false;
2883         }
2884 #endif
2885         break;
2886 
2887       case DT_JMPREL:
2888 #if defined(USE_RELA)
2889         plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
2890 #else
2891         plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
2892 #endif
2893         break;
2894 
2895       case DT_PLTRELSZ:
2896 #if defined(USE_RELA)
2897         plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
2898 #else
2899         plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
2900 #endif
2901         break;
2902 
2903       case DT_PLTGOT:
2904         // Ignored (because RTLD_LAZY is not supported).
2905         break;
2906 
2907       case DT_DEBUG:
2908         // Set the DT_DEBUG entry to the address of _r_debug for GDB
2909         // if the dynamic table is writable
2910         if ((dynamic_flags & PF_W) != 0) {
2911           d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
2912         }
2913         break;
2914 #if defined(USE_RELA)
2915       case DT_RELA:
2916         rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
2917         break;
2918 
2919       case DT_RELASZ:
2920         rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
2921         break;
2922 
2923       case DT_ANDROID_RELA:
2924         android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2925         break;
2926 
2927       case DT_ANDROID_RELASZ:
2928         android_relocs_size_ = d->d_un.d_val;
2929         break;
2930 
2931       case DT_ANDROID_REL:
2932         DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
2933         return false;
2934 
2935       case DT_ANDROID_RELSZ:
2936         DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
2937         return false;
2938 
2939       case DT_RELAENT:
2940         if (d->d_un.d_val != sizeof(ElfW(Rela))) {
2941           DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
2942           return false;
2943         }
2944         break;
2945 
2946       // Ignored (see DT_RELCOUNT comments for details).
2947       case DT_RELACOUNT:
2948         break;
2949 
2950       case DT_REL:
2951         DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
2952         return false;
2953 
2954       case DT_RELSZ:
2955         DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
2956         return false;
2957 
2958 #else
2959       case DT_REL:
2960         rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
2961         break;
2962 
2963       case DT_RELSZ:
2964         rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
2965         break;
2966 
2967       case DT_RELENT:
2968         if (d->d_un.d_val != sizeof(ElfW(Rel))) {
2969           DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
2970           return false;
2971         }
2972         break;
2973 
2974       case DT_ANDROID_REL:
2975         android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
2976         break;
2977 
2978       case DT_ANDROID_RELSZ:
2979         android_relocs_size_ = d->d_un.d_val;
2980         break;
2981 
2982       case DT_ANDROID_RELA:
2983         DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
2984         return false;
2985 
2986       case DT_ANDROID_RELASZ:
2987         DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
2988         return false;
2989 
2990       // "Indicates that all RELATIVE relocations have been concatenated together,
2991       // and specifies the RELATIVE relocation count."
2992       //
2993       // TODO: Spec also mentions that this can be used to optimize relocation process;
2994       // Not currently used by bionic linker - ignored.
2995       case DT_RELCOUNT:
2996         break;
2997 
2998       case DT_RELA:
2999         DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
3000         return false;
3001 
3002       case DT_RELASZ:
3003         DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
3004         return false;
3005 
3006 #endif
3007       case DT_RELR:
3008       case DT_ANDROID_RELR:
3009         relr_ = reinterpret_cast<ElfW(Relr)*>(load_bias + d->d_un.d_ptr);
3010         break;
3011 
3012       case DT_RELRSZ:
3013       case DT_ANDROID_RELRSZ:
3014         relr_count_ = d->d_un.d_val / sizeof(ElfW(Relr));
3015         break;
3016 
3017       case DT_RELRENT:
3018       case DT_ANDROID_RELRENT:
3019         if (d->d_un.d_val != sizeof(ElfW(Relr))) {
3020           DL_ERR("invalid DT_RELRENT: %zd", static_cast<size_t>(d->d_un.d_val));
3021           return false;
3022         }
3023         break;
3024 
3025       // Ignored (see DT_RELCOUNT comments for details).
3026       // There is no DT_RELRCOUNT specifically because it would only be ignored.
3027       case DT_ANDROID_RELRCOUNT:
3028         break;
3029 
3030       case DT_INIT:
3031         init_func_ = reinterpret_cast<linker_ctor_function_t>(load_bias + d->d_un.d_ptr);
3032         DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
3033         break;
3034 
3035       case DT_FINI:
3036         fini_func_ = reinterpret_cast<linker_dtor_function_t>(load_bias + d->d_un.d_ptr);
3037         DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
3038         break;
3039 
3040       case DT_INIT_ARRAY:
3041         init_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
3042         DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
3043         break;
3044 
3045       case DT_INIT_ARRAYSZ:
3046         init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
3047         break;
3048 
3049       case DT_FINI_ARRAY:
3050         fini_array_ = reinterpret_cast<linker_dtor_function_t*>(load_bias + d->d_un.d_ptr);
3051         DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
3052         break;
3053 
3054       case DT_FINI_ARRAYSZ:
3055         fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
3056         break;
3057 
3058       case DT_PREINIT_ARRAY:
3059         preinit_array_ = reinterpret_cast<linker_ctor_function_t*>(load_bias + d->d_un.d_ptr);
3060         DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
3061         break;
3062 
3063       case DT_PREINIT_ARRAYSZ:
3064         preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
3065         break;
3066 
3067       case DT_TEXTREL:
3068 #if defined(__LP64__)
3069         DL_ERR("\"%s\" has text relocations", get_realpath());
3070         return false;
3071 #else
3072         has_text_relocations = true;
3073         break;
3074 #endif
3075 
3076       case DT_SYMBOLIC:
3077         has_DT_SYMBOLIC = true;
3078         break;
3079 
3080       case DT_NEEDED:
3081         ++needed_count;
3082         break;
3083 
3084       case DT_FLAGS:
3085         if (d->d_un.d_val & DF_TEXTREL) {
3086 #if defined(__LP64__)
3087           DL_ERR("\"%s\" has text relocations", get_realpath());
3088           return false;
3089 #else
3090           has_text_relocations = true;
3091 #endif
3092         }
3093         if (d->d_un.d_val & DF_SYMBOLIC) {
3094           has_DT_SYMBOLIC = true;
3095         }
3096         break;
3097 
3098       case DT_FLAGS_1:
3099         set_dt_flags_1(d->d_un.d_val);
3100 
3101         if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
3102           DL_WARN("Warning: \"%s\" has unsupported flags DT_FLAGS_1=%p "
3103                   "(ignoring unsupported flags)",
3104                   get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
3105         }
3106         break;
3107 
3108       // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3109       case DT_BIND_NOW:
3110         break;
3111 
3112       case DT_VERSYM:
3113         versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3114         break;
3115 
3116       case DT_VERDEF:
3117         verdef_ptr_ = load_bias + d->d_un.d_ptr;
3118         break;
3119       case DT_VERDEFNUM:
3120         verdef_cnt_ = d->d_un.d_val;
3121         break;
3122 
3123       case DT_VERNEED:
3124         verneed_ptr_ = load_bias + d->d_un.d_ptr;
3125         break;
3126 
3127       case DT_VERNEEDNUM:
3128         verneed_cnt_ = d->d_un.d_val;
3129         break;
3130 
3131       case DT_RUNPATH:
3132         // this is parsed after we have strtab initialized (see below).
3133         break;
3134 
3135       case DT_TLSDESC_GOT:
3136       case DT_TLSDESC_PLT:
3137         // These DT entries are used for lazy TLSDESC relocations. Bionic
3138         // resolves everything eagerly, so these can be ignored.
3139         break;
3140 
3141 #if defined(__aarch64__)
3142       case DT_AARCH64_BTI_PLT:
3143       case DT_AARCH64_PAC_PLT:
3144       case DT_AARCH64_VARIANT_PCS:
3145         // Ignored: AArch64 processor-specific dynamic array tags.
3146         break;
3147 #endif
3148 
3149       default:
3150         if (!relocating_linker) {
3151           const char* tag_name;
3152           if (d->d_tag == DT_RPATH) {
3153             tag_name = "DT_RPATH";
3154           } else if (d->d_tag == DT_ENCODING) {
3155             tag_name = "DT_ENCODING";
3156           } else if (d->d_tag >= DT_LOOS && d->d_tag <= DT_HIOS) {
3157             tag_name = "unknown OS-specific";
3158           } else if (d->d_tag >= DT_LOPROC && d->d_tag <= DT_HIPROC) {
3159             tag_name = "unknown processor-specific";
3160           } else {
3161             tag_name = "unknown";
3162           }
3163           DL_WARN("Warning: \"%s\" unused DT entry: %s (type %p arg %p) (ignoring)",
3164                   get_realpath(),
3165                   tag_name,
3166                   reinterpret_cast<void*>(d->d_tag),
3167                   reinterpret_cast<void*>(d->d_un.d_val));
3168         }
3169         break;
3170     }
3171   }
3172 
3173   DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
3174         reinterpret_cast<void*>(base), strtab_, symtab_);
3175 
3176   // Validity checks.
3177   if (relocating_linker && needed_count != 0) {
3178     DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3179     return false;
3180   }
3181   if (nbucket_ == 0 && gnu_nbucket_ == 0) {
3182     DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
3183         "(new hash type from the future?)", get_realpath());
3184     return false;
3185   }
3186   if (strtab_ == nullptr) {
3187     DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
3188     return false;
3189   }
3190   if (symtab_ == nullptr) {
3191     DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
3192     return false;
3193   }
3194 
3195   // Second pass - parse entries relying on strtab. Skip this while relocating the linker so as to
3196   // avoid doing heap allocations until later in the linker's initialization.
3197   if (!relocating_linker) {
3198     for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3199       switch (d->d_tag) {
3200         case DT_SONAME:
3201           set_soname(get_string(d->d_un.d_val));
3202           break;
3203         case DT_RUNPATH:
3204           set_dt_runpath(get_string(d->d_un.d_val));
3205           break;
3206       }
3207     }
3208   }
3209 
3210   // Before M release, linker was using basename in place of soname. In the case when DT_SONAME is
3211   // absent some apps stop working because they can't find DT_NEEDED library by soname. This
3212   // workaround should keep them working. (Applies only for apps targeting sdk version < M.) Make
3213   // an exception for the main executable, which does not need to have DT_SONAME. The linker has an
3214   // DT_SONAME but the soname_ field is initialized later on.
3215   if (soname_.empty() && this != solist_get_somain() && !relocating_linker &&
3216       get_application_target_sdk_version() < 23) {
3217     soname_ = basename(realpath_.c_str());
3218     DL_WARN_documented_change(23, "missing-soname-enforced-for-api-level-23",
3219                               "\"%s\" has no DT_SONAME (will use %s instead)", get_realpath(),
3220                               soname_.c_str());
3221 
3222     // Don't call add_dlwarning because a missing DT_SONAME isn't important enough to show in the UI
3223   }
3224 
3225   // Validate each library's verdef section once, so we don't have to validate
3226   // it each time we look up a symbol with a version.
3227   if (!validate_verdef_section(this)) return false;
3228 
3229   flags_ |= FLAG_PRELINKED;
3230   return true;
3231 }
3232 
link_image(const SymbolLookupList & lookup_list,soinfo * local_group_root,const android_dlextinfo * extinfo,size_t * relro_fd_offset)3233 bool soinfo::link_image(const SymbolLookupList& lookup_list, soinfo* local_group_root,
3234                         const android_dlextinfo* extinfo, size_t* relro_fd_offset) {
3235   if (is_image_linked()) {
3236     // already linked.
3237     return true;
3238   }
3239 
3240   if (g_is_ldd && !is_main_executable()) {
3241     async_safe_format_fd(STDOUT_FILENO, "\t%s => %s (%p)\n", get_soname(),
3242                          get_realpath(), reinterpret_cast<void*>(base));
3243   }
3244 
3245   local_group_root_ = local_group_root;
3246   if (local_group_root_ == nullptr) {
3247     local_group_root_ = this;
3248   }
3249 
3250   if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3251     target_sdk_version_ = get_application_target_sdk_version();
3252   }
3253 
3254 #if !defined(__LP64__)
3255   if (has_text_relocations) {
3256     // Fail if app is targeting M or above.
3257     int app_target_api_level = get_application_target_sdk_version();
3258     if (app_target_api_level >= 23) {
3259       DL_ERR_AND_LOG("\"%s\" has text relocations (%s#Text-Relocations-Enforced-for-API-level-23)",
3260                      get_realpath(), kBionicChangesUrl);
3261       return false;
3262     }
3263     // Make segments writable to allow text relocations to work properly. We will later call
3264     // phdr_table_protect_segments() after all of them are applied.
3265     DL_WARN_documented_change(23,
3266                               "Text-Relocations-Enforced-for-API-level-23",
3267                               "\"%s\" has text relocations",
3268                               get_realpath());
3269     add_dlwarning(get_realpath(), "text relocations");
3270     if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
3271       DL_ERR("can't unprotect loadable segments for \"%s\": %s", get_realpath(), strerror(errno));
3272       return false;
3273     }
3274   }
3275 #endif
3276 
3277   if (!relocate(lookup_list)) {
3278     return false;
3279   }
3280 
3281   DEBUG("[ finished linking %s ]", get_realpath());
3282 
3283 #if !defined(__LP64__)
3284   if (has_text_relocations) {
3285     // All relocations are done, we can protect our segments back to read-only.
3286     if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
3287       DL_ERR("can't protect segments for \"%s\": %s",
3288              get_realpath(), strerror(errno));
3289       return false;
3290     }
3291   }
3292 #endif
3293 
3294   // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
3295   // itself --- it can't make system calls yet, and will have to call protect_relro later.
3296   if (!is_linker() && !protect_relro()) {
3297     return false;
3298   }
3299 
3300   /* Handle serializing/sharing the RELRO segment */
3301   if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
3302     if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
3303                                        extinfo->relro_fd, relro_fd_offset) < 0) {
3304       DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
3305              get_realpath(), strerror(errno));
3306       return false;
3307     }
3308   } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
3309     if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
3310                                  extinfo->relro_fd, relro_fd_offset) < 0) {
3311       DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
3312              get_realpath(), strerror(errno));
3313       return false;
3314     }
3315   }
3316 
3317   ++g_module_load_counter;
3318   notify_gdb_of_load(this);
3319   set_image_linked();
3320   return true;
3321 }
3322 
protect_relro()3323 bool soinfo::protect_relro() {
3324   if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
3325     DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
3326            get_realpath(), strerror(errno));
3327     return false;
3328   }
3329   return true;
3330 }
3331 
init_default_namespace_no_config(bool is_asan)3332 static std::vector<android_namespace_t*> init_default_namespace_no_config(bool is_asan) {
3333   g_default_namespace.set_isolated(false);
3334   auto default_ld_paths = is_asan ? kAsanDefaultLdPaths : kDefaultLdPaths;
3335 
3336   char real_path[PATH_MAX];
3337   std::vector<std::string> ld_default_paths;
3338   for (size_t i = 0; default_ld_paths[i] != nullptr; ++i) {
3339     if (realpath(default_ld_paths[i], real_path) != nullptr) {
3340       ld_default_paths.push_back(real_path);
3341     } else {
3342       ld_default_paths.push_back(default_ld_paths[i]);
3343     }
3344   }
3345 
3346   g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
3347 
3348   std::vector<android_namespace_t*> namespaces;
3349   namespaces.push_back(&g_default_namespace);
3350   return namespaces;
3351 }
3352 
3353 // Given an `executable_path` starting with "/apex/<name>/bin/, return
3354 // "/linkerconfig/<name>/ld.config.txt" (or "/apex/<name>/etc/ld.config.txt", if
3355 // the former does not exist).
get_ld_config_file_apex_path(const char * executable_path)3356 static std::string get_ld_config_file_apex_path(const char* executable_path) {
3357   std::vector<std::string> paths = android::base::Split(executable_path, "/");
3358   if (paths.size() >= 5 && paths[1] == "apex" && paths[3] == "bin") {
3359     // Check auto-generated ld.config.txt first
3360     std::string generated_apex_config = "/linkerconfig/" + paths[2] + "/ld.config.txt";
3361     if (file_exists(generated_apex_config.c_str())) {
3362       return generated_apex_config;
3363     }
3364 
3365     return std::string("/apex/") + paths[2] + "/etc/ld.config.txt";
3366   }
3367   return "";
3368 }
3369 
get_ld_config_file_vndk_path()3370 static std::string get_ld_config_file_vndk_path() {
3371   if (android::base::GetBoolProperty("ro.vndk.lite", false)) {
3372     return kLdConfigVndkLiteFilePath;
3373   }
3374 
3375   std::string ld_config_file_vndk = kLdConfigFilePath;
3376   size_t insert_pos = ld_config_file_vndk.find_last_of('.');
3377   if (insert_pos == std::string::npos) {
3378     insert_pos = ld_config_file_vndk.length();
3379   }
3380   ld_config_file_vndk.insert(insert_pos, Config::get_vndk_version_string('.'));
3381   return ld_config_file_vndk;
3382 }
3383 
is_linker_config_expected(const char * executable_path)3384 bool is_linker_config_expected(const char* executable_path) {
3385   // Do not raise message from a host environment which is expected to miss generated linker
3386   // configuration.
3387 #if !defined(__ANDROID__)
3388   return false;
3389 #endif
3390 
3391   if (strcmp(executable_path, "/system/bin/init") == 0) {
3392     // Generated linker configuration can be missed from processes executed
3393     // with init binary
3394     return false;
3395   }
3396 
3397   return true;
3398 }
3399 
get_ld_config_file_path(const char * executable_path)3400 static std::string get_ld_config_file_path(const char* executable_path) {
3401 #ifdef USE_LD_CONFIG_FILE
3402   // This is a debugging/testing only feature. Must not be available on
3403   // production builds.
3404   const char* ld_config_file_env = getenv("LD_CONFIG_FILE");
3405   if (ld_config_file_env != nullptr && file_exists(ld_config_file_env)) {
3406     return ld_config_file_env;
3407   }
3408 #endif
3409 
3410   std::string path = get_ld_config_file_apex_path(executable_path);
3411   if (!path.empty()) {
3412     if (file_exists(path.c_str())) {
3413       return path;
3414     }
3415     DL_WARN("Warning: couldn't read config file \"%s\" for \"%s\"",
3416             path.c_str(), executable_path);
3417   }
3418 
3419   path = kLdConfigArchFilePath;
3420   if (file_exists(path.c_str())) {
3421     return path;
3422   }
3423 
3424   if (file_exists(kLdGeneratedConfigFilePath)) {
3425     return kLdGeneratedConfigFilePath;
3426   }
3427 
3428   if (is_linker_config_expected(executable_path)) {
3429     DL_WARN("Warning: failed to find generated linker configuration from \"%s\"",
3430             kLdGeneratedConfigFilePath);
3431   }
3432 
3433   path = get_ld_config_file_vndk_path();
3434   if (file_exists(path.c_str())) {
3435     return path;
3436   }
3437 
3438   return kLdConfigFilePath;
3439 }
3440 
init_default_namespaces(const char * executable_path)3441 std::vector<android_namespace_t*> init_default_namespaces(const char* executable_path) {
3442   g_default_namespace.set_name("(default)");
3443 
3444   soinfo* somain = solist_get_somain();
3445 
3446   const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
3447                                                        somain->load_bias);
3448   const char* bname = (interp != nullptr) ? basename(interp) : nullptr;
3449 
3450   g_is_asan = bname != nullptr &&
3451               (strcmp(bname, "linker_asan") == 0 ||
3452                strcmp(bname, "linker_asan64") == 0);
3453 
3454   const Config* config = nullptr;
3455 
3456   {
3457     std::string ld_config_file_path = get_ld_config_file_path(executable_path);
3458     INFO("[ Reading linker config \"%s\" ]", ld_config_file_path.c_str());
3459     ScopedTrace trace(("linker config " + ld_config_file_path).c_str());
3460     std::string error_msg;
3461     if (!Config::read_binary_config(ld_config_file_path.c_str(), executable_path, g_is_asan,
3462                                     &config, &error_msg)) {
3463       if (!error_msg.empty()) {
3464         DL_WARN("Warning: couldn't read '%s' for '%s' (using default configuration instead): %s",
3465                 ld_config_file_path.c_str(), executable_path, error_msg.c_str());
3466       }
3467       config = nullptr;
3468     }
3469   }
3470 
3471   if (config == nullptr) {
3472     return init_default_namespace_no_config(g_is_asan);
3473   }
3474 
3475   const auto& namespace_configs = config->namespace_configs();
3476   std::unordered_map<std::string, android_namespace_t*> namespaces;
3477 
3478   // 1. Initialize default namespace
3479   const NamespaceConfig* default_ns_config = config->default_namespace_config();
3480 
3481   g_default_namespace.set_isolated(default_ns_config->isolated());
3482   g_default_namespace.set_default_library_paths(default_ns_config->search_paths());
3483   g_default_namespace.set_permitted_paths(default_ns_config->permitted_paths());
3484 
3485   namespaces[default_ns_config->name()] = &g_default_namespace;
3486   if (default_ns_config->visible()) {
3487     g_exported_namespaces[default_ns_config->name()] = &g_default_namespace;
3488   }
3489 
3490   // 2. Initialize other namespaces
3491 
3492   for (auto& ns_config : namespace_configs) {
3493     if (namespaces.find(ns_config->name()) != namespaces.end()) {
3494       continue;
3495     }
3496 
3497     android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
3498     ns->set_name(ns_config->name());
3499     ns->set_isolated(ns_config->isolated());
3500     ns->set_default_library_paths(ns_config->search_paths());
3501     ns->set_permitted_paths(ns_config->permitted_paths());
3502     ns->set_allowed_libs(ns_config->allowed_libs());
3503 
3504     namespaces[ns_config->name()] = ns;
3505     if (ns_config->visible()) {
3506       g_exported_namespaces[ns_config->name()] = ns;
3507     }
3508   }
3509 
3510   // 3. Establish links between namespaces
3511   for (auto& ns_config : namespace_configs) {
3512     auto it_from = namespaces.find(ns_config->name());
3513     CHECK(it_from != namespaces.end());
3514     android_namespace_t* namespace_from = it_from->second;
3515     for (const NamespaceLinkConfig& ns_link : ns_config->links()) {
3516       auto it_to = namespaces.find(ns_link.ns_name());
3517       CHECK(it_to != namespaces.end());
3518       android_namespace_t* namespace_to = it_to->second;
3519       if (ns_link.allow_all_shared_libs()) {
3520         link_namespaces_all_libs(namespace_from, namespace_to);
3521       } else {
3522         link_namespaces(namespace_from, namespace_to, ns_link.shared_libs().c_str());
3523       }
3524     }
3525   }
3526   // we can no longer rely on the fact that libdl.so is part of default namespace
3527   // this is why we want to add ld-android.so to all namespaces from ld.config.txt
3528   soinfo* ld_android_so = solist_get_head();
3529 
3530   // we also need vdso to be available for all namespaces (if present)
3531   soinfo* vdso = solist_get_vdso();
3532   for (auto it : namespaces) {
3533     if (it.second != &g_default_namespace) {
3534       it.second->add_soinfo(ld_android_so);
3535       if (vdso != nullptr) {
3536         it.second->add_soinfo(vdso);
3537       }
3538       // somain and ld_preloads are added to these namespaces after LD_PRELOAD libs are linked
3539     }
3540   }
3541 
3542   set_application_target_sdk_version(config->target_sdk_version());
3543 
3544   std::vector<android_namespace_t*> created_namespaces;
3545   created_namespaces.reserve(namespaces.size());
3546   for (const auto& kv : namespaces) {
3547     created_namespaces.push_back(kv.second);
3548   }
3549   return created_namespaces;
3550 }
3551 
3552 // This function finds a namespace exported in ld.config.txt by its name.
3553 // A namespace can be exported by setting .visible property to true.
get_exported_namespace(const char * name)3554 android_namespace_t* get_exported_namespace(const char* name) {
3555   if (name == nullptr) {
3556     return nullptr;
3557   }
3558   auto it = g_exported_namespaces.find(std::string(name));
3559   if (it == g_exported_namespaces.end()) {
3560     return nullptr;
3561   }
3562   return it->second;
3563 }
3564 
purge_unused_memory()3565 void purge_unused_memory() {
3566   // For now, we only purge the memory used by LoadTask because we know those
3567   // are temporary objects.
3568   //
3569   // Purging other LinkerBlockAllocator hardly yields much because they hold
3570   // information about namespaces and opened libraries, which are not freed
3571   // when the control leaves the linker.
3572   //
3573   // Purging BionicAllocator may give us a few dirty pages back, but those pages
3574   // would be already zeroed out, so they compress easily in ZRAM.  Therefore,
3575   // it is not worth munmap()'ing those pages.
3576   TypeBasedAllocator<LoadTask>::purge();
3577 }
3578