blob: 26cd0a8a8b3ba095f2812ae08cb34bad368850c9 [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
1243 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
Dima Zavin2e855792009-05-20 18:28:09 -07001244 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001245 "handle this yet", pid, si->name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246 s->st_value);
1247 return -1;
1248 }
1249 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001250 COUNT_RELOC(RELOC_SYMBOL);
1251 } else {
1252 s = 0;
1253 }
1254
1255/* TODO: This is ugly. Split up the relocations by arch into
1256 * different files.
1257 */
1258 switch(type){
1259#if defined(ANDROID_ARM_LINKER)
1260 case R_ARM_JUMP_SLOT:
1261 COUNT_RELOC(RELOC_ABSOLUTE);
1262 MARK(rel->r_offset);
1263 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1264 reloc, sym_addr, sym_name);
1265 *((unsigned*)reloc) = sym_addr;
1266 break;
1267 case R_ARM_GLOB_DAT:
1268 COUNT_RELOC(RELOC_ABSOLUTE);
1269 MARK(rel->r_offset);
1270 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1271 reloc, sym_addr, sym_name);
1272 *((unsigned*)reloc) = sym_addr;
1273 break;
1274 case R_ARM_ABS32:
1275 COUNT_RELOC(RELOC_ABSOLUTE);
1276 MARK(rel->r_offset);
1277 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1278 reloc, sym_addr, sym_name);
1279 *((unsigned*)reloc) += sym_addr;
1280 break;
1281#elif defined(ANDROID_X86_LINKER)
1282 case R_386_JUMP_SLOT:
1283 COUNT_RELOC(RELOC_ABSOLUTE);
1284 MARK(rel->r_offset);
1285 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1286 reloc, sym_addr, sym_name);
1287 *((unsigned*)reloc) = sym_addr;
1288 break;
1289 case R_386_GLOB_DAT:
1290 COUNT_RELOC(RELOC_ABSOLUTE);
1291 MARK(rel->r_offset);
1292 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1293 reloc, sym_addr, sym_name);
1294 *((unsigned*)reloc) = sym_addr;
1295 break;
1296#endif /* ANDROID_*_LINKER */
1297
1298#if defined(ANDROID_ARM_LINKER)
1299 case R_ARM_RELATIVE:
1300#elif defined(ANDROID_X86_LINKER)
1301 case R_386_RELATIVE:
1302#endif /* ANDROID_*_LINKER */
1303 COUNT_RELOC(RELOC_RELATIVE);
1304 MARK(rel->r_offset);
1305 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001306 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001307 return -1;
1308 }
1309 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1310 reloc, si->base);
1311 *((unsigned*)reloc) += si->base;
1312 break;
1313
1314#if defined(ANDROID_X86_LINKER)
1315 case R_386_32:
1316 COUNT_RELOC(RELOC_RELATIVE);
1317 MARK(rel->r_offset);
1318
1319 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1320 reloc, sym_addr, sym_name);
1321 *((unsigned *)reloc) += (unsigned)sym_addr;
1322 break;
1323
1324 case R_386_PC32:
1325 COUNT_RELOC(RELOC_RELATIVE);
1326 MARK(rel->r_offset);
1327 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1328 "+%08x (%08x - %08x) %s\n", pid, reloc,
1329 (sym_addr - reloc), sym_addr, reloc, sym_name);
1330 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1331 break;
1332#endif /* ANDROID_X86_LINKER */
1333
1334#ifdef ANDROID_ARM_LINKER
1335 case R_ARM_COPY:
1336 COUNT_RELOC(RELOC_COPY);
1337 MARK(rel->r_offset);
1338 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1339 reloc, s->st_size, sym_addr, sym_name);
1340 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1341 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001342 case R_ARM_NONE:
1343 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001344#endif /* ANDROID_ARM_LINKER */
1345
1346 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001347 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001348 pid, type, rel, (int) (rel - start));
1349 return -1;
1350 }
1351 rel++;
1352 }
1353 return 0;
1354}
1355
David 'Digit' Turner82156792009-05-18 14:37:41 +02001356
1357/* Please read the "Initialization and Termination functions" functions.
1358 * of the linker design note in bionic/linker/README.TXT to understand
1359 * what the following code is doing.
1360 *
1361 * The important things to remember are:
1362 *
1363 * DT_PREINIT_ARRAY must be called first for executables, and should
1364 * not appear in shared libraries.
1365 *
1366 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1367 *
1368 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1369 *
1370 * DT_FINI_ARRAY must be parsed in reverse order.
1371 */
1372
1373static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001374{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001375 int n, inc = 1;
1376
1377 if (reverse) {
1378 ctor += (count-1);
1379 inc = -1;
1380 }
1381
1382 for(n = count; n > 0; n--) {
1383 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1384 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001385 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001386 void (*func)() = (void (*)()) *ctor;
1387 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001388 if(((int) func == 0) || ((int) func == -1)) continue;
1389 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1390 func();
1391 }
1392}
1393
1394static void call_constructors(soinfo *si)
1395{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001396 if (si->flags & FLAG_EXE) {
1397 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1398 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1399 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001400 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001401 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1402 } else {
1403 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001404 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001405 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001406 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001407 }
1408 }
1409
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001410 if (si->init_func) {
1411 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1412 (unsigned)si->init_func, si->name);
1413 si->init_func();
1414 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1415 }
1416
1417 if (si->init_array) {
1418 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1419 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001420 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001421 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1422 }
1423}
1424
David 'Digit' Turner82156792009-05-18 14:37:41 +02001425
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001426static void call_destructors(soinfo *si)
1427{
1428 if (si->fini_array) {
1429 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1430 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001431 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001432 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1433 }
1434
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001435 if (si->fini_func) {
1436 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1437 (unsigned)si->fini_func, si->name);
1438 si->fini_func();
1439 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1440 }
1441}
1442
1443/* Force any of the closed stdin, stdout and stderr to be associated with
1444 /dev/null. */
1445static int nullify_closed_stdio (void)
1446{
1447 int dev_null, i, status;
1448 int return_value = 0;
1449
1450 dev_null = open("/dev/null", O_RDWR);
1451 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001452 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001453 return -1;
1454 }
1455 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1456
1457 /* If any of the stdio file descriptors is valid and not associated
1458 with /dev/null, dup /dev/null to it. */
1459 for (i = 0; i < 3; i++) {
1460 /* If it is /dev/null already, we are done. */
1461 if (i == dev_null)
1462 continue;
1463
1464 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1465 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1466 can be interrupted but we do this just to be safe. */
1467 do {
1468 status = fcntl(i, F_GETFL);
1469 } while (status < 0 && errno == EINTR);
1470
1471 /* If file is openned, we are good. */
1472 if (status >= 0)
1473 continue;
1474
1475 /* The only error we allow is that the file descriptor does not
1476 exist, in which case we dup /dev/null to it. */
1477 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001478 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001479 return_value = -1;
1480 continue;
1481 }
1482
1483 /* Try dupping /dev/null to this stdio file descriptor and
1484 repeat if there is a signal. Note that any errors in closing
1485 the stdio descriptor are lost. */
1486 do {
1487 status = dup2(dev_null, i);
1488 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001489
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001490 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001491 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001492 return_value = -1;
1493 continue;
1494 }
1495 }
1496
1497 /* If /dev/null is not one of the stdio file descriptors, close it. */
1498 if (dev_null > 2) {
1499 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001500 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001501 status = close(dev_null);
1502 } while (status < 0 && errno == EINTR);
1503
1504 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001505 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001506 return_value = -1;
1507 }
1508 }
1509
1510 return return_value;
1511}
1512
1513static int link_image(soinfo *si, unsigned wr_offset)
1514{
1515 unsigned *d;
1516 Elf32_Phdr *phdr = si->phdr;
1517 int phnum = si->phnum;
1518
1519 INFO("[ %5d linking %s ]\n", pid, si->name);
1520 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1521 si->base, si->flags);
1522
1523 if (si->flags & FLAG_EXE) {
1524 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1525 * linkage info if this is the executable. If this was a
1526 * dynamic lib, that would have been done at load time.
1527 *
1528 * TODO: It's unfortunate that small pieces of this are
1529 * repeated from the load_library routine. Refactor this just
1530 * slightly to reuse these bits.
1531 */
1532 si->size = 0;
1533 for(; phnum > 0; --phnum, ++phdr) {
1534#ifdef ANDROID_ARM_LINKER
1535 if(phdr->p_type == PT_ARM_EXIDX) {
1536 /* exidx entries (used for stack unwinding) are 8 bytes each.
1537 */
1538 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1539 si->ARM_exidx_count = phdr->p_memsz / 8;
1540 }
1541#endif
1542 if (phdr->p_type == PT_LOAD) {
1543 /* For the executable, we use the si->size field only in
1544 dl_unwind_find_exidx(), so the meaning of si->size
1545 is not the size of the executable; it is the last
1546 virtual address of the loadable part of the executable;
1547 since si->base == 0 for an executable, we use the
1548 range [0, si->size) to determine whether a PC value
1549 falls within the executable section. Of course, if
1550 a value is below phdr->p_vaddr, it's not in the
1551 executable section, but a) we shouldn't be asking for
1552 such a value anyway, and b) if we have to provide
1553 an EXIDX for such a value, then the executable's
1554 EXIDX is probably the better choice.
1555 */
1556 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1557 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1558 si->size = phdr->p_vaddr + phdr->p_memsz;
1559 /* try to remember what range of addresses should be write
1560 * protected */
1561 if (!(phdr->p_flags & PF_W)) {
1562 unsigned _end;
1563
1564 if (phdr->p_vaddr < si->wrprotect_start)
1565 si->wrprotect_start = phdr->p_vaddr;
1566 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1567 (~PAGE_MASK)));
1568 if (_end > si->wrprotect_end)
1569 si->wrprotect_end = _end;
1570 }
1571 } else if (phdr->p_type == PT_DYNAMIC) {
1572 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001573 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001574 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001575 pid, si->name, si->base + phdr->p_vaddr,
1576 (unsigned)si->dynamic);
1577 goto fail;
1578 }
1579 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1580 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1581 }
1582 }
1583 }
1584
1585 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001586 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001587 goto fail;
1588 }
1589
1590 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1591
1592 /* extract useful information from dynamic section */
1593 for(d = si->dynamic; *d; d++){
1594 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1595 switch(*d++){
1596 case DT_HASH:
1597 si->nbucket = ((unsigned *) (si->base + *d))[0];
1598 si->nchain = ((unsigned *) (si->base + *d))[1];
1599 si->bucket = (unsigned *) (si->base + *d + 8);
1600 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1601 break;
1602 case DT_STRTAB:
1603 si->strtab = (const char *) (si->base + *d);
1604 break;
1605 case DT_SYMTAB:
1606 si->symtab = (Elf32_Sym *) (si->base + *d);
1607 break;
1608 case DT_PLTREL:
1609 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001610 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001611 goto fail;
1612 }
1613 break;
1614 case DT_JMPREL:
1615 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1616 break;
1617 case DT_PLTRELSZ:
1618 si->plt_rel_count = *d / 8;
1619 break;
1620 case DT_REL:
1621 si->rel = (Elf32_Rel*) (si->base + *d);
1622 break;
1623 case DT_RELSZ:
1624 si->rel_count = *d / 8;
1625 break;
1626 case DT_PLTGOT:
1627 /* Save this in case we decide to do lazy binding. We don't yet. */
1628 si->plt_got = (unsigned *)(si->base + *d);
1629 break;
1630 case DT_DEBUG:
1631 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1632 *d = (int) &_r_debug;
1633 break;
1634 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001635 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001636 goto fail;
1637 case DT_INIT:
1638 si->init_func = (void (*)(void))(si->base + *d);
1639 DEBUG("%5d %s constructors (init func) found at %p\n",
1640 pid, si->name, si->init_func);
1641 break;
1642 case DT_FINI:
1643 si->fini_func = (void (*)(void))(si->base + *d);
1644 DEBUG("%5d %s destructors (fini func) found at %p\n",
1645 pid, si->name, si->fini_func);
1646 break;
1647 case DT_INIT_ARRAY:
1648 si->init_array = (unsigned *)(si->base + *d);
1649 DEBUG("%5d %s constructors (init_array) found at %p\n",
1650 pid, si->name, si->init_array);
1651 break;
1652 case DT_INIT_ARRAYSZ:
1653 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1654 break;
1655 case DT_FINI_ARRAY:
1656 si->fini_array = (unsigned *)(si->base + *d);
1657 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1658 pid, si->name, si->fini_array);
1659 break;
1660 case DT_FINI_ARRAYSZ:
1661 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1662 break;
1663 case DT_PREINIT_ARRAY:
1664 si->preinit_array = (unsigned *)(si->base + *d);
1665 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1666 pid, si->name, si->preinit_array);
1667 break;
1668 case DT_PREINIT_ARRAYSZ:
1669 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1670 break;
1671 case DT_TEXTREL:
1672 /* TODO: make use of this. */
1673 /* this means that we might have to write into where the text
1674 * segment was loaded during relocation... Do something with
1675 * it.
1676 */
1677 DEBUG("%5d Text segment should be writable during relocation.\n",
1678 pid);
1679 break;
1680 }
1681 }
1682
1683 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1684 pid, si->base, si->strtab, si->symtab);
1685
1686 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001687 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001688 goto fail;
1689 }
1690
1691 for(d = si->dynamic; *d; d += 2) {
1692 if(d[0] == DT_NEEDED){
1693 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001694 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001695 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001696 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001697 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001698 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001699 goto fail;
1700 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001701 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1702 of the DT_NEEDED entry itself, so that we can retrieve the
1703 soinfo directly later from the dynamic segment. This is a hack,
1704 but it allows us to map from DT_NEEDED to soinfo efficiently
1705 later on when we resolve relocations, trying to look up a symgol
1706 with dlsym().
1707 */
1708 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001709 lsi->refcount++;
1710 }
1711 }
1712
1713 if(si->plt_rel) {
1714 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1715 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1716 goto fail;
1717 }
1718 if(si->rel) {
1719 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1720 if(reloc_library(si, si->rel, si->rel_count))
1721 goto fail;
1722 }
1723
1724 si->flags |= FLAG_LINKED;
1725 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1726
1727#if 0
1728 /* This is the way that the old dynamic linker did protection of
1729 * non-writable areas. It would scan section headers and find where
1730 * .text ended (rather where .data/.bss began) and assume that this is
1731 * the upper range of the non-writable area. This is too coarse,
1732 * and is kept here for reference until we fully move away from single
1733 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1734 * that made this possible.
1735 */
1736 if(wr_offset < 0xffffffff){
1737 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1738 }
1739#else
1740 /* TODO: Verify that this does the right thing in all cases, as it
1741 * presently probably does not. It is possible that an ELF image will
1742 * come with multiple read-only segments. What we ought to do is scan
1743 * the program headers again and mprotect all the read-only segments.
1744 * To prevent re-scanning the program header, we would have to build a
1745 * list of loadable segments in si, and then scan that instead. */
1746 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1747 mprotect((void *)si->wrprotect_start,
1748 si->wrprotect_end - si->wrprotect_start,
1749 PROT_READ | PROT_EXEC);
1750 }
1751#endif
1752
1753 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1754 stdout and stderr to close a security hole described in:
1755
1756 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1757
1758 */
1759 if (getuid() != geteuid() || getgid() != getegid())
1760 nullify_closed_stdio ();
1761 call_constructors(si);
1762 notify_gdb_of_load(si);
1763 return 0;
1764
1765fail:
1766 ERROR("failed to link %s\n", si->name);
1767 si->flags |= FLAG_ERROR;
1768 return -1;
1769}
1770
David Bartleybc3a5c22009-06-02 18:27:28 -07001771static void parse_library_path(char *path, char *delim)
1772{
1773 size_t len;
1774 char *ldpaths_bufp = ldpaths_buf;
1775 int i = 0;
1776
1777 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1778
1779 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1780 if (*ldpaths[i] != '\0')
1781 ++i;
1782 }
1783
1784 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1785 * last char isn't '\0' (i.e. not originally a delim). */
1786 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1787 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1788 ldpaths[i - 1] = NULL;
1789 } else {
1790 ldpaths[i] = NULL;
1791 }
1792}
1793
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001794int main(int argc, char **argv)
1795{
1796 return 0;
1797}
1798
1799#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1800
1801static void * __tls_area[ANDROID_TLS_SLOTS];
1802
1803unsigned __linker_init(unsigned **elfdata)
1804{
1805 static soinfo linker_soinfo;
1806
1807 int argc = (int) *elfdata;
1808 char **argv = (char**) (elfdata + 1);
1809 unsigned *vecs = (unsigned*) (argv + argc + 1);
1810 soinfo *si;
1811 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001812 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001813
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001814 /* Setup a temporary TLS area that is used to get a working
1815 * errno for system calls.
1816 */
1817 __set_tls(__tls_area);
1818
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001819 pid = getpid();
1820
1821#if TIMING
1822 struct timeval t0, t1;
1823 gettimeofday(&t0, 0);
1824#endif
1825
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001826 /* NOTE: we store the elfdata pointer on a special location
1827 * of the temporary TLS area in order to pass it to
1828 * the C Library's runtime initializer.
1829 *
1830 * The initializer must clear the slot and reset the TLS
1831 * to point to a different location to ensure that no other
1832 * shared library constructor can access it.
1833 */
1834 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001835
1836 debugger_init();
1837
1838 /* skip past the environment */
1839 while(vecs[0] != 0) {
1840 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1841 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001842 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1843 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001844 }
1845 vecs++;
1846 }
1847 vecs++;
1848
1849 INFO("[ android linker & debugger ]\n");
1850 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1851
1852 si = alloc_info(argv[0]);
1853 if(si == 0) {
1854 exit(-1);
1855 }
1856
1857 /* bootstrap the link map, the main exe always needs to be first */
1858 si->flags |= FLAG_EXE;
1859 map = &(si->linkmap);
1860
1861 map->l_addr = 0;
1862 map->l_name = argv[0];
1863 map->l_prev = NULL;
1864 map->l_next = NULL;
1865
1866 _r_debug.r_map = map;
1867 r_debug_tail = map;
1868
1869 /* gdb expects the linker to be in the debug shared object list,
1870 * and we need to make sure that the reported load address is zero.
1871 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1872 * is. Don't use alloc_info(), because the linker shouldn't
1873 * be on the soinfo list.
1874 */
1875 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1876 linker_soinfo.flags = 0;
1877 linker_soinfo.base = 0; // This is the important part; must be zero.
1878 insert_soinfo_into_debug_map(&linker_soinfo);
1879
1880 /* extract information passed from the kernel */
1881 while(vecs[0] != 0){
1882 switch(vecs[0]){
1883 case AT_PHDR:
1884 si->phdr = (Elf32_Phdr*) vecs[1];
1885 break;
1886 case AT_PHNUM:
1887 si->phnum = (int) vecs[1];
1888 break;
1889 case AT_ENTRY:
1890 si->entry = vecs[1];
1891 break;
1892 }
1893 vecs += 2;
1894 }
1895
1896 ba_init();
1897
1898 si->base = 0;
1899 si->dynamic = (unsigned *)-1;
1900 si->wrprotect_start = 0xffffffff;
1901 si->wrprotect_end = 0;
1902
David Bartleybc3a5c22009-06-02 18:27:28 -07001903 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1904 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1905 parse_library_path(ldpath_env, ":");
1906
Dima Zavin2e855792009-05-20 18:28:09 -07001907 if(link_image(si, 0)) {
1908 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1909 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1910 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001911 exit(-1);
1912 }
1913
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001914#if ALLOW_SYMBOLS_FROM_MAIN
1915 /* Set somain after we've loaded all the libraries in order to prevent
1916 * linking of symbols back to the main image, which is not set up at that
1917 * point yet.
1918 */
1919 somain = si;
1920#endif
1921
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001922#if TIMING
1923 gettimeofday(&t1,NULL);
1924 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1925 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1926 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1927 ));
1928#endif
1929#if STATS
1930 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1931 linker_stats.reloc[RELOC_ABSOLUTE],
1932 linker_stats.reloc[RELOC_RELATIVE],
1933 linker_stats.reloc[RELOC_COPY],
1934 linker_stats.reloc[RELOC_SYMBOL]);
1935#endif
1936#if COUNT_PAGES
1937 {
1938 unsigned n;
1939 unsigned i;
1940 unsigned count = 0;
1941 for(n = 0; n < 4096; n++){
1942 if(bitmask[n]){
1943 unsigned x = bitmask[n];
1944 for(i = 0; i < 8; i++){
1945 if(x & 1) count++;
1946 x >>= 1;
1947 }
1948 }
1949 }
1950 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1951 }
1952#endif
1953
1954#if TIMING || STATS || COUNT_PAGES
1955 fflush(stdout);
1956#endif
1957
1958 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1959 si->entry);
1960 return si->entry;
1961}