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