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