blob: 50eb4150a7bb22ea7935230237b67f1fad4c71c3 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <linux/auxvec.h>
30
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35#include <fcntl.h>
36#include <errno.h>
37#include <dlfcn.h>
38#include <sys/stat.h>
39
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -070040#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
42#include <sys/mman.h>
43
44#include <sys/atomics.h>
45
46/* special private C library header - see Android.mk */
47#include <bionic_tls.h>
48
49#include "linker.h"
50#include "linker_debug.h"
51
52#include "ba.h"
53
James Dongba52b302009-04-30 20:37:36 -070054#define SO_MAX 96
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080055
David Bartleybc3a5c22009-06-02 18:27:28 -070056/* Assume average path length of 64 and max 8 paths */
57#define LDPATH_BUFSIZE 512
58#define LDPATH_MAX 8
59
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080060/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
61 *
62 * Do NOT use malloc() and friends or pthread_*() code here.
63 * Don't use printf() either; it's caused mysterious memory
64 * corruption in the past.
65 * The linker runs before we bring up libc and it's easiest
66 * to make sure it does not depend on any complex libc features
67 *
68 * open issues / todo:
69 *
70 * - should we do anything special for STB_WEAK symbols?
71 * - are we doing everything we should for ARM_COPY relocations?
72 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080073 * - after linking, set as much stuff as possible to READONLY
74 * and NOEXEC
75 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
76 * headers provide versions that are negative...
77 * - allocate space for soinfo structs dynamically instead of
78 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080079*/
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
David Bartleybc3a5c22009-06-02 18:27:28 -070090static char ldpaths_buf[LDPATH_BUFSIZE];
91static const char *ldpaths[LDPATH_MAX + 1];
92
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080093int debug_verbosity;
94static int pid;
95
96#if STATS
97struct _link_stats linker_stats;
98#endif
99
100#if COUNT_PAGES
101unsigned bitmask[4096];
102#endif
103
104#ifndef PT_ARM_EXIDX
105#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
106#endif
107
Dima Zavin2e855792009-05-20 18:28:09 -0700108#define HOODLUM(name, ret, ...) \
109 ret name __VA_ARGS__ \
110 { \
111 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
112 write(2, errstr, sizeof(errstr)); \
113 abort(); \
114 }
115HOODLUM(malloc, void *, (size_t size));
116HOODLUM(free, void, (void *ptr));
117HOODLUM(realloc, void *, (void *ptr, size_t size));
118HOODLUM(calloc, void *, (size_t cnt, size_t size));
119
Dima Zavin03531952009-05-29 17:30:25 -0700120static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700121static char __linker_dl_err_buf[768];
122#define DL_ERR(fmt, x...) \
123 do { \
124 snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
125 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700126 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700127 } while(0)
128
129const char *linker_get_error(void)
130{
131 return (const char *)&__linker_dl_err_buf[0];
132}
133
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800134/*
135 * This function is an empty stub where GDB locates a breakpoint to get notified
136 * about linker activity.
137 */
138extern void __attribute__((noinline)) rtld_db_dlactivity(void);
139
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800140static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
141 RT_CONSISTENT, 0};
142static struct link_map *r_debug_tail = 0;
143
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700144static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800145
146static void insert_soinfo_into_debug_map(soinfo * info)
147{
148 struct link_map * map;
149
150 /* Copy the necessary fields into the debug structure.
151 */
152 map = &(info->linkmap);
153 map->l_addr = info->base;
154 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800155 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800156
157 /* Stick the new library at the end of the list.
158 * gdb tends to care more about libc than it does
159 * about leaf libraries, and ordering it this way
160 * reduces the back-and-forth over the wire.
161 */
162 if (r_debug_tail) {
163 r_debug_tail->l_next = map;
164 map->l_prev = r_debug_tail;
165 map->l_next = 0;
166 } else {
167 _r_debug.r_map = map;
168 map->l_prev = 0;
169 map->l_next = 0;
170 }
171 r_debug_tail = map;
172}
173
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700174static void remove_soinfo_from_debug_map(soinfo * info)
175{
176 struct link_map * map = &(info->linkmap);
177
178 if (r_debug_tail == map)
179 r_debug_tail = map->l_prev;
180
181 if (map->l_prev) map->l_prev->l_next = map->l_next;
182 if (map->l_next) map->l_next->l_prev = map->l_prev;
183}
184
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800185void notify_gdb_of_load(soinfo * info)
186{
187 if (info->flags & FLAG_EXE) {
188 // GDB already knows about the main executable
189 return;
190 }
191
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700192 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800193
194 _r_debug.r_state = RT_ADD;
195 rtld_db_dlactivity();
196
197 insert_soinfo_into_debug_map(info);
198
199 _r_debug.r_state = RT_CONSISTENT;
200 rtld_db_dlactivity();
201
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700202 pthread_mutex_unlock(&_r_debug_lock);
203}
204
205void notify_gdb_of_unload(soinfo * info)
206{
207 if (info->flags & FLAG_EXE) {
208 // GDB already knows about the main executable
209 return;
210 }
211
212 pthread_mutex_lock(&_r_debug_lock);
213
214 _r_debug.r_state = RT_DELETE;
215 rtld_db_dlactivity();
216
217 remove_soinfo_from_debug_map(info);
218
219 _r_debug.r_state = RT_CONSISTENT;
220 rtld_db_dlactivity();
221
222 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800223}
224
225void notify_gdb_of_libraries()
226{
227 _r_debug.r_state = RT_ADD;
228 rtld_db_dlactivity();
229 _r_debug.r_state = RT_CONSISTENT;
230 rtld_db_dlactivity();
231}
232
233static soinfo *alloc_info(const char *name)
234{
235 soinfo *si;
236
237 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700238 DL_ERR("%5d library name %s too long", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800239 return 0;
240 }
241
242 /* The freelist is populated when we call free_info(), which in turn is
243 done only by dlclose(), which is not likely to be used.
244 */
245 if (!freelist) {
246 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700247 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248 return NULL;
249 }
250 freelist = sopool + socount++;
251 freelist->next = NULL;
252 }
253
254 si = freelist;
255 freelist = freelist->next;
256
257 /* Make sure we get a clean block of soinfo */
258 memset(si, 0, sizeof(soinfo));
259 strcpy((char*) si->name, name);
260 sonext->next = si;
261 si->ba_index = -1; /* by default, prelinked */
262 si->next = NULL;
263 si->refcount = 0;
264 sonext = si;
265
266 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
267 return si;
268}
269
270static void free_info(soinfo *si)
271{
272 soinfo *prev = NULL, *trav;
273
274 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
275
276 for(trav = solist; trav != NULL; trav = trav->next){
277 if (trav == si)
278 break;
279 prev = trav;
280 }
281 if (trav == NULL) {
282 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700283 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800284 return;
285 }
286
287 /* prev will never be NULL, because the first entry in solist is
288 always the static libdl_info.
289 */
290 prev->next = si->next;
291 if (si == sonext) sonext = prev;
292 si->next = freelist;
293 freelist = si;
294}
295
296#ifndef LINKER_TEXT_BASE
297#error "linker's makefile must define LINKER_TEXT_BASE"
298#endif
299#ifndef LINKER_AREA_SIZE
300#error "linker's makefile must define LINKER_AREA_SIZE"
301#endif
302#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
303#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
304
305const char *addr_to_name(unsigned addr)
306{
307 soinfo *si;
308
309 for(si = solist; si != 0; si = si->next){
310 if((addr >= si->base) && (addr < (si->base + si->size))) {
311 return si->name;
312 }
313 }
314
315 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
316 return "linker";
317 }
318
319 return "";
320}
321
322/* For a given PC, find the .so that it belongs to.
323 * Returns the base address of the .ARM.exidx section
324 * for that .so, and the number of 8-byte entries
325 * in that section (via *pcount).
326 *
327 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
328 *
329 * This function is exposed via dlfcn.c and libdl.so.
330 */
331#ifdef ANDROID_ARM_LINKER
332_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
333{
334 soinfo *si;
335 unsigned addr = (unsigned)pc;
336
337 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
338 for (si = solist; si != 0; si = si->next){
339 if ((addr >= si->base) && (addr < (si->base + si->size))) {
340 *pcount = si->ARM_exidx_count;
341 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
342 }
343 }
344 }
345 *pcount = 0;
346 return NULL;
347}
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +0900348#elif defined(ANDROID_X86_LINKER) || defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800349/* Here, we only have to provide a callback to iterate across all the
350 * loaded libraries. gcc_eh does the rest. */
351int
352dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
353 void *data)
354{
355 soinfo *si;
356 struct dl_phdr_info dl_info;
357 int rv = 0;
358
359 for (si = solist; si != NULL; si = si->next) {
360 dl_info.dlpi_addr = si->linkmap.l_addr;
361 dl_info.dlpi_name = si->linkmap.l_name;
362 dl_info.dlpi_phdr = si->phdr;
363 dl_info.dlpi_phnum = si->phnum;
364 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
365 if (rv != 0)
366 break;
367 }
368 return rv;
369}
370#endif
371
372static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
373{
374 Elf32_Sym *s;
375 Elf32_Sym *symtab = si->symtab;
376 const char *strtab = si->strtab;
377 unsigned n;
378
379 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
380 name, si->name, si->base, hash, hash % si->nbucket);
381 n = hash % si->nbucket;
382
383 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
384 s = symtab + n;
385 if(strcmp(strtab + s->st_name, name)) continue;
386
387 /* only concern ourselves with global symbols */
388 switch(ELF32_ST_BIND(s->st_info)){
389 case STB_GLOBAL:
390 /* no section == undefined */
391 if(s->st_shndx == 0) continue;
392
393 case STB_WEAK:
394 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
395 name, si->name, s->st_value, s->st_size);
396 return s;
397 }
398 }
399
400 return 0;
401}
402
403static unsigned elfhash(const char *_name)
404{
405 const unsigned char *name = (const unsigned char *) _name;
406 unsigned h = 0, g;
407
408 while(*name) {
409 h = (h << 4) + *name++;
410 g = h & 0xf0000000;
411 h ^= g;
412 h ^= g >> 24;
413 }
414 return h;
415}
416
417static Elf32_Sym *
418_do_lookup_in_so(soinfo *si, const char *name, unsigned *elf_hash)
419{
420 if (*elf_hash == 0)
421 *elf_hash = elfhash(name);
422 return _elf_lookup (si, *elf_hash, name);
423}
424
425/* This is used by dl_sym() */
426Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
427{
428 unsigned unused = 0;
429 return _do_lookup_in_so(si, name, &unused);
430}
431
432static Elf32_Sym *
433_do_lookup(soinfo *user_si, const char *name, unsigned *base)
434{
435 unsigned elf_hash = 0;
436 Elf32_Sym *s = NULL;
437 soinfo *si;
438
439 /* Look for symbols in the local scope first (the object who is
440 * searching). This happens with C++ templates on i386 for some
441 * reason. */
442 if (user_si) {
443 s = _do_lookup_in_so(user_si, name, &elf_hash);
444 if (s != NULL)
445 *base = user_si->base;
446 }
447
448 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
449 {
450 if((si->flags & FLAG_ERROR) || (si == user_si))
451 continue;
452 s = _do_lookup_in_so(si, name, &elf_hash);
453 if (s != NULL) {
454 *base = si->base;
455 break;
456 }
457 }
458
459 if (s != NULL) {
460 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
461 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
462 return s;
463 }
464
465 return 0;
466}
467
468/* This is used by dl_sym() */
469Elf32_Sym *lookup(const char *name, unsigned *base)
470{
471 return _do_lookup(NULL, name, base);
472}
473
474#if 0
475static void dump(soinfo *si)
476{
477 Elf32_Sym *s = si->symtab;
478 unsigned n;
479
480 for(n = 0; n < si->nchain; n++) {
481 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
482 s->st_info, s->st_shndx, s->st_value, s->st_size,
483 si->strtab + s->st_name);
484 s++;
485 }
486}
487#endif
488
489static const char *sopaths[] = {
490 "/system/lib",
491 "/lib",
492 0
493};
494
495static int _open_lib(const char *name)
496{
497 int fd;
498 struct stat filestat;
499
500 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
501 if ((fd = open(name, O_RDONLY)) >= 0)
502 return fd;
503 }
504
505 return -1;
506}
507
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800508static int open_library(const char *name)
509{
510 int fd;
511 char buf[512];
512 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700513 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800514
515 TRACE("[ %5d opening %s ]\n", pid, name);
516
517 if(name == 0) return -1;
518 if(strlen(name) > 256) return -1;
519
520 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
521 return fd;
522
David Bartleybc3a5c22009-06-02 18:27:28 -0700523 for (path = ldpaths; *path; path++) {
524 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
525 if (n < 0 || n >= (int)sizeof(buf)) {
526 WARN("Ignoring very long library path: %s/%s\n", *path, name);
527 continue;
528 }
529 if ((fd = _open_lib(buf)) >= 0)
530 return fd;
531 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800532 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700533 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
534 if (n < 0 || n >= (int)sizeof(buf)) {
535 WARN("Ignoring very long library path: %s/%s\n", *path, name);
536 continue;
537 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800538 if ((fd = _open_lib(buf)) >= 0)
539 return fd;
540 }
541
542 return -1;
543}
544
545/* temporary space for holding the first page of the shared lib
546 * which contains the elf header (with the pht). */
547static unsigned char __header[PAGE_SIZE];
548
549typedef struct {
550 long mmap_addr;
551 char tag[4]; /* 'P', 'R', 'E', ' ' */
552} prelink_info_t;
553
554/* Returns the requested base address if the library is prelinked,
555 * and 0 otherwise. */
556static unsigned long
557is_prelinked(int fd, const char *name)
558{
559 off_t sz;
560 prelink_info_t info;
561
562 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
563 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700564 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800565 return 0;
566 }
567
568 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
569 WARN("Could not read prelink_info_t structure for `%s`\n", name);
570 return 0;
571 }
572
573 if (strncmp(info.tag, "PRE ", 4)) {
574 WARN("`%s` is not a prelinked library\n", name);
575 return 0;
576 }
577
578 return (unsigned long)info.mmap_addr;
579}
580
581/* verify_elf_object
582 * Verifies if the object @ base is a valid ELF object
583 *
584 * Args:
585 *
586 * Returns:
587 * 0 on success
588 * -1 if no valid ELF object is found @ base.
589 */
590static int
591verify_elf_object(void *base, const char *name)
592{
593 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
594
595 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
596 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
597 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
598 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
599
600 /* TODO: Should we verify anything else in the header? */
601
602 return 0;
603}
604
605
606/* get_lib_extents
607 * Retrieves the base (*base) address where the ELF object should be
608 * mapped and its overall memory size (*total_sz).
609 *
610 * Args:
611 * fd: Opened file descriptor for the library
612 * name: The name of the library
613 * _hdr: Pointer to the header page of the library
614 * total_sz: Total size of the memory that should be allocated for
615 * this library
616 *
617 * Returns:
618 * -1 if there was an error while trying to get the lib extents.
619 * The possible reasons are:
620 * - Could not determine if the library was prelinked.
621 * - The library provided is not a valid ELF object
622 * 0 if the library did not request a specific base offset (normal
623 * for non-prelinked libs)
624 * > 0 if the library requests a specific address to be mapped to.
625 * This indicates a pre-linked library.
626 */
627static unsigned
628get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
629{
630 unsigned req_base;
631 unsigned min_vaddr = 0xffffffff;
632 unsigned max_vaddr = 0;
633 unsigned char *_hdr = (unsigned char *)__hdr;
634 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
635 Elf32_Phdr *phdr;
636 int cnt;
637
638 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
639 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700640 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800641 return (unsigned)-1;
642 }
643
644 req_base = (unsigned) is_prelinked(fd, name);
645 if (req_base == (unsigned)-1)
646 return -1;
647 else if (req_base != 0) {
648 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
649 pid, name, req_base);
650 } else {
651 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
652 }
653
654 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
655
656 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
657 * get the range. */
658 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
659 if (phdr->p_type == PT_LOAD) {
660 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
661 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
662 if (phdr->p_vaddr < min_vaddr)
663 min_vaddr = phdr->p_vaddr;
664 }
665 }
666
667 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700668 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800669 return (unsigned)-1;
670 }
671
672 /* truncate min_vaddr down to page boundary */
673 min_vaddr &= ~PAGE_MASK;
674
675 /* round max_vaddr up to the next page */
676 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
677
678 *total_sz = (max_vaddr - min_vaddr);
679 return (unsigned)req_base;
680}
681
682/* alloc_mem_region
683 *
684 * This function reserves a chunk of memory to be used for mapping in
685 * the shared library. We reserve the entire memory region here, and
686 * then the rest of the linker will relocate the individual loadable
687 * segments into the correct locations within this memory range.
688 *
689 * Args:
690 * si->base: The requested base of the allocation. If 0, a sane one will be
691 * chosen in the range LIBBASE <= base < LIBLAST.
692 * si->size: The size of the allocation.
693 *
694 * Returns:
695 * -1 on failure, and 0 on success. On success, si->base will contain
696 * the virtual address at which the library will be mapped.
697 */
698
699static int reserve_mem_region(soinfo *si)
700{
701 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
702 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
703 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700704 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700705 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800706 pid, (si->base ? "" : "non-"), si->name, si->base,
707 errno, strerror(errno));
708 return -1;
709 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700710 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700711 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800712 si->name, (unsigned)base, si->base);
713 munmap(base, si->size);
714 return -1;
715 }
716 return 0;
717}
718
719static int
720alloc_mem_region(soinfo *si)
721{
722 if (si->base) {
723 /* Attempt to mmap a prelinked library. */
724 si->ba_index = -1;
725 return reserve_mem_region(si);
726 }
727
728 /* This is not a prelinked library, so we attempt to allocate space
729 for it from the buddy allocator, which manages the area between
730 LIBBASE and LIBLAST.
731 */
732 si->ba_index = ba_allocate(si->size);
733 if(si->ba_index >= 0) {
734 si->base = ba_start_addr(si->ba_index);
735 PRINT("%5d mapping library '%s' at %08x (index %d) " \
736 "through buddy allocator.\n",
737 pid, si->name, si->base, si->ba_index);
738 if (reserve_mem_region(si) < 0) {
739 ba_free(si->ba_index);
740 si->ba_index = -1;
741 si->base = 0;
742 goto err;
743 }
744 return 0;
745 }
746
747err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700748 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800749 pid, si->name);
750 return -1;
751}
752
753#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
754#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
755 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
756 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
757/* load_segments
758 *
759 * This function loads all the loadable (PT_LOAD) segments into memory
760 * at their appropriate memory offsets off the base address.
761 *
762 * Args:
763 * fd: Open file descriptor to the library to load.
764 * header: Pointer to a header page that contains the ELF header.
765 * This is needed since we haven't mapped in the real file yet.
766 * si: ptr to soinfo struct describing the shared object.
767 *
768 * Returns:
769 * 0 on success, -1 on failure.
770 */
771static int
772load_segments(int fd, void *header, soinfo *si)
773{
774 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
775 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
776 unsigned char *base = (unsigned char *)si->base;
777 int cnt;
778 unsigned len;
779 unsigned char *tmp;
780 unsigned char *pbase;
781 unsigned char *extra_base;
782 unsigned extra_len;
783 unsigned total_sz = 0;
784
785 si->wrprotect_start = 0xffffffff;
786 si->wrprotect_end = 0;
787
788 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
789 pid, si->name, (unsigned)si->base);
790 /* Now go through all the PT_LOAD segments and map them into memory
791 * at the appropriate locations. */
792 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
793 if (phdr->p_type == PT_LOAD) {
794 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
795 /* we want to map in the segment on a page boundary */
796 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
797 /* add the # of bytes we masked off above to the total length. */
798 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
799
800 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
801 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
802 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
803 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
804 MAP_PRIVATE | MAP_FIXED, fd,
805 phdr->p_offset & (~PAGE_MASK));
806 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700807 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700808 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800809 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
810 goto fail;
811 }
812
813 /* If 'len' didn't end on page boundary, and it's a writable
814 * segment, zero-fill the rest. */
815 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
816 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
817
818 /* Check to see if we need to extend the map for this segment to
819 * cover the diff between filesz and memsz (i.e. for bss).
820 *
821 * base _+---------------------+ page boundary
822 * . .
823 * | |
824 * . .
825 * pbase _+---------------------+ page boundary
826 * | |
827 * . .
828 * base + p_vaddr _| |
829 * . \ \ .
830 * . | filesz | .
831 * pbase + len _| / | |
832 * <0 pad> . . .
833 * extra_base _+------------|--------+ page boundary
834 * / . . .
835 * | . . .
836 * | +------------|--------+ page boundary
837 * extra_len-> | | | |
838 * | . | memsz .
839 * | . | .
840 * \ _| / |
841 * . .
842 * | |
843 * _+---------------------+ page boundary
844 */
845 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
846 (~PAGE_MASK));
847 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
848 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
849 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
850 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
851 /* map in the extra page(s) as anonymous into the range.
852 * This is probably not necessary as we already mapped in
853 * the entire region previously, but we just want to be
854 * sure. This will also set the right flags on the region
855 * (though we can probably accomplish the same thing with
856 * mprotect).
857 */
858 extra_base = mmap((void *)tmp, extra_len,
859 PFLAGS_TO_PROT(phdr->p_flags),
860 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
861 -1, 0);
862 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700863 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700864 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865 extra_len);
866 goto fail;
867 }
868 /* TODO: Check if we need to memset-0 this region.
869 * Anonymous mappings are zero-filled copy-on-writes, so we
870 * shouldn't need to. */
871 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
872 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
873 extra_len);
874 }
875 /* set the len here to show the full extent of the segment we
876 * just loaded, mostly for debugging */
877 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
878 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
879 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
880 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
881 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
882 total_sz += len;
883 /* Make the section writable just in case we'll have to write to
884 * it during relocation (i.e. text segment). However, we will
885 * remember what range of addresses should be write protected.
886 *
887 */
888 if (!(phdr->p_flags & PF_W)) {
889 if ((unsigned)pbase < si->wrprotect_start)
890 si->wrprotect_start = (unsigned)pbase;
891 if (((unsigned)pbase + len) > si->wrprotect_end)
892 si->wrprotect_end = (unsigned)pbase + len;
893 mprotect(pbase, len,
894 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
895 }
896 } else if (phdr->p_type == PT_DYNAMIC) {
897 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
898 /* this segment contains the dynamic linking information */
899 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
900 } else {
901#ifdef ANDROID_ARM_LINKER
902 if (phdr->p_type == PT_ARM_EXIDX) {
903 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
904 /* exidx entries (used for stack unwinding) are 8 bytes each.
905 */
906 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
907 si->ARM_exidx_count = phdr->p_memsz / 8;
908 }
909#endif
910 }
911
912 }
913
914 /* Sanity check */
915 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700916 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700917 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800918 pid, total_sz, si->name, si->size);
919 goto fail;
920 }
921
922 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
923 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
924 (unsigned)si->base, si->size);
925 return 0;
926
927fail:
928 /* We can just blindly unmap the entire region even though some things
929 * were mapped in originally with anonymous and others could have been
930 * been mapped in from the file before we failed. The kernel will unmap
931 * all the pages in the range, irrespective of how they got there.
932 */
933 munmap((void *)si->base, si->size);
934 si->flags |= FLAG_ERROR;
935 return -1;
936}
937
938/* TODO: Implement this to take care of the fact that Android ARM
939 * ELF objects shove everything into a single loadable segment that has the
940 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
941 * non-writable.
942 */
943#if 0
944static unsigned
945get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
946{
947 Elf32_Shdr *shdr_start;
948 Elf32_Shdr *shdr;
949 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
950 int cnt;
951 unsigned wr_offset = 0xffffffff;
952
953 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
954 ehdr->e_shoff & (~PAGE_MASK));
955 if (shdr_start == MAP_FAILED) {
956 WARN("%5d - Could not read section header info from '%s'. Will not "
957 "not be able to determine write-protect offset.\n", pid, name);
958 return (unsigned)-1;
959 }
960
961 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
962 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
963 (shdr->sh_addr < wr_offset)) {
964 wr_offset = shdr->sh_addr;
965 }
966 }
967
968 munmap(shdr_start, shdr_sz);
969 return wr_offset;
970}
971#endif
972
973static soinfo *
974load_library(const char *name)
975{
976 int fd = open_library(name);
977 int cnt;
978 unsigned ext_sz;
979 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -0700980 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800981 soinfo *si = NULL;
982 Elf32_Ehdr *hdr;
983
Dima Zavin2e855792009-05-20 18:28:09 -0700984 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700985 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800986 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -0700987 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800988
989 /* We have to read the ELF header to figure out what to do with this image
990 */
991 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700992 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800993 goto fail;
994 }
995
996 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700997 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800998 goto fail;
999 }
1000
1001 /* Parse the ELF header and get the size of the memory footprint for
1002 * the library */
1003 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1004 if (req_base == (unsigned)-1)
1005 goto fail;
1006 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1007 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1008
1009 /* Now configure the soinfo struct where we'll store all of our data
1010 * for the ELF object. If the loading fails, we waste the entry, but
1011 * same thing would happen if we failed during linking. Configuring the
1012 * soinfo struct here is a lot more convenient.
1013 */
Erik Gillingfde86422009-07-28 20:28:19 -07001014 bname = strrchr(name, '/');
1015 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001016 if (si == NULL)
1017 goto fail;
1018
1019 /* Carve out a chunk of memory where we will map in the individual
1020 * segments */
1021 si->base = req_base;
1022 si->size = ext_sz;
1023 si->flags = 0;
1024 si->entry = 0;
1025 si->dynamic = (unsigned *)-1;
1026 if (alloc_mem_region(si) < 0)
1027 goto fail;
1028
1029 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1030 pid, name, (void *)si->base, (unsigned) ext_sz);
1031
1032 /* Now actually load the library's segments into right places in memory */
1033 if (load_segments(fd, &__header[0], si) < 0) {
1034 if (si->ba_index >= 0) {
1035 ba_free(si->ba_index);
1036 si->ba_index = -1;
1037 }
1038 goto fail;
1039 }
1040
1041 /* this might not be right. Technically, we don't even need this info
1042 * once we go through 'load_segments'. */
1043 hdr = (Elf32_Ehdr *)si->base;
1044 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1045 si->phnum = hdr->e_phnum;
1046 /**/
1047
1048 close(fd);
1049 return si;
1050
1051fail:
1052 if (si) free_info(si);
1053 close(fd);
1054 return NULL;
1055}
1056
1057static soinfo *
1058init_library(soinfo *si)
1059{
1060 unsigned wr_offset = 0xffffffff;
1061
1062 /* At this point we know that whatever is loaded @ base is a valid ELF
1063 * shared library whose segments are properly mapped in. */
1064 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1065 pid, si->base, si->size, si->name);
1066
1067 if (si->base < LIBBASE || si->base >= LIBLAST)
1068 si->flags |= FLAG_PRELINKED;
1069
1070 if(link_image(si, wr_offset)) {
1071 /* We failed to link. However, we can only restore libbase
1072 ** if no additional libraries have moved it since we updated it.
1073 */
1074 munmap((void *)si->base, si->size);
1075 return NULL;
1076 }
1077
1078 return si;
1079}
1080
1081soinfo *find_library(const char *name)
1082{
1083 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001084 const char *bname = strrchr(name, '/');
1085 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001086
1087 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001088 if(!strcmp(bname, si->name)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001089 if(si->flags & FLAG_ERROR) return 0;
1090 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001091 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001092 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001093 }
1094 }
1095
1096 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1097 si = load_library(name);
1098 if(si == NULL)
1099 return NULL;
1100 return init_library(si);
1101}
1102
1103/* TODO:
1104 * notify gdb of unload
1105 * for non-prelinked libraries, find a way to decrement libbase
1106 */
1107static void call_destructors(soinfo *si);
1108unsigned unload_library(soinfo *si)
1109{
1110 unsigned *d;
1111 if (si->refcount == 1) {
1112 TRACE("%5d unloading '%s'\n", pid, si->name);
1113 call_destructors(si);
1114
1115 for(d = si->dynamic; *d; d += 2) {
1116 if(d[0] == DT_NEEDED){
1117 TRACE("%5d %s needs to unload %s\n", pid,
1118 si->name, si->strtab + d[1]);
1119 soinfo *lsi = find_library(si->strtab + d[1]);
1120 if(lsi)
1121 unload_library(lsi);
1122 else
Erik Gillingd00d23a2009-07-22 17:06:11 -07001123 DL_ERR("%5d could not unload '%s'",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001124 pid, si->strtab + d[1]);
1125 }
1126 }
1127
1128 munmap((char *)si->base, si->size);
1129 if (si->ba_index >= 0) {
1130 PRINT("%5d releasing library '%s' address space at %08x "\
1131 "through buddy allocator.\n",
1132 pid, si->name, si->base);
1133 ba_free(si->ba_index);
1134 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001135 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001136 free_info(si);
1137 si->refcount = 0;
1138 }
1139 else {
1140 si->refcount--;
1141 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1142 pid, si->name, si->refcount);
1143 }
1144 return si->refcount;
1145}
1146
1147/* TODO: don't use unsigned for addrs below. It works, but is not
1148 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1149 * long.
1150 */
1151static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1152{
1153 Elf32_Sym *symtab = si->symtab;
1154 const char *strtab = si->strtab;
1155 Elf32_Sym *s;
1156 unsigned base;
1157 Elf32_Rel *start = rel;
1158 unsigned idx;
1159
1160 for (idx = 0; idx < count; ++idx) {
1161 unsigned type = ELF32_R_TYPE(rel->r_info);
1162 unsigned sym = ELF32_R_SYM(rel->r_info);
1163 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1164 unsigned sym_addr = 0;
1165 char *sym_name = NULL;
1166
1167 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1168 si->name, idx);
1169 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001170 sym_name = (char *)(strtab + symtab[sym].st_name);
1171 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001172 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001173 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001174 return -1;
1175 }
1176#if 0
1177 if((base == 0) && (si->base != 0)){
1178 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001179 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001180 pid, strtab + symtab[sym].st_name);
1181 return -1;
1182 }
1183#endif
1184 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
Dima Zavin2e855792009-05-20 18:28:09 -07001185 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001186 "handle this yet", pid, si->name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001187 s->st_value);
1188 return -1;
1189 }
1190 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191 COUNT_RELOC(RELOC_SYMBOL);
1192 } else {
1193 s = 0;
1194 }
1195
1196/* TODO: This is ugly. Split up the relocations by arch into
1197 * different files.
1198 */
1199 switch(type){
1200#if defined(ANDROID_ARM_LINKER)
1201 case R_ARM_JUMP_SLOT:
1202 COUNT_RELOC(RELOC_ABSOLUTE);
1203 MARK(rel->r_offset);
1204 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1205 reloc, sym_addr, sym_name);
1206 *((unsigned*)reloc) = sym_addr;
1207 break;
1208 case R_ARM_GLOB_DAT:
1209 COUNT_RELOC(RELOC_ABSOLUTE);
1210 MARK(rel->r_offset);
1211 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1212 reloc, sym_addr, sym_name);
1213 *((unsigned*)reloc) = sym_addr;
1214 break;
1215 case R_ARM_ABS32:
1216 COUNT_RELOC(RELOC_ABSOLUTE);
1217 MARK(rel->r_offset);
1218 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1219 reloc, sym_addr, sym_name);
1220 *((unsigned*)reloc) += sym_addr;
1221 break;
1222#elif defined(ANDROID_X86_LINKER)
1223 case R_386_JUMP_SLOT:
1224 COUNT_RELOC(RELOC_ABSOLUTE);
1225 MARK(rel->r_offset);
1226 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1227 reloc, sym_addr, sym_name);
1228 *((unsigned*)reloc) = sym_addr;
1229 break;
1230 case R_386_GLOB_DAT:
1231 COUNT_RELOC(RELOC_ABSOLUTE);
1232 MARK(rel->r_offset);
1233 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1234 reloc, sym_addr, sym_name);
1235 *((unsigned*)reloc) = sym_addr;
1236 break;
1237#endif /* ANDROID_*_LINKER */
1238
1239#if defined(ANDROID_ARM_LINKER)
1240 case R_ARM_RELATIVE:
1241#elif defined(ANDROID_X86_LINKER)
1242 case R_386_RELATIVE:
1243#endif /* ANDROID_*_LINKER */
1244 COUNT_RELOC(RELOC_RELATIVE);
1245 MARK(rel->r_offset);
1246 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001247 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001248 return -1;
1249 }
1250 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1251 reloc, si->base);
1252 *((unsigned*)reloc) += si->base;
1253 break;
1254
1255#if defined(ANDROID_X86_LINKER)
1256 case R_386_32:
1257 COUNT_RELOC(RELOC_RELATIVE);
1258 MARK(rel->r_offset);
1259
1260 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1261 reloc, sym_addr, sym_name);
1262 *((unsigned *)reloc) += (unsigned)sym_addr;
1263 break;
1264
1265 case R_386_PC32:
1266 COUNT_RELOC(RELOC_RELATIVE);
1267 MARK(rel->r_offset);
1268 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1269 "+%08x (%08x - %08x) %s\n", pid, reloc,
1270 (sym_addr - reloc), sym_addr, reloc, sym_name);
1271 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1272 break;
1273#endif /* ANDROID_X86_LINKER */
1274
1275#ifdef ANDROID_ARM_LINKER
1276 case R_ARM_COPY:
1277 COUNT_RELOC(RELOC_COPY);
1278 MARK(rel->r_offset);
1279 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1280 reloc, s->st_size, sym_addr, sym_name);
1281 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1282 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001283 case R_ARM_NONE:
1284 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001285#endif /* ANDROID_ARM_LINKER */
1286
1287 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001288 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001289 pid, type, rel, (int) (rel - start));
1290 return -1;
1291 }
1292 rel++;
1293 }
1294 return 0;
1295}
1296
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001297#if defined(ANDROID_SH_LINKER)
1298static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1299{
1300 Elf32_Sym *symtab = si->symtab;
1301 const char *strtab = si->strtab;
1302 Elf32_Sym *s;
1303 unsigned base;
1304 Elf32_Rela *start = rela;
1305 unsigned idx;
1306
1307 for (idx = 0; idx < count; ++idx) {
1308 unsigned type = ELF32_R_TYPE(rela->r_info);
1309 unsigned sym = ELF32_R_SYM(rela->r_info);
1310 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1311 unsigned sym_addr = 0;
1312 char *sym_name = NULL;
1313
1314 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1315 si->name, idx);
1316 if(sym != 0) {
1317 sym_name = (char *)(strtab + symtab[sym].st_name);
1318 s = _do_lookup(si, sym_name, &base);
1319 if(s == 0) {
1320 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1321 return -1;
1322 }
1323#if 0
1324 if((base == 0) && (si->base != 0)){
1325 /* linking from libraries to main image is bad */
1326 DL_ERR("%5d cannot locate '%s'...",
1327 pid, strtab + symtab[sym].st_name);
1328 return -1;
1329 }
1330#endif
1331 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1332 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1333 "handle this yet", pid, si->name, s->st_shndx,
1334 s->st_value);
1335 return -1;
1336 }
1337 sym_addr = (unsigned)(s->st_value + base);
1338 COUNT_RELOC(RELOC_SYMBOL);
1339 } else {
1340 s = 0;
1341 }
1342
1343/* TODO: This is ugly. Split up the relocations by arch into
1344 * different files.
1345 */
1346 switch(type){
1347 case R_SH_JUMP_SLOT:
1348 COUNT_RELOC(RELOC_ABSOLUTE);
1349 MARK(rela->r_offset);
1350 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1351 reloc, sym_addr, sym_name);
1352 *((unsigned*)reloc) = sym_addr;
1353 break;
1354 case R_SH_GLOB_DAT:
1355 COUNT_RELOC(RELOC_ABSOLUTE);
1356 MARK(rela->r_offset);
1357 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1358 reloc, sym_addr, sym_name);
1359 *((unsigned*)reloc) = sym_addr;
1360 break;
1361 case R_SH_DIR32:
1362 COUNT_RELOC(RELOC_ABSOLUTE);
1363 MARK(rela->r_offset);
1364 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1365 reloc, sym_addr, sym_name);
1366 *((unsigned*)reloc) += sym_addr;
1367 break;
1368 case R_SH_RELATIVE:
1369 COUNT_RELOC(RELOC_RELATIVE);
1370 MARK(rela->r_offset);
1371 if(sym){
1372 DL_ERR("%5d odd RELATIVE form...", pid);
1373 return -1;
1374 }
1375 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1376 reloc, si->base);
1377 *((unsigned*)reloc) += si->base;
1378 break;
1379
1380 default:
1381 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1382 pid, type, rela, (int) (rela - start));
1383 return -1;
1384 }
1385 rela++;
1386 }
1387 return 0;
1388}
1389#endif /* ANDROID_SH_LINKER */
1390
David 'Digit' Turner82156792009-05-18 14:37:41 +02001391
1392/* Please read the "Initialization and Termination functions" functions.
1393 * of the linker design note in bionic/linker/README.TXT to understand
1394 * what the following code is doing.
1395 *
1396 * The important things to remember are:
1397 *
1398 * DT_PREINIT_ARRAY must be called first for executables, and should
1399 * not appear in shared libraries.
1400 *
1401 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1402 *
1403 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1404 *
1405 * DT_FINI_ARRAY must be parsed in reverse order.
1406 */
1407
1408static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001409{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001410 int n, inc = 1;
1411
1412 if (reverse) {
1413 ctor += (count-1);
1414 inc = -1;
1415 }
1416
1417 for(n = count; n > 0; n--) {
1418 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1419 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001420 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001421 void (*func)() = (void (*)()) *ctor;
1422 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001423 if(((int) func == 0) || ((int) func == -1)) continue;
1424 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1425 func();
1426 }
1427}
1428
1429static void call_constructors(soinfo *si)
1430{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001431 if (si->flags & FLAG_EXE) {
1432 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1433 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1434 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001435 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001436 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1437 } else {
1438 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001439 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001440 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001441 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001442 }
1443 }
1444
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001445 if (si->init_func) {
1446 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1447 (unsigned)si->init_func, si->name);
1448 si->init_func();
1449 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1450 }
1451
1452 if (si->init_array) {
1453 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1454 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001455 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001456 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1457 }
1458}
1459
David 'Digit' Turner82156792009-05-18 14:37:41 +02001460
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001461static void call_destructors(soinfo *si)
1462{
1463 if (si->fini_array) {
1464 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1465 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001466 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1468 }
1469
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001470 if (si->fini_func) {
1471 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1472 (unsigned)si->fini_func, si->name);
1473 si->fini_func();
1474 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1475 }
1476}
1477
1478/* Force any of the closed stdin, stdout and stderr to be associated with
1479 /dev/null. */
1480static int nullify_closed_stdio (void)
1481{
1482 int dev_null, i, status;
1483 int return_value = 0;
1484
1485 dev_null = open("/dev/null", O_RDWR);
1486 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001487 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001488 return -1;
1489 }
1490 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1491
1492 /* If any of the stdio file descriptors is valid and not associated
1493 with /dev/null, dup /dev/null to it. */
1494 for (i = 0; i < 3; i++) {
1495 /* If it is /dev/null already, we are done. */
1496 if (i == dev_null)
1497 continue;
1498
1499 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1500 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1501 can be interrupted but we do this just to be safe. */
1502 do {
1503 status = fcntl(i, F_GETFL);
1504 } while (status < 0 && errno == EINTR);
1505
1506 /* If file is openned, we are good. */
1507 if (status >= 0)
1508 continue;
1509
1510 /* The only error we allow is that the file descriptor does not
1511 exist, in which case we dup /dev/null to it. */
1512 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001513 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001514 return_value = -1;
1515 continue;
1516 }
1517
1518 /* Try dupping /dev/null to this stdio file descriptor and
1519 repeat if there is a signal. Note that any errors in closing
1520 the stdio descriptor are lost. */
1521 do {
1522 status = dup2(dev_null, i);
1523 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001524
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001525 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001526 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001527 return_value = -1;
1528 continue;
1529 }
1530 }
1531
1532 /* If /dev/null is not one of the stdio file descriptors, close it. */
1533 if (dev_null > 2) {
1534 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001535 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001536 status = close(dev_null);
1537 } while (status < 0 && errno == EINTR);
1538
1539 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001540 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001541 return_value = -1;
1542 }
1543 }
1544
1545 return return_value;
1546}
1547
1548static int link_image(soinfo *si, unsigned wr_offset)
1549{
1550 unsigned *d;
1551 Elf32_Phdr *phdr = si->phdr;
1552 int phnum = si->phnum;
1553
1554 INFO("[ %5d linking %s ]\n", pid, si->name);
1555 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1556 si->base, si->flags);
1557
1558 if (si->flags & FLAG_EXE) {
1559 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1560 * linkage info if this is the executable. If this was a
1561 * dynamic lib, that would have been done at load time.
1562 *
1563 * TODO: It's unfortunate that small pieces of this are
1564 * repeated from the load_library routine. Refactor this just
1565 * slightly to reuse these bits.
1566 */
1567 si->size = 0;
1568 for(; phnum > 0; --phnum, ++phdr) {
1569#ifdef ANDROID_ARM_LINKER
1570 if(phdr->p_type == PT_ARM_EXIDX) {
1571 /* exidx entries (used for stack unwinding) are 8 bytes each.
1572 */
1573 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1574 si->ARM_exidx_count = phdr->p_memsz / 8;
1575 }
1576#endif
1577 if (phdr->p_type == PT_LOAD) {
1578 /* For the executable, we use the si->size field only in
1579 dl_unwind_find_exidx(), so the meaning of si->size
1580 is not the size of the executable; it is the last
1581 virtual address of the loadable part of the executable;
1582 since si->base == 0 for an executable, we use the
1583 range [0, si->size) to determine whether a PC value
1584 falls within the executable section. Of course, if
1585 a value is below phdr->p_vaddr, it's not in the
1586 executable section, but a) we shouldn't be asking for
1587 such a value anyway, and b) if we have to provide
1588 an EXIDX for such a value, then the executable's
1589 EXIDX is probably the better choice.
1590 */
1591 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1592 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1593 si->size = phdr->p_vaddr + phdr->p_memsz;
1594 /* try to remember what range of addresses should be write
1595 * protected */
1596 if (!(phdr->p_flags & PF_W)) {
1597 unsigned _end;
1598
1599 if (phdr->p_vaddr < si->wrprotect_start)
1600 si->wrprotect_start = phdr->p_vaddr;
1601 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1602 (~PAGE_MASK)));
1603 if (_end > si->wrprotect_end)
1604 si->wrprotect_end = _end;
1605 }
1606 } else if (phdr->p_type == PT_DYNAMIC) {
1607 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001608 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001609 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001610 pid, si->name, si->base + phdr->p_vaddr,
1611 (unsigned)si->dynamic);
1612 goto fail;
1613 }
1614 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1615 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1616 }
1617 }
1618 }
1619
1620 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001621 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001622 goto fail;
1623 }
1624
1625 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1626
1627 /* extract useful information from dynamic section */
1628 for(d = si->dynamic; *d; d++){
1629 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1630 switch(*d++){
1631 case DT_HASH:
1632 si->nbucket = ((unsigned *) (si->base + *d))[0];
1633 si->nchain = ((unsigned *) (si->base + *d))[1];
1634 si->bucket = (unsigned *) (si->base + *d + 8);
1635 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1636 break;
1637 case DT_STRTAB:
1638 si->strtab = (const char *) (si->base + *d);
1639 break;
1640 case DT_SYMTAB:
1641 si->symtab = (Elf32_Sym *) (si->base + *d);
1642 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001643#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001644 case DT_PLTREL:
1645 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001646 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001647 goto fail;
1648 }
1649 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001650#endif
1651#ifdef ANDROID_SH_LINKER
1652 case DT_JMPREL:
1653 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1654 break;
1655 case DT_PLTRELSZ:
1656 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1657 break;
1658#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001659 case DT_JMPREL:
1660 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1661 break;
1662 case DT_PLTRELSZ:
1663 si->plt_rel_count = *d / 8;
1664 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001665#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001666 case DT_REL:
1667 si->rel = (Elf32_Rel*) (si->base + *d);
1668 break;
1669 case DT_RELSZ:
1670 si->rel_count = *d / 8;
1671 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001672#ifdef ANDROID_SH_LINKER
1673 case DT_RELASZ:
1674 si->rela_count = *d / sizeof(Elf32_Rela);
1675 break;
1676#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001677 case DT_PLTGOT:
1678 /* Save this in case we decide to do lazy binding. We don't yet. */
1679 si->plt_got = (unsigned *)(si->base + *d);
1680 break;
1681 case DT_DEBUG:
1682 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1683 *d = (int) &_r_debug;
1684 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001685#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001686 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001687 si->rela = (Elf32_Rela *) (si->base + *d);
1688 break;
1689#else
1690 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001691 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001692 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001693#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001694 case DT_INIT:
1695 si->init_func = (void (*)(void))(si->base + *d);
1696 DEBUG("%5d %s constructors (init func) found at %p\n",
1697 pid, si->name, si->init_func);
1698 break;
1699 case DT_FINI:
1700 si->fini_func = (void (*)(void))(si->base + *d);
1701 DEBUG("%5d %s destructors (fini func) found at %p\n",
1702 pid, si->name, si->fini_func);
1703 break;
1704 case DT_INIT_ARRAY:
1705 si->init_array = (unsigned *)(si->base + *d);
1706 DEBUG("%5d %s constructors (init_array) found at %p\n",
1707 pid, si->name, si->init_array);
1708 break;
1709 case DT_INIT_ARRAYSZ:
1710 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1711 break;
1712 case DT_FINI_ARRAY:
1713 si->fini_array = (unsigned *)(si->base + *d);
1714 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1715 pid, si->name, si->fini_array);
1716 break;
1717 case DT_FINI_ARRAYSZ:
1718 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1719 break;
1720 case DT_PREINIT_ARRAY:
1721 si->preinit_array = (unsigned *)(si->base + *d);
1722 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1723 pid, si->name, si->preinit_array);
1724 break;
1725 case DT_PREINIT_ARRAYSZ:
1726 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1727 break;
1728 case DT_TEXTREL:
1729 /* TODO: make use of this. */
1730 /* this means that we might have to write into where the text
1731 * segment was loaded during relocation... Do something with
1732 * it.
1733 */
1734 DEBUG("%5d Text segment should be writable during relocation.\n",
1735 pid);
1736 break;
1737 }
1738 }
1739
1740 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1741 pid, si->base, si->strtab, si->symtab);
1742
1743 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001744 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001745 goto fail;
1746 }
1747
1748 for(d = si->dynamic; *d; d += 2) {
1749 if(d[0] == DT_NEEDED){
1750 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001751 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001752 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001753 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001754 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001755 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001756 goto fail;
1757 }
1758 lsi->refcount++;
1759 }
1760 }
1761
1762 if(si->plt_rel) {
1763 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1764 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1765 goto fail;
1766 }
1767 if(si->rel) {
1768 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1769 if(reloc_library(si, si->rel, si->rel_count))
1770 goto fail;
1771 }
1772
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001773#ifdef ANDROID_SH_LINKER
1774 if(si->plt_rela) {
1775 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1776 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1777 goto fail;
1778 }
1779 if(si->rela) {
1780 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1781 if(reloc_library_a(si, si->rela, si->rela_count))
1782 goto fail;
1783 }
1784#endif /* ANDROID_SH_LINKER */
1785
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001786 si->flags |= FLAG_LINKED;
1787 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1788
1789#if 0
1790 /* This is the way that the old dynamic linker did protection of
1791 * non-writable areas. It would scan section headers and find where
1792 * .text ended (rather where .data/.bss began) and assume that this is
1793 * the upper range of the non-writable area. This is too coarse,
1794 * and is kept here for reference until we fully move away from single
1795 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1796 * that made this possible.
1797 */
1798 if(wr_offset < 0xffffffff){
1799 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1800 }
1801#else
1802 /* TODO: Verify that this does the right thing in all cases, as it
1803 * presently probably does not. It is possible that an ELF image will
1804 * come with multiple read-only segments. What we ought to do is scan
1805 * the program headers again and mprotect all the read-only segments.
1806 * To prevent re-scanning the program header, we would have to build a
1807 * list of loadable segments in si, and then scan that instead. */
1808 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1809 mprotect((void *)si->wrprotect_start,
1810 si->wrprotect_end - si->wrprotect_start,
1811 PROT_READ | PROT_EXEC);
1812 }
1813#endif
1814
1815 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1816 stdout and stderr to close a security hole described in:
1817
1818 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1819
1820 */
1821 if (getuid() != geteuid() || getgid() != getegid())
1822 nullify_closed_stdio ();
1823 call_constructors(si);
1824 notify_gdb_of_load(si);
1825 return 0;
1826
1827fail:
1828 ERROR("failed to link %s\n", si->name);
1829 si->flags |= FLAG_ERROR;
1830 return -1;
1831}
1832
David Bartleybc3a5c22009-06-02 18:27:28 -07001833static void parse_library_path(char *path, char *delim)
1834{
1835 size_t len;
1836 char *ldpaths_bufp = ldpaths_buf;
1837 int i = 0;
1838
1839 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1840
1841 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1842 if (*ldpaths[i] != '\0')
1843 ++i;
1844 }
1845
1846 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1847 * last char isn't '\0' (i.e. not originally a delim). */
1848 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1849 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1850 ldpaths[i - 1] = NULL;
1851 } else {
1852 ldpaths[i] = NULL;
1853 }
1854}
1855
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001856int main(int argc, char **argv)
1857{
1858 return 0;
1859}
1860
1861#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1862
1863static void * __tls_area[ANDROID_TLS_SLOTS];
1864
1865unsigned __linker_init(unsigned **elfdata)
1866{
1867 static soinfo linker_soinfo;
1868
1869 int argc = (int) *elfdata;
1870 char **argv = (char**) (elfdata + 1);
1871 unsigned *vecs = (unsigned*) (argv + argc + 1);
1872 soinfo *si;
1873 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001874 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001875
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001876 /* Setup a temporary TLS area that is used to get a working
1877 * errno for system calls.
1878 */
1879 __set_tls(__tls_area);
1880
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001881 pid = getpid();
1882
1883#if TIMING
1884 struct timeval t0, t1;
1885 gettimeofday(&t0, 0);
1886#endif
1887
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001888 /* NOTE: we store the elfdata pointer on a special location
1889 * of the temporary TLS area in order to pass it to
1890 * the C Library's runtime initializer.
1891 *
1892 * The initializer must clear the slot and reset the TLS
1893 * to point to a different location to ensure that no other
1894 * shared library constructor can access it.
1895 */
1896 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001897
1898 debugger_init();
1899
1900 /* skip past the environment */
1901 while(vecs[0] != 0) {
1902 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1903 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001904 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1905 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001906 }
1907 vecs++;
1908 }
1909 vecs++;
1910
1911 INFO("[ android linker & debugger ]\n");
1912 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1913
1914 si = alloc_info(argv[0]);
1915 if(si == 0) {
1916 exit(-1);
1917 }
1918
1919 /* bootstrap the link map, the main exe always needs to be first */
1920 si->flags |= FLAG_EXE;
1921 map = &(si->linkmap);
1922
1923 map->l_addr = 0;
1924 map->l_name = argv[0];
1925 map->l_prev = NULL;
1926 map->l_next = NULL;
1927
1928 _r_debug.r_map = map;
1929 r_debug_tail = map;
1930
1931 /* gdb expects the linker to be in the debug shared object list,
1932 * and we need to make sure that the reported load address is zero.
1933 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1934 * is. Don't use alloc_info(), because the linker shouldn't
1935 * be on the soinfo list.
1936 */
1937 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1938 linker_soinfo.flags = 0;
1939 linker_soinfo.base = 0; // This is the important part; must be zero.
1940 insert_soinfo_into_debug_map(&linker_soinfo);
1941
1942 /* extract information passed from the kernel */
1943 while(vecs[0] != 0){
1944 switch(vecs[0]){
1945 case AT_PHDR:
1946 si->phdr = (Elf32_Phdr*) vecs[1];
1947 break;
1948 case AT_PHNUM:
1949 si->phnum = (int) vecs[1];
1950 break;
1951 case AT_ENTRY:
1952 si->entry = vecs[1];
1953 break;
1954 }
1955 vecs += 2;
1956 }
1957
1958 ba_init();
1959
1960 si->base = 0;
1961 si->dynamic = (unsigned *)-1;
1962 si->wrprotect_start = 0xffffffff;
1963 si->wrprotect_end = 0;
1964
David Bartleybc3a5c22009-06-02 18:27:28 -07001965 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1966 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1967 parse_library_path(ldpath_env, ":");
1968
Dima Zavin2e855792009-05-20 18:28:09 -07001969 if(link_image(si, 0)) {
1970 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1971 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1972 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001973 exit(-1);
1974 }
1975
1976#if TIMING
1977 gettimeofday(&t1,NULL);
1978 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1979 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1980 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1981 ));
1982#endif
1983#if STATS
1984 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1985 linker_stats.reloc[RELOC_ABSOLUTE],
1986 linker_stats.reloc[RELOC_RELATIVE],
1987 linker_stats.reloc[RELOC_COPY],
1988 linker_stats.reloc[RELOC_SYMBOL]);
1989#endif
1990#if COUNT_PAGES
1991 {
1992 unsigned n;
1993 unsigned i;
1994 unsigned count = 0;
1995 for(n = 0; n < 4096; n++){
1996 if(bitmask[n]){
1997 unsigned x = bitmask[n];
1998 for(i = 0; i < 8; i++){
1999 if(x & 1) count++;
2000 x >>= 1;
2001 }
2002 }
2003 }
2004 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2005 }
2006#endif
2007
2008#if TIMING || STATS || COUNT_PAGES
2009 fflush(stdout);
2010#endif
2011
2012 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2013 si->entry);
2014 return si->entry;
2015}