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