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