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