OSDN Git Service

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