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