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