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