blob: 9e28b13a0d4630f1ce18ddc3e40319a5ba13c226 [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
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070054#define ALLOW_SYMBOLS_FROM_MAIN 1
James Dongba52b302009-04-30 20:37:36 -070055#define SO_MAX 96
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056
David Bartleybc3a5c22009-06-02 18:27:28 -070057/* Assume average path length of 64 and max 8 paths */
58#define LDPATH_BUFSIZE 512
59#define LDPATH_MAX 8
60
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080061/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
62 *
63 * Do NOT use malloc() and friends or pthread_*() code here.
64 * Don't use printf() either; it's caused mysterious memory
65 * corruption in the past.
66 * The linker runs before we bring up libc and it's easiest
67 * to make sure it does not depend on any complex libc features
68 *
69 * open issues / todo:
70 *
71 * - should we do anything special for STB_WEAK symbols?
72 * - are we doing everything we should for ARM_COPY relocations?
73 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080074 * - after linking, set as much stuff as possible to READONLY
75 * and NOEXEC
76 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
77 * headers provide versions that are negative...
78 * - allocate space for soinfo structs dynamically instead of
79 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080*/
81
82
83static int link_image(soinfo *si, unsigned wr_offset);
84
85static int socount = 0;
86static soinfo sopool[SO_MAX];
87static soinfo *freelist = NULL;
88static soinfo *solist = &libdl_info;
89static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070090#if ALLOW_SYMBOLS_FROM_MAIN
91static soinfo *somain; /* main process, always the one after libdl_info */
92#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080093
Iliyan Malchev6ed80c82009-09-28 19:38:04 -070094static inline int validate_soinfo(soinfo *si)
95{
96 return (si >= sopool && si < sopool + SO_MAX) ||
97 si == &libdl_info;
98}
99
David Bartleybc3a5c22009-06-02 18:27:28 -0700100static char ldpaths_buf[LDPATH_BUFSIZE];
101static const char *ldpaths[LDPATH_MAX + 1];
102
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103int debug_verbosity;
104static int pid;
105
106#if STATS
107struct _link_stats linker_stats;
108#endif
109
110#if COUNT_PAGES
111unsigned bitmask[4096];
112#endif
113
114#ifndef PT_ARM_EXIDX
115#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
116#endif
117
Dima Zavin2e855792009-05-20 18:28:09 -0700118#define HOODLUM(name, ret, ...) \
119 ret name __VA_ARGS__ \
120 { \
121 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
122 write(2, errstr, sizeof(errstr)); \
123 abort(); \
124 }
125HOODLUM(malloc, void *, (size_t size));
126HOODLUM(free, void, (void *ptr));
127HOODLUM(realloc, void *, (void *ptr, size_t size));
128HOODLUM(calloc, void *, (size_t cnt, size_t size));
129
Dima Zavin03531952009-05-29 17:30:25 -0700130static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700131static char __linker_dl_err_buf[768];
132#define DL_ERR(fmt, x...) \
133 do { \
134 snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
135 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700136 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700137 } while(0)
138
139const char *linker_get_error(void)
140{
141 return (const char *)&__linker_dl_err_buf[0];
142}
143
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800144/*
145 * This function is an empty stub where GDB locates a breakpoint to get notified
146 * about linker activity.
147 */
148extern void __attribute__((noinline)) rtld_db_dlactivity(void);
149
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800150static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
151 RT_CONSISTENT, 0};
152static struct link_map *r_debug_tail = 0;
153
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700154static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800155
156static void insert_soinfo_into_debug_map(soinfo * info)
157{
158 struct link_map * map;
159
160 /* Copy the necessary fields into the debug structure.
161 */
162 map = &(info->linkmap);
163 map->l_addr = info->base;
164 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800165 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166
167 /* Stick the new library at the end of the list.
168 * gdb tends to care more about libc than it does
169 * about leaf libraries, and ordering it this way
170 * reduces the back-and-forth over the wire.
171 */
172 if (r_debug_tail) {
173 r_debug_tail->l_next = map;
174 map->l_prev = r_debug_tail;
175 map->l_next = 0;
176 } else {
177 _r_debug.r_map = map;
178 map->l_prev = 0;
179 map->l_next = 0;
180 }
181 r_debug_tail = map;
182}
183
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700184static void remove_soinfo_from_debug_map(soinfo * info)
185{
186 struct link_map * map = &(info->linkmap);
187
188 if (r_debug_tail == map)
189 r_debug_tail = map->l_prev;
190
191 if (map->l_prev) map->l_prev->l_next = map->l_next;
192 if (map->l_next) map->l_next->l_prev = map->l_prev;
193}
194
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800195void notify_gdb_of_load(soinfo * info)
196{
197 if (info->flags & FLAG_EXE) {
198 // GDB already knows about the main executable
199 return;
200 }
201
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700202 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800203
204 _r_debug.r_state = RT_ADD;
205 rtld_db_dlactivity();
206
207 insert_soinfo_into_debug_map(info);
208
209 _r_debug.r_state = RT_CONSISTENT;
210 rtld_db_dlactivity();
211
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700212 pthread_mutex_unlock(&_r_debug_lock);
213}
214
215void notify_gdb_of_unload(soinfo * info)
216{
217 if (info->flags & FLAG_EXE) {
218 // GDB already knows about the main executable
219 return;
220 }
221
222 pthread_mutex_lock(&_r_debug_lock);
223
224 _r_debug.r_state = RT_DELETE;
225 rtld_db_dlactivity();
226
227 remove_soinfo_from_debug_map(info);
228
229 _r_debug.r_state = RT_CONSISTENT;
230 rtld_db_dlactivity();
231
232 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233}
234
235void notify_gdb_of_libraries()
236{
237 _r_debug.r_state = RT_ADD;
238 rtld_db_dlactivity();
239 _r_debug.r_state = RT_CONSISTENT;
240 rtld_db_dlactivity();
241}
242
243static soinfo *alloc_info(const char *name)
244{
245 soinfo *si;
246
247 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700248 DL_ERR("%5d library name %s too long", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800249 return 0;
250 }
251
252 /* The freelist is populated when we call free_info(), which in turn is
253 done only by dlclose(), which is not likely to be used.
254 */
255 if (!freelist) {
256 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700257 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800258 return NULL;
259 }
260 freelist = sopool + socount++;
261 freelist->next = NULL;
262 }
263
264 si = freelist;
265 freelist = freelist->next;
266
267 /* Make sure we get a clean block of soinfo */
268 memset(si, 0, sizeof(soinfo));
269 strcpy((char*) si->name, name);
270 sonext->next = si;
271 si->ba_index = -1; /* by default, prelinked */
272 si->next = NULL;
273 si->refcount = 0;
274 sonext = si;
275
276 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
277 return si;
278}
279
280static void free_info(soinfo *si)
281{
282 soinfo *prev = NULL, *trav;
283
284 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
285
286 for(trav = solist; trav != NULL; trav = trav->next){
287 if (trav == si)
288 break;
289 prev = trav;
290 }
291 if (trav == NULL) {
292 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700293 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800294 return;
295 }
296
297 /* prev will never be NULL, because the first entry in solist is
298 always the static libdl_info.
299 */
300 prev->next = si->next;
301 if (si == sonext) sonext = prev;
302 si->next = freelist;
303 freelist = si;
304}
305
306#ifndef LINKER_TEXT_BASE
307#error "linker's makefile must define LINKER_TEXT_BASE"
308#endif
309#ifndef LINKER_AREA_SIZE
310#error "linker's makefile must define LINKER_AREA_SIZE"
311#endif
312#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
313#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
314
315const char *addr_to_name(unsigned addr)
316{
317 soinfo *si;
318
319 for(si = solist; si != 0; si = si->next){
320 if((addr >= si->base) && (addr < (si->base + si->size))) {
321 return si->name;
322 }
323 }
324
325 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
326 return "linker";
327 }
328
329 return "";
330}
331
332/* For a given PC, find the .so that it belongs to.
333 * Returns the base address of the .ARM.exidx section
334 * for that .so, and the number of 8-byte entries
335 * in that section (via *pcount).
336 *
337 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
338 *
339 * This function is exposed via dlfcn.c and libdl.so.
340 */
341#ifdef ANDROID_ARM_LINKER
342_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
343{
344 soinfo *si;
345 unsigned addr = (unsigned)pc;
346
347 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
348 for (si = solist; si != 0; si = si->next){
349 if ((addr >= si->base) && (addr < (si->base + si->size))) {
350 *pcount = si->ARM_exidx_count;
351 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
352 }
353 }
354 }
355 *pcount = 0;
356 return NULL;
357}
358#elif defined(ANDROID_X86_LINKER)
359/* Here, we only have to provide a callback to iterate across all the
360 * loaded libraries. gcc_eh does the rest. */
361int
362dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
363 void *data)
364{
365 soinfo *si;
366 struct dl_phdr_info dl_info;
367 int rv = 0;
368
369 for (si = solist; si != NULL; si = si->next) {
370 dl_info.dlpi_addr = si->linkmap.l_addr;
371 dl_info.dlpi_name = si->linkmap.l_name;
372 dl_info.dlpi_phdr = si->phdr;
373 dl_info.dlpi_phnum = si->phnum;
374 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
375 if (rv != 0)
376 break;
377 }
378 return rv;
379}
380#endif
381
382static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
383{
384 Elf32_Sym *s;
385 Elf32_Sym *symtab = si->symtab;
386 const char *strtab = si->strtab;
387 unsigned n;
388
389 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
390 name, si->name, si->base, hash, hash % si->nbucket);
391 n = hash % si->nbucket;
392
393 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
394 s = symtab + n;
395 if(strcmp(strtab + s->st_name, name)) continue;
396
397 /* only concern ourselves with global symbols */
398 switch(ELF32_ST_BIND(s->st_info)){
399 case STB_GLOBAL:
400 /* no section == undefined */
401 if(s->st_shndx == 0) continue;
402
403 case STB_WEAK:
404 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
405 name, si->name, s->st_value, s->st_size);
406 return s;
407 }
408 }
409
410 return 0;
411}
412
413static unsigned elfhash(const char *_name)
414{
415 const unsigned char *name = (const unsigned char *) _name;
416 unsigned h = 0, g;
417
418 while(*name) {
419 h = (h << 4) + *name++;
420 g = h & 0xf0000000;
421 h ^= g;
422 h ^= g >> 24;
423 }
424 return h;
425}
426
427static Elf32_Sym *
428_do_lookup_in_so(soinfo *si, const char *name, unsigned *elf_hash)
429{
430 if (*elf_hash == 0)
431 *elf_hash = elfhash(name);
432 return _elf_lookup (si, *elf_hash, name);
433}
434
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700435static Elf32_Sym *
436_do_lookup(soinfo *si, const char *name, unsigned *base)
437{
438 unsigned elf_hash = 0;
439 Elf32_Sym *s;
440 unsigned *d;
441 soinfo *lsi = si;
442
443 /* Look for symbols in the local scope first (the object who is
444 * searching). This happens with C++ templates on i386 for some
445 * reason. */
446 s = _do_lookup_in_so(si, name, &elf_hash);
447 if(s != NULL)
448 goto done;
449
450 for(d = si->dynamic; *d; d += 2) {
451 if(d[0] == DT_NEEDED){
452 lsi = (soinfo *)d[1];
453 if (!validate_soinfo(lsi)) {
454 DL_ERR("%5d bad DT_NEEDED pointer in %s",
455 pid, si->name);
456 return 0;
457 }
458
459 DEBUG("%5d %s: looking up %s in %s\n",
460 pid, si->name, name, lsi->name);
461 s = _do_lookup_in_so(lsi, name, &elf_hash);
462 if(s != NULL)
463 goto done;
464 }
465 }
466
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700467#if ALLOW_SYMBOLS_FROM_MAIN
468 /* If we are resolving relocations while dlopen()ing a library, it's OK for
469 * the library to resolve a symbol that's defined in the executable itself,
470 * although this is rare and is generally a bad idea.
471 */
472 if (somain) {
473 lsi = somain;
474 DEBUG("%5d %s: looking up %s in executable %s\n",
475 pid, si->name, name, lsi->name);
476 s = _do_lookup_in_so(lsi, name, &elf_hash);
477 }
478#endif
479
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700480done:
481 if(s != NULL) {
482 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
483 "found in %s, base = 0x%08x\n",
484 pid, si->name, name, s->st_value, lsi->name, lsi->base);
485 *base = lsi->base;
486 return s;
487 }
488
489 return 0;
490}
491
492/* This is used by dl_sym(). It performs symbol lookup only within the
493 specified soinfo object and not in any of its dependencies.
494 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800495Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
496{
497 unsigned unused = 0;
498 return _do_lookup_in_so(si, name, &unused);
499}
500
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700501/* This is used by dl_sym(). It performs a global symbol lookup.
502 */
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700503Elf32_Sym *lookup(const char *name, soinfo **found)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800504{
505 unsigned elf_hash = 0;
506 Elf32_Sym *s = NULL;
507 soinfo *si;
508
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800509 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
510 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700511 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800512 continue;
513 s = _do_lookup_in_so(si, name, &elf_hash);
514 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700515 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800516 break;
517 }
518 }
519
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700520 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800521 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
522 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
523 return s;
524 }
525
526 return 0;
527}
528
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800529#if 0
530static void dump(soinfo *si)
531{
532 Elf32_Sym *s = si->symtab;
533 unsigned n;
534
535 for(n = 0; n < si->nchain; n++) {
536 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
537 s->st_info, s->st_shndx, s->st_value, s->st_size,
538 si->strtab + s->st_name);
539 s++;
540 }
541}
542#endif
543
544static const char *sopaths[] = {
545 "/system/lib",
546 "/lib",
547 0
548};
549
550static int _open_lib(const char *name)
551{
552 int fd;
553 struct stat filestat;
554
555 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
556 if ((fd = open(name, O_RDONLY)) >= 0)
557 return fd;
558 }
559
560 return -1;
561}
562
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800563static int open_library(const char *name)
564{
565 int fd;
566 char buf[512];
567 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700568 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800569
570 TRACE("[ %5d opening %s ]\n", pid, name);
571
572 if(name == 0) return -1;
573 if(strlen(name) > 256) return -1;
574
575 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
576 return fd;
577
David Bartleybc3a5c22009-06-02 18:27:28 -0700578 for (path = ldpaths; *path; path++) {
579 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
580 if (n < 0 || n >= (int)sizeof(buf)) {
581 WARN("Ignoring very long library path: %s/%s\n", *path, name);
582 continue;
583 }
584 if ((fd = _open_lib(buf)) >= 0)
585 return fd;
586 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800587 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700588 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
589 if (n < 0 || n >= (int)sizeof(buf)) {
590 WARN("Ignoring very long library path: %s/%s\n", *path, name);
591 continue;
592 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800593 if ((fd = _open_lib(buf)) >= 0)
594 return fd;
595 }
596
597 return -1;
598}
599
600/* temporary space for holding the first page of the shared lib
601 * which contains the elf header (with the pht). */
602static unsigned char __header[PAGE_SIZE];
603
604typedef struct {
605 long mmap_addr;
606 char tag[4]; /* 'P', 'R', 'E', ' ' */
607} prelink_info_t;
608
609/* Returns the requested base address if the library is prelinked,
610 * and 0 otherwise. */
611static unsigned long
612is_prelinked(int fd, const char *name)
613{
614 off_t sz;
615 prelink_info_t info;
616
617 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
618 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700619 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800620 return 0;
621 }
622
623 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
624 WARN("Could not read prelink_info_t structure for `%s`\n", name);
625 return 0;
626 }
627
628 if (strncmp(info.tag, "PRE ", 4)) {
629 WARN("`%s` is not a prelinked library\n", name);
630 return 0;
631 }
632
633 return (unsigned long)info.mmap_addr;
634}
635
636/* verify_elf_object
637 * Verifies if the object @ base is a valid ELF object
638 *
639 * Args:
640 *
641 * Returns:
642 * 0 on success
643 * -1 if no valid ELF object is found @ base.
644 */
645static int
646verify_elf_object(void *base, const char *name)
647{
648 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
649
650 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
651 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
652 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
653 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
654
655 /* TODO: Should we verify anything else in the header? */
656
657 return 0;
658}
659
660
661/* get_lib_extents
662 * Retrieves the base (*base) address where the ELF object should be
663 * mapped and its overall memory size (*total_sz).
664 *
665 * Args:
666 * fd: Opened file descriptor for the library
667 * name: The name of the library
668 * _hdr: Pointer to the header page of the library
669 * total_sz: Total size of the memory that should be allocated for
670 * this library
671 *
672 * Returns:
673 * -1 if there was an error while trying to get the lib extents.
674 * The possible reasons are:
675 * - Could not determine if the library was prelinked.
676 * - The library provided is not a valid ELF object
677 * 0 if the library did not request a specific base offset (normal
678 * for non-prelinked libs)
679 * > 0 if the library requests a specific address to be mapped to.
680 * This indicates a pre-linked library.
681 */
682static unsigned
683get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
684{
685 unsigned req_base;
686 unsigned min_vaddr = 0xffffffff;
687 unsigned max_vaddr = 0;
688 unsigned char *_hdr = (unsigned char *)__hdr;
689 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
690 Elf32_Phdr *phdr;
691 int cnt;
692
693 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
694 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700695 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800696 return (unsigned)-1;
697 }
698
699 req_base = (unsigned) is_prelinked(fd, name);
700 if (req_base == (unsigned)-1)
701 return -1;
702 else if (req_base != 0) {
703 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
704 pid, name, req_base);
705 } else {
706 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
707 }
708
709 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
710
711 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
712 * get the range. */
713 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
714 if (phdr->p_type == PT_LOAD) {
715 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
716 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
717 if (phdr->p_vaddr < min_vaddr)
718 min_vaddr = phdr->p_vaddr;
719 }
720 }
721
722 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700723 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800724 return (unsigned)-1;
725 }
726
727 /* truncate min_vaddr down to page boundary */
728 min_vaddr &= ~PAGE_MASK;
729
730 /* round max_vaddr up to the next page */
731 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
732
733 *total_sz = (max_vaddr - min_vaddr);
734 return (unsigned)req_base;
735}
736
737/* alloc_mem_region
738 *
739 * This function reserves a chunk of memory to be used for mapping in
740 * the shared library. We reserve the entire memory region here, and
741 * then the rest of the linker will relocate the individual loadable
742 * segments into the correct locations within this memory range.
743 *
744 * Args:
745 * si->base: The requested base of the allocation. If 0, a sane one will be
746 * chosen in the range LIBBASE <= base < LIBLAST.
747 * si->size: The size of the allocation.
748 *
749 * Returns:
750 * -1 on failure, and 0 on success. On success, si->base will contain
751 * the virtual address at which the library will be mapped.
752 */
753
754static int reserve_mem_region(soinfo *si)
755{
756 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
757 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
758 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700759 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700760 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800761 pid, (si->base ? "" : "non-"), si->name, si->base,
762 errno, strerror(errno));
763 return -1;
764 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700765 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700766 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800767 si->name, (unsigned)base, si->base);
768 munmap(base, si->size);
769 return -1;
770 }
771 return 0;
772}
773
774static int
775alloc_mem_region(soinfo *si)
776{
777 if (si->base) {
778 /* Attempt to mmap a prelinked library. */
779 si->ba_index = -1;
780 return reserve_mem_region(si);
781 }
782
783 /* This is not a prelinked library, so we attempt to allocate space
784 for it from the buddy allocator, which manages the area between
785 LIBBASE and LIBLAST.
786 */
787 si->ba_index = ba_allocate(si->size);
788 if(si->ba_index >= 0) {
789 si->base = ba_start_addr(si->ba_index);
790 PRINT("%5d mapping library '%s' at %08x (index %d) " \
791 "through buddy allocator.\n",
792 pid, si->name, si->base, si->ba_index);
793 if (reserve_mem_region(si) < 0) {
794 ba_free(si->ba_index);
795 si->ba_index = -1;
796 si->base = 0;
797 goto err;
798 }
799 return 0;
800 }
801
802err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700803 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800804 pid, si->name);
805 return -1;
806}
807
808#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
809#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
810 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
811 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
812/* load_segments
813 *
814 * This function loads all the loadable (PT_LOAD) segments into memory
815 * at their appropriate memory offsets off the base address.
816 *
817 * Args:
818 * fd: Open file descriptor to the library to load.
819 * header: Pointer to a header page that contains the ELF header.
820 * This is needed since we haven't mapped in the real file yet.
821 * si: ptr to soinfo struct describing the shared object.
822 *
823 * Returns:
824 * 0 on success, -1 on failure.
825 */
826static int
827load_segments(int fd, void *header, soinfo *si)
828{
829 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
830 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
831 unsigned char *base = (unsigned char *)si->base;
832 int cnt;
833 unsigned len;
834 unsigned char *tmp;
835 unsigned char *pbase;
836 unsigned char *extra_base;
837 unsigned extra_len;
838 unsigned total_sz = 0;
839
840 si->wrprotect_start = 0xffffffff;
841 si->wrprotect_end = 0;
842
843 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
844 pid, si->name, (unsigned)si->base);
845 /* Now go through all the PT_LOAD segments and map them into memory
846 * at the appropriate locations. */
847 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
848 if (phdr->p_type == PT_LOAD) {
849 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
850 /* we want to map in the segment on a page boundary */
851 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
852 /* add the # of bytes we masked off above to the total length. */
853 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
854
855 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
856 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
857 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
858 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
859 MAP_PRIVATE | MAP_FIXED, fd,
860 phdr->p_offset & (~PAGE_MASK));
861 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700862 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700863 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800864 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
865 goto fail;
866 }
867
868 /* If 'len' didn't end on page boundary, and it's a writable
869 * segment, zero-fill the rest. */
870 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
871 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
872
873 /* Check to see if we need to extend the map for this segment to
874 * cover the diff between filesz and memsz (i.e. for bss).
875 *
876 * base _+---------------------+ page boundary
877 * . .
878 * | |
879 * . .
880 * pbase _+---------------------+ page boundary
881 * | |
882 * . .
883 * base + p_vaddr _| |
884 * . \ \ .
885 * . | filesz | .
886 * pbase + len _| / | |
887 * <0 pad> . . .
888 * extra_base _+------------|--------+ page boundary
889 * / . . .
890 * | . . .
891 * | +------------|--------+ page boundary
892 * extra_len-> | | | |
893 * | . | memsz .
894 * | . | .
895 * \ _| / |
896 * . .
897 * | |
898 * _+---------------------+ page boundary
899 */
900 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
901 (~PAGE_MASK));
902 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
903 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
904 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
905 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
906 /* map in the extra page(s) as anonymous into the range.
907 * This is probably not necessary as we already mapped in
908 * the entire region previously, but we just want to be
909 * sure. This will also set the right flags on the region
910 * (though we can probably accomplish the same thing with
911 * mprotect).
912 */
913 extra_base = mmap((void *)tmp, extra_len,
914 PFLAGS_TO_PROT(phdr->p_flags),
915 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
916 -1, 0);
917 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700918 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700919 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800920 extra_len);
921 goto fail;
922 }
923 /* TODO: Check if we need to memset-0 this region.
924 * Anonymous mappings are zero-filled copy-on-writes, so we
925 * shouldn't need to. */
926 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
927 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
928 extra_len);
929 }
930 /* set the len here to show the full extent of the segment we
931 * just loaded, mostly for debugging */
932 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
933 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
934 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
935 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
936 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
937 total_sz += len;
938 /* Make the section writable just in case we'll have to write to
939 * it during relocation (i.e. text segment). However, we will
940 * remember what range of addresses should be write protected.
941 *
942 */
943 if (!(phdr->p_flags & PF_W)) {
944 if ((unsigned)pbase < si->wrprotect_start)
945 si->wrprotect_start = (unsigned)pbase;
946 if (((unsigned)pbase + len) > si->wrprotect_end)
947 si->wrprotect_end = (unsigned)pbase + len;
948 mprotect(pbase, len,
949 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
950 }
951 } else if (phdr->p_type == PT_DYNAMIC) {
952 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
953 /* this segment contains the dynamic linking information */
954 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
955 } else {
956#ifdef ANDROID_ARM_LINKER
957 if (phdr->p_type == PT_ARM_EXIDX) {
958 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
959 /* exidx entries (used for stack unwinding) are 8 bytes each.
960 */
961 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
962 si->ARM_exidx_count = phdr->p_memsz / 8;
963 }
964#endif
965 }
966
967 }
968
969 /* Sanity check */
970 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700971 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700972 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800973 pid, total_sz, si->name, si->size);
974 goto fail;
975 }
976
977 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
978 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
979 (unsigned)si->base, si->size);
980 return 0;
981
982fail:
983 /* We can just blindly unmap the entire region even though some things
984 * were mapped in originally with anonymous and others could have been
985 * been mapped in from the file before we failed. The kernel will unmap
986 * all the pages in the range, irrespective of how they got there.
987 */
988 munmap((void *)si->base, si->size);
989 si->flags |= FLAG_ERROR;
990 return -1;
991}
992
993/* TODO: Implement this to take care of the fact that Android ARM
994 * ELF objects shove everything into a single loadable segment that has the
995 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
996 * non-writable.
997 */
998#if 0
999static unsigned
1000get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1001{
1002 Elf32_Shdr *shdr_start;
1003 Elf32_Shdr *shdr;
1004 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1005 int cnt;
1006 unsigned wr_offset = 0xffffffff;
1007
1008 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1009 ehdr->e_shoff & (~PAGE_MASK));
1010 if (shdr_start == MAP_FAILED) {
1011 WARN("%5d - Could not read section header info from '%s'. Will not "
1012 "not be able to determine write-protect offset.\n", pid, name);
1013 return (unsigned)-1;
1014 }
1015
1016 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1017 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1018 (shdr->sh_addr < wr_offset)) {
1019 wr_offset = shdr->sh_addr;
1020 }
1021 }
1022
1023 munmap(shdr_start, shdr_sz);
1024 return wr_offset;
1025}
1026#endif
1027
1028static soinfo *
1029load_library(const char *name)
1030{
1031 int fd = open_library(name);
1032 int cnt;
1033 unsigned ext_sz;
1034 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001035 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001036 soinfo *si = NULL;
1037 Elf32_Ehdr *hdr;
1038
Dima Zavin2e855792009-05-20 18:28:09 -07001039 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001040 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001041 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001042 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001043
1044 /* We have to read the ELF header to figure out what to do with this image
1045 */
1046 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001047 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001048 goto fail;
1049 }
1050
1051 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001052 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001053 goto fail;
1054 }
1055
1056 /* Parse the ELF header and get the size of the memory footprint for
1057 * the library */
1058 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1059 if (req_base == (unsigned)-1)
1060 goto fail;
1061 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1062 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1063
1064 /* Now configure the soinfo struct where we'll store all of our data
1065 * for the ELF object. If the loading fails, we waste the entry, but
1066 * same thing would happen if we failed during linking. Configuring the
1067 * soinfo struct here is a lot more convenient.
1068 */
Erik Gillingfde86422009-07-28 20:28:19 -07001069 bname = strrchr(name, '/');
1070 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001071 if (si == NULL)
1072 goto fail;
1073
1074 /* Carve out a chunk of memory where we will map in the individual
1075 * segments */
1076 si->base = req_base;
1077 si->size = ext_sz;
1078 si->flags = 0;
1079 si->entry = 0;
1080 si->dynamic = (unsigned *)-1;
1081 if (alloc_mem_region(si) < 0)
1082 goto fail;
1083
1084 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1085 pid, name, (void *)si->base, (unsigned) ext_sz);
1086
1087 /* Now actually load the library's segments into right places in memory */
1088 if (load_segments(fd, &__header[0], si) < 0) {
1089 if (si->ba_index >= 0) {
1090 ba_free(si->ba_index);
1091 si->ba_index = -1;
1092 }
1093 goto fail;
1094 }
1095
1096 /* this might not be right. Technically, we don't even need this info
1097 * once we go through 'load_segments'. */
1098 hdr = (Elf32_Ehdr *)si->base;
1099 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1100 si->phnum = hdr->e_phnum;
1101 /**/
1102
1103 close(fd);
1104 return si;
1105
1106fail:
1107 if (si) free_info(si);
1108 close(fd);
1109 return NULL;
1110}
1111
1112static soinfo *
1113init_library(soinfo *si)
1114{
1115 unsigned wr_offset = 0xffffffff;
1116
1117 /* At this point we know that whatever is loaded @ base is a valid ELF
1118 * shared library whose segments are properly mapped in. */
1119 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1120 pid, si->base, si->size, si->name);
1121
1122 if (si->base < LIBBASE || si->base >= LIBLAST)
1123 si->flags |= FLAG_PRELINKED;
1124
1125 if(link_image(si, wr_offset)) {
1126 /* We failed to link. However, we can only restore libbase
1127 ** if no additional libraries have moved it since we updated it.
1128 */
1129 munmap((void *)si->base, si->size);
1130 return NULL;
1131 }
1132
1133 return si;
1134}
1135
1136soinfo *find_library(const char *name)
1137{
1138 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001139 const char *bname = strrchr(name, '/');
1140 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001141
1142 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001143 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001144 if(si->flags & FLAG_ERROR) {
1145 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1146 return NULL;
1147 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001148 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001149 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001150 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001151 }
1152 }
1153
1154 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1155 si = load_library(name);
1156 if(si == NULL)
1157 return NULL;
1158 return init_library(si);
1159}
1160
1161/* TODO:
1162 * notify gdb of unload
1163 * for non-prelinked libraries, find a way to decrement libbase
1164 */
1165static void call_destructors(soinfo *si);
1166unsigned unload_library(soinfo *si)
1167{
1168 unsigned *d;
1169 if (si->refcount == 1) {
1170 TRACE("%5d unloading '%s'\n", pid, si->name);
1171 call_destructors(si);
1172
1173 for(d = si->dynamic; *d; d += 2) {
1174 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001175 soinfo *lsi = (soinfo *)d[1];
1176 d[1] = 0;
1177 if (validate_soinfo(lsi)) {
1178 TRACE("%5d %s needs to unload %s\n", pid,
1179 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001180 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001181 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001182 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001183 DL_ERR("%5d %s: could not unload dependent library",
1184 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001185 }
1186 }
1187
1188 munmap((char *)si->base, si->size);
1189 if (si->ba_index >= 0) {
1190 PRINT("%5d releasing library '%s' address space at %08x "\
1191 "through buddy allocator.\n",
1192 pid, si->name, si->base);
1193 ba_free(si->ba_index);
1194 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001195 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001196 free_info(si);
1197 si->refcount = 0;
1198 }
1199 else {
1200 si->refcount--;
1201 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1202 pid, si->name, si->refcount);
1203 }
1204 return si->refcount;
1205}
1206
1207/* TODO: don't use unsigned for addrs below. It works, but is not
1208 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1209 * long.
1210 */
1211static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1212{
1213 Elf32_Sym *symtab = si->symtab;
1214 const char *strtab = si->strtab;
1215 Elf32_Sym *s;
1216 unsigned base;
1217 Elf32_Rel *start = rel;
1218 unsigned idx;
1219
1220 for (idx = 0; idx < count; ++idx) {
1221 unsigned type = ELF32_R_TYPE(rel->r_info);
1222 unsigned sym = ELF32_R_SYM(rel->r_info);
1223 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1224 unsigned sym_addr = 0;
1225 char *sym_name = NULL;
1226
1227 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1228 si->name, idx);
1229 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001230 sym_name = (char *)(strtab + symtab[sym].st_name);
1231 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001232 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001233 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001234 return -1;
1235 }
1236#if 0
1237 if((base == 0) && (si->base != 0)){
1238 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001239 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 pid, strtab + symtab[sym].st_name);
1241 return -1;
1242 }
1243#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001244 // st_shndx==SHN_UNDEF means an undefined symbol.
1245 // st_value should be 0 then, except that the low bit of st_value is
1246 // used to indicate whether the symbol points to an ARM or thumb function,
1247 // and should be ignored in the following check.
1248 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1249 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1250 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001251 s->st_value);
1252 return -1;
1253 }
1254 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001255 COUNT_RELOC(RELOC_SYMBOL);
1256 } else {
1257 s = 0;
1258 }
1259
1260/* TODO: This is ugly. Split up the relocations by arch into
1261 * different files.
1262 */
1263 switch(type){
1264#if defined(ANDROID_ARM_LINKER)
1265 case R_ARM_JUMP_SLOT:
1266 COUNT_RELOC(RELOC_ABSOLUTE);
1267 MARK(rel->r_offset);
1268 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1269 reloc, sym_addr, sym_name);
1270 *((unsigned*)reloc) = sym_addr;
1271 break;
1272 case R_ARM_GLOB_DAT:
1273 COUNT_RELOC(RELOC_ABSOLUTE);
1274 MARK(rel->r_offset);
1275 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1276 reloc, sym_addr, sym_name);
1277 *((unsigned*)reloc) = sym_addr;
1278 break;
1279 case R_ARM_ABS32:
1280 COUNT_RELOC(RELOC_ABSOLUTE);
1281 MARK(rel->r_offset);
1282 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1283 reloc, sym_addr, sym_name);
1284 *((unsigned*)reloc) += sym_addr;
1285 break;
1286#elif defined(ANDROID_X86_LINKER)
1287 case R_386_JUMP_SLOT:
1288 COUNT_RELOC(RELOC_ABSOLUTE);
1289 MARK(rel->r_offset);
1290 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1291 reloc, sym_addr, sym_name);
1292 *((unsigned*)reloc) = sym_addr;
1293 break;
1294 case R_386_GLOB_DAT:
1295 COUNT_RELOC(RELOC_ABSOLUTE);
1296 MARK(rel->r_offset);
1297 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1298 reloc, sym_addr, sym_name);
1299 *((unsigned*)reloc) = sym_addr;
1300 break;
1301#endif /* ANDROID_*_LINKER */
1302
1303#if defined(ANDROID_ARM_LINKER)
1304 case R_ARM_RELATIVE:
1305#elif defined(ANDROID_X86_LINKER)
1306 case R_386_RELATIVE:
1307#endif /* ANDROID_*_LINKER */
1308 COUNT_RELOC(RELOC_RELATIVE);
1309 MARK(rel->r_offset);
1310 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001311 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001312 return -1;
1313 }
1314 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1315 reloc, si->base);
1316 *((unsigned*)reloc) += si->base;
1317 break;
1318
1319#if defined(ANDROID_X86_LINKER)
1320 case R_386_32:
1321 COUNT_RELOC(RELOC_RELATIVE);
1322 MARK(rel->r_offset);
1323
1324 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1325 reloc, sym_addr, sym_name);
1326 *((unsigned *)reloc) += (unsigned)sym_addr;
1327 break;
1328
1329 case R_386_PC32:
1330 COUNT_RELOC(RELOC_RELATIVE);
1331 MARK(rel->r_offset);
1332 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1333 "+%08x (%08x - %08x) %s\n", pid, reloc,
1334 (sym_addr - reloc), sym_addr, reloc, sym_name);
1335 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1336 break;
1337#endif /* ANDROID_X86_LINKER */
1338
1339#ifdef ANDROID_ARM_LINKER
1340 case R_ARM_COPY:
1341 COUNT_RELOC(RELOC_COPY);
1342 MARK(rel->r_offset);
1343 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1344 reloc, s->st_size, sym_addr, sym_name);
1345 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1346 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001347 case R_ARM_NONE:
1348 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001349#endif /* ANDROID_ARM_LINKER */
1350
1351 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001352 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001353 pid, type, rel, (int) (rel - start));
1354 return -1;
1355 }
1356 rel++;
1357 }
1358 return 0;
1359}
1360
David 'Digit' Turner82156792009-05-18 14:37:41 +02001361
1362/* Please read the "Initialization and Termination functions" functions.
1363 * of the linker design note in bionic/linker/README.TXT to understand
1364 * what the following code is doing.
1365 *
1366 * The important things to remember are:
1367 *
1368 * DT_PREINIT_ARRAY must be called first for executables, and should
1369 * not appear in shared libraries.
1370 *
1371 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1372 *
1373 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1374 *
1375 * DT_FINI_ARRAY must be parsed in reverse order.
1376 */
1377
1378static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001379{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001380 int n, inc = 1;
1381
1382 if (reverse) {
1383 ctor += (count-1);
1384 inc = -1;
1385 }
1386
1387 for(n = count; n > 0; n--) {
1388 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1389 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001390 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001391 void (*func)() = (void (*)()) *ctor;
1392 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001393 if(((int) func == 0) || ((int) func == -1)) continue;
1394 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1395 func();
1396 }
1397}
1398
1399static void call_constructors(soinfo *si)
1400{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001401 if (si->flags & FLAG_EXE) {
1402 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1403 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1404 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001405 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1407 } else {
1408 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001409 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001410 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001411 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001412 }
1413 }
1414
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001415 if (si->init_func) {
1416 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1417 (unsigned)si->init_func, si->name);
1418 si->init_func();
1419 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1420 }
1421
1422 if (si->init_array) {
1423 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1424 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001425 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001426 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1427 }
1428}
1429
David 'Digit' Turner82156792009-05-18 14:37:41 +02001430
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001431static void call_destructors(soinfo *si)
1432{
1433 if (si->fini_array) {
1434 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1435 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001436 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001437 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1438 }
1439
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001440 if (si->fini_func) {
1441 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1442 (unsigned)si->fini_func, si->name);
1443 si->fini_func();
1444 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1445 }
1446}
1447
1448/* Force any of the closed stdin, stdout and stderr to be associated with
1449 /dev/null. */
1450static int nullify_closed_stdio (void)
1451{
1452 int dev_null, i, status;
1453 int return_value = 0;
1454
1455 dev_null = open("/dev/null", O_RDWR);
1456 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001457 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001458 return -1;
1459 }
1460 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1461
1462 /* If any of the stdio file descriptors is valid and not associated
1463 with /dev/null, dup /dev/null to it. */
1464 for (i = 0; i < 3; i++) {
1465 /* If it is /dev/null already, we are done. */
1466 if (i == dev_null)
1467 continue;
1468
1469 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1470 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1471 can be interrupted but we do this just to be safe. */
1472 do {
1473 status = fcntl(i, F_GETFL);
1474 } while (status < 0 && errno == EINTR);
1475
1476 /* If file is openned, we are good. */
1477 if (status >= 0)
1478 continue;
1479
1480 /* The only error we allow is that the file descriptor does not
1481 exist, in which case we dup /dev/null to it. */
1482 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001483 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001484 return_value = -1;
1485 continue;
1486 }
1487
1488 /* Try dupping /dev/null to this stdio file descriptor and
1489 repeat if there is a signal. Note that any errors in closing
1490 the stdio descriptor are lost. */
1491 do {
1492 status = dup2(dev_null, i);
1493 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001494
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001495 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001496 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001497 return_value = -1;
1498 continue;
1499 }
1500 }
1501
1502 /* If /dev/null is not one of the stdio file descriptors, close it. */
1503 if (dev_null > 2) {
1504 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001505 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001506 status = close(dev_null);
1507 } while (status < 0 && errno == EINTR);
1508
1509 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001510 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511 return_value = -1;
1512 }
1513 }
1514
1515 return return_value;
1516}
1517
1518static int link_image(soinfo *si, unsigned wr_offset)
1519{
1520 unsigned *d;
1521 Elf32_Phdr *phdr = si->phdr;
1522 int phnum = si->phnum;
1523
1524 INFO("[ %5d linking %s ]\n", pid, si->name);
1525 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1526 si->base, si->flags);
1527
1528 if (si->flags & FLAG_EXE) {
1529 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1530 * linkage info if this is the executable. If this was a
1531 * dynamic lib, that would have been done at load time.
1532 *
1533 * TODO: It's unfortunate that small pieces of this are
1534 * repeated from the load_library routine. Refactor this just
1535 * slightly to reuse these bits.
1536 */
1537 si->size = 0;
1538 for(; phnum > 0; --phnum, ++phdr) {
1539#ifdef ANDROID_ARM_LINKER
1540 if(phdr->p_type == PT_ARM_EXIDX) {
1541 /* exidx entries (used for stack unwinding) are 8 bytes each.
1542 */
1543 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1544 si->ARM_exidx_count = phdr->p_memsz / 8;
1545 }
1546#endif
1547 if (phdr->p_type == PT_LOAD) {
1548 /* For the executable, we use the si->size field only in
1549 dl_unwind_find_exidx(), so the meaning of si->size
1550 is not the size of the executable; it is the last
1551 virtual address of the loadable part of the executable;
1552 since si->base == 0 for an executable, we use the
1553 range [0, si->size) to determine whether a PC value
1554 falls within the executable section. Of course, if
1555 a value is below phdr->p_vaddr, it's not in the
1556 executable section, but a) we shouldn't be asking for
1557 such a value anyway, and b) if we have to provide
1558 an EXIDX for such a value, then the executable's
1559 EXIDX is probably the better choice.
1560 */
1561 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1562 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1563 si->size = phdr->p_vaddr + phdr->p_memsz;
1564 /* try to remember what range of addresses should be write
1565 * protected */
1566 if (!(phdr->p_flags & PF_W)) {
1567 unsigned _end;
1568
1569 if (phdr->p_vaddr < si->wrprotect_start)
1570 si->wrprotect_start = phdr->p_vaddr;
1571 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1572 (~PAGE_MASK)));
1573 if (_end > si->wrprotect_end)
1574 si->wrprotect_end = _end;
1575 }
1576 } else if (phdr->p_type == PT_DYNAMIC) {
1577 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001578 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001579 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001580 pid, si->name, si->base + phdr->p_vaddr,
1581 (unsigned)si->dynamic);
1582 goto fail;
1583 }
1584 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1585 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1586 }
1587 }
1588 }
1589
1590 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001591 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001592 goto fail;
1593 }
1594
1595 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1596
1597 /* extract useful information from dynamic section */
1598 for(d = si->dynamic; *d; d++){
1599 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1600 switch(*d++){
1601 case DT_HASH:
1602 si->nbucket = ((unsigned *) (si->base + *d))[0];
1603 si->nchain = ((unsigned *) (si->base + *d))[1];
1604 si->bucket = (unsigned *) (si->base + *d + 8);
1605 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1606 break;
1607 case DT_STRTAB:
1608 si->strtab = (const char *) (si->base + *d);
1609 break;
1610 case DT_SYMTAB:
1611 si->symtab = (Elf32_Sym *) (si->base + *d);
1612 break;
1613 case DT_PLTREL:
1614 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001615 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616 goto fail;
1617 }
1618 break;
1619 case DT_JMPREL:
1620 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1621 break;
1622 case DT_PLTRELSZ:
1623 si->plt_rel_count = *d / 8;
1624 break;
1625 case DT_REL:
1626 si->rel = (Elf32_Rel*) (si->base + *d);
1627 break;
1628 case DT_RELSZ:
1629 si->rel_count = *d / 8;
1630 break;
1631 case DT_PLTGOT:
1632 /* Save this in case we decide to do lazy binding. We don't yet. */
1633 si->plt_got = (unsigned *)(si->base + *d);
1634 break;
1635 case DT_DEBUG:
1636 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1637 *d = (int) &_r_debug;
1638 break;
1639 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001640 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001641 goto fail;
1642 case DT_INIT:
1643 si->init_func = (void (*)(void))(si->base + *d);
1644 DEBUG("%5d %s constructors (init func) found at %p\n",
1645 pid, si->name, si->init_func);
1646 break;
1647 case DT_FINI:
1648 si->fini_func = (void (*)(void))(si->base + *d);
1649 DEBUG("%5d %s destructors (fini func) found at %p\n",
1650 pid, si->name, si->fini_func);
1651 break;
1652 case DT_INIT_ARRAY:
1653 si->init_array = (unsigned *)(si->base + *d);
1654 DEBUG("%5d %s constructors (init_array) found at %p\n",
1655 pid, si->name, si->init_array);
1656 break;
1657 case DT_INIT_ARRAYSZ:
1658 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1659 break;
1660 case DT_FINI_ARRAY:
1661 si->fini_array = (unsigned *)(si->base + *d);
1662 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1663 pid, si->name, si->fini_array);
1664 break;
1665 case DT_FINI_ARRAYSZ:
1666 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1667 break;
1668 case DT_PREINIT_ARRAY:
1669 si->preinit_array = (unsigned *)(si->base + *d);
1670 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1671 pid, si->name, si->preinit_array);
1672 break;
1673 case DT_PREINIT_ARRAYSZ:
1674 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1675 break;
1676 case DT_TEXTREL:
1677 /* TODO: make use of this. */
1678 /* this means that we might have to write into where the text
1679 * segment was loaded during relocation... Do something with
1680 * it.
1681 */
1682 DEBUG("%5d Text segment should be writable during relocation.\n",
1683 pid);
1684 break;
1685 }
1686 }
1687
1688 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1689 pid, si->base, si->strtab, si->symtab);
1690
1691 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001692 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001693 goto fail;
1694 }
1695
1696 for(d = si->dynamic; *d; d += 2) {
1697 if(d[0] == DT_NEEDED){
1698 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001699 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001700 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001701 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001702 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001703 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001704 goto fail;
1705 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001706 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1707 of the DT_NEEDED entry itself, so that we can retrieve the
1708 soinfo directly later from the dynamic segment. This is a hack,
1709 but it allows us to map from DT_NEEDED to soinfo efficiently
1710 later on when we resolve relocations, trying to look up a symgol
1711 with dlsym().
1712 */
1713 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001714 lsi->refcount++;
1715 }
1716 }
1717
1718 if(si->plt_rel) {
1719 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1720 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1721 goto fail;
1722 }
1723 if(si->rel) {
1724 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1725 if(reloc_library(si, si->rel, si->rel_count))
1726 goto fail;
1727 }
1728
1729 si->flags |= FLAG_LINKED;
1730 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1731
1732#if 0
1733 /* This is the way that the old dynamic linker did protection of
1734 * non-writable areas. It would scan section headers and find where
1735 * .text ended (rather where .data/.bss began) and assume that this is
1736 * the upper range of the non-writable area. This is too coarse,
1737 * and is kept here for reference until we fully move away from single
1738 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1739 * that made this possible.
1740 */
1741 if(wr_offset < 0xffffffff){
1742 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1743 }
1744#else
1745 /* TODO: Verify that this does the right thing in all cases, as it
1746 * presently probably does not. It is possible that an ELF image will
1747 * come with multiple read-only segments. What we ought to do is scan
1748 * the program headers again and mprotect all the read-only segments.
1749 * To prevent re-scanning the program header, we would have to build a
1750 * list of loadable segments in si, and then scan that instead. */
1751 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1752 mprotect((void *)si->wrprotect_start,
1753 si->wrprotect_end - si->wrprotect_start,
1754 PROT_READ | PROT_EXEC);
1755 }
1756#endif
1757
1758 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1759 stdout and stderr to close a security hole described in:
1760
1761 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1762
1763 */
1764 if (getuid() != geteuid() || getgid() != getegid())
1765 nullify_closed_stdio ();
1766 call_constructors(si);
1767 notify_gdb_of_load(si);
1768 return 0;
1769
1770fail:
1771 ERROR("failed to link %s\n", si->name);
1772 si->flags |= FLAG_ERROR;
1773 return -1;
1774}
1775
David Bartleybc3a5c22009-06-02 18:27:28 -07001776static void parse_library_path(char *path, char *delim)
1777{
1778 size_t len;
1779 char *ldpaths_bufp = ldpaths_buf;
1780 int i = 0;
1781
1782 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1783
1784 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1785 if (*ldpaths[i] != '\0')
1786 ++i;
1787 }
1788
1789 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1790 * last char isn't '\0' (i.e. not originally a delim). */
1791 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1792 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1793 ldpaths[i - 1] = NULL;
1794 } else {
1795 ldpaths[i] = NULL;
1796 }
1797}
1798
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001799int main(int argc, char **argv)
1800{
1801 return 0;
1802}
1803
1804#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1805
1806static void * __tls_area[ANDROID_TLS_SLOTS];
1807
1808unsigned __linker_init(unsigned **elfdata)
1809{
1810 static soinfo linker_soinfo;
1811
1812 int argc = (int) *elfdata;
1813 char **argv = (char**) (elfdata + 1);
1814 unsigned *vecs = (unsigned*) (argv + argc + 1);
1815 soinfo *si;
1816 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001817 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001818
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001819 /* Setup a temporary TLS area that is used to get a working
1820 * errno for system calls.
1821 */
1822 __set_tls(__tls_area);
1823
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001824 pid = getpid();
1825
1826#if TIMING
1827 struct timeval t0, t1;
1828 gettimeofday(&t0, 0);
1829#endif
1830
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001831 /* NOTE: we store the elfdata pointer on a special location
1832 * of the temporary TLS area in order to pass it to
1833 * the C Library's runtime initializer.
1834 *
1835 * The initializer must clear the slot and reset the TLS
1836 * to point to a different location to ensure that no other
1837 * shared library constructor can access it.
1838 */
1839 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001840
1841 debugger_init();
1842
1843 /* skip past the environment */
1844 while(vecs[0] != 0) {
1845 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1846 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001847 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1848 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001849 }
1850 vecs++;
1851 }
1852 vecs++;
1853
1854 INFO("[ android linker & debugger ]\n");
1855 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1856
1857 si = alloc_info(argv[0]);
1858 if(si == 0) {
1859 exit(-1);
1860 }
1861
1862 /* bootstrap the link map, the main exe always needs to be first */
1863 si->flags |= FLAG_EXE;
1864 map = &(si->linkmap);
1865
1866 map->l_addr = 0;
1867 map->l_name = argv[0];
1868 map->l_prev = NULL;
1869 map->l_next = NULL;
1870
1871 _r_debug.r_map = map;
1872 r_debug_tail = map;
1873
1874 /* gdb expects the linker to be in the debug shared object list,
1875 * and we need to make sure that the reported load address is zero.
1876 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1877 * is. Don't use alloc_info(), because the linker shouldn't
1878 * be on the soinfo list.
1879 */
1880 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1881 linker_soinfo.flags = 0;
1882 linker_soinfo.base = 0; // This is the important part; must be zero.
1883 insert_soinfo_into_debug_map(&linker_soinfo);
1884
1885 /* extract information passed from the kernel */
1886 while(vecs[0] != 0){
1887 switch(vecs[0]){
1888 case AT_PHDR:
1889 si->phdr = (Elf32_Phdr*) vecs[1];
1890 break;
1891 case AT_PHNUM:
1892 si->phnum = (int) vecs[1];
1893 break;
1894 case AT_ENTRY:
1895 si->entry = vecs[1];
1896 break;
1897 }
1898 vecs += 2;
1899 }
1900
1901 ba_init();
1902
1903 si->base = 0;
1904 si->dynamic = (unsigned *)-1;
1905 si->wrprotect_start = 0xffffffff;
1906 si->wrprotect_end = 0;
1907
David Bartleybc3a5c22009-06-02 18:27:28 -07001908 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1909 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1910 parse_library_path(ldpath_env, ":");
1911
Dima Zavin2e855792009-05-20 18:28:09 -07001912 if(link_image(si, 0)) {
1913 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1914 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1915 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001916 exit(-1);
1917 }
1918
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001919#if ALLOW_SYMBOLS_FROM_MAIN
1920 /* Set somain after we've loaded all the libraries in order to prevent
1921 * linking of symbols back to the main image, which is not set up at that
1922 * point yet.
1923 */
1924 somain = si;
1925#endif
1926
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001927#if TIMING
1928 gettimeofday(&t1,NULL);
1929 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1930 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1931 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1932 ));
1933#endif
1934#if STATS
1935 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1936 linker_stats.reloc[RELOC_ABSOLUTE],
1937 linker_stats.reloc[RELOC_RELATIVE],
1938 linker_stats.reloc[RELOC_COPY],
1939 linker_stats.reloc[RELOC_SYMBOL]);
1940#endif
1941#if COUNT_PAGES
1942 {
1943 unsigned n;
1944 unsigned i;
1945 unsigned count = 0;
1946 for(n = 0; n < 4096; n++){
1947 if(bitmask[n]){
1948 unsigned x = bitmask[n];
1949 for(i = 0; i < 8; i++){
1950 if(x & 1) count++;
1951 x >>= 1;
1952 }
1953 }
1954 }
1955 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1956 }
1957#endif
1958
1959#if TIMING || STATS || COUNT_PAGES
1960 fflush(stdout);
1961#endif
1962
1963 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1964 si->entry);
1965 return si->entry;
1966}