OSDN Git Service

am eae09772: Revert "Remove unnecessary lookups during relocations"
[android-x86/bionic.git] / linker / linker.cpp
1 /*
2  * Copyright (C) 2008, 2009 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 <dlfcn.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 <unistd.h>
39
40 #include <new>
41
42 // Private C library headers.
43 #include "private/bionic_tls.h"
44 #include "private/KernelArgumentBlock.h"
45 #include "private/ScopedPthreadMutexLocker.h"
46 #include "private/ScopedFd.h"
47 #include "private/ScopeGuard.h"
48 #include "private/UniquePtr.h"
49
50 #include "linker.h"
51 #include "linker_debug.h"
52 #include "linker_environ.h"
53 #include "linker_phdr.h"
54 #include "linker_allocator.h"
55
56 /* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
57  *
58  * Do NOT use malloc() and friends or pthread_*() code here.
59  * Don't use printf() either; it's caused mysterious memory
60  * corruption in the past.
61  * The linker runs before we bring up libc and it's easiest
62  * to make sure it does not depend on any complex libc features
63  *
64  * open issues / todo:
65  *
66  * - cleaner error reporting
67  * - after linking, set as much stuff as possible to READONLY
68  *   and NOEXEC
69  */
70
71 #if defined(__LP64__)
72 #define SEARCH_NAME(x) x
73 #else
74 // Nvidia drivers are relying on the bug:
75 // http://code.google.com/p/android/issues/detail?id=6670
76 // so we continue to use base-name lookup for lp32
77 static const char* get_base_name(const char* name) {
78   const char* bname = strrchr(name, '/');
79   return bname ? bname + 1 : name;
80 }
81 #define SEARCH_NAME(x) get_base_name(x)
82 #endif
83
84 static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
85
86 static LinkerAllocator<soinfo> g_soinfo_allocator;
87 static LinkerAllocator<LinkedListEntry<soinfo>> g_soinfo_links_allocator;
88
89 static soinfo* solist;
90 static soinfo* sonext;
91 static soinfo* somain; // main process, always the one after libdl_info
92
93 static const char* const kDefaultLdPaths[] = {
94 #if defined(__LP64__)
95   "/vendor/lib64",
96   "/system/lib64",
97 #else
98   "/vendor/lib",
99   "/system/lib",
100 #endif
101   nullptr
102 };
103
104 #define LDPATH_BUFSIZE (LDPATH_MAX*64)
105 #define LDPATH_MAX 8
106
107 #define LDPRELOAD_BUFSIZE (LDPRELOAD_MAX*64)
108 #define LDPRELOAD_MAX 8
109
110 static char g_ld_library_paths_buffer[LDPATH_BUFSIZE];
111 static const char* g_ld_library_paths[LDPATH_MAX + 1];
112
113 static char g_ld_preloads_buffer[LDPRELOAD_BUFSIZE];
114 static const char* g_ld_preload_names[LDPRELOAD_MAX + 1];
115
116 static soinfo* g_ld_preloads[LDPRELOAD_MAX + 1];
117
118 __LIBC_HIDDEN__ int g_ld_debug_verbosity;
119
120 __LIBC_HIDDEN__ abort_msg_t* g_abort_message = nullptr; // For debuggerd.
121
122 enum RelocationKind {
123   kRelocAbsolute = 0,
124   kRelocRelative,
125   kRelocCopy,
126   kRelocSymbol,
127   kRelocMax
128 };
129
130 #if STATS
131 struct linker_stats_t {
132   int count[kRelocMax];
133 };
134
135 static linker_stats_t linker_stats;
136
137 static void count_relocation(RelocationKind kind) {
138   ++linker_stats.count[kind];
139 }
140 #else
141 static void count_relocation(RelocationKind) {
142 }
143 #endif
144
145 #if COUNT_PAGES
146 static unsigned bitmask[4096];
147 #if defined(__LP64__)
148 #define MARK(offset) \
149     do { \
150       if ((((offset) >> 12) >> 5) < 4096) \
151           bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \
152     } while (0)
153 #else
154 #define MARK(offset) \
155     do { \
156       bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \
157     } while (0)
158 #endif
159 #else
160 #define MARK(x) do {} while (0)
161 #endif
162
163 // You shouldn't try to call memory-allocating functions in the dynamic linker.
164 // Guard against the most obvious ones.
165 #define DISALLOW_ALLOCATION(return_type, name, ...) \
166     return_type name __VA_ARGS__ \
167     { \
168       __libc_fatal("ERROR: " #name " called from the dynamic linker!\n"); \
169     }
170 DISALLOW_ALLOCATION(void*, malloc, (size_t u __unused));
171 DISALLOW_ALLOCATION(void, free, (void* u __unused));
172 DISALLOW_ALLOCATION(void*, realloc, (void* u1 __unused, size_t u2 __unused));
173 DISALLOW_ALLOCATION(void*, calloc, (size_t u1 __unused, size_t u2 __unused));
174
175 static char __linker_dl_err_buf[768];
176
177 char* linker_get_error_buffer() {
178   return &__linker_dl_err_buf[0];
179 }
180
181 size_t linker_get_error_buffer_size() {
182   return sizeof(__linker_dl_err_buf);
183 }
184
185 // This function is an empty stub where GDB locates a breakpoint to get notified
186 // about linker activity.
187 extern "C" void __attribute__((noinline)) __attribute__((visibility("default"))) rtld_db_dlactivity();
188
189 static pthread_mutex_t g__r_debug_mutex = PTHREAD_MUTEX_INITIALIZER;
190 static r_debug _r_debug = {1, nullptr, reinterpret_cast<uintptr_t>(&rtld_db_dlactivity), r_debug::RT_CONSISTENT, 0};
191 static link_map* r_debug_tail = 0;
192
193 static void insert_soinfo_into_debug_map(soinfo* info) {
194   // Copy the necessary fields into the debug structure.
195   link_map* map = &(info->link_map_head);
196   map->l_addr = info->load_bias;
197   map->l_name = info->name;
198   map->l_ld = info->dynamic;
199
200   // Stick the new library at the end of the list.
201   // gdb tends to care more about libc than it does
202   // about leaf libraries, and ordering it this way
203   // reduces the back-and-forth over the wire.
204   if (r_debug_tail) {
205     r_debug_tail->l_next = map;
206     map->l_prev = r_debug_tail;
207     map->l_next = 0;
208   } else {
209     _r_debug.r_map = map;
210     map->l_prev = 0;
211     map->l_next = 0;
212   }
213   r_debug_tail = map;
214 }
215
216 static void remove_soinfo_from_debug_map(soinfo* info) {
217   link_map* map = &(info->link_map_head);
218
219   if (r_debug_tail == map) {
220     r_debug_tail = map->l_prev;
221   }
222
223   if (map->l_prev) {
224     map->l_prev->l_next = map->l_next;
225   }
226   if (map->l_next) {
227     map->l_next->l_prev = map->l_prev;
228   }
229 }
230
231 static void notify_gdb_of_load(soinfo* info) {
232   if (info->flags & FLAG_EXE) {
233     // GDB already knows about the main executable
234     return;
235   }
236
237   ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
238
239   _r_debug.r_state = r_debug::RT_ADD;
240   rtld_db_dlactivity();
241
242   insert_soinfo_into_debug_map(info);
243
244   _r_debug.r_state = r_debug::RT_CONSISTENT;
245   rtld_db_dlactivity();
246 }
247
248 static void notify_gdb_of_unload(soinfo* info) {
249   if (info->flags & FLAG_EXE) {
250     // GDB already knows about the main executable
251     return;
252   }
253
254   ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
255
256   _r_debug.r_state = r_debug::RT_DELETE;
257   rtld_db_dlactivity();
258
259   remove_soinfo_from_debug_map(info);
260
261   _r_debug.r_state = r_debug::RT_CONSISTENT;
262   rtld_db_dlactivity();
263 }
264
265 void notify_gdb_of_libraries() {
266   _r_debug.r_state = r_debug::RT_ADD;
267   rtld_db_dlactivity();
268   _r_debug.r_state = r_debug::RT_CONSISTENT;
269   rtld_db_dlactivity();
270 }
271
272 LinkedListEntry<soinfo>* SoinfoListAllocator::alloc() {
273   return g_soinfo_links_allocator.alloc();
274 }
275
276 void SoinfoListAllocator::free(LinkedListEntry<soinfo>* entry) {
277   g_soinfo_links_allocator.free(entry);
278 }
279
280 static void protect_data(int protection) {
281   g_soinfo_allocator.protect_all(protection);
282   g_soinfo_links_allocator.protect_all(protection);
283 }
284
285 static soinfo* soinfo_alloc(const char* name, struct stat* file_stat, off64_t file_offset, int rtld_flags) {
286   if (strlen(name) >= SOINFO_NAME_LEN) {
287     DL_ERR("library name \"%s\" too long", name);
288     return nullptr;
289   }
290
291   soinfo* si = new (g_soinfo_allocator.alloc()) soinfo(name, file_stat, file_offset, rtld_flags);
292
293   sonext->next = si;
294   sonext = si;
295
296   TRACE("name %s: allocated soinfo @ %p", name, si);
297   return si;
298 }
299
300 static void soinfo_free(soinfo* si) {
301   if (si == nullptr) {
302     return;
303   }
304
305   if (si->base != 0 && si->size != 0) {
306     munmap(reinterpret_cast<void*>(si->base), si->size);
307   }
308
309   soinfo *prev = nullptr, *trav;
310
311   TRACE("name %s: freeing soinfo @ %p", si->name, si);
312
313   for (trav = solist; trav != nullptr; trav = trav->next) {
314     if (trav == si) {
315       break;
316     }
317     prev = trav;
318   }
319   if (trav == nullptr) {
320     // si was not in solist
321     DL_ERR("name \"%s\" is not in solist!", si->name);
322     return;
323   }
324
325   // clear links to/from si
326   si->remove_all_links();
327
328   // prev will never be null, because the first entry in solist is
329   // always the static libdl_info.
330   prev->next = si->next;
331   if (si == sonext) {
332     sonext = prev;
333   }
334
335   g_soinfo_allocator.free(si);
336 }
337
338
339 static void parse_path(const char* path, const char* delimiters,
340                        const char** array, char* buf, size_t buf_size, size_t max_count) {
341   if (path == nullptr) {
342     return;
343   }
344
345   size_t len = strlcpy(buf, path, buf_size);
346
347   size_t i = 0;
348   char* buf_p = buf;
349   while (i < max_count && (array[i] = strsep(&buf_p, delimiters))) {
350     if (*array[i] != '\0') {
351       ++i;
352     }
353   }
354
355   // Forget the last path if we had to truncate; this occurs if the 2nd to
356   // last char isn't '\0' (i.e. wasn't originally a delimiter).
357   if (i > 0 && len >= buf_size && buf[buf_size - 2] != '\0') {
358     array[i - 1] = nullptr;
359   } else {
360     array[i] = nullptr;
361   }
362 }
363
364 static void parse_LD_LIBRARY_PATH(const char* path) {
365   parse_path(path, ":", g_ld_library_paths,
366              g_ld_library_paths_buffer, sizeof(g_ld_library_paths_buffer), LDPATH_MAX);
367 }
368
369 static void parse_LD_PRELOAD(const char* path) {
370   // We have historically supported ':' as well as ' ' in LD_PRELOAD.
371   parse_path(path, " :", g_ld_preload_names,
372              g_ld_preloads_buffer, sizeof(g_ld_preloads_buffer), LDPRELOAD_MAX);
373 }
374
375 #if defined(__arm__)
376
377 // For a given PC, find the .so that it belongs to.
378 // Returns the base address of the .ARM.exidx section
379 // for that .so, and the number of 8-byte entries
380 // in that section (via *pcount).
381 //
382 // Intended to be called by libc's __gnu_Unwind_Find_exidx().
383 //
384 // This function is exposed via dlfcn.cpp and libdl.so.
385 _Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
386   unsigned addr = (unsigned)pc;
387
388   for (soinfo* si = solist; si != 0; si = si->next) {
389     if ((addr >= si->base) && (addr < (si->base + si->size))) {
390         *pcount = si->ARM_exidx_count;
391         return (_Unwind_Ptr)si->ARM_exidx;
392     }
393   }
394   *pcount = 0;
395   return nullptr;
396 }
397
398 #endif
399
400 // Here, we only have to provide a callback to iterate across all the
401 // loaded libraries. gcc_eh does the rest.
402 int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
403   int rv = 0;
404   for (soinfo* si = solist; si != nullptr; si = si->next) {
405     dl_phdr_info dl_info;
406     dl_info.dlpi_addr = si->link_map_head.l_addr;
407     dl_info.dlpi_name = si->link_map_head.l_name;
408     dl_info.dlpi_phdr = si->phdr;
409     dl_info.dlpi_phnum = si->phnum;
410     rv = cb(&dl_info, sizeof(dl_phdr_info), data);
411     if (rv != 0) {
412       break;
413     }
414   }
415   return rv;
416 }
417
418 static ElfW(Sym)* soinfo_elf_lookup(const soinfo* si, unsigned hash, const char* name) {
419   ElfW(Sym)* symtab = si->symtab;
420
421   TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p %x %zd",
422              name, si->name, reinterpret_cast<void*>(si->base), hash, hash % si->nbucket);
423
424   for (unsigned n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]) {
425     ElfW(Sym)* s = symtab + n;
426     if (strcmp(si->get_string(s->st_name), name)) continue;
427
428     // only concern ourselves with global and weak symbol definitions
429     switch (ELF_ST_BIND(s->st_info)) {
430       case STB_GLOBAL:
431       case STB_WEAK:
432         if (s->st_shndx == SHN_UNDEF) {
433           continue;
434         }
435
436         TRACE_TYPE(LOOKUP, "FOUND %s in %s (%p) %zd",
437                  name, si->name, reinterpret_cast<void*>(s->st_value),
438                  static_cast<size_t>(s->st_size));
439         return s;
440       case STB_LOCAL:
441         continue;
442       default:
443         __libc_fatal("ERROR: Unexpected ST_BIND value: %d for '%s' in '%s'",
444             ELF_ST_BIND(s->st_info), name, si->name);
445     }
446   }
447
448   TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p %x %zd",
449              name, si->name, reinterpret_cast<void*>(si->base), hash, hash % si->nbucket);
450
451
452   return nullptr;
453 }
454
455 soinfo::soinfo(const char* name, const struct stat* file_stat, off64_t file_offset, int rtld_flags) {
456   memset(this, 0, sizeof(*this));
457
458   strlcpy(this->name, name, sizeof(this->name));
459   flags = FLAG_NEW_SOINFO;
460   version = SOINFO_VERSION;
461
462   if (file_stat != nullptr) {
463     this->st_dev = file_stat->st_dev;
464     this->st_ino = file_stat->st_ino;
465     this->file_offset = file_offset;
466   }
467
468   this->rtld_flags = rtld_flags;
469 }
470
471 static unsigned elfhash(const char* _name) {
472   const unsigned char* name = reinterpret_cast<const unsigned char*>(_name);
473   unsigned h = 0, g;
474
475   while (*name) {
476     h = (h << 4) + *name++;
477     g = h & 0xf0000000;
478     h ^= g;
479     h ^= g >> 24;
480   }
481   return h;
482 }
483
484 static ElfW(Sym)* soinfo_do_lookup(soinfo* si, const char* name, soinfo** lsi, const soinfo::soinfo_list_t& local_group) {
485   unsigned elf_hash = elfhash(name);
486   ElfW(Sym)* s = nullptr;
487
488   /* "This element's presence in a shared object library alters the dynamic linker's
489    * symbol resolution algorithm for references within the library. Instead of starting
490    * a symbol search with the executable file, the dynamic linker starts from the shared
491    * object itself. If the shared object fails to supply the referenced symbol, the
492    * dynamic linker then searches the executable file and other shared objects as usual."
493    *
494    * http://www.sco.com/developers/gabi/2012-12-31/ch5.dynamic.html
495    *
496    * Note that this is unlikely since static linker avoids generating
497    * relocations for -Bsymbolic linked dynamic executables.
498    */
499   if (si->has_DT_SYMBOLIC) {
500     DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si->name, name);
501     s = soinfo_elf_lookup(si, elf_hash, name);
502     if (s != nullptr) {
503       *lsi = si;
504     }
505   }
506
507   if (s == nullptr && somain != nullptr) {
508     // 1. Look for it in the main executable unless we already did.
509     if (si != somain || !si->has_DT_SYMBOLIC) {
510       DEBUG("%s: looking up %s in executable %s",
511             si->name, name, somain->name);
512       s = soinfo_elf_lookup(somain, elf_hash, name);
513       if (s != nullptr) {
514         *lsi = somain;
515       }
516     }
517
518     // 2. Look for it in the ld_preloads
519     if (s == nullptr) {
520       for (int i = 0; g_ld_preloads[i] != NULL; i++) {
521         s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name);
522         if (s != nullptr) {
523           *lsi = g_ld_preloads[i];
524           break;
525         }
526       }
527     }
528   }
529
530   // 3. Look for it in the local group
531   if (s == nullptr) {
532     local_group.visit([&](soinfo* local_si) {
533       DEBUG("%s: looking up %s in %s (from local group)", si->name, name, local_si->name);
534       s = soinfo_elf_lookup(local_si, elf_hash, name);
535       if (s != nullptr) {
536         *lsi = local_si;
537         return false;
538       }
539
540       return true;
541     });
542   }
543
544   // 4. Look for it in this library (unless we already did it because of DT_SYMBOLIC)
545   if (s == nullptr && !si->has_DT_SYMBOLIC) {
546     DEBUG("%s: looking up %s in local scope", si->name, name);
547     s = soinfo_elf_lookup(si, elf_hash, name);
548     if (s != nullptr) {
549       *lsi = si;
550     }
551   }
552
553   // 5. Dependencies
554   if (s == nullptr) {
555     si->get_children().visit([&](soinfo* child) {
556       DEBUG("%s: looking up %s in %s", si->name, name, child->name);
557       s = soinfo_elf_lookup(child, elf_hash, name);
558       if (s != nullptr) {
559         *lsi = child;
560         return false;
561       }
562       return true;
563     });
564   }
565
566   if (s != nullptr) {
567     TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
568                "found in %s, base = %p, load bias = %p",
569                si->name, name, reinterpret_cast<void*>(s->st_value),
570                (*lsi)->name, reinterpret_cast<void*>((*lsi)->base),
571                reinterpret_cast<void*>((*lsi)->load_bias));
572   }
573
574   return s;
575 }
576
577 // Each size has it's own allocator.
578 template<size_t size>
579 class SizeBasedAllocator {
580  public:
581   static void* alloc() {
582     return allocator_.alloc();
583   }
584
585   static void free(void* ptr) {
586     allocator_.free(ptr);
587   }
588
589  private:
590   static LinkerBlockAllocator allocator_;
591 };
592
593 template<size_t size>
594 LinkerBlockAllocator SizeBasedAllocator<size>::allocator_(size);
595
596 template<typename T>
597 class TypeBasedAllocator {
598  public:
599   static T* alloc() {
600     return reinterpret_cast<T*>(SizeBasedAllocator<sizeof(T)>::alloc());
601   }
602
603   static void free(T* ptr) {
604     SizeBasedAllocator<sizeof(T)>::free(ptr);
605   }
606 };
607
608 class LoadTask {
609  public:
610   struct deleter_t {
611     void operator()(LoadTask* t) {
612       TypeBasedAllocator<LoadTask>::free(t);
613     }
614   };
615
616   typedef UniquePtr<LoadTask, deleter_t> unique_ptr;
617
618   static deleter_t deleter;
619
620   static LoadTask* create(const char* name, soinfo* needed_by) {
621     LoadTask* ptr = TypeBasedAllocator<LoadTask>::alloc();
622     return new (ptr) LoadTask(name, needed_by);
623   }
624
625   const char* get_name() const {
626     return name_;
627   }
628
629   soinfo* get_needed_by() const {
630     return needed_by_;
631   }
632  private:
633   LoadTask(const char* name, soinfo* needed_by)
634     : name_(name), needed_by_(needed_by) {}
635
636   const char* name_;
637   soinfo* needed_by_;
638
639   DISALLOW_IMPLICIT_CONSTRUCTORS(LoadTask);
640 };
641
642 LoadTask::deleter_t LoadTask::deleter;
643
644 template <typename T>
645 using linked_list_t = LinkedList<T, TypeBasedAllocator<LinkedListEntry<T>>>;
646
647 typedef linked_list_t<soinfo> SoinfoLinkedList;
648 typedef linked_list_t<const char> StringLinkedList;
649 typedef linked_list_t<LoadTask> LoadTaskList;
650
651
652 // This function walks down the tree of soinfo dependencies
653 // in breadth-first order and
654 //   * calls action(soinfo* si) for each node, and
655 //   * terminates walk if action returns false.
656 //
657 // walk_dependencies_tree returns false if walk was terminated
658 // by the action and true otherwise.
659 template<typename F>
660 static bool walk_dependencies_tree(soinfo* root_soinfos[], size_t root_soinfos_size, F action) {
661   SoinfoLinkedList visit_list;
662   SoinfoLinkedList visited;
663
664   for (size_t i = 0; i < root_soinfos_size; ++i) {
665     visit_list.push_back(root_soinfos[i]);
666   }
667
668   soinfo* si;
669   while ((si = visit_list.pop_front()) != nullptr) {
670     if (visited.contains(si)) {
671       continue;
672     }
673
674     if (!action(si)) {
675       return false;
676     }
677
678     visited.push_back(si);
679
680     si->get_children().for_each([&](soinfo* child) {
681       visit_list.push_back(child);
682     });
683   }
684
685   return true;
686 }
687
688
689 // This is used by dlsym(3).  It performs symbol lookup only within the
690 // specified soinfo object and its dependencies in breadth first order.
691 ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) {
692   ElfW(Sym)* result = nullptr;
693   uint32_t elf_hash = elfhash(name);
694
695
696   walk_dependencies_tree(&si, 1, [&](soinfo* current_soinfo) {
697     result = soinfo_elf_lookup(current_soinfo, elf_hash, name);
698     if (result != nullptr) {
699       *found = current_soinfo;
700       return false;
701     }
702
703     return true;
704   });
705
706   return result;
707 }
708
709 /* This is used by dlsym(3) to performs a global symbol lookup. If the
710    start value is null (for RTLD_DEFAULT), the search starts at the
711    beginning of the global solist. Otherwise the search starts at the
712    specified soinfo (for RTLD_NEXT).
713  */
714 ElfW(Sym)* dlsym_linear_lookup(const char* name, soinfo** found, soinfo* start) {
715   unsigned elf_hash = elfhash(name);
716
717   if (start == nullptr) {
718     start = solist;
719   }
720
721   ElfW(Sym)* s = nullptr;
722   for (soinfo* si = start; (s == nullptr) && (si != nullptr); si = si->next) {
723     if ((si->get_rtld_flags() & RTLD_GLOBAL) == 0) {
724       continue;
725     }
726
727     s = soinfo_elf_lookup(si, elf_hash, name);
728     if (s != nullptr) {
729       *found = si;
730       break;
731     }
732   }
733
734   if (s != nullptr) {
735     TRACE_TYPE(LOOKUP, "%s s->st_value = %p, found->base = %p",
736                name, reinterpret_cast<void*>(s->st_value), reinterpret_cast<void*>((*found)->base));
737   }
738
739   return s;
740 }
741
742 soinfo* find_containing_library(const void* p) {
743   ElfW(Addr) address = reinterpret_cast<ElfW(Addr)>(p);
744   for (soinfo* si = solist; si != nullptr; si = si->next) {
745     if (address >= si->base && address - si->base < si->size) {
746       return si;
747     }
748   }
749   return nullptr;
750 }
751
752 ElfW(Sym)* dladdr_find_symbol(soinfo* si, const void* addr) {
753   ElfW(Addr) soaddr = reinterpret_cast<ElfW(Addr)>(addr) - si->base;
754
755   // Search the library's symbol table for any defined symbol which
756   // contains this address.
757   for (size_t i = 0; i < si->nchain; ++i) {
758     ElfW(Sym)* sym = &si->symtab[i];
759     if (sym->st_shndx != SHN_UNDEF &&
760         soaddr >= sym->st_value &&
761         soaddr < sym->st_value + sym->st_size) {
762       return sym;
763     }
764   }
765
766   return nullptr;
767 }
768
769 static int open_library_on_path(const char* name, const char* const paths[]) {
770   char buf[512];
771   for (size_t i = 0; paths[i] != nullptr; ++i) {
772     int n = __libc_format_buffer(buf, sizeof(buf), "%s/%s", paths[i], name);
773     if (n < 0 || n >= static_cast<int>(sizeof(buf))) {
774       PRINT("Warning: ignoring very long library path: %s/%s", paths[i], name);
775       continue;
776     }
777     int fd = TEMP_FAILURE_RETRY(open(buf, O_RDONLY | O_CLOEXEC));
778     if (fd != -1) {
779       return fd;
780     }
781   }
782   return -1;
783 }
784
785 static int open_library(const char* name) {
786   TRACE("[ opening %s ]", name);
787
788   // If the name contains a slash, we should attempt to open it directly and not search the paths.
789   if (strchr(name, '/') != nullptr) {
790     int fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY | O_CLOEXEC));
791     if (fd != -1) {
792       return fd;
793     }
794     // ...but nvidia binary blobs (at least) rely on this behavior, so fall through for now.
795 #if defined(__LP64__)
796     return -1;
797 #endif
798   }
799
800   // Otherwise we try LD_LIBRARY_PATH first, and fall back to the built-in well known paths.
801   int fd = open_library_on_path(name, g_ld_library_paths);
802   if (fd == -1) {
803     fd = open_library_on_path(name, kDefaultLdPaths);
804   }
805   return fd;
806 }
807
808 template<typename F>
809 static void for_each_dt_needed(const soinfo* si, F action) {
810   for (ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
811     if (d->d_tag == DT_NEEDED) {
812       action(si->get_string(d->d_un.d_val));
813     }
814   }
815 }
816
817 static soinfo* load_library(LoadTaskList& load_tasks, const char* name, int rtld_flags, const android_dlextinfo* extinfo) {
818   int fd = -1;
819   off64_t file_offset = 0;
820   ScopedFd file_guard(-1);
821
822   if (extinfo != nullptr && (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) != 0) {
823     fd = extinfo->library_fd;
824     if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
825       file_offset = extinfo->library_fd_offset;
826     }
827   } else {
828     // Open the file.
829     fd = open_library(name);
830     if (fd == -1) {
831       DL_ERR("library \"%s\" not found", name);
832       return nullptr;
833     }
834
835     file_guard.reset(fd);
836   }
837
838   if ((file_offset % PAGE_SIZE) != 0) {
839     DL_ERR("file offset for the library \"%s\" is not page-aligned: %" PRId64, name, file_offset);
840     return nullptr;
841   }
842
843   struct stat file_stat;
844   if (TEMP_FAILURE_RETRY(fstat(fd, &file_stat)) != 0) {
845     DL_ERR("unable to stat file for the library \"%s\": %s", name, strerror(errno));
846     return nullptr;
847   }
848
849   // Check for symlink and other situations where
850   // file can have different names.
851   for (soinfo* si = solist; si != nullptr; si = si->next) {
852     if (si->get_st_dev() != 0 &&
853         si->get_st_ino() != 0 &&
854         si->get_st_dev() == file_stat.st_dev &&
855         si->get_st_ino() == file_stat.st_ino &&
856         si->get_file_offset() == file_offset) {
857       TRACE("library \"%s\" is already loaded under different name/path \"%s\" - will return existing soinfo", name, si->name);
858       return si;
859     }
860   }
861
862   if ((rtld_flags & RTLD_NOLOAD) != 0) {
863     DL_ERR("library \"%s\" wasn't loaded and RTLD_NOLOAD prevented it", name);
864     return nullptr;
865   }
866
867   // Read the ELF header and load the segments.
868   ElfReader elf_reader(name, fd, file_offset);
869   if (!elf_reader.Load(extinfo)) {
870     return nullptr;
871   }
872
873   soinfo* si = soinfo_alloc(SEARCH_NAME(name), &file_stat, file_offset, rtld_flags);
874   if (si == nullptr) {
875     return nullptr;
876   }
877   si->base = elf_reader.load_start();
878   si->size = elf_reader.load_size();
879   si->load_bias = elf_reader.load_bias();
880   si->phnum = elf_reader.phdr_count();
881   si->phdr = elf_reader.loaded_phdr();
882
883   if (!si->PrelinkImage()) {
884     soinfo_free(si);
885     return nullptr;
886   }
887
888   for_each_dt_needed(si, [&] (const char* name) {
889     load_tasks.push_back(LoadTask::create(name, si));
890   });
891
892   return si;
893 }
894
895 static soinfo *find_loaded_library_by_name(const char* name) {
896   const char* search_name = SEARCH_NAME(name);
897   for (soinfo* si = solist; si != nullptr; si = si->next) {
898     if (!strcmp(search_name, si->name)) {
899       return si;
900     }
901   }
902   return nullptr;
903 }
904
905 static soinfo* find_library_internal(LoadTaskList& load_tasks, const char* name, int rtld_flags, const android_dlextinfo* extinfo) {
906
907   soinfo* si = find_loaded_library_by_name(name);
908
909   // Library might still be loaded, the accurate detection
910   // of this fact is done by load_library.
911   if (si == nullptr) {
912     TRACE("[ '%s' has not been found by name.  Trying harder...]", name);
913     si = load_library(load_tasks, name, rtld_flags, extinfo);
914   }
915
916   return si;
917 }
918
919 static void soinfo_unload(soinfo* si);
920
921 static bool is_recursive(soinfo* si, soinfo* parent) {
922   if (parent == nullptr) {
923     return false;
924   }
925
926   if (si == parent) {
927     DL_ERR("recursive link to \"%s\"", si->name);
928     return true;
929   }
930
931   return !parent->get_parents().visit([&](soinfo* grandparent) {
932     return !is_recursive(si, grandparent);
933   });
934 }
935
936 static bool find_libraries(soinfo* start_with, const char* const library_names[], size_t library_names_count, soinfo* soinfos[],
937     soinfo* ld_preloads[], size_t ld_preloads_count, int rtld_flags, const android_dlextinfo* extinfo) {
938   // Step 0: prepare.
939   LoadTaskList load_tasks;
940   for (size_t i = 0; i < library_names_count; ++i) {
941     const char* name = library_names[i];
942     load_tasks.push_back(LoadTask::create(name, start_with));
943   }
944
945   // If soinfos array is null allocate one on stack.
946   // The array is needed in case of failure; for example
947   // when library_names[] = {libone.so, libtwo.so} and libone.so
948   // is loaded correctly but libtwo.so failed for some reason.
949   // In this case libone.so should be unloaded on return.
950   // See also implementation of failure_guard below.
951
952   if (soinfos == nullptr) {
953     size_t soinfos_size = sizeof(soinfo*)*library_names_count;
954     soinfos = reinterpret_cast<soinfo**>(alloca(soinfos_size));
955     memset(soinfos, 0, soinfos_size);
956   }
957
958   // list of libraries to link - see step 2.
959   size_t soinfos_count = 0;
960
961   auto failure_guard = make_scope_guard([&]() {
962     // Housekeeping
963     load_tasks.for_each([] (LoadTask* t) {
964       LoadTask::deleter(t);
965     });
966
967     for (size_t i = 0; i<soinfos_count; ++i) {
968       soinfo_unload(soinfos[i]);
969     }
970   });
971
972   // Step 1: load and pre-link all DT_NEEDED libraries in breadth first order.
973   for (LoadTask::unique_ptr task(load_tasks.pop_front()); task.get() != nullptr; task.reset(load_tasks.pop_front())) {
974     soinfo* si = find_library_internal(load_tasks, task->get_name(), rtld_flags, extinfo);
975     if (si == nullptr) {
976       return false;
977     }
978
979     soinfo* needed_by = task->get_needed_by();
980
981     if (is_recursive(si, needed_by)) {
982       return false;
983     }
984
985     si->ref_count++;
986     if (needed_by != nullptr) {
987       needed_by->add_child(si);
988     }
989
990     // When ld_preloads is not null, the first
991     // ld_preloads_count libs are in fact ld_preloads.
992     if (ld_preloads != nullptr && soinfos_count < ld_preloads_count) {
993       ld_preloads[soinfos_count] = si;
994     }
995
996     if (soinfos_count < library_names_count) {
997       soinfos[soinfos_count++] = si;
998     }
999   }
1000
1001   // Step 2: link libraries.
1002   soinfo::soinfo_list_t local_group;
1003   walk_dependencies_tree(
1004       start_with == nullptr ? soinfos : &start_with,
1005       start_with == nullptr ? soinfos_count : 1,
1006       [&] (soinfo* si) {
1007     local_group.push_back(si);
1008     return true;
1009   });
1010
1011   bool linked = local_group.visit([&](soinfo* si) {
1012     if ((si->flags & FLAG_LINKED) == 0) {
1013       if (!si->LinkImage(local_group, extinfo)) {
1014         return false;
1015       }
1016       si->flags |= FLAG_LINKED;
1017     }
1018
1019     return true;
1020   });
1021
1022   if (linked) {
1023     failure_guard.disable();
1024   }
1025
1026   return linked;
1027 }
1028
1029 static soinfo* find_library(const char* name, int rtld_flags, const android_dlextinfo* extinfo) {
1030   if (name == nullptr) {
1031     somain->ref_count++;
1032     return somain;
1033   }
1034
1035   soinfo* si;
1036
1037   if (!find_libraries(nullptr, &name, 1, &si, nullptr, 0, rtld_flags, extinfo)) {
1038     return nullptr;
1039   }
1040
1041   return si;
1042 }
1043
1044 static void soinfo_unload(soinfo* si) {
1045   if (!si->can_unload()) {
1046     TRACE("not unloading '%s' - the binary is flagged with NODELETE", si->name);
1047     return;
1048   }
1049
1050   if (si->ref_count == 1) {
1051     TRACE("unloading '%s'", si->name);
1052     si->CallDestructors();
1053
1054     if (si->has_min_version(0)) {
1055       soinfo* child = nullptr;
1056       while ((child = si->get_children().pop_front()) != nullptr) {
1057         TRACE("%s needs to unload %s", si->name, child->name);
1058         soinfo_unload(child);
1059       }
1060     } else {
1061       for_each_dt_needed(si, [&] (const char* library_name) {
1062         TRACE("deprecated (old format of soinfo): %s needs to unload %s", si->name, library_name);
1063         soinfo* needed = find_library(library_name, RTLD_NOLOAD, nullptr);
1064         if (needed != nullptr) {
1065           soinfo_unload(needed);
1066         } else {
1067           // Not found: for example if symlink was deleted between dlopen and dlclose
1068           // Since we cannot really handle errors at this point - print and continue.
1069           PRINT("warning: couldn't find %s needed by %s on unload.", library_name, si->name);
1070         }
1071       });
1072     }
1073
1074     notify_gdb_of_unload(si);
1075     si->ref_count = 0;
1076     soinfo_free(si);
1077   } else {
1078     si->ref_count--;
1079     TRACE("not unloading '%s', decrementing ref_count to %zd", si->name, si->ref_count);
1080   }
1081 }
1082
1083 void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
1084   // Use basic string manipulation calls to avoid snprintf.
1085   // snprintf indirectly calls pthread_getspecific to get the size of a buffer.
1086   // When debug malloc is enabled, this call returns 0. This in turn causes
1087   // snprintf to do nothing, which causes libraries to fail to load.
1088   // See b/17302493 for further details.
1089   // Once the above bug is fixed, this code can be modified to use
1090   // snprintf again.
1091   size_t required_len = strlen(kDefaultLdPaths[0]) + strlen(kDefaultLdPaths[1]) + 2;
1092   if (buffer_size < required_len) {
1093     __libc_fatal("android_get_LD_LIBRARY_PATH failed, buffer too small: buffer len %zu, required len %zu",
1094                  buffer_size, required_len);
1095   }
1096   char* end = stpcpy(buffer, kDefaultLdPaths[0]);
1097   *end = ':';
1098   strcpy(end + 1, kDefaultLdPaths[1]);
1099 }
1100
1101 void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
1102   if (!get_AT_SECURE()) {
1103     parse_LD_LIBRARY_PATH(ld_library_path);
1104   }
1105 }
1106
1107 soinfo* do_dlopen(const char* name, int flags, const android_dlextinfo* extinfo) {
1108   if ((flags & ~(RTLD_NOW|RTLD_LAZY|RTLD_LOCAL|RTLD_GLOBAL|RTLD_NODELETE|RTLD_NOLOAD)) != 0) {
1109     DL_ERR("invalid flags to dlopen: %x", flags);
1110     return nullptr;
1111   }
1112   if (extinfo != nullptr) {
1113     if ((extinfo->flags & ~(ANDROID_DLEXT_VALID_FLAG_BITS)) != 0) {
1114       DL_ERR("invalid extended flags to android_dlopen_ext: 0x%" PRIx64, extinfo->flags);
1115       return nullptr;
1116     }
1117     if ((extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD) == 0 &&
1118         (extinfo->flags & ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET) != 0) {
1119       DL_ERR("invalid extended flag combination (ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET without ANDROID_DLEXT_USE_LIBRARY_FD): 0x%" PRIx64, extinfo->flags);
1120       return nullptr;
1121     }
1122   }
1123   protect_data(PROT_READ | PROT_WRITE);
1124   soinfo* si = find_library(name, flags, extinfo);
1125   if (si != nullptr) {
1126     si->CallConstructors();
1127   }
1128   protect_data(PROT_READ);
1129   return si;
1130 }
1131
1132 void do_dlclose(soinfo* si) {
1133   protect_data(PROT_READ | PROT_WRITE);
1134   soinfo_unload(si);
1135   protect_data(PROT_READ);
1136 }
1137
1138 static ElfW(Addr) call_ifunc_resolver(ElfW(Addr) resolver_addr) {
1139   typedef ElfW(Addr) (*ifunc_resolver_t)(void);
1140   ifunc_resolver_t ifunc_resolver = reinterpret_cast<ifunc_resolver_t>(resolver_addr);
1141   ElfW(Addr) ifunc_addr = ifunc_resolver();
1142   TRACE_TYPE(RELO, "Called ifunc_resolver@%p. The result is %p", ifunc_resolver, reinterpret_cast<void*>(ifunc_addr));
1143
1144   return ifunc_addr;
1145 }
1146
1147 #if defined(USE_RELA)
1148 int soinfo::Relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& local_group) {
1149   for (size_t idx = 0; idx < count; ++idx, ++rela) {
1150     unsigned type = ELFW(R_TYPE)(rela->r_info);
1151     unsigned sym = ELFW(R_SYM)(rela->r_info);
1152     ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rela->r_offset + load_bias);
1153     ElfW(Addr) sym_addr = 0;
1154     const char* sym_name = nullptr;
1155
1156     DEBUG("Processing '%s' relocation at index %zd", name, idx);
1157     if (type == 0) { // R_*_NONE
1158       continue;
1159     }
1160
1161     ElfW(Sym)* s = nullptr;
1162     soinfo* lsi = nullptr;
1163
1164     if (sym != 0) {
1165       sym_name = get_string(symtab[sym].st_name);
1166       s = soinfo_do_lookup(this, sym_name, &lsi, local_group);
1167       if (s == nullptr) {
1168         // We only allow an undefined symbol if this is a weak reference...
1169         s = &symtab[sym];
1170         if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
1171           DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
1172           return -1;
1173         }
1174
1175         /* IHI0044C AAELF 4.5.1.1:
1176
1177            Libraries are not searched to resolve weak references.
1178            It is not an error for a weak reference to remain unsatisfied.
1179
1180            During linking, the value of an undefined weak reference is:
1181            - Zero if the relocation type is absolute
1182            - The address of the place if the relocation is pc-relative
1183            - The address of nominal base address if the relocation
1184              type is base-relative.
1185          */
1186
1187         switch (type) {
1188 #if defined(__aarch64__)
1189           case R_AARCH64_JUMP_SLOT:
1190           case R_AARCH64_GLOB_DAT:
1191           case R_AARCH64_ABS64:
1192           case R_AARCH64_ABS32:
1193           case R_AARCH64_ABS16:
1194           case R_AARCH64_RELATIVE:
1195           case R_AARCH64_IRELATIVE:
1196             /*
1197              * The sym_addr was initialized to be zero above, or the relocation
1198              * code below does not care about value of sym_addr.
1199              * No need to do anything.
1200              */
1201             break;
1202 #elif defined(__x86_64__)
1203           case R_X86_64_JUMP_SLOT:
1204           case R_X86_64_GLOB_DAT:
1205           case R_X86_64_32:
1206           case R_X86_64_64:
1207           case R_X86_64_RELATIVE:
1208           case R_X86_64_IRELATIVE:
1209             // No need to do anything.
1210             break;
1211           case R_X86_64_PC32:
1212             sym_addr = reloc;
1213             break;
1214 #endif
1215           default:
1216             DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rela, idx);
1217             return -1;
1218         }
1219       } else {
1220         // We got a definition.
1221         sym_addr = lsi->resolve_symbol_address(s);
1222       }
1223       count_relocation(kRelocSymbol);
1224     }
1225
1226     switch (type) {
1227 #if defined(__aarch64__)
1228       case R_AARCH64_JUMP_SLOT:
1229         count_relocation(kRelocAbsolute);
1230         MARK(rela->r_offset);
1231         TRACE_TYPE(RELO, "RELO JMP_SLOT %16llx <- %16llx %s\n",
1232                    reloc, (sym_addr + rela->r_addend), sym_name);
1233         *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + rela->r_addend);
1234         break;
1235       case R_AARCH64_GLOB_DAT:
1236         count_relocation(kRelocAbsolute);
1237         MARK(rela->r_offset);
1238         TRACE_TYPE(RELO, "RELO GLOB_DAT %16llx <- %16llx %s\n",
1239                    reloc, (sym_addr + rela->r_addend), sym_name);
1240         *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + rela->r_addend);
1241         break;
1242       case R_AARCH64_ABS64:
1243         count_relocation(kRelocAbsolute);
1244         MARK(rela->r_offset);
1245         TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n",
1246                    reloc, (sym_addr + rela->r_addend), sym_name);
1247         *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
1248         break;
1249       case R_AARCH64_ABS32:
1250         count_relocation(kRelocAbsolute);
1251         MARK(rela->r_offset);
1252         TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n",
1253                    reloc, (sym_addr + rela->r_addend), sym_name);
1254         if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
1255             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
1256           *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
1257         } else {
1258           DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
1259                  (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
1260                  static_cast<ElfW(Addr)>(INT32_MIN),
1261                  static_cast<ElfW(Addr)>(UINT32_MAX));
1262           return -1;
1263         }
1264         break;
1265       case R_AARCH64_ABS16:
1266         count_relocation(kRelocAbsolute);
1267         MARK(rela->r_offset);
1268         TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n",
1269                    reloc, (sym_addr + rela->r_addend), sym_name);
1270         if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
1271             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
1272           *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
1273         } else {
1274           DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
1275                  (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
1276                  static_cast<ElfW(Addr)>(INT16_MIN),
1277                  static_cast<ElfW(Addr)>(UINT16_MAX));
1278           return -1;
1279         }
1280         break;
1281       case R_AARCH64_PREL64:
1282         count_relocation(kRelocRelative);
1283         MARK(rela->r_offset);
1284         TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n",
1285                    reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
1286         *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend) - rela->r_offset;
1287         break;
1288       case R_AARCH64_PREL32:
1289         count_relocation(kRelocRelative);
1290         MARK(rela->r_offset);
1291         TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n",
1292                    reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
1293         if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
1294             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
1295           *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
1296         } else {
1297           DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
1298                  (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
1299                  static_cast<ElfW(Addr)>(INT32_MIN),
1300                  static_cast<ElfW(Addr)>(UINT32_MAX));
1301           return -1;
1302         }
1303         break;
1304       case R_AARCH64_PREL16:
1305         count_relocation(kRelocRelative);
1306         MARK(rela->r_offset);
1307         TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n",
1308                    reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
1309         if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
1310             ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
1311           *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
1312         } else {
1313           DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
1314                  (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
1315                  static_cast<ElfW(Addr)>(INT16_MIN),
1316                  static_cast<ElfW(Addr)>(UINT16_MAX));
1317           return -1;
1318         }
1319         break;
1320
1321       case R_AARCH64_RELATIVE:
1322         count_relocation(kRelocRelative);
1323         MARK(rela->r_offset);
1324         if (sym) {
1325           DL_ERR("odd RELATIVE form...");
1326           return -1;
1327         }
1328         TRACE_TYPE(RELO, "RELO RELATIVE %16llx <- %16llx\n",
1329                    reloc, (base + rela->r_addend));
1330         *reinterpret_cast<ElfW(Addr)*>(reloc) = (base + rela->r_addend);
1331         break;
1332
1333       case R_AARCH64_IRELATIVE:
1334         count_relocation(kRelocRelative);
1335         MARK(rela->r_offset);
1336         TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend));
1337         *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + rela->r_addend);
1338         break;
1339
1340       case R_AARCH64_COPY:
1341         /*
1342          * ET_EXEC is not supported so this should not happen.
1343          *
1344          * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
1345          *
1346          * Section 4.7.1.10 "Dynamic relocations"
1347          * R_AARCH64_COPY may only appear in executable objects where e_type is
1348          * set to ET_EXEC.
1349          */
1350         DL_ERR("%s R_AARCH64_COPY relocations are not supported", name);
1351         return -1;
1352       case R_AARCH64_TLS_TPREL64:
1353         TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
1354                    reloc, (sym_addr + rela->r_addend), rela->r_offset);
1355         break;
1356       case R_AARCH64_TLS_DTPREL32:
1357         TRACE_TYPE(RELO, "RELO TLS_DTPREL32 *** %16llx <- %16llx - %16llx\n",
1358                    reloc, (sym_addr + rela->r_addend), rela->r_offset);
1359         break;
1360 #elif defined(__x86_64__)
1361       case R_X86_64_JUMP_SLOT:
1362         count_relocation(kRelocAbsolute);
1363         MARK(rela->r_offset);
1364         TRACE_TYPE(RELO, "RELO JMP_SLOT %08zx <- %08zx %s", static_cast<size_t>(reloc),
1365                    static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
1366         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
1367         break;
1368       case R_X86_64_GLOB_DAT:
1369         count_relocation(kRelocAbsolute);
1370         MARK(rela->r_offset);
1371         TRACE_TYPE(RELO, "RELO GLOB_DAT %08zx <- %08zx %s", static_cast<size_t>(reloc),
1372                    static_cast<size_t>(sym_addr + rela->r_addend), sym_name);
1373         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
1374         break;
1375       case R_X86_64_RELATIVE:
1376         count_relocation(kRelocRelative);
1377         MARK(rela->r_offset);
1378         if (sym) {
1379           DL_ERR("odd RELATIVE form...");
1380           return -1;
1381         }
1382         TRACE_TYPE(RELO, "RELO RELATIVE %08zx <- +%08zx", static_cast<size_t>(reloc),
1383                    static_cast<size_t>(base));
1384         *reinterpret_cast<ElfW(Addr)*>(reloc) = base + rela->r_addend;
1385         break;
1386       case R_X86_64_IRELATIVE:
1387         count_relocation(kRelocRelative);
1388         MARK(rela->r_offset);
1389         TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend));
1390         *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + rela->r_addend);
1391         break;
1392       case R_X86_64_32:
1393         count_relocation(kRelocRelative);
1394         MARK(rela->r_offset);
1395         TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
1396                    static_cast<size_t>(sym_addr), sym_name);
1397         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
1398         break;
1399       case R_X86_64_64:
1400         count_relocation(kRelocRelative);
1401         MARK(rela->r_offset);
1402         TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
1403                    static_cast<size_t>(sym_addr), sym_name);
1404         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
1405         break;
1406       case R_X86_64_PC32:
1407         count_relocation(kRelocRelative);
1408         MARK(rela->r_offset);
1409         TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
1410                    static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
1411                    static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
1412         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend - reloc;
1413         break;
1414 #endif
1415
1416       default:
1417         DL_ERR("unknown reloc type %d @ %p (%zu)", type, rela, idx);
1418         return -1;
1419     }
1420   }
1421   return 0;
1422 }
1423
1424 #else // REL, not RELA.
1425 int soinfo::Relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& local_group) {
1426   for (size_t idx = 0; idx < count; ++idx, ++rel) {
1427     unsigned type = ELFW(R_TYPE)(rel->r_info);
1428     // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead.
1429     unsigned sym = ELFW(R_SYM)(rel->r_info);
1430     ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
1431     ElfW(Addr) sym_addr = 0;
1432     const char* sym_name = nullptr;
1433
1434     DEBUG("Processing '%s' relocation at index %zd", name, idx);
1435     if (type == 0) { // R_*_NONE
1436       continue;
1437     }
1438
1439     ElfW(Sym)* s = nullptr;
1440     soinfo* lsi = nullptr;
1441
1442     if (sym != 0) {
1443       sym_name = get_string(symtab[sym].st_name);
1444       s = soinfo_do_lookup(this, sym_name, &lsi, local_group);
1445       if (s == nullptr) {
1446         // We only allow an undefined symbol if this is a weak reference...
1447         s = &symtab[sym];
1448         if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
1449           DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
1450           return -1;
1451         }
1452
1453         /* IHI0044C AAELF 4.5.1.1:
1454
1455            Libraries are not searched to resolve weak references.
1456            It is not an error for a weak reference to remain
1457            unsatisfied.
1458
1459            During linking, the value of an undefined weak reference is:
1460            - Zero if the relocation type is absolute
1461            - The address of the place if the relocation is pc-relative
1462            - The address of nominal base address if the relocation
1463              type is base-relative.
1464         */
1465
1466         switch (type) {
1467 #if defined(__arm__)
1468           case R_ARM_JUMP_SLOT:
1469           case R_ARM_GLOB_DAT:
1470           case R_ARM_ABS32:
1471           case R_ARM_RELATIVE:    /* Don't care. */
1472             // sym_addr was initialized to be zero above or relocation
1473             // code below does not care about value of sym_addr.
1474             // No need to do anything.
1475             break;
1476 #elif defined(__i386__)
1477           case R_386_JMP_SLOT:
1478           case R_386_GLOB_DAT:
1479           case R_386_32:
1480           case R_386_RELATIVE:    /* Don't care. */
1481           case R_386_IRELATIVE:
1482             // sym_addr was initialized to be zero above or relocation
1483             // code below does not care about value of sym_addr.
1484             // No need to do anything.
1485             break;
1486           case R_386_PC32:
1487             sym_addr = reloc;
1488             break;
1489 #endif
1490
1491 #if defined(__arm__)
1492           case R_ARM_COPY:
1493             // Fall through. Can't really copy if weak symbol is not found at run-time.
1494 #endif
1495           default:
1496             DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
1497             return -1;
1498         }
1499       } else {
1500         // We got a definition.
1501         sym_addr = lsi->resolve_symbol_address(s);
1502       }
1503       count_relocation(kRelocSymbol);
1504     }
1505
1506     switch (type) {
1507 #if defined(__arm__)
1508       case R_ARM_JUMP_SLOT:
1509         count_relocation(kRelocAbsolute);
1510         MARK(rel->r_offset);
1511         TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
1512         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
1513         break;
1514       case R_ARM_GLOB_DAT:
1515         count_relocation(kRelocAbsolute);
1516         MARK(rel->r_offset);
1517         TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
1518         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
1519         break;
1520       case R_ARM_ABS32:
1521         count_relocation(kRelocAbsolute);
1522         MARK(rel->r_offset);
1523         TRACE_TYPE(RELO, "RELO ABS %08x <- %08x %s", reloc, sym_addr, sym_name);
1524         *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
1525         break;
1526       case R_ARM_REL32:
1527         count_relocation(kRelocRelative);
1528         MARK(rel->r_offset);
1529         TRACE_TYPE(RELO, "RELO REL32 %08x <- %08x - %08x %s",
1530                    reloc, sym_addr, rel->r_offset, sym_name);
1531         *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr - rel->r_offset;
1532         break;
1533       case R_ARM_COPY:
1534         /*
1535          * ET_EXEC is not supported so this should not happen.
1536          *
1537          * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
1538          *
1539          * Section 4.7.1.10 "Dynamic relocations"
1540          * R_ARM_COPY may only appear in executable objects where e_type is
1541          * set to ET_EXEC.
1542          */
1543         DL_ERR("%s R_ARM_COPY relocations are not supported", name);
1544         return -1;
1545 #elif defined(__i386__)
1546       case R_386_JMP_SLOT:
1547         count_relocation(kRelocAbsolute);
1548         MARK(rel->r_offset);
1549         TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
1550         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
1551         break;
1552       case R_386_GLOB_DAT:
1553         count_relocation(kRelocAbsolute);
1554         MARK(rel->r_offset);
1555         TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
1556         *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
1557         break;
1558       case R_386_32:
1559         count_relocation(kRelocRelative);
1560         MARK(rel->r_offset);
1561         TRACE_TYPE(RELO, "RELO R_386_32 %08x <- +%08x %s", reloc, sym_addr, sym_name);
1562         *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
1563         break;
1564       case R_386_PC32:
1565         count_relocation(kRelocRelative);
1566         MARK(rel->r_offset);
1567         TRACE_TYPE(RELO, "RELO R_386_PC32 %08x <- +%08x (%08x - %08x) %s",
1568                    reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
1569         *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
1570         break;
1571 #elif defined(__mips__)
1572       case R_MIPS_REL32:
1573 #if defined(__LP64__)
1574         // MIPS Elf64_Rel entries contain compound relocations
1575         // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case
1576         if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 ||
1577             ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) {
1578           DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)",
1579                  type, (unsigned)ELF64_R_TYPE2(rel->r_info),
1580                  (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx);
1581           return -1;
1582         }
1583 #endif
1584         count_relocation(kRelocAbsolute);
1585         MARK(rel->r_offset);
1586         TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
1587                    static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
1588         if (s) {
1589           *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
1590         } else {
1591           *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
1592         }
1593         break;
1594 #endif
1595
1596 #if defined(__arm__)
1597       case R_ARM_RELATIVE:
1598 #elif defined(__i386__)
1599       case R_386_RELATIVE:
1600 #endif
1601         count_relocation(kRelocRelative);
1602         MARK(rel->r_offset);
1603         if (sym) {
1604           DL_ERR("odd RELATIVE form...");
1605           return -1;
1606         }
1607         TRACE_TYPE(RELO, "RELO RELATIVE %p <- +%p",
1608                    reinterpret_cast<void*>(reloc), reinterpret_cast<void*>(base));
1609         *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
1610         break;
1611 #if defined(__i386__)
1612       case R_386_IRELATIVE:
1613         count_relocation(kRelocRelative);
1614         MARK(rel->r_offset);
1615         TRACE_TYPE(RELO, "RELO IRELATIVE %p <- %p", reinterpret_cast<void*>(reloc), reinterpret_cast<void*>(base));
1616         *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + *reinterpret_cast<ElfW(Addr)*>(reloc));
1617         break;
1618 #endif
1619
1620       default:
1621         DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
1622         return -1;
1623     }
1624   }
1625   return 0;
1626 }
1627 #endif
1628
1629 #if defined(__mips__)
1630 static bool mips_relocate_got(soinfo* si, const soinfo::soinfo_list_t& local_group) {
1631   ElfW(Addr)** got = si->plt_got;
1632   if (got == nullptr) {
1633     return true;
1634   }
1635   unsigned local_gotno = si->mips_local_gotno;
1636   unsigned gotsym = si->mips_gotsym;
1637   unsigned symtabno = si->mips_symtabno;
1638   ElfW(Sym)* symtab = si->symtab;
1639
1640   // got[0] is the address of the lazy resolver function.
1641   // got[1] may be used for a GNU extension.
1642   // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start).
1643   // FIXME: maybe this should be in a separate routine?
1644   if ((si->flags & FLAG_LINKER) == 0) {
1645     size_t g = 0;
1646     got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadbeef);
1647     if (reinterpret_cast<intptr_t>(got[g]) < 0) {
1648       got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
1649     }
1650     // Relocate the local GOT entries.
1651     for (; g < local_gotno; g++) {
1652       got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + si->load_bias);
1653     }
1654   }
1655
1656   // Now for the global GOT entries...
1657   ElfW(Sym)* sym = symtab + gotsym;
1658   got = si->plt_got + local_gotno;
1659   for (size_t g = gotsym; g < symtabno; g++, sym++, got++) {
1660     // This is an undefined reference... try to locate it.
1661     const char* sym_name = si->get_string(sym->st_name);
1662     soinfo* lsi = nullptr;
1663     ElfW(Sym)* s = soinfo_do_lookup(si, sym_name, &lsi, local_group);
1664     if (s == nullptr) {
1665       // We only allow an undefined symbol if this is a weak reference.
1666       s = &symtab[g];
1667       if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
1668         DL_ERR("cannot locate \"%s\"...", sym_name);
1669         return false;
1670       }
1671       *got = 0;
1672     } else {
1673       // FIXME: is this sufficient?
1674       // For reference see NetBSD link loader
1675       // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
1676       *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
1677     }
1678   }
1679   return true;
1680 }
1681 #endif
1682
1683 void soinfo::CallArray(const char* array_name __unused, linker_function_t* functions, size_t count, bool reverse) {
1684   if (functions == nullptr) {
1685     return;
1686   }
1687
1688   TRACE("[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, name);
1689
1690   int begin = reverse ? (count - 1) : 0;
1691   int end = reverse ? -1 : count;
1692   int step = reverse ? -1 : 1;
1693
1694   for (int i = begin; i != end; i += step) {
1695     TRACE("[ %s[%d] == %p ]", array_name, i, functions[i]);
1696     CallFunction("function", functions[i]);
1697   }
1698
1699   TRACE("[ Done calling %s for '%s' ]", array_name, name);
1700 }
1701
1702 void soinfo::CallFunction(const char* function_name __unused, linker_function_t function) {
1703   if (function == nullptr || reinterpret_cast<uintptr_t>(function) == static_cast<uintptr_t>(-1)) {
1704     return;
1705   }
1706
1707   TRACE("[ Calling %s @ %p for '%s' ]", function_name, function, name);
1708   function();
1709   TRACE("[ Done calling %s @ %p for '%s' ]", function_name, function, name);
1710
1711   // The function may have called dlopen(3) or dlclose(3), so we need to ensure our data structures
1712   // are still writable. This happens with our debug malloc (see http://b/7941716).
1713   protect_data(PROT_READ | PROT_WRITE);
1714 }
1715
1716 void soinfo::CallPreInitConstructors() {
1717   // DT_PREINIT_ARRAY functions are called before any other constructors for executables,
1718   // but ignored in a shared library.
1719   CallArray("DT_PREINIT_ARRAY", preinit_array, preinit_array_count, false);
1720 }
1721
1722 void soinfo::CallConstructors() {
1723   if (constructors_called) {
1724     return;
1725   }
1726
1727   // We set constructors_called before actually calling the constructors, otherwise it doesn't
1728   // protect against recursive constructor calls. One simple example of constructor recursion
1729   // is the libc debug malloc, which is implemented in libc_malloc_debug_leak.so:
1730   // 1. The program depends on libc, so libc's constructor is called here.
1731   // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
1732   // 3. dlopen() calls the constructors on the newly created
1733   //    soinfo for libc_malloc_debug_leak.so.
1734   // 4. The debug .so depends on libc, so CallConstructors is
1735   //    called again with the libc soinfo. If it doesn't trigger the early-
1736   //    out above, the libc constructor will be called again (recursively!).
1737   constructors_called = true;
1738
1739   if ((flags & FLAG_EXE) == 0 && preinit_array != nullptr) {
1740     // The GNU dynamic linker silently ignores these, but we warn the developer.
1741     PRINT("\"%s\": ignoring %zd-entry DT_PREINIT_ARRAY in shared library!",
1742           name, preinit_array_count);
1743   }
1744
1745   get_children().for_each([] (soinfo* si) {
1746     si->CallConstructors();
1747   });
1748
1749   TRACE("\"%s\": calling constructors", name);
1750
1751   // DT_INIT should be called before DT_INIT_ARRAY if both are present.
1752   CallFunction("DT_INIT", init_func);
1753   CallArray("DT_INIT_ARRAY", init_array, init_array_count, false);
1754 }
1755
1756 void soinfo::CallDestructors() {
1757   if (!constructors_called) {
1758     return;
1759   }
1760   TRACE("\"%s\": calling destructors", name);
1761
1762   // DT_FINI_ARRAY must be parsed in reverse order.
1763   CallArray("DT_FINI_ARRAY", fini_array, fini_array_count, true);
1764
1765   // DT_FINI should be called after DT_FINI_ARRAY if both are present.
1766   CallFunction("DT_FINI", fini_func);
1767
1768   // This is needed on second call to dlopen
1769   // after library has been unloaded with RTLD_NODELETE
1770   constructors_called = false;
1771 }
1772
1773 void soinfo::add_child(soinfo* child) {
1774   if (has_min_version(0)) {
1775     child->parents.push_back(this);
1776     this->children.push_back(child);
1777   }
1778 }
1779
1780 void soinfo::remove_all_links() {
1781   if (!has_min_version(0)) {
1782     return;
1783   }
1784
1785   // 1. Untie connected soinfos from 'this'.
1786   children.for_each([&] (soinfo* child) {
1787     child->parents.remove_if([&] (const soinfo* parent) {
1788       return parent == this;
1789     });
1790   });
1791
1792   parents.for_each([&] (soinfo* parent) {
1793     parent->children.remove_if([&] (const soinfo* child) {
1794       return child == this;
1795     });
1796   });
1797
1798   // 2. Once everything untied - clear local lists.
1799   parents.clear();
1800   children.clear();
1801 }
1802
1803 dev_t soinfo::get_st_dev() {
1804   if (has_min_version(0)) {
1805     return st_dev;
1806   }
1807
1808   return 0;
1809 };
1810
1811 ino_t soinfo::get_st_ino() {
1812   if (has_min_version(0)) {
1813     return st_ino;
1814   }
1815
1816   return 0;
1817 }
1818
1819 off64_t soinfo::get_file_offset() {
1820   if (has_min_version(1)) {
1821     return file_offset;
1822   }
1823
1824   return 0;
1825 }
1826
1827 int soinfo::get_rtld_flags() {
1828   if (has_min_version(1)) {
1829     return rtld_flags;
1830   }
1831
1832   return 0;
1833 }
1834
1835 // This is a return on get_children()/get_parents() if
1836 // 'this->flags' does not have FLAG_NEW_SOINFO set.
1837 static soinfo::soinfo_list_t g_empty_list;
1838
1839 soinfo::soinfo_list_t& soinfo::get_children() {
1840   if (has_min_version(0)) {
1841     return this->children;
1842   }
1843
1844   return g_empty_list;
1845 }
1846
1847 soinfo::soinfo_list_t& soinfo::get_parents() {
1848   if ((this->flags & FLAG_NEW_SOINFO) == 0) {
1849     return g_empty_list;
1850   }
1851
1852   return this->parents;
1853 }
1854
1855 ElfW(Addr) soinfo::resolve_symbol_address(ElfW(Sym)* s) {
1856   if (ELF_ST_TYPE(s->st_info) == STT_GNU_IFUNC) {
1857     return call_ifunc_resolver(s->st_value + load_bias);
1858   }
1859
1860   return static_cast<ElfW(Addr)>(s->st_value + load_bias);
1861 }
1862
1863 const char* soinfo::get_string(ElfW(Word) index) const {
1864   if (has_min_version(1) && (index >= strtab_size)) {
1865     __libc_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d", name, strtab_size, index);
1866   }
1867
1868   return strtab + index;
1869 }
1870
1871 bool soinfo::can_unload() const {
1872   return (rtld_flags & (RTLD_NODELETE | RTLD_GLOBAL)) == 0;
1873 }
1874 /* Force any of the closed stdin, stdout and stderr to be associated with
1875    /dev/null. */
1876 static int nullify_closed_stdio() {
1877   int dev_null, i, status;
1878   int return_value = 0;
1879
1880   dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
1881   if (dev_null < 0) {
1882     DL_ERR("cannot open /dev/null: %s", strerror(errno));
1883     return -1;
1884   }
1885   TRACE("[ Opened /dev/null file-descriptor=%d]", dev_null);
1886
1887   /* If any of the stdio file descriptors is valid and not associated
1888      with /dev/null, dup /dev/null to it.  */
1889   for (i = 0; i < 3; i++) {
1890     /* If it is /dev/null already, we are done. */
1891     if (i == dev_null) {
1892       continue;
1893     }
1894
1895     TRACE("[ Nullifying stdio file descriptor %d]", i);
1896     status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL));
1897
1898     /* If file is opened, we are good. */
1899     if (status != -1) {
1900       continue;
1901     }
1902
1903     /* The only error we allow is that the file descriptor does not
1904        exist, in which case we dup /dev/null to it. */
1905     if (errno != EBADF) {
1906       DL_ERR("fcntl failed: %s", strerror(errno));
1907       return_value = -1;
1908       continue;
1909     }
1910
1911     /* Try dupping /dev/null to this stdio file descriptor and
1912        repeat if there is a signal.  Note that any errors in closing
1913        the stdio descriptor are lost.  */
1914     status = TEMP_FAILURE_RETRY(dup2(dev_null, i));
1915     if (status < 0) {
1916       DL_ERR("dup2 failed: %s", strerror(errno));
1917       return_value = -1;
1918       continue;
1919     }
1920   }
1921
1922   /* If /dev/null is not one of the stdio file descriptors, close it. */
1923   if (dev_null > 2) {
1924     TRACE("[ Closing /dev/null file-descriptor=%d]", dev_null);
1925     status = TEMP_FAILURE_RETRY(close(dev_null));
1926     if (status == -1) {
1927       DL_ERR("close failed: %s", strerror(errno));
1928       return_value = -1;
1929     }
1930   }
1931
1932   return return_value;
1933 }
1934
1935 bool soinfo::PrelinkImage() {
1936   /* Extract dynamic section */
1937   ElfW(Word) dynamic_flags = 0;
1938   phdr_table_get_dynamic_section(phdr, phnum, load_bias, &dynamic, &dynamic_flags);
1939
1940   /* We can't log anything until the linker is relocated */
1941   bool relocating_linker = (flags & FLAG_LINKER) != 0;
1942   if (!relocating_linker) {
1943     INFO("[ linking %s ]", name);
1944     DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags);
1945   }
1946
1947   if (dynamic == nullptr) {
1948     if (!relocating_linker) {
1949       DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
1950     }
1951     return false;
1952   } else {
1953     if (!relocating_linker) {
1954       DEBUG("dynamic = %p", dynamic);
1955     }
1956   }
1957
1958 #if defined(__arm__)
1959   (void) phdr_table_get_arm_exidx(phdr, phnum, load_bias,
1960                                   &ARM_exidx, &ARM_exidx_count);
1961 #endif
1962
1963   // Extract useful information from dynamic section.
1964   uint32_t needed_count = 0;
1965   for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
1966     DEBUG("d = %p, d[0](tag) = %p d[1](val) = %p",
1967           d, reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
1968     switch (d->d_tag) {
1969       case DT_SONAME:
1970         // TODO: glibc dynamic linker uses this name for
1971         // initial library lookup; consider doing the same here.
1972         break;
1973
1974       case DT_HASH:
1975         nbucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[0];
1976         nchain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr)[1];
1977         bucket = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8);
1978         chain = reinterpret_cast<uint32_t*>(load_bias + d->d_un.d_ptr + 8 + nbucket * 4);
1979         break;
1980
1981       case DT_STRTAB:
1982         strtab = reinterpret_cast<const char*>(load_bias + d->d_un.d_ptr);
1983         break;
1984
1985       case DT_STRSZ:
1986         strtab_size = d->d_un.d_val;
1987         break;
1988
1989       case DT_SYMTAB:
1990         symtab = reinterpret_cast<ElfW(Sym)*>(load_bias + d->d_un.d_ptr);
1991         break;
1992
1993       case DT_SYMENT:
1994         if (d->d_un.d_val != sizeof(ElfW(Sym))) {
1995           DL_ERR("invalid DT_SYMENT: %zd", static_cast<size_t>(d->d_un.d_val));
1996           return false;
1997         }
1998         break;
1999
2000       case DT_PLTREL:
2001 #if defined(USE_RELA)
2002         if (d->d_un.d_val != DT_RELA) {
2003           DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", name);
2004           return false;
2005         }
2006 #else
2007         if (d->d_un.d_val != DT_REL) {
2008           DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", name);
2009           return false;
2010         }
2011 #endif
2012         break;
2013
2014       case DT_JMPREL:
2015 #if defined(USE_RELA)
2016         plt_rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
2017 #else
2018         plt_rel = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
2019 #endif
2020         break;
2021
2022       case DT_PLTRELSZ:
2023 #if defined(USE_RELA)
2024         plt_rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
2025 #else
2026         plt_rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
2027 #endif
2028         break;
2029
2030       case DT_PLTGOT:
2031 #if defined(__mips__)
2032         // Used by mips and mips64.
2033         plt_got = reinterpret_cast<ElfW(Addr)**>(load_bias + d->d_un.d_ptr);
2034 #endif
2035         // Ignore for other platforms... (because RTLD_LAZY is not supported)
2036         break;
2037
2038       case DT_DEBUG:
2039         // Set the DT_DEBUG entry to the address of _r_debug for GDB
2040         // if the dynamic table is writable
2041 // FIXME: not working currently for N64
2042 // The flags for the LOAD and DYNAMIC program headers do not agree.
2043 // The LOAD section containing the dynamic table has been mapped as
2044 // read-only, but the DYNAMIC header claims it is writable.
2045 #if !(defined(__mips__) && defined(__LP64__))
2046         if ((dynamic_flags & PF_W) != 0) {
2047           d->d_un.d_val = reinterpret_cast<uintptr_t>(&_r_debug);
2048         }
2049         break;
2050 #endif
2051 #if defined(USE_RELA)
2052       case DT_RELA:
2053         rela = reinterpret_cast<ElfW(Rela)*>(load_bias + d->d_un.d_ptr);
2054         break;
2055
2056       case DT_RELASZ:
2057         rela_count = d->d_un.d_val / sizeof(ElfW(Rela));
2058         break;
2059
2060       case DT_RELAENT:
2061         if (d->d_un.d_val != sizeof(ElfW(Rela))) {
2062           DL_ERR("invalid DT_RELAENT: %zd", static_cast<size_t>(d->d_un.d_val));
2063           return false;
2064         }
2065         break;
2066
2067       // ignored (see DT_RELCOUNT comments for details)
2068       case DT_RELACOUNT:
2069         break;
2070
2071       case DT_REL:
2072         DL_ERR("unsupported DT_REL in \"%s\"", name);
2073         return false;
2074
2075       case DT_RELSZ:
2076         DL_ERR("unsupported DT_RELSZ in \"%s\"", name);
2077         return false;
2078 #else
2079       case DT_REL:
2080         rel = reinterpret_cast<ElfW(Rel)*>(load_bias + d->d_un.d_ptr);
2081         break;
2082
2083       case DT_RELSZ:
2084         rel_count = d->d_un.d_val / sizeof(ElfW(Rel));
2085         break;
2086
2087       case DT_RELENT:
2088         if (d->d_un.d_val != sizeof(ElfW(Rel))) {
2089           DL_ERR("invalid DT_RELENT: %zd", static_cast<size_t>(d->d_un.d_val));
2090           return false;
2091         }
2092         break;
2093
2094       // "Indicates that all RELATIVE relocations have been concatenated together,
2095       // and specifies the RELATIVE relocation count."
2096       //
2097       // TODO: Spec also mentions that this can be used to optimize relocation process;
2098       // Not currently used by bionic linker - ignored.
2099       case DT_RELCOUNT:
2100         break;
2101       case DT_RELA:
2102         DL_ERR("unsupported DT_RELA in \"%s\"", name);
2103         return false;
2104 #endif
2105       case DT_INIT:
2106         init_func = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
2107         DEBUG("%s constructors (DT_INIT) found at %p", name, init_func);
2108         break;
2109
2110       case DT_FINI:
2111         fini_func = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
2112         DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func);
2113         break;
2114
2115       case DT_INIT_ARRAY:
2116         init_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
2117         DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array);
2118         break;
2119
2120       case DT_INIT_ARRAYSZ:
2121         init_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
2122         break;
2123
2124       case DT_FINI_ARRAY:
2125         fini_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
2126         DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array);
2127         break;
2128
2129       case DT_FINI_ARRAYSZ:
2130         fini_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
2131         break;
2132
2133       case DT_PREINIT_ARRAY:
2134         preinit_array = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
2135         DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array);
2136         break;
2137
2138       case DT_PREINIT_ARRAYSZ:
2139         preinit_array_count = ((unsigned)d->d_un.d_val) / sizeof(ElfW(Addr));
2140         break;
2141
2142       case DT_TEXTREL:
2143 #if defined(__LP64__)
2144         DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name);
2145         return false;
2146 #else
2147         has_text_relocations = true;
2148         break;
2149 #endif
2150
2151       case DT_SYMBOLIC:
2152         has_DT_SYMBOLIC = true;
2153         break;
2154
2155       case DT_NEEDED:
2156         ++needed_count;
2157         break;
2158
2159       case DT_FLAGS:
2160         if (d->d_un.d_val & DF_TEXTREL) {
2161 #if defined(__LP64__)
2162           DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name);
2163           return false;
2164 #else
2165           has_text_relocations = true;
2166 #endif
2167         }
2168         if (d->d_un.d_val & DF_SYMBOLIC) {
2169           has_DT_SYMBOLIC = true;
2170         }
2171         break;
2172
2173       case DT_FLAGS_1:
2174         if ((d->d_un.d_val & DF_1_GLOBAL) != 0) {
2175           rtld_flags |= RTLD_GLOBAL;
2176         }
2177
2178         if ((d->d_un.d_val & DF_1_NODELETE) != 0) {
2179           rtld_flags |= RTLD_NODELETE;
2180         }
2181         // TODO: Implement other flags
2182
2183         if ((d->d_un.d_val & ~(DF_1_NOW | DF_1_GLOBAL | DF_1_NODELETE)) != 0) {
2184           DL_WARN("Unsupported flags DT_FLAGS_1=%p", reinterpret_cast<void*>(d->d_un.d_val));
2185         }
2186         break;
2187 #if defined(__mips__)
2188       case DT_MIPS_RLD_MAP:
2189         // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB.
2190         {
2191           r_debug** dp = reinterpret_cast<r_debug**>(load_bias + d->d_un.d_ptr);
2192           *dp = &_r_debug;
2193         }
2194         break;
2195
2196       case DT_MIPS_RLD_VERSION:
2197       case DT_MIPS_FLAGS:
2198       case DT_MIPS_BASE_ADDRESS:
2199       case DT_MIPS_UNREFEXTNO:
2200         break;
2201
2202       case DT_MIPS_SYMTABNO:
2203         mips_symtabno = d->d_un.d_val;
2204         break;
2205
2206       case DT_MIPS_LOCAL_GOTNO:
2207         mips_local_gotno = d->d_un.d_val;
2208         break;
2209
2210       case DT_MIPS_GOTSYM:
2211         mips_gotsym = d->d_un.d_val;
2212         break;
2213 #endif
2214       // Ignored: "Its use has been superseded by the DF_BIND_NOW flag"
2215       case DT_BIND_NOW:
2216         break;
2217
2218       // Ignore: bionic does not support symbol versioning...
2219       case DT_VERSYM:
2220       case DT_VERDEF:
2221       case DT_VERDEFNUM:
2222         break;
2223
2224       default:
2225         if (!relocating_linker) {
2226           DL_WARN("%s: unused DT entry: type %p arg %p", name,
2227               reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
2228         }
2229         break;
2230     }
2231   }
2232
2233   DEBUG("si->base = %p, si->strtab = %p, si->symtab = %p",
2234         reinterpret_cast<void*>(base), strtab, symtab);
2235
2236   // Sanity checks.
2237   if (relocating_linker && needed_count != 0) {
2238     DL_ERR("linker cannot have DT_NEEDED dependencies on other libraries");
2239     return false;
2240   }
2241   if (nbucket == 0) {
2242     DL_ERR("empty/missing DT_HASH in \"%s\" (built with --hash-style=gnu?)", name);
2243     return false;
2244   }
2245   if (strtab == 0) {
2246     DL_ERR("empty/missing DT_STRTAB in \"%s\"", name);
2247     return false;
2248   }
2249   if (symtab == 0) {
2250     DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name);
2251     return false;
2252   }
2253   return true;
2254 }
2255
2256 bool soinfo::LinkImage(const soinfo_list_t& local_group, const android_dlextinfo* extinfo) {
2257
2258 #if !defined(__LP64__)
2259   if (has_text_relocations) {
2260     // Make segments writable to allow text relocations to work properly. We will later call
2261     // phdr_table_protect_segments() after all of them are applied and all constructors are run.
2262     DL_WARN("%s has text relocations. This is wasting memory and prevents "
2263             "security hardening. Please fix.", name);
2264     if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
2265       DL_ERR("can't unprotect loadable segments for \"%s\": %s",
2266              name, strerror(errno));
2267       return false;
2268     }
2269   }
2270 #endif
2271
2272 #if defined(USE_RELA)
2273   if (rela != nullptr) {
2274     DEBUG("[ relocating %s ]", name);
2275     if (Relocate(rela, rela_count, local_group)) {
2276       return false;
2277     }
2278   }
2279   if (plt_rela != nullptr) {
2280     DEBUG("[ relocating %s plt ]", name);
2281     if (Relocate(plt_rela, plt_rela_count, local_group)) {
2282       return false;
2283     }
2284   }
2285 #else
2286   if (rel != nullptr) {
2287     DEBUG("[ relocating %s ]", name);
2288     if (Relocate(rel, rel_count, local_group)) {
2289       return false;
2290     }
2291   }
2292   if (plt_rel != nullptr) {
2293     DEBUG("[ relocating %s plt ]", name);
2294     if (Relocate(plt_rel, plt_rel_count, local_group)) {
2295       return false;
2296     }
2297   }
2298 #endif
2299
2300 #if defined(__mips__)
2301   if (!mips_relocate_got(this)) {
2302     return false;
2303   }
2304 #endif
2305
2306   DEBUG("[ finished linking %s ]", name);
2307
2308 #if !defined(__LP64__)
2309   if (has_text_relocations) {
2310     // All relocations are done, we can protect our segments back to read-only.
2311     if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
2312       DL_ERR("can't protect segments for \"%s\": %s",
2313              name, strerror(errno));
2314       return false;
2315     }
2316   }
2317 #endif
2318
2319   /* We can also turn on GNU RELRO protection */
2320   if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
2321     DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
2322            name, strerror(errno));
2323     return false;
2324   }
2325
2326   /* Handle serializing/sharing the RELRO segment */
2327   if (extinfo && (extinfo->flags & ANDROID_DLEXT_WRITE_RELRO)) {
2328     if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
2329                                        extinfo->relro_fd) < 0) {
2330       DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
2331              name, strerror(errno));
2332       return false;
2333     }
2334   } else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
2335     if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
2336                                  extinfo->relro_fd) < 0) {
2337       DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
2338              name, strerror(errno));
2339       return false;
2340     }
2341   }
2342
2343   notify_gdb_of_load(this);
2344   return true;
2345 }
2346
2347 /*
2348  * This function add vdso to internal dso list.
2349  * It helps to stack unwinding through signal handlers.
2350  * Also, it makes bionic more like glibc.
2351  */
2352 static void add_vdso(KernelArgumentBlock& args __unused) {
2353 #if defined(AT_SYSINFO_EHDR)
2354   ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(args.getauxval(AT_SYSINFO_EHDR));
2355   if (ehdr_vdso == nullptr) {
2356     return;
2357   }
2358
2359   soinfo* si = soinfo_alloc("[vdso]", nullptr, 0, 0);
2360
2361   si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
2362   si->phnum = ehdr_vdso->e_phnum;
2363   si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
2364   si->size = phdr_table_get_load_size(si->phdr, si->phnum);
2365   si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
2366
2367   si->PrelinkImage();
2368   si->LinkImage(g_empty_list, nullptr);
2369 #endif
2370 }
2371
2372 /*
2373  * This is linker soinfo for GDB. See details below.
2374  */
2375 #if defined(__LP64__)
2376 #define LINKER_PATH "/system/bin/linker64"
2377 #else
2378 #define LINKER_PATH "/system/bin/linker"
2379 #endif
2380 static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0, 0);
2381
2382 /* gdb expects the linker to be in the debug shared object list.
2383  * Without this, gdb has trouble locating the linker's ".text"
2384  * and ".plt" sections. Gdb could also potentially use this to
2385  * relocate the offset of our exported 'rtld_db_dlactivity' symbol.
2386  * Don't use soinfo_alloc(), because the linker shouldn't
2387  * be on the soinfo list.
2388  */
2389 static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
2390   linker_soinfo_for_gdb.base = linker_base;
2391
2392   /*
2393    * Set the dynamic field in the link map otherwise gdb will complain with
2394    * the following:
2395    *   warning: .dynamic section for "/system/bin/linker" is not at the
2396    *   expected address (wrong library or version mismatch?)
2397    */
2398   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
2399   ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
2400   phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
2401                                  &linker_soinfo_for_gdb.dynamic, nullptr);
2402   insert_soinfo_into_debug_map(&linker_soinfo_for_gdb);
2403 }
2404
2405 /*
2406  * This code is called after the linker has linked itself and
2407  * fixed it's own GOT. It is safe to make references to externs
2408  * and other non-local data at this point.
2409  */
2410 static ElfW(Addr) __linker_init_post_relocation(KernelArgumentBlock& args, ElfW(Addr) linker_base) {
2411 #if TIMING
2412   struct timeval t0, t1;
2413   gettimeofday(&t0, 0);
2414 #endif
2415
2416   // Initialize environment functions, and get to the ELF aux vectors table.
2417   linker_env_init(args);
2418
2419   // If this is a setuid/setgid program, close the security hole described in
2420   // ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
2421   if (get_AT_SECURE()) {
2422     nullify_closed_stdio();
2423   }
2424
2425   debuggerd_init();
2426
2427   // Get a few environment variables.
2428   const char* LD_DEBUG = linker_env_get("LD_DEBUG");
2429   if (LD_DEBUG != nullptr) {
2430     g_ld_debug_verbosity = atoi(LD_DEBUG);
2431   }
2432
2433   // Normally, these are cleaned by linker_env_init, but the test
2434   // doesn't cost us anything.
2435   const char* ldpath_env = nullptr;
2436   const char* ldpreload_env = nullptr;
2437   if (!get_AT_SECURE()) {
2438     ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2439     ldpreload_env = linker_env_get("LD_PRELOAD");
2440   }
2441
2442   INFO("[ android linker & debugger ]");
2443
2444   soinfo* si = soinfo_alloc(args.argv[0], nullptr, 0, RTLD_GLOBAL);
2445   if (si == nullptr) {
2446     exit(EXIT_FAILURE);
2447   }
2448
2449   /* bootstrap the link map, the main exe always needs to be first */
2450   si->flags |= FLAG_EXE;
2451   link_map* map = &(si->link_map_head);
2452
2453   map->l_addr = 0;
2454   map->l_name = args.argv[0];
2455   map->l_prev = nullptr;
2456   map->l_next = nullptr;
2457
2458   _r_debug.r_map = map;
2459   r_debug_tail = map;
2460
2461   init_linker_info_for_gdb(linker_base);
2462
2463   // Extract information passed from the kernel.
2464   si->phdr = reinterpret_cast<ElfW(Phdr)*>(args.getauxval(AT_PHDR));
2465   si->phnum = args.getauxval(AT_PHNUM);
2466   si->entry = args.getauxval(AT_ENTRY);
2467
2468   /* Compute the value of si->base. We can't rely on the fact that
2469    * the first entry is the PHDR because this will not be true
2470    * for certain executables (e.g. some in the NDK unit test suite)
2471    */
2472   si->base = 0;
2473   si->size = phdr_table_get_load_size(si->phdr, si->phnum);
2474   si->load_bias = 0;
2475   for (size_t i = 0; i < si->phnum; ++i) {
2476     if (si->phdr[i].p_type == PT_PHDR) {
2477       si->load_bias = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_vaddr;
2478       si->base = reinterpret_cast<ElfW(Addr)>(si->phdr) - si->phdr[i].p_offset;
2479       break;
2480     }
2481   }
2482   si->dynamic = nullptr;
2483   si->ref_count = 1;
2484
2485   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
2486   if (elf_hdr->e_type != ET_DYN) {
2487     __libc_format_fd(2, "error: only position independent executables (PIE) are supported.\n");
2488     exit(EXIT_FAILURE);
2489   }
2490
2491   // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
2492   parse_LD_LIBRARY_PATH(ldpath_env);
2493   parse_LD_PRELOAD(ldpreload_env);
2494
2495   somain = si;
2496
2497   si->PrelinkImage();
2498
2499   // Load ld_preloads and dependencies.
2500   StringLinkedList needed_library_name_list;
2501   size_t needed_libraries_count = 0;
2502   size_t ld_preloads_count = 0;
2503   while (g_ld_preload_names[ld_preloads_count] != nullptr) {
2504     needed_library_name_list.push_back(g_ld_preload_names[ld_preloads_count++]);
2505     ++needed_libraries_count;
2506   }
2507
2508   for_each_dt_needed(si, [&](const char* name) {
2509     needed_library_name_list.push_back(name);
2510     ++needed_libraries_count;
2511   });
2512
2513   const char* needed_library_names[needed_libraries_count];
2514
2515   memset(needed_library_names, 0, sizeof(needed_library_names));
2516   needed_library_name_list.copy_to_array(needed_library_names, needed_libraries_count);
2517
2518   if (needed_libraries_count > 0 && !find_libraries(si, needed_library_names, needed_libraries_count, nullptr, g_ld_preloads, ld_preloads_count, RTLD_GLOBAL, nullptr)) {
2519     __libc_format_fd(2, "CANNOT LINK EXECUTABLE: %s\n", linker_get_error_buffer());
2520     exit(EXIT_FAILURE);
2521   }
2522
2523   add_vdso(args);
2524
2525   si->CallPreInitConstructors();
2526
2527   /* After the PrelinkImage, the si->load_bias is initialized.
2528    * For so lib, the map->l_addr will be updated in notify_gdb_of_load.
2529    * We need to update this value for so exe here. So Unwind_Backtrace
2530    * for some arch like x86 could work correctly within so exe.
2531    */
2532   map->l_addr = si->load_bias;
2533   si->CallConstructors();
2534
2535 #if TIMING
2536   gettimeofday(&t1, nullptr);
2537   PRINT("LINKER TIME: %s: %d microseconds", args.argv[0], (int) (
2538            (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2539            (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)));
2540 #endif
2541 #if STATS
2542   PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol", args.argv[0],
2543          linker_stats.count[kRelocAbsolute],
2544          linker_stats.count[kRelocRelative],
2545          linker_stats.count[kRelocCopy],
2546          linker_stats.count[kRelocSymbol]);
2547 #endif
2548 #if COUNT_PAGES
2549   {
2550     unsigned n;
2551     unsigned i;
2552     unsigned count = 0;
2553     for (n = 0; n < 4096; n++) {
2554       if (bitmask[n]) {
2555         unsigned x = bitmask[n];
2556 #if defined(__LP64__)
2557         for (i = 0; i < 32; i++) {
2558 #else
2559         for (i = 0; i < 8; i++) {
2560 #endif
2561           if (x & 1) {
2562             count++;
2563           }
2564           x >>= 1;
2565         }
2566       }
2567     }
2568     PRINT("PAGES MODIFIED: %s: %d (%dKB)", args.argv[0], count, count * 4);
2569   }
2570 #endif
2571
2572 #if TIMING || STATS || COUNT_PAGES
2573   fflush(stdout);
2574 #endif
2575
2576   TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast<void*>(si->entry));
2577   return si->entry;
2578 }
2579
2580 /* Compute the load-bias of an existing executable. This shall only
2581  * be used to compute the load bias of an executable or shared library
2582  * that was loaded by the kernel itself.
2583  *
2584  * Input:
2585  *    elf    -> address of ELF header, assumed to be at the start of the file.
2586  * Return:
2587  *    load bias, i.e. add the value of any p_vaddr in the file to get
2588  *    the corresponding address in memory.
2589  */
2590 static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
2591   ElfW(Addr) offset = elf->e_phoff;
2592   const ElfW(Phdr)* phdr_table = reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
2593   const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
2594
2595   for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
2596     if (phdr->p_type == PT_LOAD) {
2597       return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
2598     }
2599   }
2600   return 0;
2601 }
2602
2603 extern "C" void _start();
2604
2605 /*
2606  * This is the entry point for the linker, called from begin.S. This
2607  * method is responsible for fixing the linker's own relocations, and
2608  * then calling __linker_init_post_relocation().
2609  *
2610  * Because this method is called before the linker has fixed it's own
2611  * relocations, any attempt to reference an extern variable, extern
2612  * function, or other GOT reference will generate a segfault.
2613  */
2614 extern "C" ElfW(Addr) __linker_init(void* raw_args) {
2615   KernelArgumentBlock args(raw_args);
2616
2617   ElfW(Addr) linker_addr = args.getauxval(AT_BASE);
2618   ElfW(Addr) entry_point = args.getauxval(AT_ENTRY);
2619   ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
2620   ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
2621
2622   soinfo linker_so("[dynamic linker]", nullptr, 0, 0);
2623
2624   // If the linker is not acting as PT_INTERP entry_point is equal to
2625   // _start. Which means that the linker is running as an executable and
2626   // already linked by PT_INTERP.
2627   //
2628   // This happens when user tries to run 'adb shell /system/bin/linker'
2629   // see also https://code.google.com/p/android/issues/detail?id=63174
2630   if (reinterpret_cast<ElfW(Addr)>(&_start) == entry_point) {
2631     __libc_fatal("This is %s, the helper program for shared library executables.\n", args.argv[0]);
2632   }
2633
2634   linker_so.base = linker_addr;
2635   linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
2636   linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
2637   linker_so.dynamic = nullptr;
2638   linker_so.phdr = phdr;
2639   linker_so.phnum = elf_hdr->e_phnum;
2640   linker_so.flags |= FLAG_LINKER;
2641
2642   if (!(linker_so.PrelinkImage() && linker_so.LinkImage(g_empty_list, nullptr))) {
2643     // It would be nice to print an error message, but if the linker
2644     // can't link itself, there's no guarantee that we'll be able to
2645     // call write() (because it involves a GOT reference). We may as
2646     // well try though...
2647     const char* msg = "CANNOT LINK EXECUTABLE: ";
2648     write(2, msg, strlen(msg));
2649     write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2650     write(2, "\n", 1);
2651     _exit(EXIT_FAILURE);
2652   }
2653
2654   __libc_init_tls(args);
2655
2656   // Initialize the linker's own global variables
2657   linker_so.CallConstructors();
2658
2659   // Initialize static variables. Note that in order to
2660   // get correct libdl_info we need to call constructors
2661   // before get_libdl_info().
2662   solist = get_libdl_info();
2663   sonext = get_libdl_info();
2664
2665   // We have successfully fixed our own relocations. It's safe to run
2666   // the main part of the linker now.
2667   args.abort_message_ptr = &g_abort_message;
2668   ElfW(Addr) start_address = __linker_init_post_relocation(args, linker_addr);
2669
2670   protect_data(PROT_READ);
2671
2672   // Return the address that the calling assembly stub should jump to.
2673   return start_address;
2674 }