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