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