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