blob: 300a95c0dd5c7edcb21b45bfeec8f8573a456ace [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 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 <linux/auxvec.h>
30
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35#include <fcntl.h>
36#include <errno.h>
37#include <dlfcn.h>
38#include <sys/stat.h>
39
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -070040#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
42#include <sys/mman.h>
43
44#include <sys/atomics.h>
45
46/* special private C library header - see Android.mk */
47#include <bionic_tls.h>
48
49#include "linker.h"
50#include "linker_debug.h"
51
52#include "ba.h"
53
54#define SO_MAX 64
55
56/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
57 *
58 * Do NOT use malloc() and friends or pthread_*() code here.
59 * Don't use printf() either; it's caused mysterious memory
60 * corruption in the past.
61 * The linker runs before we bring up libc and it's easiest
62 * to make sure it does not depend on any complex libc features
63 *
64 * open issues / todo:
65 *
66 * - should we do anything special for STB_WEAK symbols?
67 * - are we doing everything we should for ARM_COPY relocations?
68 * - cleaner error reporting
69 * - configuration for paths (LD_LIBRARY_PATH?)
70 * - after linking, set as much stuff as possible to READONLY
71 * and NOEXEC
72 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
73 * headers provide versions that are negative...
74 * - allocate space for soinfo structs dynamically instead of
75 * having a hard limit (64)
76 *
77 * features to add someday:
78 *
79 * - dlopen() and friends
80 *
81*/
82
83
84static int link_image(soinfo *si, unsigned wr_offset);
85
86static int socount = 0;
87static soinfo sopool[SO_MAX];
88static soinfo *freelist = NULL;
89static soinfo *solist = &libdl_info;
90static soinfo *sonext = &libdl_info;
91
92int debug_verbosity;
93static int pid;
94
95#if STATS
96struct _link_stats linker_stats;
97#endif
98
99#if COUNT_PAGES
100unsigned bitmask[4096];
101#endif
102
103#ifndef PT_ARM_EXIDX
104#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
105#endif
106
107/*
108 * This function is an empty stub where GDB locates a breakpoint to get notified
109 * about linker activity.
110 */
111extern void __attribute__((noinline)) rtld_db_dlactivity(void);
112
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800113static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
114 RT_CONSISTENT, 0};
115static struct link_map *r_debug_tail = 0;
116
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700117static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800118
119static void insert_soinfo_into_debug_map(soinfo * info)
120{
121 struct link_map * map;
122
123 /* Copy the necessary fields into the debug structure.
124 */
125 map = &(info->linkmap);
126 map->l_addr = info->base;
127 map->l_name = (char*) info->name;
128
129 /* Stick the new library at the end of the list.
130 * gdb tends to care more about libc than it does
131 * about leaf libraries, and ordering it this way
132 * reduces the back-and-forth over the wire.
133 */
134 if (r_debug_tail) {
135 r_debug_tail->l_next = map;
136 map->l_prev = r_debug_tail;
137 map->l_next = 0;
138 } else {
139 _r_debug.r_map = map;
140 map->l_prev = 0;
141 map->l_next = 0;
142 }
143 r_debug_tail = map;
144}
145
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700146static void remove_soinfo_from_debug_map(soinfo * info)
147{
148 struct link_map * map = &(info->linkmap);
149
150 if (r_debug_tail == map)
151 r_debug_tail = map->l_prev;
152
153 if (map->l_prev) map->l_prev->l_next = map->l_next;
154 if (map->l_next) map->l_next->l_prev = map->l_prev;
155}
156
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800157void notify_gdb_of_load(soinfo * info)
158{
159 if (info->flags & FLAG_EXE) {
160 // GDB already knows about the main executable
161 return;
162 }
163
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700164 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800165
166 _r_debug.r_state = RT_ADD;
167 rtld_db_dlactivity();
168
169 insert_soinfo_into_debug_map(info);
170
171 _r_debug.r_state = RT_CONSISTENT;
172 rtld_db_dlactivity();
173
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700174 pthread_mutex_unlock(&_r_debug_lock);
175}
176
177void notify_gdb_of_unload(soinfo * info)
178{
179 if (info->flags & FLAG_EXE) {
180 // GDB already knows about the main executable
181 return;
182 }
183
184 pthread_mutex_lock(&_r_debug_lock);
185
186 _r_debug.r_state = RT_DELETE;
187 rtld_db_dlactivity();
188
189 remove_soinfo_from_debug_map(info);
190
191 _r_debug.r_state = RT_CONSISTENT;
192 rtld_db_dlactivity();
193
194 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800195}
196
197void notify_gdb_of_libraries()
198{
199 _r_debug.r_state = RT_ADD;
200 rtld_db_dlactivity();
201 _r_debug.r_state = RT_CONSISTENT;
202 rtld_db_dlactivity();
203}
204
205static soinfo *alloc_info(const char *name)
206{
207 soinfo *si;
208
209 if(strlen(name) >= SOINFO_NAME_LEN) {
210 ERROR("%5d library name %s too long\n", pid, name);
211 return 0;
212 }
213
214 /* The freelist is populated when we call free_info(), which in turn is
215 done only by dlclose(), which is not likely to be used.
216 */
217 if (!freelist) {
218 if(socount == SO_MAX) {
219 ERROR("%5d too many libraries when loading %s\n", pid, name);
220 return NULL;
221 }
222 freelist = sopool + socount++;
223 freelist->next = NULL;
224 }
225
226 si = freelist;
227 freelist = freelist->next;
228
229 /* Make sure we get a clean block of soinfo */
230 memset(si, 0, sizeof(soinfo));
231 strcpy((char*) si->name, name);
232 sonext->next = si;
233 si->ba_index = -1; /* by default, prelinked */
234 si->next = NULL;
235 si->refcount = 0;
236 sonext = si;
237
238 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
239 return si;
240}
241
242static void free_info(soinfo *si)
243{
244 soinfo *prev = NULL, *trav;
245
246 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
247
248 for(trav = solist; trav != NULL; trav = trav->next){
249 if (trav == si)
250 break;
251 prev = trav;
252 }
253 if (trav == NULL) {
254 /* si was not ni solist */
255 ERROR("%5d name %s is not in solist!\n", pid, si->name);
256 return;
257 }
258
259 /* prev will never be NULL, because the first entry in solist is
260 always the static libdl_info.
261 */
262 prev->next = si->next;
263 if (si == sonext) sonext = prev;
264 si->next = freelist;
265 freelist = si;
266}
267
268#ifndef LINKER_TEXT_BASE
269#error "linker's makefile must define LINKER_TEXT_BASE"
270#endif
271#ifndef LINKER_AREA_SIZE
272#error "linker's makefile must define LINKER_AREA_SIZE"
273#endif
274#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
275#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
276
277const char *addr_to_name(unsigned addr)
278{
279 soinfo *si;
280
281 for(si = solist; si != 0; si = si->next){
282 if((addr >= si->base) && (addr < (si->base + si->size))) {
283 return si->name;
284 }
285 }
286
287 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
288 return "linker";
289 }
290
291 return "";
292}
293
294/* For a given PC, find the .so that it belongs to.
295 * Returns the base address of the .ARM.exidx section
296 * for that .so, and the number of 8-byte entries
297 * in that section (via *pcount).
298 *
299 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
300 *
301 * This function is exposed via dlfcn.c and libdl.so.
302 */
303#ifdef ANDROID_ARM_LINKER
304_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
305{
306 soinfo *si;
307 unsigned addr = (unsigned)pc;
308
309 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
310 for (si = solist; si != 0; si = si->next){
311 if ((addr >= si->base) && (addr < (si->base + si->size))) {
312 *pcount = si->ARM_exidx_count;
313 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
314 }
315 }
316 }
317 *pcount = 0;
318 return NULL;
319}
320#elif defined(ANDROID_X86_LINKER)
321/* Here, we only have to provide a callback to iterate across all the
322 * loaded libraries. gcc_eh does the rest. */
323int
324dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
325 void *data)
326{
327 soinfo *si;
328 struct dl_phdr_info dl_info;
329 int rv = 0;
330
331 for (si = solist; si != NULL; si = si->next) {
332 dl_info.dlpi_addr = si->linkmap.l_addr;
333 dl_info.dlpi_name = si->linkmap.l_name;
334 dl_info.dlpi_phdr = si->phdr;
335 dl_info.dlpi_phnum = si->phnum;
336 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
337 if (rv != 0)
338 break;
339 }
340 return rv;
341}
342#endif
343
344static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
345{
346 Elf32_Sym *s;
347 Elf32_Sym *symtab = si->symtab;
348 const char *strtab = si->strtab;
349 unsigned n;
350
351 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
352 name, si->name, si->base, hash, hash % si->nbucket);
353 n = hash % si->nbucket;
354
355 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
356 s = symtab + n;
357 if(strcmp(strtab + s->st_name, name)) continue;
358
359 /* only concern ourselves with global symbols */
360 switch(ELF32_ST_BIND(s->st_info)){
361 case STB_GLOBAL:
362 /* no section == undefined */
363 if(s->st_shndx == 0) continue;
364
365 case STB_WEAK:
366 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
367 name, si->name, s->st_value, s->st_size);
368 return s;
369 }
370 }
371
372 return 0;
373}
374
375static unsigned elfhash(const char *_name)
376{
377 const unsigned char *name = (const unsigned char *) _name;
378 unsigned h = 0, g;
379
380 while(*name) {
381 h = (h << 4) + *name++;
382 g = h & 0xf0000000;
383 h ^= g;
384 h ^= g >> 24;
385 }
386 return h;
387}
388
389static Elf32_Sym *
390_do_lookup_in_so(soinfo *si, const char *name, unsigned *elf_hash)
391{
392 if (*elf_hash == 0)
393 *elf_hash = elfhash(name);
394 return _elf_lookup (si, *elf_hash, name);
395}
396
397/* This is used by dl_sym() */
398Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
399{
400 unsigned unused = 0;
401 return _do_lookup_in_so(si, name, &unused);
402}
403
404static Elf32_Sym *
405_do_lookup(soinfo *user_si, const char *name, unsigned *base)
406{
407 unsigned elf_hash = 0;
408 Elf32_Sym *s = NULL;
409 soinfo *si;
410
411 /* Look for symbols in the local scope first (the object who is
412 * searching). This happens with C++ templates on i386 for some
413 * reason. */
414 if (user_si) {
415 s = _do_lookup_in_so(user_si, name, &elf_hash);
416 if (s != NULL)
417 *base = user_si->base;
418 }
419
420 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
421 {
422 if((si->flags & FLAG_ERROR) || (si == user_si))
423 continue;
424 s = _do_lookup_in_so(si, name, &elf_hash);
425 if (s != NULL) {
426 *base = si->base;
427 break;
428 }
429 }
430
431 if (s != NULL) {
432 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
433 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
434 return s;
435 }
436
437 return 0;
438}
439
440/* This is used by dl_sym() */
441Elf32_Sym *lookup(const char *name, unsigned *base)
442{
443 return _do_lookup(NULL, name, base);
444}
445
446#if 0
447static void dump(soinfo *si)
448{
449 Elf32_Sym *s = si->symtab;
450 unsigned n;
451
452 for(n = 0; n < si->nchain; n++) {
453 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
454 s->st_info, s->st_shndx, s->st_value, s->st_size,
455 si->strtab + s->st_name);
456 s++;
457 }
458}
459#endif
460
461static const char *sopaths[] = {
462 "/system/lib",
463 "/lib",
464 0
465};
466
467static int _open_lib(const char *name)
468{
469 int fd;
470 struct stat filestat;
471
472 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
473 if ((fd = open(name, O_RDONLY)) >= 0)
474 return fd;
475 }
476
477 return -1;
478}
479
480/* TODO: Need to add support for initializing the so search path with
481 * LD_LIBRARY_PATH env variable for non-setuid programs. */
482static int open_library(const char *name)
483{
484 int fd;
485 char buf[512];
486 const char **path;
487
488 TRACE("[ %5d opening %s ]\n", pid, name);
489
490 if(name == 0) return -1;
491 if(strlen(name) > 256) return -1;
492
493 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
494 return fd;
495
496 for (path = sopaths; *path; path++) {
497 snprintf(buf, sizeof(buf), "%s/%s", *path, name);
498 if ((fd = _open_lib(buf)) >= 0)
499 return fd;
500 }
501
502 return -1;
503}
504
505/* temporary space for holding the first page of the shared lib
506 * which contains the elf header (with the pht). */
507static unsigned char __header[PAGE_SIZE];
508
509typedef struct {
510 long mmap_addr;
511 char tag[4]; /* 'P', 'R', 'E', ' ' */
512} prelink_info_t;
513
514/* Returns the requested base address if the library is prelinked,
515 * and 0 otherwise. */
516static unsigned long
517is_prelinked(int fd, const char *name)
518{
519 off_t sz;
520 prelink_info_t info;
521
522 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
523 if (sz < 0) {
524 ERROR("lseek() failed!\n");
525 return 0;
526 }
527
528 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
529 WARN("Could not read prelink_info_t structure for `%s`\n", name);
530 return 0;
531 }
532
533 if (strncmp(info.tag, "PRE ", 4)) {
534 WARN("`%s` is not a prelinked library\n", name);
535 return 0;
536 }
537
538 return (unsigned long)info.mmap_addr;
539}
540
541/* verify_elf_object
542 * Verifies if the object @ base is a valid ELF object
543 *
544 * Args:
545 *
546 * Returns:
547 * 0 on success
548 * -1 if no valid ELF object is found @ base.
549 */
550static int
551verify_elf_object(void *base, const char *name)
552{
553 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
554
555 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
556 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
557 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
558 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
559
560 /* TODO: Should we verify anything else in the header? */
561
562 return 0;
563}
564
565
566/* get_lib_extents
567 * Retrieves the base (*base) address where the ELF object should be
568 * mapped and its overall memory size (*total_sz).
569 *
570 * Args:
571 * fd: Opened file descriptor for the library
572 * name: The name of the library
573 * _hdr: Pointer to the header page of the library
574 * total_sz: Total size of the memory that should be allocated for
575 * this library
576 *
577 * Returns:
578 * -1 if there was an error while trying to get the lib extents.
579 * The possible reasons are:
580 * - Could not determine if the library was prelinked.
581 * - The library provided is not a valid ELF object
582 * 0 if the library did not request a specific base offset (normal
583 * for non-prelinked libs)
584 * > 0 if the library requests a specific address to be mapped to.
585 * This indicates a pre-linked library.
586 */
587static unsigned
588get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
589{
590 unsigned req_base;
591 unsigned min_vaddr = 0xffffffff;
592 unsigned max_vaddr = 0;
593 unsigned char *_hdr = (unsigned char *)__hdr;
594 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
595 Elf32_Phdr *phdr;
596 int cnt;
597
598 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
599 if (verify_elf_object(_hdr, name) < 0) {
600 ERROR("%5d - %s is not a valid ELF object\n", pid, name);
601 return (unsigned)-1;
602 }
603
604 req_base = (unsigned) is_prelinked(fd, name);
605 if (req_base == (unsigned)-1)
606 return -1;
607 else if (req_base != 0) {
608 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
609 pid, name, req_base);
610 } else {
611 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
612 }
613
614 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
615
616 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
617 * get the range. */
618 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
619 if (phdr->p_type == PT_LOAD) {
620 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
621 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
622 if (phdr->p_vaddr < min_vaddr)
623 min_vaddr = phdr->p_vaddr;
624 }
625 }
626
627 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
628 ERROR("%5d - No loadable segments found in %s.\n", pid, name);
629 return (unsigned)-1;
630 }
631
632 /* truncate min_vaddr down to page boundary */
633 min_vaddr &= ~PAGE_MASK;
634
635 /* round max_vaddr up to the next page */
636 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
637
638 *total_sz = (max_vaddr - min_vaddr);
639 return (unsigned)req_base;
640}
641
642/* alloc_mem_region
643 *
644 * This function reserves a chunk of memory to be used for mapping in
645 * the shared library. We reserve the entire memory region here, and
646 * then the rest of the linker will relocate the individual loadable
647 * segments into the correct locations within this memory range.
648 *
649 * Args:
650 * si->base: The requested base of the allocation. If 0, a sane one will be
651 * chosen in the range LIBBASE <= base < LIBLAST.
652 * si->size: The size of the allocation.
653 *
654 * Returns:
655 * -1 on failure, and 0 on success. On success, si->base will contain
656 * the virtual address at which the library will be mapped.
657 */
658
659static int reserve_mem_region(soinfo *si)
660{
661 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
662 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
663 if (base == MAP_FAILED) {
664 ERROR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
665 "as requested, will try general pool: %d (%s)\n",
666 pid, (si->base ? "" : "non-"), si->name, si->base,
667 errno, strerror(errno));
668 return -1;
669 } else if (base != (void *)si->base) {
670 ERROR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
671 "not at 0x%08x\n", pid, (si->base ? "" : "non-"),
672 si->name, (unsigned)base, si->base);
673 munmap(base, si->size);
674 return -1;
675 }
676 return 0;
677}
678
679static int
680alloc_mem_region(soinfo *si)
681{
682 if (si->base) {
683 /* Attempt to mmap a prelinked library. */
684 si->ba_index = -1;
685 return reserve_mem_region(si);
686 }
687
688 /* This is not a prelinked library, so we attempt to allocate space
689 for it from the buddy allocator, which manages the area between
690 LIBBASE and LIBLAST.
691 */
692 si->ba_index = ba_allocate(si->size);
693 if(si->ba_index >= 0) {
694 si->base = ba_start_addr(si->ba_index);
695 PRINT("%5d mapping library '%s' at %08x (index %d) " \
696 "through buddy allocator.\n",
697 pid, si->name, si->base, si->ba_index);
698 if (reserve_mem_region(si) < 0) {
699 ba_free(si->ba_index);
700 si->ba_index = -1;
701 si->base = 0;
702 goto err;
703 }
704 return 0;
705 }
706
707err:
708 ERROR("OOPS: %5d cannot map library '%s'. no vspace available.\n",
709 pid, si->name);
710 return -1;
711}
712
713#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
714#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
715 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
716 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
717/* load_segments
718 *
719 * This function loads all the loadable (PT_LOAD) segments into memory
720 * at their appropriate memory offsets off the base address.
721 *
722 * Args:
723 * fd: Open file descriptor to the library to load.
724 * header: Pointer to a header page that contains the ELF header.
725 * This is needed since we haven't mapped in the real file yet.
726 * si: ptr to soinfo struct describing the shared object.
727 *
728 * Returns:
729 * 0 on success, -1 on failure.
730 */
731static int
732load_segments(int fd, void *header, soinfo *si)
733{
734 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
735 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
736 unsigned char *base = (unsigned char *)si->base;
737 int cnt;
738 unsigned len;
739 unsigned char *tmp;
740 unsigned char *pbase;
741 unsigned char *extra_base;
742 unsigned extra_len;
743 unsigned total_sz = 0;
744
745 si->wrprotect_start = 0xffffffff;
746 si->wrprotect_end = 0;
747
748 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
749 pid, si->name, (unsigned)si->base);
750 /* Now go through all the PT_LOAD segments and map them into memory
751 * at the appropriate locations. */
752 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
753 if (phdr->p_type == PT_LOAD) {
754 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
755 /* we want to map in the segment on a page boundary */
756 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
757 /* add the # of bytes we masked off above to the total length. */
758 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
759
760 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
761 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
762 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
763 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
764 MAP_PRIVATE | MAP_FIXED, fd,
765 phdr->p_offset & (~PAGE_MASK));
766 if (pbase == MAP_FAILED) {
767 ERROR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
768 "p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
769 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
770 goto fail;
771 }
772
773 /* If 'len' didn't end on page boundary, and it's a writable
774 * segment, zero-fill the rest. */
775 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
776 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
777
778 /* Check to see if we need to extend the map for this segment to
779 * cover the diff between filesz and memsz (i.e. for bss).
780 *
781 * base _+---------------------+ page boundary
782 * . .
783 * | |
784 * . .
785 * pbase _+---------------------+ page boundary
786 * | |
787 * . .
788 * base + p_vaddr _| |
789 * . \ \ .
790 * . | filesz | .
791 * pbase + len _| / | |
792 * <0 pad> . . .
793 * extra_base _+------------|--------+ page boundary
794 * / . . .
795 * | . . .
796 * | +------------|--------+ page boundary
797 * extra_len-> | | | |
798 * | . | memsz .
799 * | . | .
800 * \ _| / |
801 * . .
802 * | |
803 * _+---------------------+ page boundary
804 */
805 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
806 (~PAGE_MASK));
807 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
808 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
809 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
810 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
811 /* map in the extra page(s) as anonymous into the range.
812 * This is probably not necessary as we already mapped in
813 * the entire region previously, but we just want to be
814 * sure. This will also set the right flags on the region
815 * (though we can probably accomplish the same thing with
816 * mprotect).
817 */
818 extra_base = mmap((void *)tmp, extra_len,
819 PFLAGS_TO_PROT(phdr->p_flags),
820 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
821 -1, 0);
822 if (extra_base == MAP_FAILED) {
823 ERROR("[ %5d - failed to extend segment from '%s' @ 0x%08x "
824 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp,
825 extra_len);
826 goto fail;
827 }
828 /* TODO: Check if we need to memset-0 this region.
829 * Anonymous mappings are zero-filled copy-on-writes, so we
830 * shouldn't need to. */
831 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
832 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
833 extra_len);
834 }
835 /* set the len here to show the full extent of the segment we
836 * just loaded, mostly for debugging */
837 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
838 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
839 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
840 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
841 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
842 total_sz += len;
843 /* Make the section writable just in case we'll have to write to
844 * it during relocation (i.e. text segment). However, we will
845 * remember what range of addresses should be write protected.
846 *
847 */
848 if (!(phdr->p_flags & PF_W)) {
849 if ((unsigned)pbase < si->wrprotect_start)
850 si->wrprotect_start = (unsigned)pbase;
851 if (((unsigned)pbase + len) > si->wrprotect_end)
852 si->wrprotect_end = (unsigned)pbase + len;
853 mprotect(pbase, len,
854 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
855 }
856 } else if (phdr->p_type == PT_DYNAMIC) {
857 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
858 /* this segment contains the dynamic linking information */
859 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
860 } else {
861#ifdef ANDROID_ARM_LINKER
862 if (phdr->p_type == PT_ARM_EXIDX) {
863 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
864 /* exidx entries (used for stack unwinding) are 8 bytes each.
865 */
866 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
867 si->ARM_exidx_count = phdr->p_memsz / 8;
868 }
869#endif
870 }
871
872 }
873
874 /* Sanity check */
875 if (total_sz > si->size) {
876 ERROR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
877 "greater than what was allocated (0x%08x). THIS IS BAD!\n",
878 pid, total_sz, si->name, si->size);
879 goto fail;
880 }
881
882 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
883 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
884 (unsigned)si->base, si->size);
885 return 0;
886
887fail:
888 /* We can just blindly unmap the entire region even though some things
889 * were mapped in originally with anonymous and others could have been
890 * been mapped in from the file before we failed. The kernel will unmap
891 * all the pages in the range, irrespective of how they got there.
892 */
893 munmap((void *)si->base, si->size);
894 si->flags |= FLAG_ERROR;
895 return -1;
896}
897
898/* TODO: Implement this to take care of the fact that Android ARM
899 * ELF objects shove everything into a single loadable segment that has the
900 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
901 * non-writable.
902 */
903#if 0
904static unsigned
905get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
906{
907 Elf32_Shdr *shdr_start;
908 Elf32_Shdr *shdr;
909 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
910 int cnt;
911 unsigned wr_offset = 0xffffffff;
912
913 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
914 ehdr->e_shoff & (~PAGE_MASK));
915 if (shdr_start == MAP_FAILED) {
916 WARN("%5d - Could not read section header info from '%s'. Will not "
917 "not be able to determine write-protect offset.\n", pid, name);
918 return (unsigned)-1;
919 }
920
921 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
922 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
923 (shdr->sh_addr < wr_offset)) {
924 wr_offset = shdr->sh_addr;
925 }
926 }
927
928 munmap(shdr_start, shdr_sz);
929 return wr_offset;
930}
931#endif
932
933static soinfo *
934load_library(const char *name)
935{
936 int fd = open_library(name);
937 int cnt;
938 unsigned ext_sz;
939 unsigned req_base;
940 soinfo *si = NULL;
941 Elf32_Ehdr *hdr;
942
943 if(fd == -1)
944 return NULL;
945
946 /* We have to read the ELF header to figure out what to do with this image
947 */
948 if (lseek(fd, 0, SEEK_SET) < 0) {
949 ERROR("lseek() failed!\n");
950 goto fail;
951 }
952
953 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
954 ERROR("read() failed!\n");
955 goto fail;
956 }
957
958 /* Parse the ELF header and get the size of the memory footprint for
959 * the library */
960 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
961 if (req_base == (unsigned)-1)
962 goto fail;
963 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
964 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
965
966 /* Now configure the soinfo struct where we'll store all of our data
967 * for the ELF object. If the loading fails, we waste the entry, but
968 * same thing would happen if we failed during linking. Configuring the
969 * soinfo struct here is a lot more convenient.
970 */
971 si = alloc_info(name);
972 if (si == NULL)
973 goto fail;
974
975 /* Carve out a chunk of memory where we will map in the individual
976 * segments */
977 si->base = req_base;
978 si->size = ext_sz;
979 si->flags = 0;
980 si->entry = 0;
981 si->dynamic = (unsigned *)-1;
982 if (alloc_mem_region(si) < 0)
983 goto fail;
984
985 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
986 pid, name, (void *)si->base, (unsigned) ext_sz);
987
988 /* Now actually load the library's segments into right places in memory */
989 if (load_segments(fd, &__header[0], si) < 0) {
990 if (si->ba_index >= 0) {
991 ba_free(si->ba_index);
992 si->ba_index = -1;
993 }
994 goto fail;
995 }
996
997 /* this might not be right. Technically, we don't even need this info
998 * once we go through 'load_segments'. */
999 hdr = (Elf32_Ehdr *)si->base;
1000 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1001 si->phnum = hdr->e_phnum;
1002 /**/
1003
1004 close(fd);
1005 return si;
1006
1007fail:
1008 if (si) free_info(si);
1009 close(fd);
1010 return NULL;
1011}
1012
1013static soinfo *
1014init_library(soinfo *si)
1015{
1016 unsigned wr_offset = 0xffffffff;
1017
1018 /* At this point we know that whatever is loaded @ base is a valid ELF
1019 * shared library whose segments are properly mapped in. */
1020 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1021 pid, si->base, si->size, si->name);
1022
1023 if (si->base < LIBBASE || si->base >= LIBLAST)
1024 si->flags |= FLAG_PRELINKED;
1025
1026 if(link_image(si, wr_offset)) {
1027 /* We failed to link. However, we can only restore libbase
1028 ** if no additional libraries have moved it since we updated it.
1029 */
1030 munmap((void *)si->base, si->size);
1031 return NULL;
1032 }
1033
1034 return si;
1035}
1036
1037soinfo *find_library(const char *name)
1038{
1039 soinfo *si;
1040
1041 for(si = solist; si != 0; si = si->next){
1042 if(!strcmp(name, si->name)) {
1043 if(si->flags & FLAG_ERROR) return 0;
1044 if(si->flags & FLAG_LINKED) return si;
1045 ERROR("OOPS: %5d recursive link to '%s'\n", pid, si->name);
1046 return 0;
1047 }
1048 }
1049
1050 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1051 si = load_library(name);
1052 if(si == NULL)
1053 return NULL;
1054 return init_library(si);
1055}
1056
1057/* TODO:
1058 * notify gdb of unload
1059 * for non-prelinked libraries, find a way to decrement libbase
1060 */
1061static void call_destructors(soinfo *si);
1062unsigned unload_library(soinfo *si)
1063{
1064 unsigned *d;
1065 if (si->refcount == 1) {
1066 TRACE("%5d unloading '%s'\n", pid, si->name);
1067 call_destructors(si);
1068
1069 for(d = si->dynamic; *d; d += 2) {
1070 if(d[0] == DT_NEEDED){
1071 TRACE("%5d %s needs to unload %s\n", pid,
1072 si->name, si->strtab + d[1]);
1073 soinfo *lsi = find_library(si->strtab + d[1]);
1074 if(lsi)
1075 unload_library(lsi);
1076 else
1077 ERROR("%5d could not unload '%s'\n",
1078 pid, si->strtab + d[1]);
1079 }
1080 }
1081
1082 munmap((char *)si->base, si->size);
1083 if (si->ba_index >= 0) {
1084 PRINT("%5d releasing library '%s' address space at %08x "\
1085 "through buddy allocator.\n",
1086 pid, si->name, si->base);
1087 ba_free(si->ba_index);
1088 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001089 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001090 free_info(si);
1091 si->refcount = 0;
1092 }
1093 else {
1094 si->refcount--;
1095 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1096 pid, si->name, si->refcount);
1097 }
1098 return si->refcount;
1099}
1100
1101/* TODO: don't use unsigned for addrs below. It works, but is not
1102 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1103 * long.
1104 */
1105static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1106{
1107 Elf32_Sym *symtab = si->symtab;
1108 const char *strtab = si->strtab;
1109 Elf32_Sym *s;
1110 unsigned base;
1111 Elf32_Rel *start = rel;
1112 unsigned idx;
1113
1114 for (idx = 0; idx < count; ++idx) {
1115 unsigned type = ELF32_R_TYPE(rel->r_info);
1116 unsigned sym = ELF32_R_SYM(rel->r_info);
1117 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1118 unsigned sym_addr = 0;
1119 char *sym_name = NULL;
1120
1121 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1122 si->name, idx);
1123 if(sym != 0) {
1124 s = _do_lookup(si, strtab + symtab[sym].st_name, &base);
1125 if(s == 0) {
1126 ERROR("%5d cannot locate '%s'...\n", pid, sym_name);
1127 return -1;
1128 }
1129#if 0
1130 if((base == 0) && (si->base != 0)){
1131 /* linking from libraries to main image is bad */
1132 ERROR("%5d cannot locate '%s'...\n",
1133 pid, strtab + symtab[sym].st_name);
1134 return -1;
1135 }
1136#endif
1137 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1138 ERROR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1139 "handle this yet\n", pid, si->name, s->st_shndx,
1140 s->st_value);
1141 return -1;
1142 }
1143 sym_addr = (unsigned)(s->st_value + base);
1144 sym_name = (char *)(strtab + symtab[sym].st_name);
1145 COUNT_RELOC(RELOC_SYMBOL);
1146 } else {
1147 s = 0;
1148 }
1149
1150/* TODO: This is ugly. Split up the relocations by arch into
1151 * different files.
1152 */
1153 switch(type){
1154#if defined(ANDROID_ARM_LINKER)
1155 case R_ARM_JUMP_SLOT:
1156 COUNT_RELOC(RELOC_ABSOLUTE);
1157 MARK(rel->r_offset);
1158 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1159 reloc, sym_addr, sym_name);
1160 *((unsigned*)reloc) = sym_addr;
1161 break;
1162 case R_ARM_GLOB_DAT:
1163 COUNT_RELOC(RELOC_ABSOLUTE);
1164 MARK(rel->r_offset);
1165 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1166 reloc, sym_addr, sym_name);
1167 *((unsigned*)reloc) = sym_addr;
1168 break;
1169 case R_ARM_ABS32:
1170 COUNT_RELOC(RELOC_ABSOLUTE);
1171 MARK(rel->r_offset);
1172 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1173 reloc, sym_addr, sym_name);
1174 *((unsigned*)reloc) += sym_addr;
1175 break;
1176#elif defined(ANDROID_X86_LINKER)
1177 case R_386_JUMP_SLOT:
1178 COUNT_RELOC(RELOC_ABSOLUTE);
1179 MARK(rel->r_offset);
1180 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1181 reloc, sym_addr, sym_name);
1182 *((unsigned*)reloc) = sym_addr;
1183 break;
1184 case R_386_GLOB_DAT:
1185 COUNT_RELOC(RELOC_ABSOLUTE);
1186 MARK(rel->r_offset);
1187 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1188 reloc, sym_addr, sym_name);
1189 *((unsigned*)reloc) = sym_addr;
1190 break;
1191#endif /* ANDROID_*_LINKER */
1192
1193#if defined(ANDROID_ARM_LINKER)
1194 case R_ARM_RELATIVE:
1195#elif defined(ANDROID_X86_LINKER)
1196 case R_386_RELATIVE:
1197#endif /* ANDROID_*_LINKER */
1198 COUNT_RELOC(RELOC_RELATIVE);
1199 MARK(rel->r_offset);
1200 if(sym){
1201 ERROR("%5d odd RELATIVE form...\n", pid);
1202 return -1;
1203 }
1204 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1205 reloc, si->base);
1206 *((unsigned*)reloc) += si->base;
1207 break;
1208
1209#if defined(ANDROID_X86_LINKER)
1210 case R_386_32:
1211 COUNT_RELOC(RELOC_RELATIVE);
1212 MARK(rel->r_offset);
1213
1214 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1215 reloc, sym_addr, sym_name);
1216 *((unsigned *)reloc) += (unsigned)sym_addr;
1217 break;
1218
1219 case R_386_PC32:
1220 COUNT_RELOC(RELOC_RELATIVE);
1221 MARK(rel->r_offset);
1222 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1223 "+%08x (%08x - %08x) %s\n", pid, reloc,
1224 (sym_addr - reloc), sym_addr, reloc, sym_name);
1225 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1226 break;
1227#endif /* ANDROID_X86_LINKER */
1228
1229#ifdef ANDROID_ARM_LINKER
1230 case R_ARM_COPY:
1231 COUNT_RELOC(RELOC_COPY);
1232 MARK(rel->r_offset);
1233 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1234 reloc, s->st_size, sym_addr, sym_name);
1235 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1236 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001237 case R_ARM_NONE:
1238 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001239#endif /* ANDROID_ARM_LINKER */
1240
1241 default:
1242 ERROR("%5d unknown reloc type %d @ %p (%d)\n",
1243 pid, type, rel, (int) (rel - start));
1244 return -1;
1245 }
1246 rel++;
1247 }
1248 return 0;
1249}
1250
1251static void call_array(unsigned *ctor, int count)
1252{
1253 int n;
1254 for(n = count; n > 0; n--){
1255 TRACE("[ %5d Looking at ctor *0x%08x == 0x%08x ]\n", pid,
1256 (unsigned)ctor, (unsigned)*ctor);
1257 void (*func)() = (void (*)()) *ctor++;
1258 if(((int) func == 0) || ((int) func == -1)) continue;
1259 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1260 func();
1261 }
1262}
1263
1264static void call_constructors(soinfo *si)
1265{
1266 /* TODO: THE ORIGINAL CODE SEEMED TO CALL THE INIT FUNCS IN THE WRONG ORDER.
1267 * Old order: init, init_array, preinit_array..
1268 * Correct order: preinit_array, init, init_array.
1269 * Verify WHY.
1270 */
1271
1272 if (si->flags & FLAG_EXE) {
1273 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1274 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1275 si->name);
1276 call_array(si->preinit_array, si->preinit_array_count);
1277 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1278 } else {
1279 if (si->preinit_array) {
1280 ERROR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
1281 " This is INVALID.\n", pid, si->name,
1282 (unsigned)si->preinit_array);
1283 }
1284 }
1285
1286 // If we have an init section, then we should call it now, to make sure
1287 // that all the funcs in the .ctors section get run.
1288 // Note: For ARM, we shouldn't have a .ctor section (should be empty)
1289 // when we have an (pre)init_array section, but let's be compatible with
1290 // old (non-eabi) binaries and try the _init (DT_INIT) anyway.
1291 if (si->init_func) {
1292 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1293 (unsigned)si->init_func, si->name);
1294 si->init_func();
1295 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1296 }
1297
1298 if (si->init_array) {
1299 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1300 (unsigned)si->init_array, si->init_array_count, si->name);
1301 call_array(si->init_array, si->init_array_count);
1302 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1303 }
1304}
1305
1306static void call_destructors(soinfo *si)
1307{
1308 if (si->fini_array) {
1309 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1310 (unsigned)si->fini_array, si->fini_array_count, si->name);
1311 call_array(si->fini_array, si->fini_array_count);
1312 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1313 }
1314
1315 // If we have an fini section, then we should call it now, to make sure
1316 // that all the funcs in the .dtors section get run.
1317 // Note: For ARM, we shouldn't have a .dtor section (should be empty)
1318 // when we have an fini_array section, but let's be compatible with
1319 // old (non-eabi) binaries and try the _fini (DT_FINI) anyway.
1320 if (si->fini_func) {
1321 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1322 (unsigned)si->fini_func, si->name);
1323 si->fini_func();
1324 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1325 }
1326}
1327
1328/* Force any of the closed stdin, stdout and stderr to be associated with
1329 /dev/null. */
1330static int nullify_closed_stdio (void)
1331{
1332 int dev_null, i, status;
1333 int return_value = 0;
1334
1335 dev_null = open("/dev/null", O_RDWR);
1336 if (dev_null < 0) {
1337 ERROR("Cannot open /dev/null.\n");
1338 return -1;
1339 }
1340 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1341
1342 /* If any of the stdio file descriptors is valid and not associated
1343 with /dev/null, dup /dev/null to it. */
1344 for (i = 0; i < 3; i++) {
1345 /* If it is /dev/null already, we are done. */
1346 if (i == dev_null)
1347 continue;
1348
1349 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1350 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1351 can be interrupted but we do this just to be safe. */
1352 do {
1353 status = fcntl(i, F_GETFL);
1354 } while (status < 0 && errno == EINTR);
1355
1356 /* If file is openned, we are good. */
1357 if (status >= 0)
1358 continue;
1359
1360 /* The only error we allow is that the file descriptor does not
1361 exist, in which case we dup /dev/null to it. */
1362 if (errno != EBADF) {
1363 ERROR("nullify_stdio: unhandled error %s\n", strerror(errno));
1364 return_value = -1;
1365 continue;
1366 }
1367
1368 /* Try dupping /dev/null to this stdio file descriptor and
1369 repeat if there is a signal. Note that any errors in closing
1370 the stdio descriptor are lost. */
1371 do {
1372 status = dup2(dev_null, i);
1373 } while (status < 0 && errno == EINTR);
1374
1375 if (status < 0) {
1376 ERROR("nullify_stdio: dup2 error %s\n", strerror(errno));
1377 return_value = -1;
1378 continue;
1379 }
1380 }
1381
1382 /* If /dev/null is not one of the stdio file descriptors, close it. */
1383 if (dev_null > 2) {
1384 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
1385 do {
1386 status = close(dev_null);
1387 } while (status < 0 && errno == EINTR);
1388
1389 if (status < 0) {
1390 ERROR("nullify_stdio: close error %s\n", strerror(errno));
1391 return_value = -1;
1392 }
1393 }
1394
1395 return return_value;
1396}
1397
1398static int link_image(soinfo *si, unsigned wr_offset)
1399{
1400 unsigned *d;
1401 Elf32_Phdr *phdr = si->phdr;
1402 int phnum = si->phnum;
1403
1404 INFO("[ %5d linking %s ]\n", pid, si->name);
1405 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1406 si->base, si->flags);
1407
1408 if (si->flags & FLAG_EXE) {
1409 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1410 * linkage info if this is the executable. If this was a
1411 * dynamic lib, that would have been done at load time.
1412 *
1413 * TODO: It's unfortunate that small pieces of this are
1414 * repeated from the load_library routine. Refactor this just
1415 * slightly to reuse these bits.
1416 */
1417 si->size = 0;
1418 for(; phnum > 0; --phnum, ++phdr) {
1419#ifdef ANDROID_ARM_LINKER
1420 if(phdr->p_type == PT_ARM_EXIDX) {
1421 /* exidx entries (used for stack unwinding) are 8 bytes each.
1422 */
1423 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1424 si->ARM_exidx_count = phdr->p_memsz / 8;
1425 }
1426#endif
1427 if (phdr->p_type == PT_LOAD) {
1428 /* For the executable, we use the si->size field only in
1429 dl_unwind_find_exidx(), so the meaning of si->size
1430 is not the size of the executable; it is the last
1431 virtual address of the loadable part of the executable;
1432 since si->base == 0 for an executable, we use the
1433 range [0, si->size) to determine whether a PC value
1434 falls within the executable section. Of course, if
1435 a value is below phdr->p_vaddr, it's not in the
1436 executable section, but a) we shouldn't be asking for
1437 such a value anyway, and b) if we have to provide
1438 an EXIDX for such a value, then the executable's
1439 EXIDX is probably the better choice.
1440 */
1441 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1442 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1443 si->size = phdr->p_vaddr + phdr->p_memsz;
1444 /* try to remember what range of addresses should be write
1445 * protected */
1446 if (!(phdr->p_flags & PF_W)) {
1447 unsigned _end;
1448
1449 if (phdr->p_vaddr < si->wrprotect_start)
1450 si->wrprotect_start = phdr->p_vaddr;
1451 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1452 (~PAGE_MASK)));
1453 if (_end > si->wrprotect_end)
1454 si->wrprotect_end = _end;
1455 }
1456 } else if (phdr->p_type == PT_DYNAMIC) {
1457 if (si->dynamic != (unsigned *)-1) {
1458 ERROR("%5d multiple PT_DYNAMIC segments found in '%s'. "
1459 "Segment at 0x%08x, previously one found at 0x%08x\n",
1460 pid, si->name, si->base + phdr->p_vaddr,
1461 (unsigned)si->dynamic);
1462 goto fail;
1463 }
1464 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1465 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1466 }
1467 }
1468 }
1469
1470 if (si->dynamic == (unsigned *)-1) {
1471 ERROR("%5d missing PT_DYNAMIC?!\n", pid);
1472 goto fail;
1473 }
1474
1475 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1476
1477 /* extract useful information from dynamic section */
1478 for(d = si->dynamic; *d; d++){
1479 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1480 switch(*d++){
1481 case DT_HASH:
1482 si->nbucket = ((unsigned *) (si->base + *d))[0];
1483 si->nchain = ((unsigned *) (si->base + *d))[1];
1484 si->bucket = (unsigned *) (si->base + *d + 8);
1485 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1486 break;
1487 case DT_STRTAB:
1488 si->strtab = (const char *) (si->base + *d);
1489 break;
1490 case DT_SYMTAB:
1491 si->symtab = (Elf32_Sym *) (si->base + *d);
1492 break;
1493 case DT_PLTREL:
1494 if(*d != DT_REL) {
1495 ERROR("DT_RELA not supported\n");
1496 goto fail;
1497 }
1498 break;
1499 case DT_JMPREL:
1500 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1501 break;
1502 case DT_PLTRELSZ:
1503 si->plt_rel_count = *d / 8;
1504 break;
1505 case DT_REL:
1506 si->rel = (Elf32_Rel*) (si->base + *d);
1507 break;
1508 case DT_RELSZ:
1509 si->rel_count = *d / 8;
1510 break;
1511 case DT_PLTGOT:
1512 /* Save this in case we decide to do lazy binding. We don't yet. */
1513 si->plt_got = (unsigned *)(si->base + *d);
1514 break;
1515 case DT_DEBUG:
1516 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1517 *d = (int) &_r_debug;
1518 break;
1519 case DT_RELA:
1520 ERROR("%5d DT_RELA not supported\n", pid);
1521 goto fail;
1522 case DT_INIT:
1523 si->init_func = (void (*)(void))(si->base + *d);
1524 DEBUG("%5d %s constructors (init func) found at %p\n",
1525 pid, si->name, si->init_func);
1526 break;
1527 case DT_FINI:
1528 si->fini_func = (void (*)(void))(si->base + *d);
1529 DEBUG("%5d %s destructors (fini func) found at %p\n",
1530 pid, si->name, si->fini_func);
1531 break;
1532 case DT_INIT_ARRAY:
1533 si->init_array = (unsigned *)(si->base + *d);
1534 DEBUG("%5d %s constructors (init_array) found at %p\n",
1535 pid, si->name, si->init_array);
1536 break;
1537 case DT_INIT_ARRAYSZ:
1538 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1539 break;
1540 case DT_FINI_ARRAY:
1541 si->fini_array = (unsigned *)(si->base + *d);
1542 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1543 pid, si->name, si->fini_array);
1544 break;
1545 case DT_FINI_ARRAYSZ:
1546 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1547 break;
1548 case DT_PREINIT_ARRAY:
1549 si->preinit_array = (unsigned *)(si->base + *d);
1550 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1551 pid, si->name, si->preinit_array);
1552 break;
1553 case DT_PREINIT_ARRAYSZ:
1554 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1555 break;
1556 case DT_TEXTREL:
1557 /* TODO: make use of this. */
1558 /* this means that we might have to write into where the text
1559 * segment was loaded during relocation... Do something with
1560 * it.
1561 */
1562 DEBUG("%5d Text segment should be writable during relocation.\n",
1563 pid);
1564 break;
1565 }
1566 }
1567
1568 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1569 pid, si->base, si->strtab, si->symtab);
1570
1571 if((si->strtab == 0) || (si->symtab == 0)) {
1572 ERROR("%5d missing essential tables\n", pid);
1573 goto fail;
1574 }
1575
1576 for(d = si->dynamic; *d; d += 2) {
1577 if(d[0] == DT_NEEDED){
1578 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
1579 soinfo *lsi = find_library(si->strtab + d[1]);
1580 if(lsi == 0) {
1581 ERROR("%5d could not load '%s'\n", pid, si->strtab + d[1]);
1582 goto fail;
1583 }
1584 lsi->refcount++;
1585 }
1586 }
1587
1588 if(si->plt_rel) {
1589 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1590 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1591 goto fail;
1592 }
1593 if(si->rel) {
1594 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1595 if(reloc_library(si, si->rel, si->rel_count))
1596 goto fail;
1597 }
1598
1599 si->flags |= FLAG_LINKED;
1600 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1601
1602#if 0
1603 /* This is the way that the old dynamic linker did protection of
1604 * non-writable areas. It would scan section headers and find where
1605 * .text ended (rather where .data/.bss began) and assume that this is
1606 * the upper range of the non-writable area. This is too coarse,
1607 * and is kept here for reference until we fully move away from single
1608 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1609 * that made this possible.
1610 */
1611 if(wr_offset < 0xffffffff){
1612 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1613 }
1614#else
1615 /* TODO: Verify that this does the right thing in all cases, as it
1616 * presently probably does not. It is possible that an ELF image will
1617 * come with multiple read-only segments. What we ought to do is scan
1618 * the program headers again and mprotect all the read-only segments.
1619 * To prevent re-scanning the program header, we would have to build a
1620 * list of loadable segments in si, and then scan that instead. */
1621 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1622 mprotect((void *)si->wrprotect_start,
1623 si->wrprotect_end - si->wrprotect_start,
1624 PROT_READ | PROT_EXEC);
1625 }
1626#endif
1627
1628 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1629 stdout and stderr to close a security hole described in:
1630
1631 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1632
1633 */
1634 if (getuid() != geteuid() || getgid() != getegid())
1635 nullify_closed_stdio ();
1636 call_constructors(si);
1637 notify_gdb_of_load(si);
1638 return 0;
1639
1640fail:
1641 ERROR("failed to link %s\n", si->name);
1642 si->flags |= FLAG_ERROR;
1643 return -1;
1644}
1645
1646int main(int argc, char **argv)
1647{
1648 return 0;
1649}
1650
1651#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1652
1653static void * __tls_area[ANDROID_TLS_SLOTS];
1654
1655unsigned __linker_init(unsigned **elfdata)
1656{
1657 static soinfo linker_soinfo;
1658
1659 int argc = (int) *elfdata;
1660 char **argv = (char**) (elfdata + 1);
1661 unsigned *vecs = (unsigned*) (argv + argc + 1);
1662 soinfo *si;
1663 struct link_map * map;
1664
1665 pid = getpid();
1666
1667#if TIMING
1668 struct timeval t0, t1;
1669 gettimeofday(&t0, 0);
1670#endif
1671
1672 __set_tls(__tls_area);
1673 ((unsigned *)__get_tls())[TLS_SLOT_THREAD_ID] = gettid();
1674
1675 debugger_init();
1676
1677 /* skip past the environment */
1678 while(vecs[0] != 0) {
1679 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1680 debug_verbosity = atoi(((char*) vecs[0]) + 6);
1681 }
1682 vecs++;
1683 }
1684 vecs++;
1685
1686 INFO("[ android linker & debugger ]\n");
1687 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1688
1689 si = alloc_info(argv[0]);
1690 if(si == 0) {
1691 exit(-1);
1692 }
1693
1694 /* bootstrap the link map, the main exe always needs to be first */
1695 si->flags |= FLAG_EXE;
1696 map = &(si->linkmap);
1697
1698 map->l_addr = 0;
1699 map->l_name = argv[0];
1700 map->l_prev = NULL;
1701 map->l_next = NULL;
1702
1703 _r_debug.r_map = map;
1704 r_debug_tail = map;
1705
1706 /* gdb expects the linker to be in the debug shared object list,
1707 * and we need to make sure that the reported load address is zero.
1708 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1709 * is. Don't use alloc_info(), because the linker shouldn't
1710 * be on the soinfo list.
1711 */
1712 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1713 linker_soinfo.flags = 0;
1714 linker_soinfo.base = 0; // This is the important part; must be zero.
1715 insert_soinfo_into_debug_map(&linker_soinfo);
1716
1717 /* extract information passed from the kernel */
1718 while(vecs[0] != 0){
1719 switch(vecs[0]){
1720 case AT_PHDR:
1721 si->phdr = (Elf32_Phdr*) vecs[1];
1722 break;
1723 case AT_PHNUM:
1724 si->phnum = (int) vecs[1];
1725 break;
1726 case AT_ENTRY:
1727 si->entry = vecs[1];
1728 break;
1729 }
1730 vecs += 2;
1731 }
1732
1733 ba_init();
1734
1735 si->base = 0;
1736 si->dynamic = (unsigned *)-1;
1737 si->wrprotect_start = 0xffffffff;
1738 si->wrprotect_end = 0;
1739
1740 if(link_image(si, 0)){
1741 ERROR("CANNOT LINK EXECUTABLE '%s'\n", argv[0]);
1742 exit(-1);
1743 }
1744
1745#if TIMING
1746 gettimeofday(&t1,NULL);
1747 PRINT("LINKER TIME: %s: %d microseconds\n", 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", argv[0],
1754 linker_stats.reloc[RELOC_ABSOLUTE],
1755 linker_stats.reloc[RELOC_RELATIVE],
1756 linker_stats.reloc[RELOC_COPY],
1757 linker_stats.reloc[RELOC_SYMBOL]);
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) count++;
1769 x >>= 1;
1770 }
1771 }
1772 }
1773 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1774 }
1775#endif
1776
1777#if TIMING || STATS || COUNT_PAGES
1778 fflush(stdout);
1779#endif
1780
1781 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1782 si->entry);
1783 return si->entry;
1784}