blob: 27fe9d772abec93e881b92935769b5e22d348939 [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}
348#elif defined(ANDROID_X86_LINKER)
349/* 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
David 'Digit' Turner82156792009-05-18 14:37:41 +02001297
1298/* Please read the "Initialization and Termination functions" functions.
1299 * of the linker design note in bionic/linker/README.TXT to understand
1300 * what the following code is doing.
1301 *
1302 * The important things to remember are:
1303 *
1304 * DT_PREINIT_ARRAY must be called first for executables, and should
1305 * not appear in shared libraries.
1306 *
1307 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1308 *
1309 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1310 *
1311 * DT_FINI_ARRAY must be parsed in reverse order.
1312 */
1313
1314static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001315{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001316 int n, inc = 1;
1317
1318 if (reverse) {
1319 ctor += (count-1);
1320 inc = -1;
1321 }
1322
1323 for(n = count; n > 0; n--) {
1324 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1325 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001326 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001327 void (*func)() = (void (*)()) *ctor;
1328 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001329 if(((int) func == 0) || ((int) func == -1)) continue;
1330 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1331 func();
1332 }
1333}
1334
1335static void call_constructors(soinfo *si)
1336{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001337 if (si->flags & FLAG_EXE) {
1338 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1339 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1340 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001341 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001342 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1343 } else {
1344 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001345 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001346 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001347 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001348 }
1349 }
1350
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001351 if (si->init_func) {
1352 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1353 (unsigned)si->init_func, si->name);
1354 si->init_func();
1355 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1356 }
1357
1358 if (si->init_array) {
1359 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1360 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001361 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001362 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1363 }
1364}
1365
David 'Digit' Turner82156792009-05-18 14:37:41 +02001366
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001367static void call_destructors(soinfo *si)
1368{
1369 if (si->fini_array) {
1370 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1371 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001372 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001373 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1374 }
1375
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001376 if (si->fini_func) {
1377 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1378 (unsigned)si->fini_func, si->name);
1379 si->fini_func();
1380 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1381 }
1382}
1383
1384/* Force any of the closed stdin, stdout and stderr to be associated with
1385 /dev/null. */
1386static int nullify_closed_stdio (void)
1387{
1388 int dev_null, i, status;
1389 int return_value = 0;
1390
1391 dev_null = open("/dev/null", O_RDWR);
1392 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001393 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001394 return -1;
1395 }
1396 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1397
1398 /* If any of the stdio file descriptors is valid and not associated
1399 with /dev/null, dup /dev/null to it. */
1400 for (i = 0; i < 3; i++) {
1401 /* If it is /dev/null already, we are done. */
1402 if (i == dev_null)
1403 continue;
1404
1405 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1406 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1407 can be interrupted but we do this just to be safe. */
1408 do {
1409 status = fcntl(i, F_GETFL);
1410 } while (status < 0 && errno == EINTR);
1411
1412 /* If file is openned, we are good. */
1413 if (status >= 0)
1414 continue;
1415
1416 /* The only error we allow is that the file descriptor does not
1417 exist, in which case we dup /dev/null to it. */
1418 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001419 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001420 return_value = -1;
1421 continue;
1422 }
1423
1424 /* Try dupping /dev/null to this stdio file descriptor and
1425 repeat if there is a signal. Note that any errors in closing
1426 the stdio descriptor are lost. */
1427 do {
1428 status = dup2(dev_null, i);
1429 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001430
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001431 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001432 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001433 return_value = -1;
1434 continue;
1435 }
1436 }
1437
1438 /* If /dev/null is not one of the stdio file descriptors, close it. */
1439 if (dev_null > 2) {
1440 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001441 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001442 status = close(dev_null);
1443 } while (status < 0 && errno == EINTR);
1444
1445 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001446 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001447 return_value = -1;
1448 }
1449 }
1450
1451 return return_value;
1452}
1453
1454static int link_image(soinfo *si, unsigned wr_offset)
1455{
1456 unsigned *d;
1457 Elf32_Phdr *phdr = si->phdr;
1458 int phnum = si->phnum;
1459
1460 INFO("[ %5d linking %s ]\n", pid, si->name);
1461 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1462 si->base, si->flags);
1463
1464 if (si->flags & FLAG_EXE) {
1465 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1466 * linkage info if this is the executable. If this was a
1467 * dynamic lib, that would have been done at load time.
1468 *
1469 * TODO: It's unfortunate that small pieces of this are
1470 * repeated from the load_library routine. Refactor this just
1471 * slightly to reuse these bits.
1472 */
1473 si->size = 0;
1474 for(; phnum > 0; --phnum, ++phdr) {
1475#ifdef ANDROID_ARM_LINKER
1476 if(phdr->p_type == PT_ARM_EXIDX) {
1477 /* exidx entries (used for stack unwinding) are 8 bytes each.
1478 */
1479 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1480 si->ARM_exidx_count = phdr->p_memsz / 8;
1481 }
1482#endif
1483 if (phdr->p_type == PT_LOAD) {
1484 /* For the executable, we use the si->size field only in
1485 dl_unwind_find_exidx(), so the meaning of si->size
1486 is not the size of the executable; it is the last
1487 virtual address of the loadable part of the executable;
1488 since si->base == 0 for an executable, we use the
1489 range [0, si->size) to determine whether a PC value
1490 falls within the executable section. Of course, if
1491 a value is below phdr->p_vaddr, it's not in the
1492 executable section, but a) we shouldn't be asking for
1493 such a value anyway, and b) if we have to provide
1494 an EXIDX for such a value, then the executable's
1495 EXIDX is probably the better choice.
1496 */
1497 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1498 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1499 si->size = phdr->p_vaddr + phdr->p_memsz;
1500 /* try to remember what range of addresses should be write
1501 * protected */
1502 if (!(phdr->p_flags & PF_W)) {
1503 unsigned _end;
1504
1505 if (phdr->p_vaddr < si->wrprotect_start)
1506 si->wrprotect_start = phdr->p_vaddr;
1507 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1508 (~PAGE_MASK)));
1509 if (_end > si->wrprotect_end)
1510 si->wrprotect_end = _end;
1511 }
1512 } else if (phdr->p_type == PT_DYNAMIC) {
1513 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001514 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001515 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001516 pid, si->name, si->base + phdr->p_vaddr,
1517 (unsigned)si->dynamic);
1518 goto fail;
1519 }
1520 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1521 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1522 }
1523 }
1524 }
1525
1526 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001527 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001528 goto fail;
1529 }
1530
1531 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1532
1533 /* extract useful information from dynamic section */
1534 for(d = si->dynamic; *d; d++){
1535 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1536 switch(*d++){
1537 case DT_HASH:
1538 si->nbucket = ((unsigned *) (si->base + *d))[0];
1539 si->nchain = ((unsigned *) (si->base + *d))[1];
1540 si->bucket = (unsigned *) (si->base + *d + 8);
1541 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1542 break;
1543 case DT_STRTAB:
1544 si->strtab = (const char *) (si->base + *d);
1545 break;
1546 case DT_SYMTAB:
1547 si->symtab = (Elf32_Sym *) (si->base + *d);
1548 break;
1549 case DT_PLTREL:
1550 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001551 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001552 goto fail;
1553 }
1554 break;
1555 case DT_JMPREL:
1556 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1557 break;
1558 case DT_PLTRELSZ:
1559 si->plt_rel_count = *d / 8;
1560 break;
1561 case DT_REL:
1562 si->rel = (Elf32_Rel*) (si->base + *d);
1563 break;
1564 case DT_RELSZ:
1565 si->rel_count = *d / 8;
1566 break;
1567 case DT_PLTGOT:
1568 /* Save this in case we decide to do lazy binding. We don't yet. */
1569 si->plt_got = (unsigned *)(si->base + *d);
1570 break;
1571 case DT_DEBUG:
1572 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1573 *d = (int) &_r_debug;
1574 break;
1575 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001576 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001577 goto fail;
1578 case DT_INIT:
1579 si->init_func = (void (*)(void))(si->base + *d);
1580 DEBUG("%5d %s constructors (init func) found at %p\n",
1581 pid, si->name, si->init_func);
1582 break;
1583 case DT_FINI:
1584 si->fini_func = (void (*)(void))(si->base + *d);
1585 DEBUG("%5d %s destructors (fini func) found at %p\n",
1586 pid, si->name, si->fini_func);
1587 break;
1588 case DT_INIT_ARRAY:
1589 si->init_array = (unsigned *)(si->base + *d);
1590 DEBUG("%5d %s constructors (init_array) found at %p\n",
1591 pid, si->name, si->init_array);
1592 break;
1593 case DT_INIT_ARRAYSZ:
1594 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1595 break;
1596 case DT_FINI_ARRAY:
1597 si->fini_array = (unsigned *)(si->base + *d);
1598 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1599 pid, si->name, si->fini_array);
1600 break;
1601 case DT_FINI_ARRAYSZ:
1602 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1603 break;
1604 case DT_PREINIT_ARRAY:
1605 si->preinit_array = (unsigned *)(si->base + *d);
1606 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1607 pid, si->name, si->preinit_array);
1608 break;
1609 case DT_PREINIT_ARRAYSZ:
1610 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1611 break;
1612 case DT_TEXTREL:
1613 /* TODO: make use of this. */
1614 /* this means that we might have to write into where the text
1615 * segment was loaded during relocation... Do something with
1616 * it.
1617 */
1618 DEBUG("%5d Text segment should be writable during relocation.\n",
1619 pid);
1620 break;
1621 }
1622 }
1623
1624 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1625 pid, si->base, si->strtab, si->symtab);
1626
1627 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001628 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001629 goto fail;
1630 }
1631
1632 for(d = si->dynamic; *d; d += 2) {
1633 if(d[0] == DT_NEEDED){
1634 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001635 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001636 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001637 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001638 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001639 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001640 goto fail;
1641 }
1642 lsi->refcount++;
1643 }
1644 }
1645
1646 if(si->plt_rel) {
1647 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1648 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1649 goto fail;
1650 }
1651 if(si->rel) {
1652 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1653 if(reloc_library(si, si->rel, si->rel_count))
1654 goto fail;
1655 }
1656
1657 si->flags |= FLAG_LINKED;
1658 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1659
1660#if 0
1661 /* This is the way that the old dynamic linker did protection of
1662 * non-writable areas. It would scan section headers and find where
1663 * .text ended (rather where .data/.bss began) and assume that this is
1664 * the upper range of the non-writable area. This is too coarse,
1665 * and is kept here for reference until we fully move away from single
1666 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1667 * that made this possible.
1668 */
1669 if(wr_offset < 0xffffffff){
1670 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1671 }
1672#else
1673 /* TODO: Verify that this does the right thing in all cases, as it
1674 * presently probably does not. It is possible that an ELF image will
1675 * come with multiple read-only segments. What we ought to do is scan
1676 * the program headers again and mprotect all the read-only segments.
1677 * To prevent re-scanning the program header, we would have to build a
1678 * list of loadable segments in si, and then scan that instead. */
1679 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1680 mprotect((void *)si->wrprotect_start,
1681 si->wrprotect_end - si->wrprotect_start,
1682 PROT_READ | PROT_EXEC);
1683 }
1684#endif
1685
1686 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1687 stdout and stderr to close a security hole described in:
1688
1689 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1690
1691 */
1692 if (getuid() != geteuid() || getgid() != getegid())
1693 nullify_closed_stdio ();
1694 call_constructors(si);
1695 notify_gdb_of_load(si);
1696 return 0;
1697
1698fail:
1699 ERROR("failed to link %s\n", si->name);
1700 si->flags |= FLAG_ERROR;
1701 return -1;
1702}
1703
David Bartleybc3a5c22009-06-02 18:27:28 -07001704static void parse_library_path(char *path, char *delim)
1705{
1706 size_t len;
1707 char *ldpaths_bufp = ldpaths_buf;
1708 int i = 0;
1709
1710 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1711
1712 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1713 if (*ldpaths[i] != '\0')
1714 ++i;
1715 }
1716
1717 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1718 * last char isn't '\0' (i.e. not originally a delim). */
1719 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1720 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1721 ldpaths[i - 1] = NULL;
1722 } else {
1723 ldpaths[i] = NULL;
1724 }
1725}
1726
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001727int main(int argc, char **argv)
1728{
1729 return 0;
1730}
1731
1732#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1733
1734static void * __tls_area[ANDROID_TLS_SLOTS];
1735
1736unsigned __linker_init(unsigned **elfdata)
1737{
1738 static soinfo linker_soinfo;
1739
1740 int argc = (int) *elfdata;
1741 char **argv = (char**) (elfdata + 1);
1742 unsigned *vecs = (unsigned*) (argv + argc + 1);
1743 soinfo *si;
1744 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001745 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001746
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001747 /* Setup a temporary TLS area that is used to get a working
1748 * errno for system calls.
1749 */
1750 __set_tls(__tls_area);
1751
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001752 pid = getpid();
1753
1754#if TIMING
1755 struct timeval t0, t1;
1756 gettimeofday(&t0, 0);
1757#endif
1758
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001759 /* NOTE: we store the elfdata pointer on a special location
1760 * of the temporary TLS area in order to pass it to
1761 * the C Library's runtime initializer.
1762 *
1763 * The initializer must clear the slot and reset the TLS
1764 * to point to a different location to ensure that no other
1765 * shared library constructor can access it.
1766 */
1767 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001768
1769 debugger_init();
1770
1771 /* skip past the environment */
1772 while(vecs[0] != 0) {
1773 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1774 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001775 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1776 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001777 }
1778 vecs++;
1779 }
1780 vecs++;
1781
1782 INFO("[ android linker & debugger ]\n");
1783 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1784
1785 si = alloc_info(argv[0]);
1786 if(si == 0) {
1787 exit(-1);
1788 }
1789
1790 /* bootstrap the link map, the main exe always needs to be first */
1791 si->flags |= FLAG_EXE;
1792 map = &(si->linkmap);
1793
1794 map->l_addr = 0;
1795 map->l_name = argv[0];
1796 map->l_prev = NULL;
1797 map->l_next = NULL;
1798
1799 _r_debug.r_map = map;
1800 r_debug_tail = map;
1801
1802 /* gdb expects the linker to be in the debug shared object list,
1803 * and we need to make sure that the reported load address is zero.
1804 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1805 * is. Don't use alloc_info(), because the linker shouldn't
1806 * be on the soinfo list.
1807 */
1808 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1809 linker_soinfo.flags = 0;
1810 linker_soinfo.base = 0; // This is the important part; must be zero.
1811 insert_soinfo_into_debug_map(&linker_soinfo);
1812
1813 /* extract information passed from the kernel */
1814 while(vecs[0] != 0){
1815 switch(vecs[0]){
1816 case AT_PHDR:
1817 si->phdr = (Elf32_Phdr*) vecs[1];
1818 break;
1819 case AT_PHNUM:
1820 si->phnum = (int) vecs[1];
1821 break;
1822 case AT_ENTRY:
1823 si->entry = vecs[1];
1824 break;
1825 }
1826 vecs += 2;
1827 }
1828
1829 ba_init();
1830
1831 si->base = 0;
1832 si->dynamic = (unsigned *)-1;
1833 si->wrprotect_start = 0xffffffff;
1834 si->wrprotect_end = 0;
1835
David Bartleybc3a5c22009-06-02 18:27:28 -07001836 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1837 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1838 parse_library_path(ldpath_env, ":");
1839
Dima Zavin2e855792009-05-20 18:28:09 -07001840 if(link_image(si, 0)) {
1841 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1842 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1843 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001844 exit(-1);
1845 }
1846
1847#if TIMING
1848 gettimeofday(&t1,NULL);
1849 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1850 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1851 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1852 ));
1853#endif
1854#if STATS
1855 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1856 linker_stats.reloc[RELOC_ABSOLUTE],
1857 linker_stats.reloc[RELOC_RELATIVE],
1858 linker_stats.reloc[RELOC_COPY],
1859 linker_stats.reloc[RELOC_SYMBOL]);
1860#endif
1861#if COUNT_PAGES
1862 {
1863 unsigned n;
1864 unsigned i;
1865 unsigned count = 0;
1866 for(n = 0; n < 4096; n++){
1867 if(bitmask[n]){
1868 unsigned x = bitmask[n];
1869 for(i = 0; i < 8; i++){
1870 if(x & 1) count++;
1871 x >>= 1;
1872 }
1873 }
1874 }
1875 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1876 }
1877#endif
1878
1879#if TIMING || STATS || COUNT_PAGES
1880 fflush(stdout);
1881#endif
1882
1883 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1884 si->entry);
1885 return si->entry;
1886}