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 <unistd.h>
40 
41 #include <new>
42 #include <string>
43 #include <unordered_map>
44 #include <vector>
45 
46 // Private C library headers.
47 #include "private/bionic_globals.h"
48 #include "private/bionic_tls.h"
49 #include "private/KernelArgumentBlock.h"
50 #include "private/ScopedPthreadMutexLocker.h"
51 #include "private/ScopeGuard.h"
52 
53 #include "linker.h"
54 #include "linker_block_allocator.h"
55 #include "linker_gdb_support.h"
56 #include "linker_debug.h"
57 #include "linker_dlwarning.h"
58 #include "linker_sleb128.h"
59 #include "linker_phdr.h"
60 #include "linker_relocs.h"
61 #include "linker_reloc_iterators.h"
62 #include "linker_utils.h"
63 
64 #include "android-base/strings.h"
65 #include "ziparchive/zip_archive.h"
66 
67 extern void __libc_init_globals(KernelArgumentBlock&);
68 extern void __libc_init_AT_SECURE(KernelArgumentBlock&);
69 
70 extern "C" void _start();
71 
72 // Override macros to use C++ style casts.
73 #undef ELF_ST_TYPE
74 #define ELF_ST_TYPE(x) (static_cast<uint32_t>(x) & 0xf)
75 
76 struct android_namespace_t {
77  public:
android_namespace_tandroid_namespace_t78   android_namespace_t() : name_(nullptr), is_isolated_(false) {}
79 
get_nameandroid_namespace_t80   const char* get_name() const { return name_; }
set_nameandroid_namespace_t81   void set_name(const char* name) { name_ = name; }
82 
is_isolatedandroid_namespace_t83   bool is_isolated() const { return is_isolated_; }
set_isolatedandroid_namespace_t84   void set_isolated(bool isolated) { is_isolated_ = isolated; }
85 
get_ld_library_pathsandroid_namespace_t86   const std::vector<std::string>& get_ld_library_paths() const {
87     return ld_library_paths_;
88   }
set_ld_library_pathsandroid_namespace_t89   void set_ld_library_paths(std::vector<std::string>&& library_paths) {
90     ld_library_paths_ = library_paths;
91   }
92 
get_default_library_pathsandroid_namespace_t93   const std::vector<std::string>& get_default_library_paths() const {
94     return default_library_paths_;
95   }
set_default_library_pathsandroid_namespace_t96   void set_default_library_paths(std::vector<std::string>&& library_paths) {
97     default_library_paths_ = library_paths;
98   }
99 
get_permitted_pathsandroid_namespace_t100   const std::vector<std::string>& get_permitted_paths() const {
101     return permitted_paths_;
102   }
set_permitted_pathsandroid_namespace_t103   void set_permitted_paths(std::vector<std::string>&& permitted_paths) {
104     permitted_paths_ = permitted_paths;
105   }
106 
add_soinfoandroid_namespace_t107   void add_soinfo(soinfo* si) {
108     soinfo_list_.push_back(si);
109   }
110 
add_soinfosandroid_namespace_t111   void add_soinfos(const soinfo::soinfo_list_t& soinfos) {
112     for (auto si : soinfos) {
113       add_soinfo(si);
114       si->add_secondary_namespace(this);
115     }
116   }
117 
remove_soinfoandroid_namespace_t118   void remove_soinfo(soinfo* si) {
119     soinfo_list_.remove_if([&](soinfo* candidate) {
120       return si == candidate;
121     });
122   }
123 
soinfo_listandroid_namespace_t124   const soinfo::soinfo_list_t& soinfo_list() const { return soinfo_list_; }
125 
126   // For isolated namespaces - checks if the file is on the search path;
127   // always returns true for not isolated namespace.
128   bool is_accessible(const std::string& path);
129 
130  private:
131   const char* name_;
132   bool is_isolated_;
133   std::vector<std::string> ld_library_paths_;
134   std::vector<std::string> default_library_paths_;
135   std::vector<std::string> permitted_paths_;
136   soinfo::soinfo_list_t soinfo_list_;
137 
138   DISALLOW_COPY_AND_ASSIGN(android_namespace_t);
139 };
140 
141 android_namespace_t g_default_namespace;
142 
143 static std::unordered_map<uintptr_t, soinfo*> g_soinfo_handles_map;
144 static android_namespace_t* g_anonymous_namespace = &g_default_namespace;
145 
146 static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
147 
148 static LinkerTypeAllocator<soinfo> g_soinfo_allocator;
149 static LinkerTypeAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
150 
151 static LinkerTypeAllocator<android_namespace_t> g_namespace_allocator;
152 static LinkerTypeAllocator<LinkedListEntry<android_namespace_t>> g_namespace_list_allocator;
153 
154 static soinfo* solist;
155 static soinfo* sonext;
156 static soinfo* somain; // main process, always the one after libdl_info
157 
158 static const char* const kDefaultLdPaths[] = {
159 #if defined(__LP64__)
160   "/system/lib64",
161   "/vendor/lib64",
162 #else
163   "/system/lib",
164   "/vendor/lib",
165 #endif
166   nullptr
167 };
168 
169 static const char* const kAsanDefaultLdPaths[] = {
170 #if defined(__LP64__)
171   "/data/lib64",
172   "/system/lib64",
173   "/data/vendor/lib64",
174   "/vendor/lib64",
175 #else
176   "/data/lib",
177   "/system/lib",
178   "/data/vendor/lib",
179   "/vendor/lib",
180 #endif
181   nullptr
182 };
183 
is_system_library(const std::string & realpath)184 static bool is_system_library(const std::string& realpath) {
185   for (const auto& dir : g_default_namespace.get_default_library_paths()) {
186     if (file_is_in_dir(realpath, dir)) {
187       return true;
188     }
189   }
190   return false;
191 }
192 
193 #if defined(__LP64__)
194 static const char* const kSystemLibDir = "/system/lib64";
195 #else
196 static const char* const kSystemLibDir = "/system/lib";
197 #endif
198 
199 static std::string dirname(const char *path);
200 
201 // TODO(dimitry): The grey-list is a workaround for http://b/26394120 ---
202 // gradually remove libraries from this list until it is gone.
is_greylisted(const char * name,const soinfo * needed_by)203 static bool is_greylisted(const char* name, const soinfo* needed_by) {
204   static const char* const kLibraryGreyList[] = {
205     "libandroid_runtime.so",
206     "libbinder.so",
207     "libcrypto.so",
208     "libcutils.so",
209     "libexpat.so",
210     "libgui.so",
211     "libmedia.so",
212     "libnativehelper.so",
213     "libskia.so",
214     "libssl.so",
215     "libstagefright.so",
216     "libsqlite.so",
217     "libui.so",
218     "libutils.so",
219     "libvorbisidec.so",
220     nullptr
221   };
222 
223   // limit greylisting to apps targeting sdk version 23 and below
224   if (get_application_target_sdk_version() > 23) {
225     return false;
226   }
227 
228   // if the library needed by a system library - implicitly assume it
229   // is greylisted
230 
231   if (needed_by != nullptr && is_system_library(needed_by->get_realpath())) {
232     return true;
233   }
234 
235   // if this is an absolute path - make sure it points to /system/lib(64)
236   if (name[0] == '/' && dirname(name) == kSystemLibDir) {
237     // and reduce the path to basename
238     name = basename(name);
239   }
240 
241   for (size_t i = 0; kLibraryGreyList[i] != nullptr; ++i) {
242     if (strcmp(name, kLibraryGreyList[i]) == 0) {
243       return true;
244     }
245   }
246 
247   return false;
248 }
249 // END OF WORKAROUND
250 
251 static const ElfW(Versym) kVersymNotNeeded = 0;
252 static const ElfW(Versym) kVersymGlobal = 1;
253 
254 static const char* const* g_default_ld_paths;
255 static std::vector<std::string> g_ld_preload_names;
256 
257 static std::vector<soinfo*> g_ld_preloads;
258 
259 static bool g_public_namespace_initialized;
260 static soinfo::soinfo_list_t g_public_namespace;
261 
262 __LIBC_HIDDEN__ int g_ld_debug_verbosity;
263 
264 __LIBC_HIDDEN__ abort_msg_t* g_abort_message = nullptr; // For debuggerd.
265 
dirname(const char * path)266 static std::string dirname(const char *path) {
267   const char* last_slash = strrchr(path, '/');
268   if (last_slash == path) return "/";
269   else if (last_slash == nullptr) return ".";
270   else
271     return std::string(path, last_slash - path);
272 }
273 
274 #if STATS
275 struct linker_stats_t {
276   int count[kRelocMax];
277 };
278 
279 static linker_stats_t linker_stats;
280 
count_relocation(RelocationKind kind)281 void count_relocation(RelocationKind kind) {
282   ++linker_stats.count[kind];
283 }
284 #else
count_relocation(RelocationKind)285 void count_relocation(RelocationKind) {
286 }
287 #endif
288 
289 #if COUNT_PAGES
290 uint32_t bitmask[4096];
291 #endif
292 
293 static char __linker_dl_err_buf[768];
294 
linker_get_error_buffer()295 char* linker_get_error_buffer() {
296   return &__linker_dl_err_buf[0];
297 }
298 
linker_get_error_buffer_size()299 size_t linker_get_error_buffer_size() {
300   return sizeof(__linker_dl_err_buf);
301 }
302 
notify_gdb_of_load(soinfo * info)303 static void notify_gdb_of_load(soinfo* info) {
304   if (info->is_linker() || info->is_main_executable()) {
305     // gdb already knows about the linker and the main executable.
306     return;
307   }
308 
309   link_map* map = &(info->link_map_head);
310 
311   map->l_addr = info->load_bias;
312   // link_map l_name field is not const.
313   map->l_name = const_cast<char*>(info->get_realpath());
314   map->l_ld = info->dynamic;
315 
316   CHECK(map->l_name != nullptr);
317   CHECK(map->l_name[0] != '\0');
318 
319   notify_gdb_of_load(map);
320 }
321 
notify_gdb_of_unload(soinfo * info)322 static void notify_gdb_of_unload(soinfo* info) {
323   notify_gdb_of_unload(&(info->link_map_head));
324 }
325 
is_accessible(const std::string & file)326 bool android_namespace_t::is_accessible(const std::string& file) {
327   if (!is_isolated_) {
328     return true;
329   }
330 
331   for (const auto& dir : ld_library_paths_) {
332     if (file_is_in_dir(file, dir)) {
333       return true;
334     }
335   }
336 
337   for (const auto& dir : default_library_paths_) {
338     if (file_is_in_dir(file, dir)) {
339       return true;
340     }
341   }
342 
343   for (const auto& dir : permitted_paths_) {
344     if (file_is_under_dir(file, dir)) {
345       return true;
346     }
347   }
348 
349   return false;
350 }
351 
alloc()352 LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
353   return g_soinfo_links_allocator.alloc();
354 }
355 
free(LinkedListEntry<soinfo> * entry)356 void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
357   g_soinfo_links_allocator.free(entry);
358 }
359 
alloc()360 LinkedListEntry<android_namespace_t>* NamespaceListAllocator::alloc() {
361   return g_namespace_list_allocator.alloc();
362 }
363 
free(LinkedListEntry<android_namespace_t> * entry)364 void NamespaceListAllocator::free(LinkedListEntry<android_namespace_t>* entry) {
365   g_namespace_list_allocator.free(entry);
366 }
367 
soinfo_alloc(android_namespace_t * ns,const char * name,struct stat * file_stat,off64_t file_offset,uint32_t rtld_flags)368 static soinfo* soinfo_alloc(android_namespace_t* ns, const char* name,
369                             struct stat* file_stat, off64_t file_offset,
370                             uint32_t rtld_flags) {
371   if (strlen(name) >= PATH_MAX) {
372     DL_ERR("library name \"%s\" too long", name);
373     return nullptr;
374   }
375 
376   soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(ns, name, file_stat,
377                                                        file_offset, rtld_flags);
378 
379   sonext->next = si;
380   sonext = si;
381 
382   si->generate_handle();
383   ns->add_soinfo(si);
384 
385   TRACE("name %s: allocated soinfo @ %p", name, si);
386   return si;
387 }
388 
soinfo_free(soinfo * si)389 static void soinfo_free(soinfo* si) {
390   if (si == nullptr) {
391     return;
392   }
393 
394   if (si->base != 0 && si->size != 0) {
395     if (!si->is_mapped_by_caller()) {
396       munmap(reinterpret_cast<void*>(si->base), si->size);
397     } else {
398       // remap the region as PROT_NONE, MAP_ANONYMOUS | MAP_NORESERVE
399       mmap(reinterpret_cast<void*>(si->base), si->size, PROT_NONE,
400            MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
401     }
402   }
403 
404   soinfo *prev = nullptr, *trav;
405 
406   TRACE("name %s: freeing soinfo @ %p", si->get_realpath(), si);
407 
408   for (trav = solist; trav != nullptr; trav = trav->next) {
409     if (trav == si) {
410       break;
411     }
412     prev = trav;
413   }
414 
415   if (trav == nullptr) {
416     // si was not in solist
417     DL_ERR("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
418     return;
419   }
420 
421   // clear links to/from si
422   si->remove_all_links();
423 
424   // prev will never be null, because the first entry in solist is
425   // always the static libdl_info.
426   prev->next = si->next;
427   if (si == sonext) {
428     sonext = prev;
429   }
430 
431   si->~soinfo();
432   g_soinfo_allocator.free(si);
433 }
434 
435 // For every path element this function checks of it exists, and is a directory,
436 // and normalizes it:
437 // 1. For regular path it converts it to realpath()
438 // 2. For path in a zip file it uses realpath on the zipfile
439 //    normalizes entry name by calling normalize_path function.
resolve_paths(std::vector<std::string> & paths,std::vector<std::string> * resolved_paths)440 static void resolve_paths(std::vector<std::string>& paths,
441                           std::vector<std::string>* resolved_paths) {
442   resolved_paths->clear();
443   for (const auto& path : paths) {
444     char resolved_path[PATH_MAX];
445     const char* original_path = path.c_str();
446     if (realpath(original_path, resolved_path) != nullptr) {
447       struct stat s;
448       if (stat(resolved_path, &s) == 0) {
449         if (S_ISDIR(s.st_mode)) {
450           resolved_paths->push_back(resolved_path);
451         } else {
452           DL_WARN("Warning: \"%s\" is not a directory (excluding from path)", resolved_path);
453           continue;
454         }
455       } else {
456         DL_WARN("Warning: cannot stat file \"%s\": %s", resolved_path, strerror(errno));
457         continue;
458       }
459     } else {
460       std::string zip_path;
461       std::string entry_path;
462 
463       std::string normalized_path;
464 
465       if (!normalize_path(original_path, &normalized_path)) {
466         DL_WARN("Warning: unable to normalize \"%s\"", original_path);
467         continue;
468       }
469 
470       if (parse_zip_path(normalized_path.c_str(), &zip_path, &entry_path)) {
471         if (realpath(zip_path.c_str(), resolved_path) == nullptr) {
472           DL_WARN("Warning: unable to resolve \"%s\": %s", zip_path.c_str(), strerror(errno));
473           continue;
474         }
475 
476         resolved_paths->push_back(std::string(resolved_path) + kZipFileSeparator + entry_path);
477       }
478     }
479   }
480 }
481 
split_path(const char * path,const char * delimiters,std::vector<std::string> * paths)482 static void split_path(const char* path, const char* delimiters,
483                        std::vector<std::string>* paths) {
484   if (path != nullptr && path[0] != 0) {
485     *paths = android::base::Split(path, delimiters);
486   }
487 }
488 
parse_path(const char * path,const char * delimiters,std::vector<std::string> * resolved_paths)489 static void parse_path(const char* path, const char* delimiters,
490                        std::vector<std::string>* resolved_paths) {
491   std::vector<std::string> paths;
492   split_path(path, delimiters, &paths);
493   resolve_paths(paths, resolved_paths);
494 }
495 
parse_LD_LIBRARY_PATH(const char * path)496 static void parse_LD_LIBRARY_PATH(const char* path) {
497   std::vector<std::string> ld_libary_paths;
498   parse_path(path, ":", &ld_libary_paths);
499   g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
500 }
501 
set_dt_runpath(const char * path)502 void soinfo::set_dt_runpath(const char* path) {
503   if (!has_min_version(3)) {
504     return;
505   }
506 
507   std::vector<std::string> runpaths;
508 
509   split_path(path, ":", &runpaths);
510 
511   std::string origin = dirname(get_realpath());
512   // FIXME: add $LIB and $PLATFORM.
513   std::pair<std::string, std::string> substs[] = {{"ORIGIN", origin}};
514   for (auto&& s : runpaths) {
515     size_t pos = 0;
516     while (pos < s.size()) {
517       pos = s.find("$", pos);
518       if (pos == std::string::npos) break;
519       for (const auto& subst : substs) {
520         const std::string& token = subst.first;
521         const std::string& replacement = subst.second;
522         if (s.substr(pos + 1, token.size()) == token) {
523           s.replace(pos, token.size() + 1, replacement);
524           // -1 to compensate for the ++pos below.
525           pos += replacement.size() - 1;
526           break;
527         } else if (s.substr(pos + 1, token.size() + 2) == "{" + token + "}") {
528           s.replace(pos, token.size() + 3, replacement);
529           pos += replacement.size() - 1;
530           break;
531         }
532       }
533       // Skip $ in case it did not match any of the known substitutions.
534       ++pos;
535     }
536   }
537 
538   resolve_paths(runpaths, &dt_runpath_);
539 }
540 
parse_LD_PRELOAD(const char * path)541 static void parse_LD_PRELOAD(const char* path) {
542   g_ld_preload_names.clear();
543   if (path != nullptr) {
544     // We have historically supported ':' as well as ' ' in LD_PRELOAD.
545     g_ld_preload_names = android::base::Split(path, " :");
546     std::remove_if(g_ld_preload_names.begin(),
547                    g_ld_preload_names.end(),
548                    [] (const std::string& s) { return s.empty(); });
549   }
550 }
551 
realpath_fd(int fd,std::string * realpath)552 static bool realpath_fd(int fd, std::string* realpath) {
553   std::vector<char> buf(PATH_MAX), proc_self_fd(PATH_MAX);
554   __libc_format_buffer(&proc_self_fd[0], proc_self_fd.size(), "/proc/self/fd/%d", fd);
555   if (readlink(&proc_self_fd[0], &buf[0], buf.size()) == -1) {
556     PRINT("readlink(\"%s\") failed: %s [fd=%d]", &proc_self_fd[0], strerror(errno), fd);
557     return false;
558   }
559 
560   *realpath = &buf[0];
561   return true;
562 }
563 
564 #if defined(__arm__)
565 
566 // For a given PC, find the .so that it belongs to.
567 // Returns the base address of the .ARM.exidx section
568 // for that .so, and the number of 8-byte entries
569 // in that section (via *pcount).
570 //
571 // Intended to be called by libc's __gnu_Unwind_Find_exidx().
572 //
573 // This function is exposed via dlfcn.cpp and libdl.so.
dl_unwind_find_exidx(_Unwind_Ptr pc,int * pcount)574 _Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
575   uintptr_t addr = reinterpret_cast<uintptr_t>(pc);
576 
577   for (soinfo* si = solist; si != 0; si = si->next) {
578     if ((addr >= si->base) && (addr < (si->base + si->size))) {
579         *pcount = si->ARM_exidx_count;
580         return reinterpret_cast<_Unwind_Ptr>(si->ARM_exidx);
581     }
582   }
583   *pcount = 0;
584   return nullptr;
585 }
586 
587 #endif
588 
589 // Here, we only have to provide a callback to iterate across all the
590 // loaded libraries. gcc_eh does the rest.
do_dl_iterate_phdr(int (* cb)(dl_phdr_info * info,size_t size,void * data),void * data)591 int do_dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
592   int rv = 0;
593   for (soinfo* si = solist; si != nullptr; si = si->next) {
594     dl_phdr_info dl_info;
595     dl_info.dlpi_addr = si->link_map_head.l_addr;
596     dl_info.dlpi_name = si->link_map_head.l_name;
597     dl_info.dlpi_phdr = si->phdr;
598     dl_info.dlpi_phnum = si->phnum;
599     rv = cb(&dl_info, sizeof(dl_phdr_info), data);
600     if (rv != 0) {
601       break;
602     }
603   }
604   return rv;
605 }
606 
ElfW(Versym)607 const ElfW(Versym)* soinfo::get_versym(size_t n) const {
608   if (has_min_version(2) && versym_ != nullptr) {
609     return versym_ + n;
610   }
611 
612   return nullptr;
613 }
614 
ElfW(Addr)615 ElfW(Addr) soinfo::get_verneed_ptr() const {
616   if (has_min_version(2)) {
617     return verneed_ptr_;
618   }
619 
620   return 0;
621 }
622 
get_verneed_cnt() const623 size_t soinfo::get_verneed_cnt() const {
624   if (has_min_version(2)) {
625     return verneed_cnt_;
626   }
627 
628   return 0;
629 }
630 
ElfW(Addr)631 ElfW(Addr) soinfo::get_verdef_ptr() const {
632   if (has_min_version(2)) {
633     return verdef_ptr_;
634   }
635 
636   return 0;
637 }
638 
get_verdef_cnt() const639 size_t soinfo::get_verdef_cnt() const {
640   if (has_min_version(2)) {
641     return verdef_cnt_;
642   }
643 
644   return 0;
645 }
646 
647 template<typename F>
for_each_verdef(const soinfo * si,F functor)648 static bool for_each_verdef(const soinfo* si, F functor) {
649   if (!si->has_min_version(2)) {
650     return true;
651   }
652 
653   uintptr_t verdef_ptr = si->get_verdef_ptr();
654   if (verdef_ptr == 0) {
655     return true;
656   }
657 
658   size_t offset = 0;
659 
660   size_t verdef_cnt = si->get_verdef_cnt();
661   for (size_t i = 0; i<verdef_cnt; ++i) {
662     const ElfW(Verdef)* verdef = reinterpret_cast<ElfW(Verdef)*>(verdef_ptr + offset);
663     size_t verdaux_offset = offset + verdef->vd_aux;
664     offset += verdef->vd_next;
665 
666     if (verdef->vd_version != 1) {
667       DL_ERR("unsupported verdef[%zd] vd_version: %d (expected 1) library: %s",
668           i, verdef->vd_version, si->get_realpath());
669       return false;
670     }
671 
672     if ((verdef->vd_flags & VER_FLG_BASE) != 0) {
673       // "this is the version of the file itself.  It must not be used for
674       //  matching a symbol. It can be used to match references."
675       //
676       // http://www.akkadia.org/drepper/symbol-versioning
677       continue;
678     }
679 
680     if (verdef->vd_cnt == 0) {
681       DL_ERR("invalid verdef[%zd] vd_cnt == 0 (version without a name)", i);
682       return false;
683     }
684 
685     const ElfW(Verdaux)* verdaux = reinterpret_cast<ElfW(Verdaux)*>(verdef_ptr + verdaux_offset);
686 
687     if (functor(i, verdef, verdaux) == true) {
688       break;
689     }
690   }
691 
692   return true;
693 }
694 
find_verdef_version_index(const version_info * vi,ElfW (Versym)* versym) const695 bool soinfo::find_verdef_version_index(const version_info* vi, ElfW(Versym)* versym) const {
696   if (vi == nullptr) {
697     *versym = kVersymNotNeeded;
698     return true;
699   }
700 
701   *versym = kVersymGlobal;
702 
703   return for_each_verdef(this,
704     [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
705       if (verdef->vd_hash == vi->elf_hash &&
706           strcmp(vi->name, get_string(verdaux->vda_name)) == 0) {
707         *versym = verdef->vd_ndx;
708         return true;
709       }
710 
711       return false;
712     }
713   );
714 }
715 
find_symbol_by_name(SymbolName & symbol_name,const version_info * vi,const ElfW (Sym)** symbol) const716 bool soinfo::find_symbol_by_name(SymbolName& symbol_name,
717                                  const version_info* vi,
718                                  const ElfW(Sym)** symbol) const {
719   uint32_t symbol_index;
720   bool success =
721       is_gnu_hash() ?
722       gnu_lookup(symbol_name, vi, &symbol_index) :
723       elf_lookup(symbol_name, vi, &symbol_index);
724 
725   if (success) {
726     *symbol = symbol_index == 0 ? nullptr : symtab_ + symbol_index;
727   }
728 
729   return success;
730 }
731 
is_symbol_global_and_defined(const soinfo * si,const ElfW (Sym)* s)732 static bool is_symbol_global_and_defined(const soinfo* si, const ElfW(Sym)* s) {
733   if (ELF_ST_BIND(s->st_info) == STB_GLOBAL ||
734       ELF_ST_BIND(s->st_info) == STB_WEAK) {
735     return s->st_shndx != SHN_UNDEF;
736   } else if (ELF_ST_BIND(s->st_info) != STB_LOCAL) {
737     DL_WARN("unexpected ST_BIND value: %d for \"%s\" in \"%s\"",
738             ELF_ST_BIND(s->st_info), si->get_string(s->st_name), si->get_realpath());
739   }
740 
741   return false;
742 }
743 
744 static const ElfW(Versym) kVersymHiddenBit = 0x8000;
745 
is_versym_hidden(const ElfW (Versym)* versym)746 static inline bool is_versym_hidden(const ElfW(Versym)* versym) {
747   // the symbol is hidden if bit 15 of versym is set.
748   return versym != nullptr && (*versym & kVersymHiddenBit) != 0;
749 }
750 
check_symbol_version(const ElfW (Versym)verneed,const ElfW (Versym)* verdef)751 static inline bool check_symbol_version(const ElfW(Versym) verneed,
752                                         const ElfW(Versym)* verdef) {
753   return verneed == kVersymNotNeeded ||
754       verdef == nullptr ||
755       verneed == (*verdef & ~kVersymHiddenBit);
756 }
757 
gnu_lookup(SymbolName & symbol_name,const version_info * vi,uint32_t * symbol_index) const758 bool soinfo::gnu_lookup(SymbolName& symbol_name,
759                         const version_info* vi,
760                         uint32_t* symbol_index) const {
761   uint32_t hash = symbol_name.gnu_hash();
762   uint32_t h2 = hash >> gnu_shift2_;
763 
764   uint32_t bloom_mask_bits = sizeof(ElfW(Addr))*8;
765   uint32_t word_num = (hash / bloom_mask_bits) & gnu_maskwords_;
766   ElfW(Addr) bloom_word = gnu_bloom_filter_[word_num];
767 
768   *symbol_index = 0;
769 
770   TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p (gnu)",
771       symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
772 
773   // test against bloom filter
774   if ((1 & (bloom_word >> (hash % bloom_mask_bits)) & (bloom_word >> (h2 % bloom_mask_bits))) == 0) {
775     TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p",
776         symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
777 
778     return true;
779   }
780 
781   // bloom test says "probably yes"...
782   uint32_t n = gnu_bucket_[hash % gnu_nbucket_];
783 
784   if (n == 0) {
785     TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p",
786         symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
787 
788     return true;
789   }
790 
791   // lookup versym for the version definition in this library
792   // note the difference between "version is not requested" (vi == nullptr)
793   // and "version not found". In the first case verneed is kVersymNotNeeded
794   // which implies that the default version can be accepted; the second case results in
795   // verneed = 1 (kVersymGlobal) and implies that we should ignore versioned symbols
796   // for this library and consider only *global* ones.
797   ElfW(Versym) verneed = 0;
798   if (!find_verdef_version_index(vi, &verneed)) {
799     return false;
800   }
801 
802   do {
803     ElfW(Sym)* s = symtab_ + n;
804     const ElfW(Versym)* verdef = get_versym(n);
805     // skip hidden versions when verneed == kVersymNotNeeded (0)
806     if (verneed == kVersymNotNeeded && is_versym_hidden(verdef)) {
807         continue;
808     }
809     if (((gnu_chain_[n] ^ hash) >> 1) == 0 &&
810         check_symbol_version(verneed, verdef) &&
811         strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
812         is_symbol_global_and_defined(this, s)) {
813       TRACE_TYPE(LOOKUP, "FOUND %s in %s (%p) %zd",
814           symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(s->st_value),
815           static_cast<size_t>(s->st_size));
816       *symbol_index = n;
817       return true;
818     }
819   } while ((gnu_chain_[n++] & 1) == 0);
820 
821   TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p",
822              symbol_name.get_name(), get_realpath(), reinterpret_cast<void*>(base));
823 
824   return true;
825 }
826 
elf_lookup(SymbolName & symbol_name,const version_info * vi,uint32_t * symbol_index) const827 bool soinfo::elf_lookup(SymbolName& symbol_name,
828                         const version_info* vi,
829                         uint32_t* symbol_index) const {
830   uint32_t hash = symbol_name.elf_hash();
831 
832   TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p h=%x(elf) %zd",
833              symbol_name.get_name(), get_realpath(),
834              reinterpret_cast<void*>(base), hash, hash % nbucket_);
835 
836   ElfW(Versym) verneed = 0;
837   if (!find_verdef_version_index(vi, &verneed)) {
838     return false;
839   }
840 
841   for (uint32_t n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
842     ElfW(Sym)* s = symtab_ + n;
843     const ElfW(Versym)* verdef = get_versym(n);
844 
845     // skip hidden versions when verneed == 0
846     if (verneed == kVersymNotNeeded && is_versym_hidden(verdef)) {
847         continue;
848     }
849 
850     if (check_symbol_version(verneed, verdef) &&
851         strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
852         is_symbol_global_and_defined(this, s)) {
853       TRACE_TYPE(LOOKUP, "FOUND %s in %s (%p) %zd",
854                  symbol_name.get_name(), get_realpath(),
855                  reinterpret_cast<void*>(s->st_value),
856                  static_cast<size_t>(s->st_size));
857       *symbol_index = n;
858       return true;
859     }
860   }
861 
862   TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p %x %zd",
863              symbol_name.get_name(), get_realpath(),
864              reinterpret_cast<void*>(base), hash, hash % nbucket_);
865 
866   *symbol_index = 0;
867   return true;
868 }
869 
soinfo(android_namespace_t * ns,const char * realpath,const struct stat * file_stat,off64_t file_offset,int rtld_flags)870 soinfo::soinfo(android_namespace_t* ns, const char* realpath,
871                const struct stat* file_stat, off64_t file_offset,
872                int rtld_flags) {
873   memset(this, 0, sizeof(*this));
874 
875   if (realpath != nullptr) {
876     realpath_ = realpath;
877   }
878 
879   flags_ = FLAG_NEW_SOINFO;
880   version_ = SOINFO_VERSION;
881 
882   if (file_stat != nullptr) {
883     this->st_dev_ = file_stat->st_dev;
884     this->st_ino_ = file_stat->st_ino;
885     this->file_offset_ = file_offset;
886   }
887 
888   this->rtld_flags_ = rtld_flags;
889   this->primary_namespace_ = ns;
890 }
891 
~soinfo()892 soinfo::~soinfo() {
893   g_soinfo_handles_map.erase(handle_);
894 }
895 
calculate_elf_hash(const char * name)896 static uint32_t calculate_elf_hash(const char* name) {
897   const uint8_t* name_bytes = reinterpret_cast<const uint8_t*>(name);
898   uint32_t h = 0, g;
899 
900   while (*name_bytes) {
901     h = (h << 4) + *name_bytes++;
902     g = h & 0xf0000000;
903     h ^= g;
904     h ^= g >> 24;
905   }
906 
907   return h;
908 }
909 
elf_hash()910 uint32_t SymbolName::elf_hash() {
911   if (!has_elf_hash_) {
912     elf_hash_ = calculate_elf_hash(name_);
913     has_elf_hash_ = true;
914   }
915 
916   return elf_hash_;
917 }
918 
gnu_hash()919 uint32_t SymbolName::gnu_hash() {
920   if (!has_gnu_hash_) {
921     uint32_t h = 5381;
922     const uint8_t* name = reinterpret_cast<const uint8_t*>(name_);
923     while (*name != 0) {
924       h += (h << 5) + *name++; // h*33 + c = h + h * 32 + c = h + h << 5 + c
925     }
926 
927     gnu_hash_ =  h;
928     has_gnu_hash_ = true;
929   }
930 
931   return gnu_hash_;
932 }
933 
soinfo_do_lookup(soinfo * si_from,const char * name,const version_info * vi,soinfo ** si_found_in,const soinfo::soinfo_list_t & global_group,const soinfo::soinfo_list_t & local_group,const ElfW (Sym)** symbol)934 bool soinfo_do_lookup(soinfo* si_from, const char* name, const version_info* vi,
935                       soinfo** si_found_in, const soinfo::soinfo_list_t& global_group,
936                       const soinfo::soinfo_list_t& local_group, const ElfW(Sym)** symbol) {
937   SymbolName symbol_name(name);
938   const ElfW(Sym)* s = nullptr;
939 
940   /* "This element's presence in a shared object library alters the dynamic linker's
941    * symbol resolution algorithm for references within the library. Instead of starting
942    * a symbol search with the executable file, the dynamic linker starts from the shared
943    * object itself. If the shared object fails to supply the referenced symbol, the
944    * dynamic linker then searches the executable file and other shared objects as usual."
945    *
946    * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
947    *
948    * Note that this is unlikely since static linker avoids generating
949    * relocations for -Bsymbolic linked dynamic executables.
950    */
951   if (si_from->has_DT_SYMBOLIC) {
952     DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->get_realpath(), name);
953     if (!si_from->find_symbol_by_name(symbol_name, vi, &s)) {
954       return false;
955     }
956 
957     if (s != nullptr) {
958       *si_found_in = si_from;
959     }
960   }
961 
962   // 1. Look for it in global_group
963   if (s == nullptr) {
964     bool error = false;
965     global_group.visit([&](soinfo* global_si) {
966       DEBUG("%s: looking up %s in %s (from global group)",
967           si_from->get_realpath(), name, global_si->get_realpath());
968       if (!global_si->find_symbol_by_name(symbol_name, vi, &s)) {
969         error = true;
970         return false;
971       }
972 
973       if (s != nullptr) {
974         *si_found_in = global_si;
975         return false;
976       }
977 
978       return true;
979     });
980 
981     if (error) {
982       return false;
983     }
984   }
985 
986   // 2. Look for it in the local group
987   if (s == nullptr) {
988     bool error = false;
989     local_group.visit([&](soinfo* local_si) {
990       if (local_si == si_from && si_from->has_DT_SYMBOLIC) {
991         // we already did this - skip
992         return true;
993       }
994 
995       DEBUG("%s: looking up %s in %s (from local group)",
996           si_from->get_realpath(), name, local_si->get_realpath());
997       if (!local_si->find_symbol_by_name(symbol_name, vi, &s)) {
998         error = true;
999         return false;
1000       }
1001 
1002       if (s != nullptr) {
1003         *si_found_in = local_si;
1004         return false;
1005       }
1006 
1007       return true;
1008     });
1009 
1010     if (error) {
1011       return false;
1012     }
1013   }
1014 
1015   if (s != nullptr) {
1016     TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
1017                "found in %s, base = %p, load bias = %p",
1018                si_from->get_realpath(), name, reinterpret_cast<void*>(s->st_value),
1019                (*si_found_in)->get_realpath(), reinterpret_cast<void*>((*si_found_in)->base),
1020                reinterpret_cast<void*>((*si_found_in)->load_bias));
1021   }
1022 
1023   *symbol = s;
1024   return true;
1025 }
1026 
1027 class ProtectedDataGuard {
1028  public:
ProtectedDataGuard()1029   ProtectedDataGuard() {
1030     if (ref_count_++ == 0) {
1031       protect_data(PROT_READ | PROT_WRITE);
1032     }
1033   }
1034 
~ProtectedDataGuard()1035   ~ProtectedDataGuard() {
1036     if (ref_count_ == 0) { // overflow
1037       __libc_fatal("Too many nested calls to dlopen()");
1038     }
1039 
1040     if (--ref_count_ == 0) {
1041       protect_data(PROT_READ);
1042     }
1043   }
1044  private:
protect_data(int protection)1045   void protect_data(int protection) {
1046     g_soinfo_allocator.protect_all(protection);
1047     g_soinfo_links_allocator.protect_all(protection);
1048     g_namespace_allocator.protect_all(protection);
1049     g_namespace_list_allocator.protect_all(protection);
1050   }
1051 
1052   static size_t ref_count_;
1053 };
1054 
1055 size_t ProtectedDataGuard::ref_count_ = 0;
1056 
1057 // Each size has it's own allocator.
1058 template<size_t size>
1059 class SizeBasedAllocator {
1060  public:
alloc()1061   static void* alloc() {
1062     return allocator_.alloc();
1063   }
1064 
free(void * ptr)1065   static void free(void* ptr) {
1066     allocator_.free(ptr);
1067   }
1068 
1069  private:
1070   static LinkerBlockAllocator allocator_;
1071 };
1072 
1073 template<size_t size>
1074 LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
1075 
1076 template<typename T>
1077 class TypeBasedAllocator {
1078  public:
alloc()1079   static T* alloc() {
1080     return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
1081   }
1082 
free(T * ptr)1083   static void free(T* ptr) {
1084     SizeBasedAllocator<sizeof(T)>::free(ptr);
1085   }
1086 };
1087 
1088 class LoadTask {
1089  public:
1090   struct deleter_t {
operator ()LoadTask::deleter_t1091     void operator()(LoadTask* t) {
1092       t->~LoadTask();
1093       TypeBasedAllocator<LoadTask>::free(t);
1094     }
1095   };
1096 
1097   static deleter_t deleter;
1098 
create(const char * name,soinfo * needed_by,std::unordered_map<const soinfo *,ElfReader> * readers_map)1099   static LoadTask* create(const char* name, soinfo* needed_by,
1100                           std::unordered_map<const soinfo*, ElfReader>* readers_map) {
1101     LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
1102     return new (ptr) LoadTask(name, needed_by, readers_map);
1103   }
1104 
get_name() const1105   const char* get_name() const {
1106     return name_;
1107   }
1108 
get_needed_by() const1109   soinfo* get_needed_by() const {
1110     return needed_by_;
1111   }
1112 
get_soinfo() const1113   soinfo* get_soinfo() const {
1114     return si_;
1115   }
1116 
set_soinfo(soinfo * si)1117   void set_soinfo(soinfo* si) {
1118     si_ = si;
1119   }
1120 
get_file_offset() const1121   off64_t get_file_offset() const {
1122     return file_offset_;
1123   }
1124 
set_file_offset(off64_t offset)1125   void set_file_offset(off64_t offset) {
1126     file_offset_ = offset;
1127   }
1128 
get_fd() const1129   int get_fd() const {
1130     return fd_;
1131   }
1132 
set_fd(int fd,bool assume_ownership)1133   void set_fd(int fd, bool assume_ownership) {
1134     fd_ = fd;
1135     close_fd_ = assume_ownership;
1136   }
1137 
get_extinfo() const1138   const android_dlextinfo* get_extinfo() const {
1139     return extinfo_;
1140   }
1141 
set_extinfo(const android_dlextinfo * extinfo)1142   void set_extinfo(const android_dlextinfo* extinfo) {
1143     extinfo_ = extinfo;
1144   }
1145 
is_dt_needed() const1146   bool is_dt_needed() const {
1147     return is_dt_needed_;
1148   }
1149 
set_dt_needed(bool is_dt_needed)1150   void set_dt_needed(bool is_dt_needed) {
1151     is_dt_needed_ = is_dt_needed;
1152   }
1153 
get_elf_reader() const1154   const ElfReader& get_elf_reader() const {
1155     CHECK(si_ != nullptr);
1156     return (*elf_readers_map_)[si_];
1157   }
1158 
get_elf_reader()1159   ElfReader& get_elf_reader() {
1160     CHECK(si_ != nullptr);
1161     return (*elf_readers_map_)[si_];
1162   }
1163 
get_readers_map()1164   std::unordered_map<const soinfo*, ElfReader>* get_readers_map() {
1165     return elf_readers_map_;
1166   }
1167 
read(const char * realpath,off64_t file_size)1168   bool read(const char* realpath, off64_t file_size) {
1169     ElfReader& elf_reader = get_elf_reader();
1170     return elf_reader.Read(realpath, fd_, file_offset_, file_size);
1171   }
1172 
load()1173   bool load() {
1174     ElfReader& elf_reader = get_elf_reader();
1175     if (!elf_reader.Load(extinfo_)) {
1176       return false;
1177     }
1178 
1179     si_->base = elf_reader.load_start();
1180     si_->size = elf_reader.load_size();
1181     si_->set_mapped_by_caller(elf_reader.is_mapped_by_caller());
1182     si_->load_bias = elf_reader.load_bias();
1183     si_->phnum = elf_reader.phdr_count();
1184     si_->phdr = elf_reader.loaded_phdr();
1185 
1186     return true;
1187   }
1188 
1189  private:
LoadTask(const char * name,soinfo * needed_by,std::unordered_map<const soinfo *,ElfReader> * readers_map)1190   LoadTask(const char* name, soinfo* needed_by,
1191            std::unordered_map<const soinfo*, ElfReader>* readers_map)
1192     : name_(name), needed_by_(needed_by), si_(nullptr),
1193       fd_(-1), close_fd_(false), file_offset_(0), elf_readers_map_(readers_map),
1194       is_dt_needed_(false) {}
1195 
~LoadTask()1196   ~LoadTask() {
1197     if (fd_ != -1 && close_fd_) {
1198       close(fd_);
1199     }
1200   }
1201 
1202   const char* name_;
1203   soinfo* needed_by_;
1204   soinfo* si_;
1205   const android_dlextinfo* extinfo_;
1206   int fd_;
1207   bool close_fd_;
1208   off64_t file_offset_;
1209   std::unordered_map<const soinfo*, ElfReader>* elf_readers_map_;
1210   // TODO(dimitry): needed by workaround for http://b/26394120 (the grey-list)
1211   bool is_dt_needed_;
1212   // END OF WORKAROUND
1213 
1214   DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
1215 };
1216 
1217 LoadTask::deleter_t LoadTask::deleter;
1218 
1219 template <typename T>
1220 using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
1221 
1222 typedef linked_list_t<soinfo> SoinfoLinkedList;
1223 typedef linked_list_t<const char> StringLinkedList;
1224 typedef std::vector<LoadTask*> LoadTaskList;
1225 
1226 
1227 // This function walks down the tree of soinfo dependencies
1228 // in breadth-first order and
1229 //   * calls action(soinfo* si) for each node, and
1230 //   * terminates walk if action returns false.
1231 //
1232 // walk_dependencies_tree returns false if walk was terminated
1233 // by the action and true otherwise.
1234 template<typename F>
walk_dependencies_tree(soinfo * root_soinfos[],size_t root_soinfos_size,F action)1235 static bool walk_dependencies_tree(soinfo* root_soinfos[], size_t root_soinfos_size, F action) {
1236   SoinfoLinkedList visit_list;
1237   SoinfoLinkedList visited;
1238 
1239   for (size_t i = 0; i < root_soinfos_size; ++i) {
1240     visit_list.push_back(root_soinfos[i]);
1241   }
1242 
1243   soinfo* si;
1244   while ((si = visit_list.pop_front()) != nullptr) {
1245     if (visited.contains(si)) {
1246       continue;
1247     }
1248 
1249     if (!action(si)) {
1250       return false;
1251     }
1252 
1253     visited.push_back(si);
1254 
1255     si->get_children().for_each([&](soinfo* child) {
1256       visit_list.push_back(child);
1257     });
1258   }
1259 
1260   return true;
1261 }
1262 
1263 
ElfW(Sym)1264 static const ElfW(Sym)* dlsym_handle_lookup(soinfo* root, soinfo* skip_until,
1265                                             soinfo** found, SymbolName& symbol_name,
1266                                             const version_info* vi) {
1267   const ElfW(Sym)* result = nullptr;
1268   bool skip_lookup = skip_until != nullptr;
1269 
1270   walk_dependencies_tree(&root, 1, [&](soinfo* current_soinfo) {
1271     if (skip_lookup) {
1272       skip_lookup = current_soinfo != skip_until;
1273       return true;
1274     }
1275 
1276     if (!current_soinfo->find_symbol_by_name(symbol_name, vi, &result)) {
1277       result = nullptr;
1278       return false;
1279     }
1280 
1281     if (result != nullptr) {
1282       *found = current_soinfo;
1283       return false;
1284     }
1285 
1286     return true;
1287   });
1288 
1289   return result;
1290 }
1291 
1292 static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
1293                                             const char* name,
1294                                             const version_info* vi,
1295                                             soinfo** found,
1296                                             soinfo* caller,
1297                                             void* handle);
1298 
1299 // This is used by dlsym(3).  It performs symbol lookup only within the
1300 // specified soinfo object and its dependencies in breadth first order.
ElfW(Sym)1301 static const ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found,
1302                                             const char* name, const version_info* vi) {
1303   // According to man dlopen(3) and posix docs in the case when si is handle
1304   // of the main executable we need to search not only in the executable and its
1305   // dependencies but also in all libraries loaded with RTLD_GLOBAL.
1306   //
1307   // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
1308   // libraries and they are loaded in breath-first (correct) order we can just execute
1309   // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
1310   if (si == somain) {
1311     return dlsym_linear_lookup(&g_default_namespace, name, vi, found, nullptr, RTLD_DEFAULT);
1312   }
1313 
1314   SymbolName symbol_name(name);
1315   return dlsym_handle_lookup(si, nullptr, found, symbol_name, vi);
1316 }
1317 
1318 /* This is used by dlsym(3) to performs a global symbol lookup. If the
1319    start value is null (for RTLD_DEFAULT), the search starts at the
1320    beginning of the global solist. Otherwise the search starts at the
1321    specified soinfo (for RTLD_NEXT).
1322  */
ElfW(Sym)1323 static const ElfW(Sym)* dlsym_linear_lookup(android_namespace_t* ns,
1324                                             const char* name,
1325                                             const version_info* vi,
1326                                             soinfo** found,
1327                                             soinfo* caller,
1328                                             void* handle) {
1329   SymbolName symbol_name(name);
1330 
1331   auto& soinfo_list = ns->soinfo_list();
1332   auto start = soinfo_list.begin();
1333 
1334   if (handle == RTLD_NEXT) {
1335     if (caller == nullptr) {
1336       return nullptr;
1337     } else {
1338       auto it = soinfo_list.find(caller);
1339       CHECK (it != soinfo_list.end());
1340       start = ++it;
1341     }
1342   }
1343 
1344   const ElfW(Sym)* s = nullptr;
1345   for (auto it = start, end = soinfo_list.end(); it != end; ++it) {
1346     soinfo* si = *it;
1347     // Do not skip RTLD_LOCAL libraries in dlsym(RTLD_DEFAULT, ...)
1348     // if the library is opened by application with target api level <= 22
1349     // See http://b/21565766
1350     if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0 && si->get_target_sdk_version() > 22) {
1351       continue;
1352     }
1353 
1354     if (!si->find_symbol_by_name(symbol_name, vi, &s)) {
1355       return nullptr;
1356     }
1357 
1358     if (s != nullptr) {
1359       *found = si;
1360       break;
1361     }
1362   }
1363 
1364   // If not found - use dlsym_handle_lookup for caller's
1365   // local_group unless it is part of the global group in which
1366   // case we already did it.
1367   if (s == nullptr && caller != nullptr &&
1368       (caller->get_rtld_flags() & RTLD_GLOBAL) == 0) {
1369     return dlsym_handle_lookup(caller->get_local_group_root(),
1370         (handle == RTLD_NEXT) ? caller : nullptr, found, symbol_name, vi);
1371   }
1372 
1373   if (s != nullptr) {
1374     TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
1375                name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
1376   }
1377 
1378   return s;
1379 }
1380 
find_containing_library(const void * p)1381 soinfo* find_containing_library(const void* p) {
1382   ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(p);
1383   for (soinfo* si = solist; si != nullptr; si = si->next) {
1384     if (address >= si->base && address - si->base < si->size) {
1385       return si;
1386     }
1387   }
1388   return nullptr;
1389 }
1390 
ElfW(Sym)1391 ElfW(Sym)* soinfo::find_symbol_by_address(const void* addr) {
1392   return is_gnu_hash() ? gnu_addr_lookup(addr) : elf_addr_lookup(addr);
1393 }
1394 
symbol_matches_soaddr(const ElfW (Sym)* sym,ElfW (Addr)soaddr)1395 static bool symbol_matches_soaddr(const ElfW(Sym)* sym, ElfW(Addr) soaddr) {
1396   return sym->st_shndx != SHN_UNDEF &&
1397       soaddr >= sym->st_value &&
1398       soaddr < sym->st_value + sym->st_size;
1399 }
1400 
ElfW(Sym)1401 ElfW(Sym)* soinfo::gnu_addr_lookup(const void* addr) {
1402   ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
1403 
1404   for (size_t i = 0; i < gnu_nbucket_; ++i) {
1405     uint32_t n = gnu_bucket_[i];
1406 
1407     if (n == 0) {
1408       continue;
1409     }
1410 
1411     do {
1412       ElfW(Sym)* sym = symtab_ + n;
1413       if (symbol_matches_soaddr(sym, soaddr)) {
1414         return sym;
1415       }
1416     } while ((gnu_chain_[n++] & 1) == 0);
1417   }
1418 
1419   return nullptr;
1420 }
1421 
ElfW(Sym)1422 ElfW(Sym)* soinfo::elf_addr_lookup(const void* addr) {
1423   ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - load_bias;
1424 
1425   // Search the library's symbol table for any defined symbol which
1426   // contains this address.
1427   for (size_t i = 0; i < nchain_; ++i) {
1428     ElfW(Sym)* sym = symtab_ + i;
1429     if (symbol_matches_soaddr(sym, soaddr)) {
1430       return sym;
1431     }
1432   }
1433 
1434   return nullptr;
1435 }
1436 
1437 class ZipArchiveCache {
1438  public:
ZipArchiveCache()1439   ZipArchiveCache() {}
1440   ~ZipArchiveCache();
1441 
1442   bool get_or_open(const char* zip_path, ZipArchiveHandle* handle);
1443  private:
1444   DISALLOW_COPY_AND_ASSIGN(ZipArchiveCache);
1445 
1446   std::unordered_map<std::string, ZipArchiveHandle> cache_;
1447 };
1448 
get_or_open(const char * zip_path,ZipArchiveHandle * handle)1449 bool ZipArchiveCache::get_or_open(const char* zip_path, ZipArchiveHandle* handle) {
1450   std::string key(zip_path);
1451 
1452   auto it = cache_.find(key);
1453   if (it != cache_.end()) {
1454     *handle = it->second;
1455     return true;
1456   }
1457 
1458   int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
1459   if (fd == -1) {
1460     return false;
1461   }
1462 
1463   if (OpenArchiveFd(fd, "", handle) != 0) {
1464     // invalid zip-file (?)
1465     CloseArchive(handle);
1466     close(fd);
1467     return false;
1468   }
1469 
1470   cache_[key] = *handle;
1471   return true;
1472 }
1473 
~ZipArchiveCache()1474 ZipArchiveCache::~ZipArchiveCache() {
1475   for (const auto& it : cache_) {
1476     CloseArchive(it.second);
1477   }
1478 }
1479 
open_library_in_zipfile(ZipArchiveCache * zip_archive_cache,const char * const input_path,off64_t * file_offset,std::string * realpath)1480 static int open_library_in_zipfile(ZipArchiveCache* zip_archive_cache,
1481                                    const char* const input_path,
1482                                    off64_t* file_offset, std::string* realpath) {
1483   std::string normalized_path;
1484   if (!normalize_path(input_path, &normalized_path)) {
1485     return -1;
1486   }
1487 
1488   const char* const path = normalized_path.c_str();
1489   TRACE("Trying zip file open from path \"%s\" -> normalized \"%s\"", input_path, path);
1490 
1491   // Treat an '!/' separator inside a path as the separator between the name
1492   // of the zip file on disk and the subdirectory to search within it.
1493   // For example, if path is "foo.zip!/bar/bas/x.so", then we search for
1494   // "bar/bas/x.so" within "foo.zip".
1495   const char* const separator = strstr(path, kZipFileSeparator);
1496   if (separator == nullptr) {
1497     return -1;
1498   }
1499 
1500   char buf[512];
1501   if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) {
1502     PRINT("Warning: ignoring very long library path: %s", path);
1503     return -1;
1504   }
1505 
1506   buf[separator - path] = '\0';
1507 
1508   const char* zip_path = buf;
1509   const char* file_path = &buf[separator - path + 2];
1510   int fd = TEMP_FAILURE_RETRY(open(zip_path, O_RDONLY | O_CLOEXEC));
1511   if (fd == -1) {
1512     return -1;
1513   }
1514 
1515   ZipArchiveHandle handle;
1516   if (!zip_archive_cache->get_or_open(zip_path, &handle)) {
1517     // invalid zip-file (?)
1518     close(fd);
1519     return -1;
1520   }
1521 
1522   ZipEntry entry;
1523 
1524   if (FindEntry(handle, ZipString(file_path), &entry) != 0) {
1525     // Entry was not found.
1526     close(fd);
1527     return -1;
1528   }
1529 
1530   // Check if it is properly stored
1531   if (entry.method != kCompressStored || (entry.offset % PAGE_SIZE) != 0) {
1532     close(fd);
1533     return -1;
1534   }
1535 
1536   *file_offset = entry.offset;
1537 
1538   if (realpath_fd(fd, realpath)) {
1539     *realpath += separator;
1540   } else {
1541     PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.",
1542           normalized_path.c_str());
1543     *realpath = normalized_path;
1544   }
1545 
1546   return fd;
1547 }
1548 
format_path(char * buf,size_t buf_size,const char * path,const char * name)1549 static bool format_path(char* buf, size_t buf_size, const char* path, const char* name) {
1550   int n = __libc_format_buffer(buf, buf_size, "%s/%s", path, name);
1551   if (n < 0 || n >= static_cast<int>(buf_size)) {
1552     PRINT("Warning: ignoring very long library path: %s/%s", path, name);
1553     return false;
1554   }
1555 
1556   return true;
1557 }
1558 
open_library_on_paths(ZipArchiveCache * zip_archive_cache,const char * name,off64_t * file_offset,const std::vector<std::string> & paths,std::string * realpath)1559 static int open_library_on_paths(ZipArchiveCache* zip_archive_cache,
1560                                  const char* name, off64_t* file_offset,
1561                                  const std::vector<std::string>& paths,
1562                                  std::string* realpath) {
1563   for (const auto& path : paths) {
1564     char buf[512];
1565     if (!format_path(buf, sizeof(buf), path.c_str(), name)) {
1566       continue;
1567     }
1568 
1569     int fd = -1;
1570     if (strstr(buf, kZipFileSeparator) != nullptr) {
1571       fd = open_library_in_zipfile(zip_archive_cache, buf, file_offset, realpath);
1572     }
1573 
1574     if (fd == -1) {
1575       fd = TEMP_FAILURE_RETRY(open(buf, O_RDONLY | O_CLOEXEC));
1576       if (fd != -1) {
1577         *file_offset = 0;
1578         if (!realpath_fd(fd, realpath)) {
1579           PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.", buf);
1580           *realpath = buf;
1581         }
1582       }
1583     }
1584 
1585     if (fd != -1) {
1586       return fd;
1587     }
1588   }
1589 
1590   return -1;
1591 }
1592 
open_library(android_namespace_t * ns,ZipArchiveCache * zip_archive_cache,const char * name,soinfo * needed_by,off64_t * file_offset,std::string * realpath)1593 static int open_library(android_namespace_t* ns,
1594                         ZipArchiveCache* zip_archive_cache,
1595                         const char* name, soinfo *needed_by,
1596                         off64_t* file_offset, std::string* realpath) {
1597   TRACE("[ opening %s ]", name);
1598 
1599   // If the name contains a slash, we should attempt to open it directly and not search the paths.
1600   if (strchr(name, '/') != nullptr) {
1601     int fd = -1;
1602 
1603     if (strstr(name, kZipFileSeparator) != nullptr) {
1604       fd = open_library_in_zipfile(zip_archive_cache, name, file_offset, realpath);
1605     }
1606 
1607     if (fd == -1) {
1608       fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_CLOEXEC));
1609       if (fd != -1) {
1610         *file_offset = 0;
1611         if (!realpath_fd(fd, realpath)) {
1612           PRINT("warning: unable to get realpath for the library \"%s\". Will use given path.", name);
1613           *realpath = name;
1614         }
1615       }
1616     }
1617 
1618     return fd;
1619   }
1620 
1621   // Otherwise we try LD_LIBRARY_PATH first, and fall back to the default library path
1622   int fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_ld_library_paths(), realpath);
1623   if (fd == -1 && needed_by != nullptr) {
1624     fd = open_library_on_paths(zip_archive_cache, name, file_offset, needed_by->get_dt_runpath(), realpath);
1625     // Check if the library is accessible
1626     if (fd != -1 && !ns->is_accessible(*realpath)) {
1627       fd = -1;
1628     }
1629   }
1630 
1631   if (fd == -1) {
1632     fd = open_library_on_paths(zip_archive_cache, name, file_offset, ns->get_default_library_paths(), realpath);
1633   }
1634 
1635   // TODO(dimitry): workaround for http://b/26394120 (the grey-list)
1636   if (fd == -1 && ns != &g_default_namespace && is_greylisted(name, needed_by)) {
1637     // try searching for it on default_namespace default_library_path
1638     fd = open_library_on_paths(zip_archive_cache, name, file_offset,
1639                                g_default_namespace.get_default_library_paths(), realpath);
1640   }
1641   // END OF WORKAROUND
1642 
1643   return fd;
1644 }
1645 
fix_dt_needed(const char * dt_needed,const char * sopath __unused)1646 static const char* fix_dt_needed(const char* dt_needed, const char* sopath __unused) {
1647 #if !defined(__LP64__)
1648   // Work around incorrect DT_NEEDED entries for old apps: http://b/21364029
1649   if (get_application_target_sdk_version() <= 22) {
1650     const char* bname = basename(dt_needed);
1651     if (bname != dt_needed) {
1652       DL_WARN("library \"%s\" has invalid DT_NEEDED entry \"%s\"", sopath, dt_needed);
1653       add_dlwarning(sopath, "invalid DT_NEEDED entry",  dt_needed);
1654     }
1655 
1656     return bname;
1657   }
1658 #endif
1659   return dt_needed;
1660 }
1661 
1662 template<typename F>
for_each_dt_needed(const soinfo * si,F action)1663 static void for_each_dt_needed(const soinfo* si, F action) {
1664   for (const ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
1665     if (d->d_tag == DT_NEEDED) {
1666       action(fix_dt_needed(si->get_string(d->d_un.d_val), si->get_realpath()));
1667     }
1668   }
1669 }
1670 
1671 template<typename F>
for_each_dt_needed(const ElfReader & elf_reader,F action)1672 static void for_each_dt_needed(const ElfReader& elf_reader, F action) {
1673   for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1674     if (d->d_tag == DT_NEEDED) {
1675       action(fix_dt_needed(elf_reader.get_string(d->d_un.d_val), elf_reader.name()));
1676     }
1677   }
1678 }
1679 
load_library(android_namespace_t * ns,LoadTask * task,LoadTaskList * load_tasks,int rtld_flags,const std::string & realpath)1680 static bool load_library(android_namespace_t* ns,
1681                          LoadTask* task,
1682                          LoadTaskList* load_tasks,
1683                          int rtld_flags,
1684                          const std::string& realpath) {
1685   off64_t file_offset = task->get_file_offset();
1686   const char* name = task->get_name();
1687   const android_dlextinfo* extinfo = task->get_extinfo();
1688 
1689   if ((file_offset % PAGE_SIZE) != 0) {
1690     DL_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
1691     return false;
1692   }
1693   if (file_offset < 0) {
1694     DL_ERR("file offset for the library \"%s\" is negative: %" PRId64, name, file_offset);
1695     return false;
1696   }
1697 
1698   struct stat file_stat;
1699   if (TEMP_FAILURE_RETRY(fstat(task->get_fd(), &file_stat)) != 0) {
1700     DL_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
1701     return false;
1702   }
1703   if (file_offset >= file_stat.st_size) {
1704     DL_ERR("file offset for the library \"%s\" >= file size: %" PRId64 " >= %" PRId64,
1705         name, file_offset, file_stat.st_size);
1706     return false;
1707   }
1708 
1709   // Check for symlink and other situations where
1710   // file can have different names, unless ANDROID_DLEXT_FORCE_LOAD is set
1711   if (extinfo == nullptr || (extinfo->flags & ANDROID_DLEXT_FORCE_LOAD) == 0) {
1712     auto predicate = [&](soinfo* si) {
1713       return si->get_st_dev() != 0 &&
1714              si->get_st_ino() != 0 &&
1715              si->get_st_dev() == file_stat.st_dev &&
1716              si->get_st_ino() == file_stat.st_ino &&
1717              si->get_file_offset() == file_offset;
1718     };
1719 
1720     soinfo* si = ns->soinfo_list().find_if(predicate);
1721 
1722     // check public namespace
1723     if (si == nullptr) {
1724       si = g_public_namespace.find_if(predicate);
1725       if (si != nullptr) {
1726         ns->add_soinfo(si);
1727       }
1728     }
1729 
1730     if (si != nullptr) {
1731       TRACE("library \"%s\" is already loaded under different name/path \"%s\" - "
1732             "will return existing soinfo", name, si->get_realpath());
1733       task->set_soinfo(si);
1734       return true;
1735     }
1736   }
1737 
1738   if ((rtld_flags & RTLD_NOLOAD) != 0) {
1739     DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
1740     return false;
1741   }
1742 
1743   if (!ns->is_accessible(realpath)) {
1744     // TODO(dimitry): workaround for http://b/26394120 - the grey-list
1745     const soinfo* needed_by = task->is_dt_needed() ? task->get_needed_by() : nullptr;
1746     if (is_greylisted(name, needed_by)) {
1747       // print warning only if needed by non-system library
1748       if (needed_by == nullptr || !is_system_library(needed_by->get_realpath())) {
1749         const soinfo* needed_or_dlopened_by = task->get_needed_by();
1750         const char* sopath = needed_or_dlopened_by == nullptr ? "(unknown)" :
1751                                                       needed_or_dlopened_by->get_realpath();
1752         DL_WARN("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the namespace \"%s\""
1753                 " - the access is temporarily granted as a workaround for http://b/26394120, note that the access"
1754                 " will be removed in future releases of Android.",
1755                 name, realpath.c_str(), sopath, ns->get_name());
1756         add_dlwarning(sopath, "unauthorized access to",  name);
1757       }
1758     } else {
1759       // do not load libraries if they are not accessible for the specified namespace.
1760       const char* needed_or_dlopened_by = task->get_needed_by() == nullptr ?
1761                                           "(unknown)" :
1762                                           task->get_needed_by()->get_realpath();
1763 
1764       DL_ERR("library \"%s\" needed or dlopened by \"%s\" is not accessible for the namespace \"%s\"",
1765              name, needed_or_dlopened_by, ns->get_name());
1766 
1767       PRINT("library \"%s\" (\"%s\") needed or dlopened by \"%s\" is not accessible for the"
1768             " namespace: [name=\"%s\", ld_library_paths=\"%s\", default_library_paths=\"%s\","
1769             " permitted_paths=\"%s\"]",
1770             name, realpath.c_str(),
1771             needed_or_dlopened_by,
1772             ns->get_name(),
1773             android::base::Join(ns->get_ld_library_paths(), ':').c_str(),
1774             android::base::Join(ns->get_default_library_paths(), ':').c_str(),
1775             android::base::Join(ns->get_permitted_paths(), ':').c_str());
1776       return false;
1777     }
1778   }
1779 
1780   soinfo* si = soinfo_alloc(ns, realpath.c_str(), &file_stat, file_offset, rtld_flags);
1781   if (si == nullptr) {
1782     return false;
1783   }
1784 
1785   task->set_soinfo(si);
1786 
1787   // Read the ELF header and some of the segments.
1788   if (!task->read(realpath.c_str(), file_stat.st_size)) {
1789     soinfo_free(si);
1790     task->set_soinfo(nullptr);
1791     return false;
1792   }
1793 
1794   // find and set DT_RUNPATH and dt_soname
1795   // Note that these field values are temporary and are
1796   // going to be overwritten on soinfo::prelink_image
1797   // with values from PT_LOAD segments.
1798   const ElfReader& elf_reader = task->get_elf_reader();
1799   for (const ElfW(Dyn)* d = elf_reader.dynamic(); d->d_tag != DT_NULL; ++d) {
1800     if (d->d_tag == DT_RUNPATH) {
1801       si->set_dt_runpath(elf_reader.get_string(d->d_un.d_val));
1802     }
1803     if (d->d_tag == DT_SONAME) {
1804       si->set_soname(elf_reader.get_string(d->d_un.d_val));
1805     }
1806   }
1807 
1808   for_each_dt_needed(task->get_elf_reader(), [&](const char* name) {
1809     load_tasks->push_back(LoadTask::create(name, si, task->get_readers_map()));
1810   });
1811 
1812   return true;
1813 }
1814 
load_library(android_namespace_t * ns,LoadTask * task,ZipArchiveCache * zip_archive_cache,LoadTaskList * load_tasks,int rtld_flags)1815 static bool load_library(android_namespace_t* ns,
1816                          LoadTask* task,
1817                          ZipArchiveCache* zip_archive_cache,
1818                          LoadTaskList* load_tasks,
1819                          int rtld_flags) {
1820   const char* name = task->get_name();
1821   soinfo* needed_by = task->get_needed_by();
1822   const android_dlextinfo* extinfo = task->get_extinfo();
1823 
1824   off64_t file_offset;
1825   std::string realpath;
1826   if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
1827     file_offset = 0;
1828     if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1829       file_offset = extinfo->library_fd_offset;
1830     }
1831 
1832     if (!realpath_fd(extinfo->library_fd, &realpath)) {
1833       PRINT("warning: unable to get realpath for the library \"%s\" by extinfo->library_fd. "
1834             "Will use given name.", name);
1835       realpath = name;
1836     }
1837 
1838     task->set_fd(extinfo->library_fd, false);
1839     task->set_file_offset(file_offset);
1840     return load_library(ns, task, load_tasks, rtld_flags, realpath);
1841   }
1842 
1843   // Open the file.
1844   int fd = open_library(ns, zip_archive_cache, name, needed_by, &file_offset, &realpath);
1845   if (fd == -1) {
1846     DL_ERR("library \"%s\" not found", name);
1847     return false;
1848   }
1849 
1850   task->set_fd(fd, true);
1851   task->set_file_offset(file_offset);
1852 
1853   return load_library(ns, task, load_tasks, rtld_flags, realpath);
1854 }
1855 
1856 // Returns true if library was found and false in 2 cases
1857 // 1. (for default namespace only) The library was found but loaded under different
1858 //    target_sdk_version (*candidate != nullptr)
1859 // 2. The library was not found by soname (*candidate is nullptr)
find_loaded_library_by_soname(android_namespace_t * ns,const char * name,soinfo ** candidate)1860 static bool find_loaded_library_by_soname(android_namespace_t* ns,
1861                                           const char* name, soinfo** candidate) {
1862   *candidate = nullptr;
1863 
1864   // Ignore filename with path.
1865   if (strchr(name, '/') != nullptr) {
1866     return false;
1867   }
1868 
1869   uint32_t target_sdk_version = get_application_target_sdk_version();
1870 
1871   return !ns->soinfo_list().visit([&](soinfo* si) {
1872     const char* soname = si->get_soname();
1873     if (soname != nullptr && (strcmp(name, soname) == 0)) {
1874       // If the library was opened under different target sdk version
1875       // skip this step and try to reopen it. The exceptions are
1876       // "libdl.so" and global group. There is no point in skipping
1877       // them because relocation process is going to use them
1878       // in any case.
1879       bool is_libdl = si == solist;
1880       if (is_libdl || (si->get_dt_flags_1() & DF_1_GLOBAL) != 0 ||
1881           !si->is_linked() || si->get_target_sdk_version() == target_sdk_version ||
1882           ns != &g_default_namespace) {
1883         *candidate = si;
1884         return false;
1885       } else if (*candidate == nullptr) {
1886         // for the different sdk version in the default namespace
1887         // remember the first library.
1888         *candidate = si;
1889       }
1890     }
1891 
1892     return true;
1893   });
1894 }
1895 
find_library_internal(android_namespace_t * ns,LoadTask * task,ZipArchiveCache * zip_archive_cache,LoadTaskList * load_tasks,int rtld_flags)1896 static bool find_library_internal(android_namespace_t* ns,
1897                                   LoadTask* task,
1898                                   ZipArchiveCache* zip_archive_cache,
1899                                   LoadTaskList* load_tasks,
1900                                   int rtld_flags) {
1901   soinfo* candidate;
1902 
1903   if (find_loaded_library_by_soname(ns, task->get_name(), &candidate)) {
1904     task->set_soinfo(candidate);
1905     return true;
1906   }
1907 
1908   if (ns != &g_default_namespace) {
1909     // check public namespace
1910     candidate = g_public_namespace.find_if([&](soinfo* si) {
1911       return strcmp(task->get_name(), si->get_soname()) == 0;
1912     });
1913 
1914     if (candidate != nullptr) {
1915       ns->add_soinfo(candidate);
1916       task->set_soinfo(candidate);
1917       return true;
1918     }
1919   }
1920 
1921   // Library might still be loaded, the accurate detection
1922   // of this fact is done by load_library.
1923   TRACE("[ \"%s\" find_loaded_library_by_soname failed (*candidate=%s@%p). Trying harder...]",
1924       task->get_name(), candidate == nullptr ? "n/a" : candidate->get_realpath(), candidate);
1925 
1926   if (load_library(ns, task, zip_archive_cache, load_tasks, rtld_flags)) {
1927     return true;
1928   } else {
1929     // In case we were unable to load the library but there
1930     // is a candidate loaded under the same soname but different
1931     // sdk level - return it anyways.
1932     if (candidate != nullptr) {
1933       task->set_soinfo(candidate);
1934       return true;
1935     }
1936   }
1937 
1938   return false;
1939 }
1940 
1941 static void soinfo_unload(soinfo* si);
1942 static void soinfo_unload(soinfo* soinfos[], size_t count);
1943 
1944 // TODO: this is slightly unusual way to construct
1945 // the global group for relocation. Not every RTLD_GLOBAL
1946 // library is included in this group for backwards-compatibility
1947 // reasons.
1948 //
1949 // This group consists of the main executable, LD_PRELOADs
1950 // and libraries with the DF_1_GLOBAL flag set.
make_global_group(android_namespace_t * ns)1951 static soinfo::soinfo_list_t make_global_group(android_namespace_t* ns) {
1952   soinfo::soinfo_list_t global_group;
1953   ns->soinfo_list().for_each([&](soinfo* si) {
1954     if ((si->get_dt_flags_1() & DF_1_GLOBAL) != 0) {
1955       global_group.push_back(si);
1956     }
1957   });
1958 
1959   return global_group;
1960 }
1961 
1962 // This function provides a list of libraries to be shared
1963 // by the namespace. For the default namespace this is the global
1964 // group (see make_global_group). For all others this is a group
1965 // of RTLD_GLOBAL libraries (which includes the global group from
1966 // the default namespace).
get_shared_group(android_namespace_t * ns)1967 static soinfo::soinfo_list_t get_shared_group(android_namespace_t* ns) {
1968   if (ns == &g_default_namespace) {
1969     return make_global_group(ns);
1970   }
1971 
1972   soinfo::soinfo_list_t shared_group;
1973   ns->soinfo_list().for_each([&](soinfo* si) {
1974     if ((si->get_rtld_flags() & RTLD_GLOBAL) != 0) {
1975       shared_group.push_back(si);
1976     }
1977   });
1978 
1979   return shared_group;
1980 }
1981 
shuffle(std::vector<LoadTask * > * v)1982 static void shuffle(std::vector<LoadTask*>* v) {
1983   for (size_t i = 0, size = v->size(); i < size; ++i) {
1984     size_t n = size - i;
1985     size_t r = arc4random_uniform(n);
1986     std::swap((*v)[n-1], (*v)[r]);
1987   }
1988 }
1989 
1990 // add_as_children - add first-level loaded libraries (i.e. library_names[], but
1991 // not their transitive dependencies) as children of the start_with library.
1992 // This is false when find_libraries is called for dlopen(), when newly loaded
1993 // libraries must form a disjoint tree.
find_libraries(android_namespace_t * ns,soinfo * start_with,const char * const library_names[],size_t library_names_count,soinfo * soinfos[],std::vector<soinfo * > * ld_preloads,size_t ld_preloads_count,int rtld_flags,const android_dlextinfo * extinfo,bool add_as_children)1994 static bool find_libraries(android_namespace_t* ns,
1995                            soinfo* start_with,
1996                            const char* const library_names[],
1997                            size_t library_names_count, soinfo* soinfos[],
1998                            std::vector<soinfo*>* ld_preloads,
1999                            size_t ld_preloads_count, int rtld_flags,
2000                            const android_dlextinfo* extinfo,
2001                            bool add_as_children) {
2002   // Step 0: prepare.
2003   LoadTaskList load_tasks;
2004   std::unordered_map<const soinfo*, ElfReader> readers_map;
2005 
2006   for (size_t i = 0; i < library_names_count; ++i) {
2007     const char* name = library_names[i];
2008     load_tasks.push_back(LoadTask::create(name, start_with, &readers_map));
2009   }
2010 
2011   // Construct global_group.
2012   soinfo::soinfo_list_t global_group = make_global_group(ns);
2013 
2014   // If soinfos array is null allocate one on stack.
2015   // The array is needed in case of failure; for example
2016   // when library_names[] = {libone.so, libtwo.so} and libone.so
2017   // is loaded correctly but libtwo.so failed for some reason.
2018   // In this case libone.so should be unloaded on return.
2019   // See also implementation of failure_guard below.
2020 
2021   if (soinfos == nullptr) {
2022     size_t soinfos_size = sizeof(soinfo*)*library_names_count;
2023     soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
2024     memset(soinfos, 0, soinfos_size);
2025   }
2026 
2027   // list of libraries to link - see step 2.
2028   size_t soinfos_count = 0;
2029 
2030   auto scope_guard = make_scope_guard([&]() {
2031     for (LoadTask* t : load_tasks) {
2032       LoadTask::deleter(t);
2033     }
2034   });
2035 
2036   auto failure_guard = make_scope_guard([&]() {
2037     // Housekeeping
2038     soinfo_unload(soinfos, soinfos_count);
2039   });
2040 
2041   ZipArchiveCache zip_archive_cache;
2042 
2043   // Step 1: expand the list of load_tasks to include
2044   // all DT_NEEDED libraries (do not load them just yet)
2045   for (size_t i = 0; i<load_tasks.size(); ++i) {
2046     LoadTask* task = load_tasks[i];
2047     soinfo* needed_by = task->get_needed_by();
2048 
2049     bool is_dt_needed = needed_by != nullptr && (needed_by != start_with || add_as_children);
2050     task->set_extinfo(is_dt_needed ? nullptr : extinfo);
2051     task->set_dt_needed(is_dt_needed);
2052 
2053     if(!find_library_internal(ns, task, &zip_archive_cache, &load_tasks, rtld_flags)) {
2054       return false;
2055     }
2056 
2057     soinfo* si = task->get_soinfo();
2058 
2059     if (is_dt_needed) {
2060       needed_by->add_child(si);
2061     }
2062 
2063     if (si->is_linked()) {
2064       si->increment_ref_count();
2065     }
2066 
2067     // When ld_preloads is not null, the first
2068     // ld_preloads_count libs are in fact ld_preloads.
2069     if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
2070       ld_preloads->push_back(si);
2071     }
2072 
2073     if (soinfos_count < library_names_count) {
2074       soinfos[soinfos_count++] = si;
2075     }
2076   }
2077 
2078   // Step 2: Load libraries in random order (see b/24047022)
2079   LoadTaskList load_list;
2080   for (auto&& task : load_tasks) {
2081     soinfo* si = task->get_soinfo();
2082     auto pred = [&](const LoadTask* t) {
2083       return t->get_soinfo() == si;
2084     };
2085 
2086     if (!si->is_linked() &&
2087         std::find_if(load_list.begin(), load_list.end(), pred) == load_list.end() ) {
2088       load_list.push_back(task);
2089     }
2090   }
2091   shuffle(&load_list);
2092 
2093   for (auto&& task : load_list) {
2094     if (!task->load()) {
2095       return false;
2096     }
2097   }
2098 
2099   // Step 3: pre-link all DT_NEEDED libraries in breadth first order.
2100   for (auto&& task : load_tasks) {
2101     soinfo* si = task->get_soinfo();
2102     if (!si->is_linked() && !si->prelink_image()) {
2103       return false;
2104     }
2105   }
2106 
2107   // Step 4: Add LD_PRELOADed libraries to the global group for
2108   // future runs. There is no need to explicitly add them to
2109   // the global group for this run because they are going to
2110   // appear in the local group in the correct order.
2111   if (ld_preloads != nullptr) {
2112     for (auto&& si : *ld_preloads) {
2113       si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
2114     }
2115   }
2116 
2117 
2118   // Step 5: link libraries.
2119   soinfo::soinfo_list_t local_group;
2120   walk_dependencies_tree(
2121       (start_with != nullptr && add_as_children) ? &start_with : soinfos,
2122       (start_with != nullptr && add_as_children) ? 1 : soinfos_count,
2123       [&] (soinfo* si) {
2124     local_group.push_back(si);
2125     return true;
2126   });
2127 
2128   // We need to increment ref_count in case
2129   // the root of the local group was not linked.
2130   bool was_local_group_root_linked = local_group.front()->is_linked();
2131 
2132   bool linked = local_group.visit([&](soinfo* si) {
2133     if (!si->is_linked()) {
2134       if (!si->link_image(global_group, local_group, extinfo)) {
2135         return false;
2136       }
2137     }
2138 
2139     return true;
2140   });
2141 
2142   if (linked) {
2143     local_group.for_each([](soinfo* si) {
2144       if (!si->is_linked()) {
2145         si->set_linked();
2146       }
2147     });
2148 
2149     failure_guard.disable();
2150   }
2151 
2152   if (!was_local_group_root_linked) {
2153     local_group.front()->increment_ref_count();
2154   }
2155 
2156   return linked;
2157 }
2158 
find_library(android_namespace_t * ns,const char * name,int rtld_flags,const android_dlextinfo * extinfo,soinfo * needed_by)2159 static soinfo* find_library(android_namespace_t* ns,
2160                             const char* name, int rtld_flags,
2161                             const android_dlextinfo* extinfo,
2162                             soinfo* needed_by) {
2163   soinfo* si;
2164 
2165   if (name == nullptr) {
2166     si = somain;
2167   } else if (!find_libraries(ns, needed_by, &name, 1, &si, nullptr, 0, rtld_flags,
2168                              extinfo, /* add_as_children */ false)) {
2169     return nullptr;
2170   }
2171 
2172   return si;
2173 }
2174 
soinfo_unload(soinfo * root)2175 static void soinfo_unload(soinfo* root) {
2176   if (root->is_linked()) {
2177     root = root->get_local_group_root();
2178   }
2179 
2180   if (!root->can_unload()) {
2181     TRACE("not unloading \"%s\" - the binary is flagged with NODELETE", root->get_realpath());
2182     return;
2183   }
2184 
2185   soinfo_unload(&root, 1);
2186 }
2187 
soinfo_unload(soinfo * soinfos[],size_t count)2188 static void soinfo_unload(soinfo* soinfos[], size_t count) {
2189   // Note that the library can be loaded but not linked;
2190   // in which case there is no root but we still need
2191   // to walk the tree and unload soinfos involved.
2192   //
2193   // This happens on unsuccessful dlopen, when one of
2194   // the DT_NEEDED libraries could not be linked/found.
2195   if (count == 0) {
2196     return;
2197   }
2198 
2199   soinfo::soinfo_list_t unload_list;
2200   for (size_t i = 0; i < count; ++i) {
2201     soinfo* si = soinfos[i];
2202 
2203     if (si->can_unload()) {
2204       size_t ref_count = si->is_linked() ? si->decrement_ref_count() : 0;
2205       if (ref_count == 0) {
2206         unload_list.push_back(si);
2207       } else {
2208         TRACE("not unloading '%s' group, decrementing ref_count to %zd",
2209             si->get_realpath(), ref_count);
2210       }
2211     } else {
2212       TRACE("not unloading '%s' - the binary is flagged with NODELETE", si->get_realpath());
2213       return;
2214     }
2215   }
2216 
2217   // This is used to identify soinfos outside of the load-group
2218   // note that we cannot have > 1 in the array and have any of them
2219   // linked. This is why we can safely use the first one.
2220   soinfo* root = soinfos[0];
2221 
2222   soinfo::soinfo_list_t local_unload_list;
2223   soinfo::soinfo_list_t external_unload_list;
2224   soinfo* si = nullptr;
2225 
2226   while ((si = unload_list.pop_front()) != nullptr) {
2227     if (local_unload_list.contains(si)) {
2228       continue;
2229     }
2230 
2231     local_unload_list.push_back(si);
2232 
2233     if (si->has_min_version(0)) {
2234       soinfo* child = nullptr;
2235       while ((child = si->get_children().pop_front()) != nullptr) {
2236         TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
2237             child->get_realpath(), child);
2238 
2239         if (local_unload_list.contains(child)) {
2240           continue;
2241         } else if (child->is_linked() && child->get_local_group_root() != root) {
2242           external_unload_list.push_back(child);
2243         } else {
2244           unload_list.push_front(child);
2245         }
2246       }
2247     } else {
2248 #if !defined(__work_around_b_24465209__)
2249       __libc_fatal("soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
2250 #else
2251       PRINT("warning: soinfo for \"%s\"@%p has no version", si->get_realpath(), si);
2252       for_each_dt_needed(si, [&] (const char* library_name) {
2253         TRACE("deprecated (old format of soinfo): %s needs to unload %s",
2254             si->get_realpath(), library_name);
2255 
2256         soinfo* needed = find_library(si->get_primary_namespace(),
2257                                       library_name, RTLD_NOLOAD, nullptr, nullptr);
2258 
2259         if (needed != nullptr) {
2260           // Not found: for example if symlink was deleted between dlopen and dlclose
2261           // Since we cannot really handle errors at this point - print and continue.
2262           PRINT("warning: couldn't find %s needed by %s on unload.",
2263               library_name, si->get_realpath());
2264           return;
2265         } else if (local_unload_list.contains(needed)) {
2266           // already visited
2267           return;
2268         } else if (needed->is_linked() && needed->get_local_group_root() != root) {
2269           // external group
2270           external_unload_list.push_back(needed);
2271         } else {
2272           // local group
2273           unload_list.push_front(needed);
2274         }
2275       });
2276 #endif
2277     }
2278   }
2279 
2280   local_unload_list.for_each([](soinfo* si) {
2281     si->call_destructors();
2282   });
2283 
2284   while ((si = local_unload_list.pop_front()) != nullptr) {
2285     notify_gdb_of_unload(si);
2286     soinfo_free(si);
2287   }
2288 
2289   while ((si = external_unload_list.pop_front()) != nullptr) {
2290     soinfo_unload(si);
2291   }
2292 }
2293 
symbol_display_name(const char * sym_name,const char * sym_ver)2294 static std::string symbol_display_name(const char* sym_name, const char* sym_ver) {
2295   if (sym_ver == nullptr) {
2296     return sym_name;
2297   }
2298 
2299   return std::string(sym_name) + ", version " + sym_ver;
2300 }
2301 
get_caller_namespace(soinfo * caller)2302 static android_namespace_t* get_caller_namespace(soinfo* caller) {
2303   return caller != nullptr ? caller->get_primary_namespace() : g_anonymous_namespace;
2304 }
2305 
do_android_get_LD_LIBRARY_PATH(char * buffer,size_t buffer_size)2306 void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
2307   // Use basic string manipulation calls to avoid snprintf.
2308   // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
2309   // When debug malloc is enabled, this call returns 0. This in turn causes
2310   // snprintf to do nothing, which causes libraries to fail to load.
2311   // See b/17302493 for further details.
2312   // Once the above bug is fixed, this code can be modified to use
2313   // snprintf again.
2314   size_t required_len = 0;
2315   for (size_t i = 0; g_default_ld_paths[i] != nullptr; ++i) {
2316     required_len += strlen(g_default_ld_paths[i]) + 1;
2317   }
2318   if (buffer_size < required_len) {
2319     __libc_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: "
2320                  "buffer len %zu, required len %zu", buffer_size, required_len);
2321   }
2322   char* end = buffer;
2323   for (size_t i = 0; g_default_ld_paths[i] != nullptr; ++i) {
2324     if (i > 0) *end++ = ':';
2325     end = stpcpy(end, g_default_ld_paths[i]);
2326   }
2327 }
2328 
do_android_update_LD_LIBRARY_PATH(const char * ld_library_path)2329 void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
2330   parse_LD_LIBRARY_PATH(ld_library_path);
2331 }
2332 
do_dlopen(const char * name,int flags,const android_dlextinfo * extinfo,void * caller_addr)2333 void* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo,
2334                   void* caller_addr) {
2335   soinfo* const caller = find_containing_library(caller_addr);
2336 
2337   if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
2338     DL_ERR("invalid flags to dlopen: %x", flags);
2339     return nullptr;
2340   }
2341 
2342   android_namespace_t* ns = get_caller_namespace(caller);
2343 
2344   if (extinfo != nullptr) {
2345     if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
2346       DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
2347       return nullptr;
2348     }
2349 
2350     if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
2351         (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
2352       DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without "
2353           "ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
2354       return nullptr;
2355     }
2356 
2357     if ((extinfo->flags & ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS) != 0 &&
2358         (extinfo->flags & (ANDROID_DLEXT_RESERVED_ADDRESS | ANDROID_DLEXT_RESERVED_ADDRESS_HINT)) != 0) {
2359       DL_ERR("invalid extended flag combination: ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS is not "
2360              "compatible with ANDROID_DLEXT_RESERVED_ADDRESS/ANDROID_DLEXT_RESERVED_ADDRESS_HINT");
2361       return nullptr;
2362     }
2363 
2364     if ((extinfo->flags & ANDROID_DLEXT_USE_NAMESPACE) != 0) {
2365       if (extinfo->library_namespace == nullptr) {
2366         DL_ERR("ANDROID_DLEXT_USE_NAMESPACE is set but extinfo->library_namespace is null");
2367         return nullptr;
2368       }
2369       ns = extinfo->library_namespace;
2370     }
2371   }
2372 
2373   ProtectedDataGuard guard;
2374   soinfo* si = find_library(ns, name, flags, extinfo, caller);
2375   if (si != nullptr) {
2376     si->call_constructors();
2377     return si->to_handle();
2378   }
2379 
2380   return nullptr;
2381 }
2382 
do_dladdr(const void * addr,Dl_info * info)2383 int do_dladdr(const void* addr, Dl_info* info) {
2384   // Determine if this address can be found in any library currently mapped.
2385   soinfo* si = find_containing_library(addr);
2386   if (si == nullptr) {
2387     return 0;
2388   }
2389 
2390   memset(info, 0, sizeof(Dl_info));
2391 
2392   info->dli_fname = si->get_realpath();
2393   // Address at which the shared object is loaded.
2394   info->dli_fbase = reinterpret_cast<void*>(si->base);
2395 
2396   // Determine if any symbol in the library contains the specified address.
2397   ElfW(Sym)* sym = si->find_symbol_by_address(addr);
2398   if (sym != nullptr) {
2399     info->dli_sname = si->get_string(sym->st_name);
2400     info->dli_saddr = reinterpret_cast<void*>(si->resolve_symbol_address(sym));
2401   }
2402 
2403   return 1;
2404 }
2405 
soinfo_from_handle(void * handle)2406 static soinfo* soinfo_from_handle(void* handle) {
2407   if ((reinterpret_cast<uintptr_t>(handle) & 1) != 0) {
2408     auto it = g_soinfo_handles_map.find(reinterpret_cast<uintptr_t>(handle));
2409     if (it == g_soinfo_handles_map.end()) {
2410       return nullptr;
2411     } else {
2412       return it->second;
2413     }
2414   }
2415 
2416   return static_cast<soinfo*>(handle);
2417 }
2418 
do_dlsym(void * handle,const char * sym_name,const char * sym_ver,void * caller_addr,void ** symbol)2419 bool do_dlsym(void* handle, const char* sym_name, const char* sym_ver,
2420               void* caller_addr, void** symbol) {
2421 #if !defined(__LP64__)
2422   if (handle == nullptr) {
2423     DL_ERR("dlsym failed: library handle is null");
2424     return false;
2425   }
2426 #endif
2427 
2428   if (sym_name == nullptr) {
2429     DL_ERR("dlsym failed: symbol name is null");
2430     return false;
2431   }
2432 
2433   soinfo* found = nullptr;
2434   const ElfW(Sym)* sym = nullptr;
2435   soinfo* caller = find_containing_library(caller_addr);
2436   android_namespace_t* ns = get_caller_namespace(caller);
2437 
2438   version_info vi_instance;
2439   version_info* vi = nullptr;
2440 
2441   if (sym_ver != nullptr) {
2442     vi_instance.name = sym_ver;
2443     vi_instance.elf_hash = calculate_elf_hash(sym_ver);
2444     vi = &vi_instance;
2445   }
2446 
2447   if (handle == RTLD_DEFAULT || handle == RTLD_NEXT) {
2448     sym = dlsym_linear_lookup(ns, sym_name, vi, &found, caller, handle);
2449   } else {
2450     soinfo* si = soinfo_from_handle(handle);
2451     if (si == nullptr) {
2452       DL_ERR("dlsym failed: invalid handle: %p", handle);
2453       return false;
2454     }
2455     sym = dlsym_handle_lookup(si, &found, sym_name, vi);
2456   }
2457 
2458   if (sym != nullptr) {
2459     uint32_t bind = ELF_ST_BIND(sym->st_info);
2460 
2461     if ((bind == STB_GLOBAL || bind == STB_WEAK) && sym->st_shndx != 0) {
2462       *symbol = reinterpret_cast<void*>(found->resolve_symbol_address(sym));
2463       return true;
2464     }
2465 
2466     DL_ERR("symbol \"%s\" found but not global", symbol_display_name(sym_name, sym_ver).c_str());
2467     return false;
2468   }
2469 
2470   DL_ERR("undefined symbol: %s", symbol_display_name(sym_name, sym_ver).c_str());
2471   return false;
2472 }
2473 
do_dlclose(void * handle)2474 int do_dlclose(void* handle) {
2475   ProtectedDataGuard guard;
2476   soinfo* si = soinfo_from_handle(handle);
2477   if (si == nullptr) {
2478     DL_ERR("invalid handle: %p", handle);
2479     return -1;
2480   }
2481 
2482   soinfo_unload(si);
2483   return 0;
2484 }
2485 
init_namespaces(const char * public_ns_sonames,const char * anon_ns_library_path)2486 bool init_namespaces(const char* public_ns_sonames, const char* anon_ns_library_path) {
2487   CHECK(public_ns_sonames != nullptr);
2488   if (g_public_namespace_initialized) {
2489     DL_ERR("public namespace has already been initialized.");
2490     return false;
2491   }
2492 
2493   std::vector<std::string> sonames = android::base::Split(public_ns_sonames, ":");
2494 
2495   ProtectedDataGuard guard;
2496 
2497   auto failure_guard = make_scope_guard([&]() {
2498     g_public_namespace.clear();
2499   });
2500 
2501   for (const auto& soname : sonames) {
2502     soinfo* candidate = nullptr;
2503 
2504     find_loaded_library_by_soname(&g_default_namespace, soname.c_str(), &candidate);
2505 
2506     if (candidate == nullptr) {
2507       DL_ERR("error initializing public namespace: \"%s\" was not found"
2508              " in the default namespace", soname.c_str());
2509       return false;
2510     }
2511 
2512     candidate->set_nodelete();
2513     g_public_namespace.push_back(candidate);
2514   }
2515 
2516   g_public_namespace_initialized = true;
2517 
2518   // create anonymous namespace
2519   // When the caller is nullptr - create_namespace will take global group
2520   // from the anonymous namespace, which is fine because anonymous namespace
2521   // is still pointing to the default one.
2522   android_namespace_t* anon_ns =
2523       create_namespace(nullptr, "(anonymous)", nullptr, anon_ns_library_path,
2524                        ANDROID_NAMESPACE_TYPE_REGULAR, nullptr, &g_default_namespace);
2525 
2526   if (anon_ns == nullptr) {
2527     g_public_namespace_initialized = false;
2528     return false;
2529   }
2530   g_anonymous_namespace = anon_ns;
2531   failure_guard.disable();
2532   return true;
2533 }
2534 
create_namespace(const void * caller_addr,const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,android_namespace_t * parent_namespace)2535 android_namespace_t* create_namespace(const void* caller_addr,
2536                                       const char* name,
2537                                       const char* ld_library_path,
2538                                       const char* default_library_path,
2539                                       uint64_t type,
2540                                       const char* permitted_when_isolated_path,
2541                                       android_namespace_t* parent_namespace) {
2542   if (!g_public_namespace_initialized) {
2543     DL_ERR("cannot create namespace: public namespace is not initialized.");
2544     return nullptr;
2545   }
2546 
2547   if (parent_namespace == nullptr) {
2548     // if parent_namespace is nullptr -> set it to the caller namespace
2549     soinfo* caller_soinfo = find_containing_library(caller_addr);
2550 
2551     parent_namespace = caller_soinfo != nullptr ?
2552                        caller_soinfo->get_primary_namespace() :
2553                        g_anonymous_namespace;
2554   }
2555 
2556   ProtectedDataGuard guard;
2557   std::vector<std::string> ld_library_paths;
2558   std::vector<std::string> default_library_paths;
2559   std::vector<std::string> permitted_paths;
2560 
2561   parse_path(ld_library_path, ":", &ld_library_paths);
2562   parse_path(default_library_path, ":", &default_library_paths);
2563   parse_path(permitted_when_isolated_path, ":", &permitted_paths);
2564 
2565   android_namespace_t* ns = new (g_namespace_allocator.alloc()) android_namespace_t();
2566   ns->set_name(name);
2567   ns->set_isolated((type & ANDROID_NAMESPACE_TYPE_ISOLATED) != 0);
2568   ns->set_ld_library_paths(std::move(ld_library_paths));
2569   ns->set_default_library_paths(std::move(default_library_paths));
2570   ns->set_permitted_paths(std::move(permitted_paths));
2571 
2572   if ((type & ANDROID_NAMESPACE_TYPE_SHARED) != 0) {
2573     // If shared - clone the parent namespace
2574     ns->add_soinfos(parent_namespace->soinfo_list());
2575   } else {
2576     // If not shared - copy only the shared group
2577     ns->add_soinfos(get_shared_group(parent_namespace));
2578   }
2579 
2580   return ns;
2581 }
2582 
call_ifunc_resolver(ElfW (Addr)resolver_addr)2583 static ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
2584   typedef ElfW(Addr) (*ifunc_resolver_t)(void);
2585   ifunc_resolver_t ifunc_resolver = reinterpret_cast<ifunc_resolver_t>(resolver_addr);
2586   ElfW(Addr) ifunc_addr = ifunc_resolver();
2587   TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p",
2588       ifunc_resolver, reinterpret_cast<void*>(ifunc_addr));
2589 
2590   return ifunc_addr;
2591 }
2592 
get_version_info(ElfW (Versym)source_symver) const2593 const version_info* VersionTracker::get_version_info(ElfW(Versym) source_symver) const {
2594   if (source_symver < 2 ||
2595       source_symver >= version_infos.size() ||
2596       version_infos[source_symver].name == nullptr) {
2597     return nullptr;
2598   }
2599 
2600   return &version_infos[source_symver];
2601 }
2602 
add_version_info(size_t source_index,ElfW (Word)elf_hash,const char * ver_name,const soinfo * target_si)2603 void VersionTracker::add_version_info(size_t source_index,
2604                                       ElfW(Word) elf_hash,
2605                                       const char* ver_name,
2606                                       const soinfo* target_si) {
2607   if (source_index >= version_infos.size()) {
2608     version_infos.resize(source_index+1);
2609   }
2610 
2611   version_infos[source_index].elf_hash = elf_hash;
2612   version_infos[source_index].name = ver_name;
2613   version_infos[source_index].target_si = target_si;
2614 }
2615 
init_verneed(const soinfo * si_from)2616 bool VersionTracker::init_verneed(const soinfo* si_from) {
2617   uintptr_t verneed_ptr = si_from->get_verneed_ptr();
2618 
2619   if (verneed_ptr == 0) {
2620     return true;
2621   }
2622 
2623   size_t verneed_cnt = si_from->get_verneed_cnt();
2624 
2625   for (size_t i = 0, offset = 0; i<verneed_cnt; ++i) {
2626     const ElfW(Verneed)* verneed = reinterpret_cast<ElfW(Verneed)*>(verneed_ptr + offset);
2627     size_t vernaux_offset = offset + verneed->vn_aux;
2628     offset += verneed->vn_next;
2629 
2630     if (verneed->vn_version != 1) {
2631       DL_ERR("unsupported verneed[%zd] vn_version: %d (expected 1)", i, verneed->vn_version);
2632       return false;
2633     }
2634 
2635     const char* target_soname = si_from->get_string(verneed->vn_file);
2636     // find it in dependencies
2637     soinfo* target_si = si_from->get_children().find_if([&](const soinfo* si) {
2638       return si->get_soname() != nullptr && strcmp(si->get_soname(), target_soname) == 0;
2639     });
2640 
2641     if (target_si == nullptr) {
2642       DL_ERR("cannot find \"%s\" from verneed[%zd] in DT_NEEDED list for \"%s\"",
2643           target_soname, i, si_from->get_realpath());
2644       return false;
2645     }
2646 
2647     for (size_t j = 0; j<verneed->vn_cnt; ++j) {
2648       const ElfW(Vernaux)* vernaux = reinterpret_cast<ElfW(Vernaux)*>(verneed_ptr + vernaux_offset);
2649       vernaux_offset += vernaux->vna_next;
2650 
2651       const ElfW(Word) elf_hash = vernaux->vna_hash;
2652       const char* ver_name = si_from->get_string(vernaux->vna_name);
2653       ElfW(Half) source_index = vernaux->vna_other;
2654 
2655       add_version_info(source_index, elf_hash, ver_name, target_si);
2656     }
2657   }
2658 
2659   return true;
2660 }
2661 
init_verdef(const soinfo * si_from)2662 bool VersionTracker::init_verdef(const soinfo* si_from) {
2663   return for_each_verdef(si_from,
2664     [&](size_t, const ElfW(Verdef)* verdef, const ElfW(Verdaux)* verdaux) {
2665       add_version_info(verdef->vd_ndx, verdef->vd_hash,
2666           si_from->get_string(verdaux->vda_name), si_from);
2667       return false;
2668     }
2669   );
2670 }
2671 
init(const soinfo * si_from)2672 bool VersionTracker::init(const soinfo* si_from) {
2673   if (!si_from->has_min_version(2)) {
2674     return true;
2675   }
2676 
2677   return init_verneed(si_from) && init_verdef(si_from);
2678 }
2679 
lookup_version_info(const VersionTracker & version_tracker,ElfW (Word)sym,const char * sym_name,const version_info ** vi)2680 bool soinfo::lookup_version_info(const VersionTracker& version_tracker, ElfW(Word) sym,
2681                                  const char* sym_name, const version_info** vi) {
2682   const ElfW(Versym)* sym_ver_ptr = get_versym(sym);
2683   ElfW(Versym) sym_ver = sym_ver_ptr == nullptr ? 0 : *sym_ver_ptr;
2684 
2685   if (sym_ver != VER_NDX_LOCAL && sym_ver != VER_NDX_GLOBAL) {
2686     *vi = version_tracker.get_version_info(sym_ver);
2687 
2688     if (*vi == nullptr) {
2689       DL_ERR("cannot find verneed/verdef for version index=%d "
2690           "referenced by symbol \"%s\" at \"%s\"", sym_ver, sym_name, get_realpath());
2691       return false;
2692     }
2693   } else {
2694     // there is no version info
2695     *vi = nullptr;
2696   }
2697 
2698   return true;
2699 }
2700 
2701 #if !defined(__mips__)
2702 #if defined(USE_RELA)
get_addend(ElfW (Rela)* rela,ElfW (Addr)reloc_addr __unused)2703 static ElfW(Addr) get_addend(ElfW(Rela)* rela, ElfW(Addr) reloc_addr __unused) {
2704   return rela->r_addend;
2705 }
2706 #else
get_addend(ElfW (Rel)* rel,ElfW (Addr)reloc_addr)2707 static ElfW(Addr) get_addend(ElfW(Rel)* rel, ElfW(Addr) reloc_addr) {
2708   if (ELFW(R_TYPE)(rel->r_info) == R_GENERIC_RELATIVE ||
2709       ELFW(R_TYPE)(rel->r_info) == R_GENERIC_IRELATIVE) {
2710     return *reinterpret_cast<ElfW(Addr)*>(reloc_addr);
2711   }
2712   return 0;
2713 }
2714 #endif
2715 
2716 template<typename ElfRelIteratorT>
relocate(const VersionTracker & version_tracker,ElfRelIteratorT && rel_iterator,const soinfo_list_t & global_group,const soinfo_list_t & local_group)2717 bool soinfo::relocate(const VersionTracker& version_tracker, ElfRelIteratorT&& rel_iterator,
2718                       const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
2719   for (size_t idx = 0; rel_iterator.has_next(); ++idx) {
2720     const auto rel = rel_iterator.next();
2721     if (rel == nullptr) {
2722       return false;
2723     }
2724 
2725     ElfW(Word) type = ELFW(R_TYPE)(rel->r_info);
2726     ElfW(Word) sym = ELFW(R_SYM)(rel->r_info);
2727 
2728     ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
2729     ElfW(Addr) sym_addr = 0;
2730     const char* sym_name = nullptr;
2731     ElfW(Addr) addend = get_addend(rel, reloc);
2732 
2733     DEBUG("Processing \"%s\" relocation at index %zd", get_realpath(), idx);
2734     if (type == R_GENERIC_NONE) {
2735       continue;
2736     }
2737 
2738     const ElfW(Sym)* s = nullptr;
2739     soinfo* lsi = nullptr;
2740 
2741     if (sym != 0) {
2742       sym_name = get_string(symtab_[sym].st_name);
2743       const version_info* vi = nullptr;
2744 
2745       if (!lookup_version_info(version_tracker, sym, sym_name, &vi)) {
2746         return false;
2747       }
2748 
2749       if (!soinfo_do_lookup(this, sym_name, vi, &lsi, global_group, local_group, &s)) {
2750         return false;
2751       }
2752 
2753       if (s == nullptr) {
2754         // We only allow an undefined symbol if this is a weak reference...
2755         s = &symtab_[sym];
2756         if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
2757           DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, get_realpath());
2758           return false;
2759         }
2760 
2761         /* IHI0044C AAELF 4.5.1.1:
2762 
2763            Libraries are not searched to resolve weak references.
2764            It is not an error for a weak reference to remain unsatisfied.
2765 
2766            During linking, the value of an undefined weak reference is:
2767            - Zero if the relocation type is absolute
2768            - The address of the place if the relocation is pc-relative
2769            - The address of nominal base address if the relocation
2770              type is base-relative.
2771          */
2772 
2773         switch (type) {
2774           case R_GENERIC_JUMP_SLOT:
2775           case R_GENERIC_GLOB_DAT:
2776           case R_GENERIC_RELATIVE:
2777           case R_GENERIC_IRELATIVE:
2778 #if defined(__aarch64__)
2779           case R_AARCH64_ABS64:
2780           case R_AARCH64_ABS32:
2781           case R_AARCH64_ABS16:
2782 #elif defined(__x86_64__)
2783           case R_X86_64_32:
2784           case R_X86_64_64:
2785 #elif defined(__arm__)
2786           case R_ARM_ABS32:
2787 #elif defined(__i386__)
2788           case R_386_32:
2789 #endif
2790             /*
2791              * The sym_addr was initialized to be zero above, or the relocation
2792              * code below does not care about value of sym_addr.
2793              * No need to do anything.
2794              */
2795             break;
2796 #if defined(__x86_64__)
2797           case R_X86_64_PC32:
2798             sym_addr = reloc;
2799             break;
2800 #elif defined(__i386__)
2801           case R_386_PC32:
2802             sym_addr = reloc;
2803             break;
2804 #endif
2805           default:
2806             DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
2807             return false;
2808         }
2809       } else { // We got a definition.
2810 #if !defined(__LP64__)
2811         // When relocating dso with text_relocation .text segment is
2812         // not executable. We need to restore elf flags before resolving
2813         // STT_GNU_IFUNC symbol.
2814         bool protect_segments = has_text_relocations &&
2815                                 lsi == this &&
2816                                 ELF_ST_TYPE(s->st_info) == STT_GNU_IFUNC;
2817         if (protect_segments) {
2818           if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
2819             DL_ERR("can't protect segments for \"%s\": %s",
2820                    get_realpath(), strerror(errno));
2821             return false;
2822           }
2823         }
2824 #endif
2825         sym_addr = lsi->resolve_symbol_address(s);
2826 #if !defined(__LP64__)
2827         if (protect_segments) {
2828           if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
2829             DL_ERR("can't unprotect loadable segments for \"%s\": %s",
2830                    get_realpath(), strerror(errno));
2831             return false;
2832           }
2833         }
2834 #endif
2835       }
2836       count_relocation(kRelocSymbol);
2837     }
2838 
2839     switch (type) {
2840       case R_GENERIC_JUMP_SLOT:
2841         count_relocation(kRelocAbsolute);
2842         MARK(rel->r_offset);
2843         TRACE_TYPE(RELO, "RELO JMP_SLOT %16p <- %16p %s\n",
2844                    reinterpret_cast<void*>(reloc),
2845                    reinterpret_cast<void*>(sym_addr + addend), sym_name);
2846 
2847         *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
2848         break;
2849       case R_GENERIC_GLOB_DAT:
2850         count_relocation(kRelocAbsolute);
2851         MARK(rel->r_offset);
2852         TRACE_TYPE(RELO, "RELO GLOB_DAT %16p <- %16p %s\n",
2853                    reinterpret_cast<void*>(reloc),
2854                    reinterpret_cast<void*>(sym_addr + addend), sym_name);
2855         *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
2856         break;
2857       case R_GENERIC_RELATIVE:
2858         count_relocation(kRelocRelative);
2859         MARK(rel->r_offset);
2860         TRACE_TYPE(RELO, "RELO RELATIVE %16p <- %16p\n",
2861                    reinterpret_cast<void*>(reloc),
2862                    reinterpret_cast<void*>(load_bias + addend));
2863         *reinterpret_cast<ElfW(Addr)*>(reloc) = (load_bias + addend);
2864         break;
2865       case R_GENERIC_IRELATIVE:
2866         count_relocation(kRelocRelative);
2867         MARK(rel->r_offset);
2868         TRACE_TYPE(RELO, "RELO IRELATIVE %16p <- %16p\n",
2869                     reinterpret_cast<void*>(reloc),
2870                     reinterpret_cast<void*>(load_bias + addend));
2871         {
2872 #if !defined(__LP64__)
2873           // When relocating dso with text_relocation .text segment is
2874           // not executable. We need to restore elf flags for this
2875           // particular call.
2876           if (has_text_relocations) {
2877             if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
2878               DL_ERR("can't protect segments for \"%s\": %s",
2879                      get_realpath(), strerror(errno));
2880               return false;
2881             }
2882           }
2883 #endif
2884           ElfW(Addr) ifunc_addr = call_ifunc_resolver(load_bias + addend);
2885 #if !defined(__LP64__)
2886           // Unprotect it afterwards...
2887           if (has_text_relocations) {
2888             if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
2889               DL_ERR("can't unprotect loadable segments for \"%s\": %s",
2890                      get_realpath(), strerror(errno));
2891               return false;
2892             }
2893           }
2894 #endif
2895           *reinterpret_cast<ElfW(Addr)*>(reloc) = ifunc_addr;
2896         }
2897         break;
2898 
2899 #if defined(__aarch64__)
2900       case R_AARCH64_ABS64:
2901         count_relocation(kRelocAbsolute);
2902         MARK(rel->r_offset);
2903         TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n",
2904                    reloc, sym_addr + addend, sym_name);
2905         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
2906         break;
2907       case R_AARCH64_ABS32:
2908         count_relocation(kRelocAbsolute);
2909         MARK(rel->r_offset);
2910         TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n",
2911                    reloc, sym_addr + addend, sym_name);
2912         {
2913           const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT32_MIN);
2914           const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT32_MAX);
2915           if ((min_value <= (sym_addr + addend)) &&
2916               ((sym_addr + addend) <= max_value)) {
2917             *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
2918           } else {
2919             DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
2920                    sym_addr + addend, min_value, max_value);
2921             return false;
2922           }
2923         }
2924         break;
2925       case R_AARCH64_ABS16:
2926         count_relocation(kRelocAbsolute);
2927         MARK(rel->r_offset);
2928         TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n",
2929                    reloc, sym_addr + addend, sym_name);
2930         {
2931           const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT16_MIN);
2932           const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT16_MAX);
2933           if ((min_value <= (sym_addr + addend)) &&
2934               ((sym_addr + addend) <= max_value)) {
2935             *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
2936           } else {
2937             DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
2938                    sym_addr + addend, min_value, max_value);
2939             return false;
2940           }
2941         }
2942         break;
2943       case R_AARCH64_PREL64:
2944         count_relocation(kRelocRelative);
2945         MARK(rel->r_offset);
2946         TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n",
2947                    reloc, sym_addr + addend, rel->r_offset, sym_name);
2948         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
2949         break;
2950       case R_AARCH64_PREL32:
2951         count_relocation(kRelocRelative);
2952         MARK(rel->r_offset);
2953         TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n",
2954                    reloc, sym_addr + addend, rel->r_offset, sym_name);
2955         {
2956           const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT32_MIN);
2957           const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT32_MAX);
2958           if ((min_value <= (sym_addr + addend - rel->r_offset)) &&
2959               ((sym_addr + addend - rel->r_offset) <= max_value)) {
2960             *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
2961           } else {
2962             DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
2963                    sym_addr + addend - rel->r_offset, min_value, max_value);
2964             return false;
2965           }
2966         }
2967         break;
2968       case R_AARCH64_PREL16:
2969         count_relocation(kRelocRelative);
2970         MARK(rel->r_offset);
2971         TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n",
2972                    reloc, sym_addr + addend, rel->r_offset, sym_name);
2973         {
2974           const ElfW(Addr) min_value = static_cast<ElfW(Addr)>(INT16_MIN);
2975           const ElfW(Addr) max_value = static_cast<ElfW(Addr)>(UINT16_MAX);
2976           if ((min_value <= (sym_addr + addend - rel->r_offset)) &&
2977               ((sym_addr + addend - rel->r_offset) <= max_value)) {
2978             *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - rel->r_offset;
2979           } else {
2980             DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
2981                    sym_addr + addend - rel->r_offset, min_value, max_value);
2982             return false;
2983           }
2984         }
2985         break;
2986 
2987       case R_AARCH64_COPY:
2988         /*
2989          * ET_EXEC is not supported so this should not happen.
2990          *
2991          * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0056b/IHI0056B_aaelf64.pdf
2992          *
2993          * Section 4.6.11 "Dynamic relocations"
2994          * R_AARCH64_COPY may only appear in executable objects where e_type is
2995          * set to ET_EXEC.
2996          */
2997         DL_ERR("%s R_AARCH64_COPY relocations are not supported", get_realpath());
2998         return false;
2999       case R_AARCH64_TLS_TPREL64:
3000         TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
3001                    reloc, (sym_addr + addend), rel->r_offset);
3002         break;
3003       case R_AARCH64_TLS_DTPREL32:
3004         TRACE_TYPE(RELO, "RELO TLS_DTPREL32 *** %16llx <- %16llx - %16llx\n",
3005                    reloc, (sym_addr + addend), rel->r_offset);
3006         break;
3007 #elif defined(__x86_64__)
3008       case R_X86_64_32:
3009         count_relocation(kRelocRelative);
3010         MARK(rel->r_offset);
3011         TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
3012                    static_cast<size_t>(sym_addr), sym_name);
3013         *reinterpret_cast<Elf32_Addr*>(reloc) = sym_addr + addend;
3014         break;
3015       case R_X86_64_64:
3016         count_relocation(kRelocRelative);
3017         MARK(rel->r_offset);
3018         TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
3019                    static_cast<size_t>(sym_addr), sym_name);
3020         *reinterpret_cast<Elf64_Addr*>(reloc) = sym_addr + addend;
3021         break;
3022       case R_X86_64_PC32:
3023         count_relocation(kRelocRelative);
3024         MARK(rel->r_offset);
3025         TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
3026                    static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
3027                    static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
3028         *reinterpret_cast<Elf32_Addr*>(reloc) = sym_addr + addend - reloc;
3029         break;
3030 #elif defined(__arm__)
3031       case R_ARM_ABS32:
3032         count_relocation(kRelocAbsolute);
3033         MARK(rel->r_offset);
3034         TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name);
3035         *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
3036         break;
3037       case R_ARM_REL32:
3038         count_relocation(kRelocRelative);
3039         MARK(rel->r_offset);
3040         TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s",
3041                    reloc, sym_addr, rel->r_offset, sym_name);
3042         *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
3043         break;
3044       case R_ARM_COPY:
3045         /*
3046          * ET_EXEC is not supported so this should not happen.
3047          *
3048          * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
3049          *
3050          * Section 4.6.1.10 "Dynamic relocations"
3051          * R_ARM_COPY may only appear in executable objects where e_type is
3052          * set to ET_EXEC.
3053          */
3054         DL_ERR("%s R_ARM_COPY relocations are not supported", get_realpath());
3055         return false;
3056 #elif defined(__i386__)
3057       case R_386_32:
3058         count_relocation(kRelocRelative);
3059         MARK(rel->r_offset);
3060         TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name);
3061         *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
3062         break;
3063       case R_386_PC32:
3064         count_relocation(kRelocRelative);
3065         MARK(rel->r_offset);
3066         TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s",
3067                    reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
3068         *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
3069         break;
3070 #endif
3071       default:
3072         DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
3073         return false;
3074     }
3075   }
3076   return true;
3077 }
3078 #endif  // !defined(__mips__)
3079 
call_array(const char * array_name __unused,linker_function_t * functions,size_t count,bool reverse)3080 void soinfo::call_array(const char* array_name __unused, linker_function_t* functions,
3081                         size_t count, bool reverse) {
3082   if (functions == nullptr) {
3083     return;
3084   }
3085 
3086   TRACE("[ Calling %s (size %zd) @ %p for \"%s\" ]", array_name, count, functions, get_realpath());
3087 
3088   int begin = reverse ? (count - 1) : 0;
3089   int end = reverse ? -1 : count;
3090   int step = reverse ? -1 : 1;
3091 
3092   for (int i = begin; i != end; i += step) {
3093     TRACE("[ %s[%d] == %p ]", array_name, i, functions[i]);
3094     call_function("function", functions[i]);
3095   }
3096 
3097   TRACE("[ Done calling %s for \"%s\" ]", array_name, get_realpath());
3098 }
3099 
call_function(const char * function_name __unused,linker_function_t function)3100 void soinfo::call_function(const char* function_name __unused, linker_function_t function) {
3101   if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
3102     return;
3103   }
3104 
3105   TRACE("[ Calling %s @ %p for \"%s\" ]", function_name, function, get_realpath());
3106   function();
3107   TRACE("[ Done calling %s @ %p for \"%s\" ]", function_name, function, get_realpath());
3108 }
3109 
call_pre_init_constructors()3110 void soinfo::call_pre_init_constructors() {
3111   // DT_PREINIT_ARRAY functions are called before any other constructors for executables,
3112   // but ignored in a shared library.
3113   call_array("DT_PREINIT_ARRAY", preinit_array_, preinit_array_count_, false);
3114 }
3115 
call_constructors()3116 void soinfo::call_constructors() {
3117   if (constructors_called) {
3118     return;
3119   }
3120 
3121   // We set constructors_called before actually calling the constructors, otherwise it doesn't
3122   // protect against recursive constructor calls. One simple example of constructor recursion
3123   // is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so:
3124   // 1. The program depends on libc, so libc's constructor is called here.
3125   // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
3126   // 3. dlopen() calls the constructors on the newly created
3127   //    soinfo for libc_malloc_debug_leak.so.
3128   // 4. The debug .so depends on libc, so CallConstructors is
3129   //    called again with the libc soinfo. If it doesn't trigger the early-
3130   //    out above, the libc constructor will be called again (recursively!).
3131   constructors_called = true;
3132 
3133   if (!is_main_executable() && preinit_array_ != nullptr) {
3134     // The GNU dynamic linker silently ignores these, but we warn the developer.
3135     PRINT("\"%s\": ignoring DT_PREINIT_ARRAY in shared library!", get_realpath());
3136   }
3137 
3138   get_children().for_each([] (soinfo* si) {
3139     si->call_constructors();
3140   });
3141 
3142   TRACE("\"%s\": calling constructors", get_realpath());
3143 
3144   // DT_INIT should be called before DT_INIT_ARRAY if both are present.
3145   call_function("DT_INIT", init_func_);
3146   call_array("DT_INIT_ARRAY", init_array_, init_array_count_, false);
3147 }
3148 
call_destructors()3149 void soinfo::call_destructors() {
3150   if (!constructors_called) {
3151     return;
3152   }
3153   TRACE("\"%s\": calling destructors", get_realpath());
3154 
3155   // DT_FINI_ARRAY must be parsed in reverse order.
3156   call_array("DT_FINI_ARRAY", fini_array_, fini_array_count_, true);
3157 
3158   // DT_FINI should be called after DT_FINI_ARRAY if both are present.
3159   call_function("DT_FINI", fini_func_);
3160 
3161   // This is needed on second call to dlopen
3162   // after library has been unloaded with RTLD_NODELETE
3163   constructors_called = false;
3164 }
3165 
add_child(soinfo * child)3166 void soinfo::add_child(soinfo* child) {
3167   if (has_min_version(0)) {
3168     child->parents_.push_back(this);
3169     this->children_.push_back(child);
3170   }
3171 }
3172 
remove_all_links()3173 void soinfo::remove_all_links() {
3174   if (!has_min_version(0)) {
3175     return;
3176   }
3177 
3178   // 1. Untie connected soinfos from 'this'.
3179   children_.for_each([&] (soinfo* child) {
3180     child->parents_.remove_if([&] (const soinfo* parent) {
3181       return parent == this;
3182     });
3183   });
3184 
3185   parents_.for_each([&] (soinfo* parent) {
3186     parent->children_.remove_if([&] (const soinfo* child) {
3187       return child == this;
3188     });
3189   });
3190 
3191   // 2. Remove from the primary namespace
3192   primary_namespace_->remove_soinfo(this);
3193   primary_namespace_ = nullptr;
3194 
3195   // 3. Remove from secondary namespaces
3196   secondary_namespaces_.for_each([&](android_namespace_t* ns) {
3197     ns->remove_soinfo(this);
3198   });
3199 
3200 
3201   // 4. Once everything untied - clear local lists.
3202   parents_.clear();
3203   children_.clear();
3204   secondary_namespaces_.clear();
3205 }
3206 
get_st_dev() const3207 dev_t soinfo::get_st_dev() const {
3208   if (has_min_version(0)) {
3209     return st_dev_;
3210   }
3211 
3212   return 0;
3213 };
3214 
get_st_ino() const3215 ino_t soinfo::get_st_ino() const {
3216   if (has_min_version(0)) {
3217     return st_ino_;
3218   }
3219 
3220   return 0;
3221 }
3222 
get_file_offset() const3223 off64_t soinfo::get_file_offset() const {
3224   if (has_min_version(1)) {
3225     return file_offset_;
3226   }
3227 
3228   return 0;
3229 }
3230 
get_rtld_flags() const3231 uint32_t soinfo::get_rtld_flags() const {
3232   if (has_min_version(1)) {
3233     return rtld_flags_;
3234   }
3235 
3236   return 0;
3237 }
3238 
get_dt_flags_1() const3239 uint32_t soinfo::get_dt_flags_1() const {
3240   if (has_min_version(1)) {
3241     return dt_flags_1_;
3242   }
3243 
3244   return 0;
3245 }
3246 
set_dt_flags_1(uint32_t dt_flags_1)3247 void soinfo::set_dt_flags_1(uint32_t dt_flags_1) {
3248   if (has_min_version(1)) {
3249     if ((dt_flags_1 & DF_1_GLOBAL) != 0) {
3250       rtld_flags_ |= RTLD_GLOBAL;
3251     }
3252 
3253     if ((dt_flags_1 & DF_1_NODELETE) != 0) {
3254       rtld_flags_ |= RTLD_NODELETE;
3255     }
3256 
3257     dt_flags_1_ = dt_flags_1;
3258   }
3259 }
3260 
set_nodelete()3261 void soinfo::set_nodelete() {
3262   rtld_flags_ |= RTLD_NODELETE;
3263 }
3264 
get_realpath() const3265 const char* soinfo::get_realpath() const {
3266 #if defined(__work_around_b_24465209__)
3267   if (has_min_version(2)) {
3268     return realpath_.c_str();
3269   } else {
3270     return old_name_;
3271   }
3272 #else
3273   return realpath_.c_str();
3274 #endif
3275 }
3276 
set_soname(const char * soname)3277 void soinfo::set_soname(const char* soname) {
3278 #if defined(__work_around_b_24465209__)
3279   if (has_min_version(2)) {
3280     soname_ = soname;
3281   }
3282   strlcpy(old_name_, soname_, sizeof(old_name_));
3283 #else
3284   soname_ = soname;
3285 #endif
3286 }
3287 
get_soname() const3288 const char* soinfo::get_soname() const {
3289 #if defined(__work_around_b_24465209__)
3290   if (has_min_version(2)) {
3291     return soname_;
3292   } else {
3293     return old_name_;
3294   }
3295 #else
3296   return soname_;
3297 #endif
3298 }
3299 
3300 // This is a return on get_children()/get_parents() if
3301 // 'this->flags' does not have FLAG_NEW_SOINFO set.
3302 static soinfo::soinfo_list_t g_empty_list;
3303 
get_children()3304 soinfo::soinfo_list_t& soinfo::get_children() {
3305   if (has_min_version(0)) {
3306     return children_;
3307   }
3308 
3309   return g_empty_list;
3310 }
3311 
get_children() const3312 const soinfo::soinfo_list_t& soinfo::get_children() const {
3313   if (has_min_version(0)) {
3314     return children_;
3315   }
3316 
3317   return g_empty_list;
3318 }
3319 
get_parents()3320 soinfo::soinfo_list_t& soinfo::get_parents() {
3321   if (has_min_version(0)) {
3322     return parents_;
3323   }
3324 
3325   return g_empty_list;
3326 }
3327 
3328 static std::vector<std::string> g_empty_runpath;
3329 
get_dt_runpath() const3330 const std::vector<std::string>& soinfo::get_dt_runpath() const {
3331   if (has_min_version(3)) {
3332     return dt_runpath_;
3333   }
3334 
3335   return g_empty_runpath;
3336 }
3337 
get_primary_namespace()3338 android_namespace_t* soinfo::get_primary_namespace() {
3339   if (has_min_version(3)) {
3340     return primary_namespace_;
3341   }
3342 
3343   return &g_default_namespace;
3344 }
3345 
add_secondary_namespace(android_namespace_t * secondary_ns)3346 void soinfo::add_secondary_namespace(android_namespace_t* secondary_ns) {
3347   CHECK(has_min_version(3));
3348   secondary_namespaces_.push_back(secondary_ns);
3349 }
3350 
ElfW(Addr)3351 ElfW(Addr) soinfo::resolve_symbol_address(const ElfW(Sym)* s) const {
3352   if (ELF_ST_TYPE(s->st_info) == STT_GNU_IFUNC) {
3353     return call_ifunc_resolver(s->st_value + load_bias);
3354   }
3355 
3356   return static_cast<ElfW(Addr)>(s->st_value + load_bias);
3357 }
3358 
get_string(ElfW (Word)index) const3359 const char* soinfo::get_string(ElfW(Word) index) const {
3360   if (has_min_version(1) && (index >= strtab_size_)) {
3361     __libc_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
3362         get_realpath(), strtab_size_, index);
3363   }
3364 
3365   return strtab_ + index;
3366 }
3367 
is_gnu_hash() const3368 bool soinfo::is_gnu_hash() const {
3369   return (flags_ & FLAG_GNU_HASH) != 0;
3370 }
3371 
can_unload() const3372 bool soinfo::can_unload() const {
3373   return !is_linked() || ((get_rtld_flags() & (RTLD_NODELETE | RTLD_GLOBAL)) == 0);
3374 }
3375 
is_linked() const3376 bool soinfo::is_linked() const {
3377   return (flags_ & FLAG_LINKED) != 0;
3378 }
3379 
is_main_executable() const3380 bool soinfo::is_main_executable() const {
3381   return (flags_ & FLAG_EXE) != 0;
3382 }
3383 
is_linker() const3384 bool soinfo::is_linker() const {
3385   return (flags_ & FLAG_LINKER) != 0;
3386 }
3387 
set_linked()3388 void soinfo::set_linked() {
3389   flags_ |= FLAG_LINKED;
3390 }
3391 
set_linker_flag()3392 void soinfo::set_linker_flag() {
3393   flags_ |= FLAG_LINKER;
3394 }
3395 
set_main_executable()3396 void soinfo::set_main_executable() {
3397   flags_ |= FLAG_EXE;
3398 }
3399 
increment_ref_count()3400 void soinfo::increment_ref_count() {
3401   local_group_root_->ref_count_++;
3402 }
3403 
decrement_ref_count()3404 size_t soinfo::decrement_ref_count() {
3405   return --local_group_root_->ref_count_;
3406 }
3407 
get_local_group_root() const3408 soinfo* soinfo::get_local_group_root() const {
3409   return local_group_root_;
3410 }
3411 
3412 
set_mapped_by_caller(bool mapped_by_caller)3413 void soinfo::set_mapped_by_caller(bool mapped_by_caller) {
3414   if (mapped_by_caller) {
3415     flags_ |= FLAG_MAPPED_BY_CALLER;
3416   } else {
3417     flags_ &= ~FLAG_MAPPED_BY_CALLER;
3418   }
3419 }
3420 
is_mapped_by_caller() const3421 bool soinfo::is_mapped_by_caller() const {
3422   return (flags_ & FLAG_MAPPED_BY_CALLER) != 0;
3423 }
3424 
3425 // This function returns api-level at the time of
3426 // dlopen/load. Note that libraries opened by system
3427 // will always have 'current' api level.
get_target_sdk_version() const3428 uint32_t soinfo::get_target_sdk_version() const {
3429   if (!has_min_version(2)) {
3430     return __ANDROID_API__;
3431   }
3432 
3433   return local_group_root_->target_sdk_version_;
3434 }
3435 
get_handle() const3436 uintptr_t soinfo::get_handle() const {
3437   CHECK(has_min_version(3));
3438   CHECK(handle_ != 0);
3439   return handle_;
3440 }
3441 
to_handle()3442 void* soinfo::to_handle() {
3443   if (get_application_target_sdk_version() <= 23 || !has_min_version(3)) {
3444     return this;
3445   }
3446 
3447   return reinterpret_cast<void*>(get_handle());
3448 }
3449 
generate_handle()3450 void soinfo::generate_handle() {
3451   CHECK(has_min_version(3));
3452   CHECK(handle_ == 0); // Make sure this is the first call
3453 
3454   // Make sure the handle is unique and does not collide
3455   // with special values which are RTLD_DEFAULT and RTLD_NEXT.
3456   do {
3457     arc4random_buf(&handle_, sizeof(handle_));
3458     // the least significant bit for the handle is always 1
3459     // making it easy to test the type of handle passed to
3460     // dl* functions.
3461     handle_ = handle_ | 1;
3462   } while (handle_ == reinterpret_cast<uintptr_t>(RTLD_DEFAULT) ||
3463            handle_ == reinterpret_cast<uintptr_t>(RTLD_NEXT) ||
3464            g_soinfo_handles_map.find(handle_) != g_soinfo_handles_map.end());
3465 
3466   g_soinfo_handles_map[handle_] = this;
3467 }
3468 
prelink_image()3469 bool soinfo::prelink_image() {
3470   /* Extract dynamic section */
3471   ElfW(Word) dynamic_flags = 0;
3472   phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
3473 
3474   /* We can't log anything until the linker is relocated */
3475   bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
3476   if (!relocating_linker) {
3477     INFO("[ Linking \"%s\" ]", get_realpath());
3478     DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
3479   }
3480 
3481   if (dynamic == nullptr) {
3482     if (!relocating_linker) {
3483       DL_ERR("missing PT_DYNAMIC in \"%s\"", get_realpath());
3484     }
3485     return false;
3486   } else {
3487     if (!relocating_linker) {
3488       DEBUG("dynamic = %p", dynamic);
3489     }
3490   }
3491 
3492 #if defined(__arm__)
3493   (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
3494                                   &ARM_exidx, &ARM_exidx_count);
3495 #endif
3496 
3497   // Extract useful information from dynamic section.
3498   // Note that: "Except for the DT_NULL element at the end of the array,
3499   // and the relative order of DT_NEEDED elements, entries may appear in any order."
3500   //
3501   // source: http://www.sco.com/developers/gabi/1998-04-29/ch5.dynamic.html
3502   uint32_t needed_count = 0;
3503   for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3504     DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
3505           d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
3506     switch (d->d_tag) {
3507       case DT_SONAME:
3508         // this is parsed after we have strtab initialized (see below).
3509         break;
3510 
3511       case DT_HASH:
3512         nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
3513         nchain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
3514         bucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
3515         chain_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket_ * 4);
3516         break;
3517 
3518       case DT_GNU_HASH:
3519         gnu_nbucket_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
3520         // skip symndx
3521         gnu_maskwords_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[2];
3522         gnu_shift2_ = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[3];
3523 
3524         gnu_bloom_filter_ = reinterpret_cast<ElfW(Addr)*>(load_bias + d->d_un.d_ptr + 16);
3525         gnu_bucket_ = reinterpret_cast<uint32_t*>(gnu_bloom_filter_ + gnu_maskwords_);
3526         // amend chain for symndx = header[1]
3527         gnu_chain_ = gnu_bucket_ + gnu_nbucket_ -
3528             reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
3529 
3530         if (!powerof2(gnu_maskwords_)) {
3531           DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
3532               gnu_maskwords_, get_realpath());
3533           return false;
3534         }
3535         --gnu_maskwords_;
3536 
3537         flags_ |= FLAG_GNU_HASH;
3538         break;
3539 
3540       case DT_STRTAB:
3541         strtab_ = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
3542         break;
3543 
3544       case DT_STRSZ:
3545         strtab_size_ = d->d_un.d_val;
3546         break;
3547 
3548       case DT_SYMTAB:
3549         symtab_ = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
3550         break;
3551 
3552       case DT_SYMENT:
3553         if (d->d_un.d_val != sizeof(ElfW(Sym))) {
3554           DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
3555               static_cast<size_t>(d->d_un.d_val), get_realpath());
3556           return false;
3557         }
3558         break;
3559 
3560       case DT_PLTREL:
3561 #if defined(USE_RELA)
3562         if (d->d_un.d_val != DT_RELA) {
3563           DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
3564           return false;
3565         }
3566 #else
3567         if (d->d_un.d_val != DT_REL) {
3568           DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
3569           return false;
3570         }
3571 #endif
3572         break;
3573 
3574       case DT_JMPREL:
3575 #if defined(USE_RELA)
3576         plt_rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
3577 #else
3578         plt_rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
3579 #endif
3580         break;
3581 
3582       case DT_PLTRELSZ:
3583 #if defined(USE_RELA)
3584         plt_rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
3585 #else
3586         plt_rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
3587 #endif
3588         break;
3589 
3590       case DT_PLTGOT:
3591 #if defined(__mips__)
3592         // Used by mips and mips64.
3593         plt_got_ = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
3594 #endif
3595         // Ignore for other platforms... (because RTLD_LAZY is not supported)
3596         break;
3597 
3598       case DT_DEBUG:
3599         // Set the DT_DEBUG entry to the address of _r_debug for GDB
3600         // if the dynamic table is writable
3601 // FIXME: not working currently for N64
3602 // The flags for the LOAD and DYNAMIC program headers do not agree.
3603 // The LOAD section containing the dynamic table has been mapped as
3604 // read-only, but the DYNAMIC header claims it is writable.
3605 #if !(defined(__mips__) && defined(__LP64__))
3606         if ((dynamic_flags & PF_W) != 0) {
3607           d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
3608         }
3609 #endif
3610         break;
3611 #if defined(USE_RELA)
3612       case DT_RELA:
3613         rela_ = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
3614         break;
3615 
3616       case DT_RELASZ:
3617         rela_count_ = d->d_un.d_val / sizeof(ElfW(Rela));
3618         break;
3619 
3620       case DT_ANDROID_RELA:
3621         android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3622         break;
3623 
3624       case DT_ANDROID_RELASZ:
3625         android_relocs_size_ = d->d_un.d_val;
3626         break;
3627 
3628       case DT_ANDROID_REL:
3629         DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
3630         return false;
3631 
3632       case DT_ANDROID_RELSZ:
3633         DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
3634         return false;
3635 
3636       case DT_RELAENT:
3637         if (d->d_un.d_val != sizeof(ElfW(Rela))) {
3638           DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
3639           return false;
3640         }
3641         break;
3642 
3643       // ignored (see DT_RELCOUNT comments for details)
3644       case DT_RELACOUNT:
3645         break;
3646 
3647       case DT_REL:
3648         DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
3649         return false;
3650 
3651       case DT_RELSZ:
3652         DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
3653         return false;
3654 
3655 #else
3656       case DT_REL:
3657         rel_ = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
3658         break;
3659 
3660       case DT_RELSZ:
3661         rel_count_ = d->d_un.d_val / sizeof(ElfW(Rel));
3662         break;
3663 
3664       case DT_RELENT:
3665         if (d->d_un.d_val != sizeof(ElfW(Rel))) {
3666           DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
3667           return false;
3668         }
3669         break;
3670 
3671       case DT_ANDROID_REL:
3672         android_relocs_ = reinterpret_cast<uint8_t*>(load_bias + d->d_un.d_ptr);
3673         break;
3674 
3675       case DT_ANDROID_RELSZ:
3676         android_relocs_size_ = d->d_un.d_val;
3677         break;
3678 
3679       case DT_ANDROID_RELA:
3680         DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
3681         return false;
3682 
3683       case DT_ANDROID_RELASZ:
3684         DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
3685         return false;
3686 
3687       // "Indicates that all RELATIVE relocations have been concatenated together,
3688       // and specifies the RELATIVE relocation count."
3689       //
3690       // TODO: Spec also mentions that this can be used to optimize relocation process;
3691       // Not currently used by bionic linker - ignored.
3692       case DT_RELCOUNT:
3693         break;
3694 
3695       case DT_RELA:
3696         DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
3697         return false;
3698 
3699       case DT_RELASZ:
3700         DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
3701         return false;
3702 
3703 #endif
3704       case DT_INIT:
3705         init_func_ = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
3706         DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
3707         break;
3708 
3709       case DT_FINI:
3710         fini_func_ = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
3711         DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
3712         break;
3713 
3714       case DT_INIT_ARRAY:
3715         init_array_ = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
3716         DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
3717         break;
3718 
3719       case DT_INIT_ARRAYSZ:
3720         init_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
3721         break;
3722 
3723       case DT_FINI_ARRAY:
3724         fini_array_ = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
3725         DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
3726         break;
3727 
3728       case DT_FINI_ARRAYSZ:
3729         fini_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
3730         break;
3731 
3732       case DT_PREINIT_ARRAY:
3733         preinit_array_ = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
3734         DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
3735         break;
3736 
3737       case DT_PREINIT_ARRAYSZ:
3738         preinit_array_count_ = static_cast<uint32_t>(d->d_un.d_val) / sizeof(ElfW(Addr));
3739         break;
3740 
3741       case DT_TEXTREL:
3742 #if defined(__LP64__)
3743         DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", get_realpath());
3744         return false;
3745 #else
3746         has_text_relocations = true;
3747         break;
3748 #endif
3749 
3750       case DT_SYMBOLIC:
3751         has_DT_SYMBOLIC = true;
3752         break;
3753 
3754       case DT_NEEDED:
3755         ++needed_count;
3756         break;
3757 
3758       case DT_FLAGS:
3759         if (d->d_un.d_val & DF_TEXTREL) {
3760 #if defined(__LP64__)
3761           DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", get_realpath());
3762           return false;
3763 #else
3764           has_text_relocations = true;
3765 #endif
3766         }
3767         if (d->d_un.d_val & DF_SYMBOLIC) {
3768           has_DT_SYMBOLIC = true;
3769         }
3770         break;
3771 
3772       case DT_FLAGS_1:
3773         set_dt_flags_1(d->d_un.d_val);
3774 
3775         if ((d->d_un.d_val & ~SUPPORTED_DT_FLAGS_1) != 0) {
3776           DL_WARN("%s: unsupported flags DT_FLAGS_1=%p", get_realpath(), reinterpret_cast<void*>(d->d_un.d_val));
3777         }
3778         break;
3779 #if defined(__mips__)
3780       case DT_MIPS_RLD_MAP:
3781         // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
3782         {
3783           r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
3784           *dp = &_r_debug;
3785         }
3786         break;
3787       case DT_MIPS_RLD_MAP2:
3788         // Set the DT_MIPS_RLD_MAP2 entry to the address of _r_debug for GDB.
3789         {
3790           r_debug** dp = reinterpret_cast<r_debug**>(
3791               reinterpret_cast<ElfW(Addr)>(d) + d->d_un.d_val);
3792           *dp = &_r_debug;
3793         }
3794         break;
3795 
3796       case DT_MIPS_RLD_VERSION:
3797       case DT_MIPS_FLAGS:
3798       case DT_MIPS_BASE_ADDRESS:
3799       case DT_MIPS_UNREFEXTNO:
3800         break;
3801 
3802       case DT_MIPS_SYMTABNO:
3803         mips_symtabno_ = d->d_un.d_val;
3804         break;
3805 
3806       case DT_MIPS_LOCAL_GOTNO:
3807         mips_local_gotno_ = d->d_un.d_val;
3808         break;
3809 
3810       case DT_MIPS_GOTSYM:
3811         mips_gotsym_ = d->d_un.d_val;
3812         break;
3813 #endif
3814       // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
3815       case DT_BIND_NOW:
3816         break;
3817 
3818       case DT_VERSYM:
3819         versym_ = reinterpret_cast<ElfW(Versym)*>(load_bias + d->d_un.d_ptr);
3820         break;
3821 
3822       case DT_VERDEF:
3823         verdef_ptr_ = load_bias + d->d_un.d_ptr;
3824         break;
3825       case DT_VERDEFNUM:
3826         verdef_cnt_ = d->d_un.d_val;
3827         break;
3828 
3829       case DT_VERNEED:
3830         verneed_ptr_ = load_bias + d->d_un.d_ptr;
3831         break;
3832 
3833       case DT_VERNEEDNUM:
3834         verneed_cnt_ = d->d_un.d_val;
3835         break;
3836 
3837       case DT_RUNPATH:
3838         // this is parsed after we have strtab initialized (see below).
3839         break;
3840 
3841       default:
3842         if (!relocating_linker) {
3843           DL_WARN("%s: unused DT entry: type %p arg %p", get_realpath(),
3844               reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
3845         }
3846         break;
3847     }
3848   }
3849 
3850 #if defined(__mips__) && !defined(__LP64__)
3851   if (!mips_check_and_adjust_fp_modes()) {
3852     return false;
3853   }
3854 #endif
3855 
3856   DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
3857         reinterpret_cast<void*>(base), strtab_, symtab_);
3858 
3859   // Sanity checks.
3860   if (relocating_linker && needed_count != 0) {
3861     DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
3862     return false;
3863   }
3864   if (nbucket_ == 0 && gnu_nbucket_ == 0) {
3865     DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
3866         "(new hash type from the future?)", get_realpath());
3867     return false;
3868   }
3869   if (strtab_ == 0) {
3870     DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_realpath());
3871     return false;
3872   }
3873   if (symtab_ == 0) {
3874     DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_realpath());
3875     return false;
3876   }
3877 
3878   // second pass - parse entries relying on strtab
3879   for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
3880     switch (d->d_tag) {
3881       case DT_SONAME:
3882         set_soname(get_string(d->d_un.d_val));
3883         break;
3884       case DT_RUNPATH:
3885         set_dt_runpath(get_string(d->d_un.d_val));
3886         break;
3887     }
3888   }
3889 
3890   // Before M release linker was using basename in place of soname.
3891   // In the case when dt_soname is absent some apps stop working
3892   // because they can't find dt_needed library by soname.
3893   // This workaround should keep them working. (applies only
3894   // for apps targeting sdk version <=22). Make an exception for
3895   // the main executable and linker; they do not need to have dt_soname
3896   if (soname_ == nullptr && this != somain && (flags_ & FLAG_LINKER) == 0 &&
3897       get_application_target_sdk_version() <= 22) {
3898     soname_ = basename(realpath_.c_str());
3899     DL_WARN("%s: is missing DT_SONAME will use basename as a replacement: \"%s\"",
3900         get_realpath(), soname_);
3901     // Don't call add_dlwarning because a missing DT_SONAME isn't important enough to show in the UI
3902   }
3903   return true;
3904 }
3905 
link_image(const soinfo_list_t & global_group,const soinfo_list_t & local_group,const android_dlextinfo * extinfo)3906 bool soinfo::link_image(const soinfo_list_t& global_group, const soinfo_list_t& local_group,
3907                         const android_dlextinfo* extinfo) {
3908 
3909   local_group_root_ = local_group.front();
3910   if (local_group_root_ == nullptr) {
3911     local_group_root_ = this;
3912   }
3913 
3914   if ((flags_ & FLAG_LINKER) == 0 && local_group_root_ == this) {
3915     target_sdk_version_ = get_application_target_sdk_version();
3916   }
3917 
3918   VersionTracker version_tracker;
3919 
3920   if (!version_tracker.init(this)) {
3921     return false;
3922   }
3923 
3924 #if !defined(__LP64__)
3925   if (has_text_relocations) {
3926     // Fail if app is targeting sdk version > 22
3927     if (get_application_target_sdk_version() > 22) {
3928       PRINT("%s: has text relocations", get_realpath());
3929       DL_ERR("%s: has text relocations", get_realpath());
3930       return false;
3931     }
3932     // Make segments writable to allow text relocations to work properly. We will later call
3933     // phdr_table_protect_segments() after all of them are applied.
3934     DL_WARN("%s has text relocations. This is wasting memory and prevents "
3935             "security hardening. Please fix.", get_realpath());
3936     add_dlwarning(get_realpath(), "text relocations");
3937     if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
3938       DL_ERR("can't unprotect loadable segments for \"%s\": %s",
3939              get_realpath(), strerror(errno));
3940       return false;
3941     }
3942   }
3943 #endif
3944 
3945   if (android_relocs_ != nullptr) {
3946     // check signature
3947     if (android_relocs_size_ > 3 &&
3948         android_relocs_[0] == 'A' &&
3949         android_relocs_[1] == 'P' &&
3950         android_relocs_[2] == 'S' &&
3951         android_relocs_[3] == '2') {
3952       DEBUG("[ android relocating %s ]", get_realpath());
3953 
3954       bool relocated = false;
3955       const uint8_t* packed_relocs = android_relocs_ + 4;
3956       const size_t packed_relocs_size = android_relocs_size_ - 4;
3957 
3958       relocated = relocate(
3959           version_tracker,
3960           packed_reloc_iterator<sleb128_decoder>(
3961             sleb128_decoder(packed_relocs, packed_relocs_size)),
3962           global_group, local_group);
3963 
3964       if (!relocated) {
3965         return false;
3966       }
3967     } else {
3968       DL_ERR("bad android relocation header.");
3969       return false;
3970     }
3971   }
3972 
3973 #if defined(USE_RELA)
3974   if (rela_ != nullptr) {
3975     DEBUG("[ relocating %s ]", get_realpath());
3976     if (!relocate(version_tracker,
3977             plain_reloc_iterator(rela_, rela_count_), global_group, local_group)) {
3978       return false;
3979     }
3980   }
3981   if (plt_rela_ != nullptr) {
3982     DEBUG("[ relocating %s plt ]", get_realpath());
3983     if (!relocate(version_tracker,
3984             plain_reloc_iterator(plt_rela_, plt_rela_count_), global_group, local_group)) {
3985       return false;
3986     }
3987   }
3988 #else
3989   if (rel_ != nullptr) {
3990     DEBUG("[ relocating %s ]", get_realpath());
3991     if (!relocate(version_tracker,
3992             plain_reloc_iterator(rel_, rel_count_), global_group, local_group)) {
3993       return false;
3994     }
3995   }
3996   if (plt_rel_ != nullptr) {
3997     DEBUG("[ relocating %s plt ]", get_realpath());
3998     if (!relocate(version_tracker,
3999             plain_reloc_iterator(plt_rel_, plt_rel_count_), global_group, local_group)) {
4000       return false;
4001     }
4002   }
4003 #endif
4004 
4005 #if defined(__mips__)
4006   if (!mips_relocate_got(version_tracker, global_group, local_group)) {
4007     return false;
4008   }
4009 #endif
4010 
4011   DEBUG("[ finished linking %s ]", get_realpath());
4012 
4013 #if !defined(__LP64__)
4014   if (has_text_relocations) {
4015     // All relocations are done, we can protect our segments back to read-only.
4016     if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
4017       DL_ERR("can't protect segments for \"%s\": %s",
4018              get_realpath(), strerror(errno));
4019       return false;
4020     }
4021   }
4022 #endif
4023 
4024   // We can also turn on GNU RELRO protection if we're not linking the dynamic linker
4025   // itself --- it can't make system calls yet, and will have to call protect_relro later.
4026   if (!is_linker() && !protect_relro()) {
4027     return false;
4028   }
4029 
4030   /* Handle serializing/sharing the RELRO segment */
4031   if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
4032     if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
4033                                        extinfo->relro_fd) < 0) {
4034       DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
4035              get_realpath(), strerror(errno));
4036       return false;
4037     }
4038   } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
4039     if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
4040                                  extinfo->relro_fd) < 0) {
4041       DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
4042              get_realpath(), strerror(errno));
4043       return false;
4044     }
4045   }
4046 
4047   notify_gdb_of_load(this);
4048   return true;
4049 }
4050 
protect_relro()4051 bool soinfo::protect_relro() {
4052   if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
4053     DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
4054            get_realpath(), strerror(errno));
4055     return false;
4056   }
4057   return true;
4058 }
4059 
4060 /*
4061  * This function add vdso to internal dso list.
4062  * It helps to stack unwinding through signal handlers.
4063  * Also, it makes bionic more like glibc.
4064  */
add_vdso(KernelArgumentBlock & args __unused)4065 static void add_vdso(KernelArgumentBlock& args __unused) {
4066 #if defined(AT_SYSINFO_EHDR)
4067   ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(args.getauxval(AT_SYSINFO_EHDR));
4068   if (ehdr_vdso == nullptr) {
4069     return;
4070   }
4071 
4072   soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
4073 
4074   si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
4075   si->phnum = ehdr_vdso->e_phnum;
4076   si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
4077   si->size = phdr_table_get_load_size(si->phdr, si->phnum);
4078   si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
4079 
4080   si->prelink_image();
4081   si->link_image(g_empty_list, soinfo::soinfo_list_t::make_list(si), nullptr);
4082 #endif
4083 }
4084 
4085 /* gdb expects the linker to be in the debug shared object list.
4086  * Without this, gdb has trouble locating the linker's ".text"
4087  * and ".plt" sections. Gdb could also potentially use this to
4088  * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
4089  * Note that the linker shouldn't be on the soinfo list.
4090  */
init_linker_info_for_gdb(ElfW (Addr)linker_base)4091 static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
4092   static link_map linker_link_map_for_gdb;
4093 #if defined(__LP64__)
4094   static char kLinkerPath[] = "/system/bin/linker64";
4095 #else
4096   static char kLinkerPath[] = "/system/bin/linker";
4097 #endif
4098 
4099   linker_link_map_for_gdb.l_addr = linker_base;
4100   linker_link_map_for_gdb.l_name = kLinkerPath;
4101 
4102   /*
4103    * Set the dynamic field in the link map otherwise gdb will complain with
4104    * the following:
4105    *   warning: .dynamic section for "/system/bin/linker" is not at the
4106    *   expected address (wrong library or version mismatch?)
4107    */
4108   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
4109   ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
4110   phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
4111                                  &linker_link_map_for_gdb.l_ld, nullptr);
4112 
4113   insert_link_map_into_debug_map(&linker_link_map_for_gdb);
4114 }
4115 
init_default_namespace()4116 static void init_default_namespace() {
4117   g_default_namespace.set_name("(default)");
4118   g_default_namespace.set_isolated(false);
4119 
4120   const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
4121                                                        somain->load_bias);
4122   const char* bname = basename(interp);
4123   if (bname && (strcmp(bname, "linker_asan") == 0 || strcmp(bname, "linker_asan64") == 0)) {
4124     g_default_ld_paths = kAsanDefaultLdPaths;
4125   } else {
4126     g_default_ld_paths = kDefaultLdPaths;
4127   }
4128 
4129   std::vector<std::string> ld_default_paths;
4130   for (size_t i = 0; g_default_ld_paths[i] != nullptr; ++i) {
4131     ld_default_paths.push_back(g_default_ld_paths[i]);
4132   }
4133 
4134   g_default_namespace.set_default_library_paths(std::move(ld_default_paths));
4135 };
4136 
4137 extern "C" int __system_properties_init(void);
4138 
get_executable_path()4139 static const char* get_executable_path() {
4140   static std::string executable_path;
4141   if (executable_path.empty()) {
4142     char path[PATH_MAX];
4143     ssize_t path_len = readlink("/proc/self/exe", path, sizeof(path));
4144     if (path_len == -1 || path_len >= static_cast<ssize_t>(sizeof(path))) {
4145       __libc_fatal("readlink('/proc/self/exe') failed: %s", strerror(errno));
4146     }
4147     executable_path = std::string(path, path_len);
4148   }
4149 
4150   return executable_path.c_str();
4151 }
4152 
4153 /*
4154  * This code is called after the linker has linked itself and
4155  * fixed it's own GOT. It is safe to make references to externs
4156  * and other non-local data at this point.
4157  */
__linker_init_post_relocation(KernelArgumentBlock & args,ElfW (Addr)linker_base)4158 static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW(Addr) linker_base) {
4159 #if TIMING
4160   struct timeval t0, t1;
4161   gettimeofday(&t0, 0);
4162 #endif
4163 
4164   // Sanitize the environment.
4165   __libc_init_AT_SECURE(args);
4166 
4167   // Initialize system properties
4168   __system_properties_init(); // may use 'environ'
4169 
4170   debuggerd_init();
4171 
4172   // Get a few environment variables.
4173   const char* LD_DEBUG = getenv("LD_DEBUG");
4174   if (LD_DEBUG != nullptr) {
4175     g_ld_debug_verbosity = atoi(LD_DEBUG);
4176   }
4177 
4178 #if defined(__LP64__)
4179   INFO("[ Android dynamic linker (64-bit) ]");
4180 #else
4181   INFO("[ Android dynamic linker (32-bit) ]");
4182 #endif
4183 
4184   // These should have been sanitized by __libc_init_AT_SECURE, but the test
4185   // doesn't cost us anything.
4186   const char* ldpath_env = nullptr;
4187   const char* ldpreload_env = nullptr;
4188   if (!getauxval(AT_SECURE)) {
4189     ldpath_env = getenv("LD_LIBRARY_PATH");
4190     if (ldpath_env != nullptr) {
4191       INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
4192     }
4193     ldpreload_env = getenv("LD_PRELOAD");
4194     if (ldpreload_env != nullptr) {
4195       INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
4196     }
4197   }
4198 
4199   const char* executable_path = get_executable_path();
4200   struct stat file_stat;
4201   if (TEMP_FAILURE_RETRY(stat(executable_path, &file_stat)) != 0) {
4202     __libc_fatal("unable to stat file for the executable \"%s\": %s", executable_path, strerror(errno));
4203   }
4204 
4205   soinfo* si = soinfo_alloc(&g_default_namespace, executable_path, &file_stat, 0, RTLD_GLOBAL);
4206   if (si == nullptr) {
4207     __libc_fatal("Couldn't allocate soinfo: out of memory?");
4208   }
4209 
4210   /* bootstrap the link map, the main exe always needs to be first */
4211   si->set_main_executable();
4212   link_map* map = &(si->link_map_head);
4213 
4214   // Register the main executable and the linker upfront to have
4215   // gdb aware of them before loading the rest of the dependency
4216   // tree.
4217   map->l_addr = 0;
4218   map->l_name = const_cast<char*>(executable_path);
4219   insert_link_map_into_debug_map(map);
4220   init_linker_info_for_gdb(linker_base);
4221 
4222   // Extract information passed from the kernel.
4223   si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
4224   si->phnum = args.getauxval(AT_PHNUM);
4225   si->entry = args.getauxval(AT_ENTRY);
4226 
4227   /* Compute the value of si->base. We can't rely on the fact that
4228    * the first entry is the PHDR because this will not be true
4229    * for certain executables (e.g. some in the NDK unit test suite)
4230    */
4231   si->base = 0;
4232   si->size = phdr_table_get_load_size(si->phdr, si->phnum);
4233   si->load_bias = 0;
4234   for (size_t i = 0; i < si->phnum; ++i) {
4235     if (si->phdr[i].p_type == PT_PHDR) {
4236       si->load_bias = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
4237       si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
4238       break;
4239     }
4240   }
4241   si->dynamic = nullptr;
4242 
4243   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
4244   if (elf_hdr->e_type != ET_DYN) {
4245     __libc_fatal("\"%s\": error: only position independent executables (PIE) are supported.",
4246                  args.argv[0]);
4247   }
4248 
4249   // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
4250   parse_LD_LIBRARY_PATH(ldpath_env);
4251   parse_LD_PRELOAD(ldpreload_env);
4252 
4253   somain = si;
4254 
4255   init_default_namespace();
4256 
4257   if (!si->prelink_image()) {
4258     __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", args.argv[0], linker_get_error_buffer());
4259   }
4260 
4261   // add somain to global group
4262   si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
4263 
4264   // Load ld_preloads and dependencies.
4265   StringLinkedList needed_library_name_list;
4266   size_t needed_libraries_count = 0;
4267   size_t ld_preloads_count = 0;
4268 
4269   for (const auto& ld_preload_name : g_ld_preload_names) {
4270     needed_library_name_list.push_back(ld_preload_name.c_str());
4271     ++needed_libraries_count;
4272     ++ld_preloads_count;
4273   }
4274 
4275   for_each_dt_needed(si, [&](const char* name) {
4276     needed_library_name_list.push_back(name);
4277     ++needed_libraries_count;
4278   });
4279 
4280   const char* needed_library_names[needed_libraries_count];
4281 
4282   memset(needed_library_names, 0, sizeof(needed_library_names));
4283   needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count);
4284 
4285   if (needed_libraries_count > 0 &&
4286       !find_libraries(&g_default_namespace, si, needed_library_names, needed_libraries_count,
4287                       nullptr, &g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr,
4288                       /* add_as_children */ true)) {
4289     __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", args.argv[0], linker_get_error_buffer());
4290   } else if (needed_libraries_count == 0) {
4291     if (!si->link_image(g_empty_list, soinfo::soinfo_list_t::make_list(si), nullptr)) {
4292       __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", args.argv[0], linker_get_error_buffer());
4293     }
4294     si->increment_ref_count();
4295   }
4296 
4297   add_vdso(args);
4298 
4299   {
4300     ProtectedDataGuard guard;
4301 
4302     si->call_pre_init_constructors();
4303 
4304     /* After the prelink_image, the si->load_bias is initialized.
4305      * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
4306      * We need to update this value for so exe here. So Unwind_Backtrace
4307      * for some arch like x86 could work correctly within so exe.
4308      */
4309     map->l_addr = si->load_bias;
4310     si->call_constructors();
4311   }
4312 
4313 #if TIMING
4314   gettimeofday(&t1, nullptr);
4315   PRINT("LINKER TIME: %s: %d microseconds", args.argv[0], (int) (
4316            (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
4317            (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
4318 #endif
4319 #if STATS
4320   PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", args.argv[0],
4321          linker_stats.count[kRelocAbsolute],
4322          linker_stats.count[kRelocRelative],
4323          linker_stats.count[kRelocCopy],
4324          linker_stats.count[kRelocSymbol]);
4325 #endif
4326 #if COUNT_PAGES
4327   {
4328     unsigned n;
4329     unsigned i;
4330     unsigned count = 0;
4331     for (n = 0; n < 4096; n++) {
4332       if (bitmask[n]) {
4333         unsigned x = bitmask[n];
4334 #if defined(__LP64__)
4335         for (i = 0; i < 32; i++) {
4336 #else
4337         for (i = 0; i < 8; i++) {
4338 #endif
4339           if (x & 1) {
4340             count++;
4341           }
4342           x >>= 1;
4343         }
4344       }
4345     }
4346     PRINT("PAGES MODIFIED: %s: %d (%dKB)", args.argv[0], count, count * 4);
4347   }
4348 #endif
4349 
4350 #if TIMING || STATS || COUNT_PAGES
4351   fflush(stdout);
4352 #endif
4353 
4354   TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(si->entry));
4355   return si->entry;
4356 }
4357 
4358 /* Compute the load-bias of an existing executable. This shall only
4359  * be used to compute the load bias of an executable or shared library
4360  * that was loaded by the kernel itself.
4361  *
4362  * Input:
4363  *    elf    -> address of ELF header, assumed to be at the start of the file.
4364  * Return:
4365  *    load bias, i.e. add the value of any p_vaddr in the file to get
4366  *    the corresponding address in memory.
4367  */
4368 static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
4369   ElfW(Addr) offset = elf->e_phoff;
4370   const ElfW(Phdr)* phdr_table =
4371       reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
4372   const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
4373 
4374   for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
4375     if (phdr->p_type == PT_LOAD) {
4376       return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
4377     }
4378   }
4379   return 0;
4380 }
4381 
4382 static void __linker_cannot_link(KernelArgumentBlock& args) {
4383   __libc_fatal("CANNOT LINK EXECUTABLE \"%s\": %s", args.argv[0], linker_get_error_buffer());
4384 }
4385 
4386 /*
4387  * This is the entry point for the linker, called from begin.S. This
4388  * method is responsible for fixing the linker's own relocations, and
4389  * then calling __linker_init_post_relocation().
4390  *
4391  * Because this method is called before the linker has fixed it's own
4392  * relocations, any attempt to reference an extern variable, extern
4393  * function, or other GOT reference will generate a segfault.
4394  */
4395 extern "C" ElfW(Addr) __linker_init(void* raw_args) {
4396   KernelArgumentBlock args(raw_args);
4397 
4398   ElfW(Addr) linker_addr = args.getauxval(AT_BASE);
4399   ElfW(Addr) entry_point = args.getauxval(AT_ENTRY);
4400   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
4401   ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
4402 
4403   soinfo linker_so(nullptr, nullptr, nullptr, 0, 0);
4404 
4405   // If the linker is not acting as PT_INTERP entry_point is equal to
4406   // _start. Which means that the linker is running as an executable and
4407   // already linked by PT_INTERP.
4408   //
4409   // This happens when user tries to run 'adb shell /system/bin/linker'
4410   // see also https://code.google.com/p/android/issues/detail?id=63174
4411   if (reinterpret_cast<ElfW(Addr)>(&_start) == entry_point) {
4412     __libc_format_fd(STDOUT_FILENO,
4413                      "This is %s, the helper program for shared library executables.\n",
4414                      args.argv[0]);
4415     exit(0);
4416   }
4417 
4418   linker_so.base = linker_addr;
4419   linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
4420   linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
4421   linker_so.dynamic = nullptr;
4422   linker_so.phdr = phdr;
4423   linker_so.phnum = elf_hdr->e_phnum;
4424   linker_so.set_linker_flag();
4425 
4426   // Prelink the linker so we can access linker globals.
4427   if (!linker_so.prelink_image()) __linker_cannot_link(args);
4428 
4429   // This might not be obvious... The reasons why we pass g_empty_list
4430   // in place of local_group here are (1) we do not really need it, because
4431   // linker is built with DT_SYMBOLIC and therefore relocates its symbols against
4432   // itself without having to look into local_group and (2) allocators
4433   // are not yet initialized, and therefore we cannot use linked_list.push_*
4434   // functions at this point.
4435   if (!linker_so.link_image(g_empty_list, g_empty_list, nullptr)) __linker_cannot_link(args);
4436 
4437 #if defined(__i386__)
4438   // On x86, we can't make system calls before this point.
4439   // We can't move this up because this needs to assign to a global.
4440   // Note that until we call __libc_init_main_thread below we have
4441   // no TLS, so you shouldn't make a system call that can fail, because
4442   // it will SEGV when it tries to set errno.
4443   __libc_init_sysinfo(args);
4444 #endif
4445 
4446   // Initialize the main thread (including TLS, so system calls really work).
4447   __libc_init_main_thread(args);
4448 
4449   // We didn't protect the linker's RELRO pages in link_image because we
4450   // couldn't make system calls on x86 at that point, but we can now...
4451   if (!linker_so.protect_relro()) __linker_cannot_link(args);
4452 
4453   // Initialize the linker's static libc's globals
4454   __libc_init_globals(args);
4455 
4456   // Initialize the linker's own global variables
4457   linker_so.call_constructors();
4458 
4459   // Initialize static variables. Note that in order to
4460   // get correct libdl_info we need to call constructors
4461   // before get_libdl_info().
4462   solist = get_libdl_info();
4463   sonext = get_libdl_info();
4464   g_default_namespace.add_soinfo(get_libdl_info());
4465 
4466   // We have successfully fixed our own relocations. It's safe to run
4467   // the main part of the linker now.
4468   args.abort_message_ptr = &g_abort_message;
4469   ElfW(Addr) start_address = __linker_init_post_relocation(args, linker_addr);
4470 
4471   INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
4472 
4473   // Return the address that the calling assembly stub should jump to.
4474   return start_address;
4475 }
4476