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