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