blob: 451e96c2b18af080ae463ce8ac688d20423857ff [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 Malchevaf7315a2009-10-16 17:50:42 -070094
95/* Set up for the buddy allocator managing the prelinked libraries. */
96static struct ba_bits ba_prelink_bitmap[(LIBLAST - LIBBASE) / LIBINC];
97static struct ba ba_prelink = {
98 .base = LIBBASE,
99 .size = LIBLAST - LIBBASE,
100 .min_alloc = LIBINC,
Iliyan Malchevbb9eede2009-10-19 14:25:17 -0700101 /* max_order will be determined automatically */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700102 .bitmap = ba_prelink_bitmap,
103 .num_entries = sizeof(ba_prelink_bitmap)/sizeof(ba_prelink_bitmap[0]),
104};
105
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700106static inline int validate_soinfo(soinfo *si)
107{
108 return (si >= sopool && si < sopool + SO_MAX) ||
109 si == &libdl_info;
110}
111
David Bartleybc3a5c22009-06-02 18:27:28 -0700112static char ldpaths_buf[LDPATH_BUFSIZE];
113static const char *ldpaths[LDPATH_MAX + 1];
114
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800115int debug_verbosity;
116static int pid;
117
118#if STATS
119struct _link_stats linker_stats;
120#endif
121
122#if COUNT_PAGES
123unsigned bitmask[4096];
124#endif
125
126#ifndef PT_ARM_EXIDX
127#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
128#endif
129
Dima Zavin2e855792009-05-20 18:28:09 -0700130#define HOODLUM(name, ret, ...) \
131 ret name __VA_ARGS__ \
132 { \
133 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
134 write(2, errstr, sizeof(errstr)); \
135 abort(); \
136 }
137HOODLUM(malloc, void *, (size_t size));
138HOODLUM(free, void, (void *ptr));
139HOODLUM(realloc, void *, (void *ptr, size_t size));
140HOODLUM(calloc, void *, (size_t cnt, size_t size));
141
Dima Zavin03531952009-05-29 17:30:25 -0700142static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700143static char __linker_dl_err_buf[768];
144#define DL_ERR(fmt, x...) \
145 do { \
146 snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
147 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700148 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700149 } while(0)
150
151const char *linker_get_error(void)
152{
153 return (const char *)&__linker_dl_err_buf[0];
154}
155
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800156/*
157 * This function is an empty stub where GDB locates a breakpoint to get notified
158 * about linker activity.
159 */
160extern void __attribute__((noinline)) rtld_db_dlactivity(void);
161
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800162static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
163 RT_CONSISTENT, 0};
164static struct link_map *r_debug_tail = 0;
165
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700166static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800167
168static void insert_soinfo_into_debug_map(soinfo * info)
169{
170 struct link_map * map;
171
172 /* Copy the necessary fields into the debug structure.
173 */
174 map = &(info->linkmap);
175 map->l_addr = info->base;
176 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800177 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800178
179 /* Stick the new library at the end of the list.
180 * gdb tends to care more about libc than it does
181 * about leaf libraries, and ordering it this way
182 * reduces the back-and-forth over the wire.
183 */
184 if (r_debug_tail) {
185 r_debug_tail->l_next = map;
186 map->l_prev = r_debug_tail;
187 map->l_next = 0;
188 } else {
189 _r_debug.r_map = map;
190 map->l_prev = 0;
191 map->l_next = 0;
192 }
193 r_debug_tail = map;
194}
195
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700196static void remove_soinfo_from_debug_map(soinfo * info)
197{
198 struct link_map * map = &(info->linkmap);
199
200 if (r_debug_tail == map)
201 r_debug_tail = map->l_prev;
202
203 if (map->l_prev) map->l_prev->l_next = map->l_next;
204 if (map->l_next) map->l_next->l_prev = map->l_prev;
205}
206
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800207void notify_gdb_of_load(soinfo * info)
208{
209 if (info->flags & FLAG_EXE) {
210 // GDB already knows about the main executable
211 return;
212 }
213
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700214 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800215
216 _r_debug.r_state = RT_ADD;
217 rtld_db_dlactivity();
218
219 insert_soinfo_into_debug_map(info);
220
221 _r_debug.r_state = RT_CONSISTENT;
222 rtld_db_dlactivity();
223
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700224 pthread_mutex_unlock(&_r_debug_lock);
225}
226
227void notify_gdb_of_unload(soinfo * info)
228{
229 if (info->flags & FLAG_EXE) {
230 // GDB already knows about the main executable
231 return;
232 }
233
234 pthread_mutex_lock(&_r_debug_lock);
235
236 _r_debug.r_state = RT_DELETE;
237 rtld_db_dlactivity();
238
239 remove_soinfo_from_debug_map(info);
240
241 _r_debug.r_state = RT_CONSISTENT;
242 rtld_db_dlactivity();
243
244 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800245}
246
247void notify_gdb_of_libraries()
248{
249 _r_debug.r_state = RT_ADD;
250 rtld_db_dlactivity();
251 _r_debug.r_state = RT_CONSISTENT;
252 rtld_db_dlactivity();
253}
254
255static soinfo *alloc_info(const char *name)
256{
257 soinfo *si;
258
259 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700260 DL_ERR("%5d library name %s too long", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261 return 0;
262 }
263
264 /* The freelist is populated when we call free_info(), which in turn is
265 done only by dlclose(), which is not likely to be used.
266 */
267 if (!freelist) {
268 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700269 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800270 return NULL;
271 }
272 freelist = sopool + socount++;
273 freelist->next = NULL;
274 }
275
276 si = freelist;
277 freelist = freelist->next;
278
279 /* Make sure we get a clean block of soinfo */
280 memset(si, 0, sizeof(soinfo));
281 strcpy((char*) si->name, name);
282 sonext->next = si;
283 si->ba_index = -1; /* by default, prelinked */
284 si->next = NULL;
285 si->refcount = 0;
286 sonext = si;
287
288 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
289 return si;
290}
291
292static void free_info(soinfo *si)
293{
294 soinfo *prev = NULL, *trav;
295
296 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
297
298 for(trav = solist; trav != NULL; trav = trav->next){
299 if (trav == si)
300 break;
301 prev = trav;
302 }
303 if (trav == NULL) {
304 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700305 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800306 return;
307 }
308
309 /* prev will never be NULL, because the first entry in solist is
310 always the static libdl_info.
311 */
312 prev->next = si->next;
313 if (si == sonext) sonext = prev;
314 si->next = freelist;
315 freelist = si;
316}
317
318#ifndef LINKER_TEXT_BASE
319#error "linker's makefile must define LINKER_TEXT_BASE"
320#endif
321#ifndef LINKER_AREA_SIZE
322#error "linker's makefile must define LINKER_AREA_SIZE"
323#endif
324#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
325#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
326
327const char *addr_to_name(unsigned addr)
328{
329 soinfo *si;
330
331 for(si = solist; si != 0; si = si->next){
332 if((addr >= si->base) && (addr < (si->base + si->size))) {
333 return si->name;
334 }
335 }
336
337 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
338 return "linker";
339 }
340
341 return "";
342}
343
344/* For a given PC, find the .so that it belongs to.
345 * Returns the base address of the .ARM.exidx section
346 * for that .so, and the number of 8-byte entries
347 * in that section (via *pcount).
348 *
349 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
350 *
351 * This function is exposed via dlfcn.c and libdl.so.
352 */
353#ifdef ANDROID_ARM_LINKER
354_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
355{
356 soinfo *si;
357 unsigned addr = (unsigned)pc;
358
359 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
360 for (si = solist; si != 0; si = si->next){
361 if ((addr >= si->base) && (addr < (si->base + si->size))) {
362 *pcount = si->ARM_exidx_count;
363 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
364 }
365 }
366 }
367 *pcount = 0;
368 return NULL;
369}
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +0900370#elif defined(ANDROID_X86_LINKER) || defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800371/* Here, we only have to provide a callback to iterate across all the
372 * loaded libraries. gcc_eh does the rest. */
373int
374dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
375 void *data)
376{
377 soinfo *si;
378 struct dl_phdr_info dl_info;
379 int rv = 0;
380
381 for (si = solist; si != NULL; si = si->next) {
382 dl_info.dlpi_addr = si->linkmap.l_addr;
383 dl_info.dlpi_name = si->linkmap.l_name;
384 dl_info.dlpi_phdr = si->phdr;
385 dl_info.dlpi_phnum = si->phnum;
386 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
387 if (rv != 0)
388 break;
389 }
390 return rv;
391}
392#endif
393
394static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
395{
396 Elf32_Sym *s;
397 Elf32_Sym *symtab = si->symtab;
398 const char *strtab = si->strtab;
399 unsigned n;
400
401 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
402 name, si->name, si->base, hash, hash % si->nbucket);
403 n = hash % si->nbucket;
404
405 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
406 s = symtab + n;
407 if(strcmp(strtab + s->st_name, name)) continue;
408
409 /* only concern ourselves with global symbols */
410 switch(ELF32_ST_BIND(s->st_info)){
411 case STB_GLOBAL:
412 /* no section == undefined */
413 if(s->st_shndx == 0) continue;
414
415 case STB_WEAK:
416 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
417 name, si->name, s->st_value, s->st_size);
418 return s;
419 }
420 }
421
422 return 0;
423}
424
425static unsigned elfhash(const char *_name)
426{
427 const unsigned char *name = (const unsigned char *) _name;
428 unsigned h = 0, g;
429
430 while(*name) {
431 h = (h << 4) + *name++;
432 g = h & 0xf0000000;
433 h ^= g;
434 h ^= g >> 24;
435 }
436 return h;
437}
438
439static Elf32_Sym *
440_do_lookup_in_so(soinfo *si, const char *name, unsigned *elf_hash)
441{
442 if (*elf_hash == 0)
443 *elf_hash = elfhash(name);
444 return _elf_lookup (si, *elf_hash, name);
445}
446
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700447static Elf32_Sym *
448_do_lookup(soinfo *si, const char *name, unsigned *base)
449{
450 unsigned elf_hash = 0;
451 Elf32_Sym *s;
452 unsigned *d;
453 soinfo *lsi = si;
454
455 /* Look for symbols in the local scope first (the object who is
456 * searching). This happens with C++ templates on i386 for some
457 * reason. */
458 s = _do_lookup_in_so(si, name, &elf_hash);
459 if(s != NULL)
460 goto done;
461
462 for(d = si->dynamic; *d; d += 2) {
463 if(d[0] == DT_NEEDED){
464 lsi = (soinfo *)d[1];
465 if (!validate_soinfo(lsi)) {
466 DL_ERR("%5d bad DT_NEEDED pointer in %s",
467 pid, si->name);
468 return 0;
469 }
470
471 DEBUG("%5d %s: looking up %s in %s\n",
472 pid, si->name, name, lsi->name);
473 s = _do_lookup_in_so(lsi, name, &elf_hash);
Min-su, Kim3cab22c2010-01-19 10:05:33 +0900474 if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700475 goto done;
476 }
477 }
478
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700479#if ALLOW_SYMBOLS_FROM_MAIN
480 /* If we are resolving relocations while dlopen()ing a library, it's OK for
481 * the library to resolve a symbol that's defined in the executable itself,
482 * although this is rare and is generally a bad idea.
483 */
484 if (somain) {
485 lsi = somain;
486 DEBUG("%5d %s: looking up %s in executable %s\n",
487 pid, si->name, name, lsi->name);
488 s = _do_lookup_in_so(lsi, name, &elf_hash);
489 }
490#endif
491
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700492done:
493 if(s != NULL) {
494 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
495 "found in %s, base = 0x%08x\n",
496 pid, si->name, name, s->st_value, lsi->name, lsi->base);
497 *base = lsi->base;
498 return s;
499 }
500
501 return 0;
502}
503
504/* This is used by dl_sym(). It performs symbol lookup only within the
505 specified soinfo object and not in any of its dependencies.
506 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800507Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
508{
509 unsigned unused = 0;
510 return _do_lookup_in_so(si, name, &unused);
511}
512
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700513/* This is used by dl_sym(). It performs a global symbol lookup.
514 */
Matt Fischer1698d9e2009-12-31 12:17:56 -0600515Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800516{
517 unsigned elf_hash = 0;
518 Elf32_Sym *s = NULL;
519 soinfo *si;
520
Matt Fischer1698d9e2009-12-31 12:17:56 -0600521 if(start == NULL) {
522 start = solist;
523 }
524
525 for(si = start; (s == NULL) && (si != NULL); si = si->next)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800526 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700527 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800528 continue;
529 s = _do_lookup_in_so(si, name, &elf_hash);
530 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700531 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800532 break;
533 }
534 }
535
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700536 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800537 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
538 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
539 return s;
540 }
541
542 return 0;
543}
544
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600545soinfo *find_containing_library(void *addr)
546{
547 soinfo *si;
548
549 for(si = solist; si != NULL; si = si->next)
550 {
551 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
552 return si;
553 }
554 }
555
556 return NULL;
557}
558
559Elf32_Sym *find_containing_symbol(void *addr, soinfo *si)
560{
561 unsigned int i;
562 unsigned soaddr = (unsigned)addr - si->base;
563
564 /* Search the library's symbol table for any defined symbol which
565 * contains this address */
566 for(i=0; i<si->nchain; i++) {
567 Elf32_Sym *sym = &si->symtab[i];
568
569 if(sym->st_shndx != SHN_UNDEF &&
570 soaddr >= sym->st_value &&
571 soaddr < sym->st_value + sym->st_size) {
572 return sym;
573 }
574 }
575
576 return NULL;
577}
578
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800579#if 0
580static void dump(soinfo *si)
581{
582 Elf32_Sym *s = si->symtab;
583 unsigned n;
584
585 for(n = 0; n < si->nchain; n++) {
586 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
587 s->st_info, s->st_shndx, s->st_value, s->st_size,
588 si->strtab + s->st_name);
589 s++;
590 }
591}
592#endif
593
594static const char *sopaths[] = {
595 "/system/lib",
596 "/lib",
597 0
598};
599
600static int _open_lib(const char *name)
601{
602 int fd;
603 struct stat filestat;
604
605 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
606 if ((fd = open(name, O_RDONLY)) >= 0)
607 return fd;
608 }
609
610 return -1;
611}
612
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800613static int open_library(const char *name)
614{
615 int fd;
616 char buf[512];
617 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700618 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800619
620 TRACE("[ %5d opening %s ]\n", pid, name);
621
622 if(name == 0) return -1;
623 if(strlen(name) > 256) return -1;
624
625 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
626 return fd;
627
David Bartleybc3a5c22009-06-02 18:27:28 -0700628 for (path = ldpaths; *path; path++) {
629 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
630 if (n < 0 || n >= (int)sizeof(buf)) {
631 WARN("Ignoring very long library path: %s/%s\n", *path, name);
632 continue;
633 }
634 if ((fd = _open_lib(buf)) >= 0)
635 return fd;
636 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800637 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700638 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
639 if (n < 0 || n >= (int)sizeof(buf)) {
640 WARN("Ignoring very long library path: %s/%s\n", *path, name);
641 continue;
642 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800643 if ((fd = _open_lib(buf)) >= 0)
644 return fd;
645 }
646
647 return -1;
648}
649
650/* temporary space for holding the first page of the shared lib
651 * which contains the elf header (with the pht). */
652static unsigned char __header[PAGE_SIZE];
653
654typedef struct {
655 long mmap_addr;
656 char tag[4]; /* 'P', 'R', 'E', ' ' */
657} prelink_info_t;
658
659/* Returns the requested base address if the library is prelinked,
660 * and 0 otherwise. */
661static unsigned long
662is_prelinked(int fd, const char *name)
663{
664 off_t sz;
665 prelink_info_t info;
666
667 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
668 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700669 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800670 return 0;
671 }
672
673 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
674 WARN("Could not read prelink_info_t structure for `%s`\n", name);
675 return 0;
676 }
677
678 if (strncmp(info.tag, "PRE ", 4)) {
679 WARN("`%s` is not a prelinked library\n", name);
680 return 0;
681 }
682
683 return (unsigned long)info.mmap_addr;
684}
685
686/* verify_elf_object
687 * Verifies if the object @ base is a valid ELF object
688 *
689 * Args:
690 *
691 * Returns:
692 * 0 on success
693 * -1 if no valid ELF object is found @ base.
694 */
695static int
696verify_elf_object(void *base, const char *name)
697{
698 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
699
700 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
701 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
702 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
703 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
704
705 /* TODO: Should we verify anything else in the header? */
706
707 return 0;
708}
709
710
711/* get_lib_extents
712 * Retrieves the base (*base) address where the ELF object should be
713 * mapped and its overall memory size (*total_sz).
714 *
715 * Args:
716 * fd: Opened file descriptor for the library
717 * name: The name of the library
718 * _hdr: Pointer to the header page of the library
719 * total_sz: Total size of the memory that should be allocated for
720 * this library
721 *
722 * Returns:
723 * -1 if there was an error while trying to get the lib extents.
724 * The possible reasons are:
725 * - Could not determine if the library was prelinked.
726 * - The library provided is not a valid ELF object
727 * 0 if the library did not request a specific base offset (normal
728 * for non-prelinked libs)
729 * > 0 if the library requests a specific address to be mapped to.
730 * This indicates a pre-linked library.
731 */
732static unsigned
733get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
734{
735 unsigned req_base;
736 unsigned min_vaddr = 0xffffffff;
737 unsigned max_vaddr = 0;
738 unsigned char *_hdr = (unsigned char *)__hdr;
739 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
740 Elf32_Phdr *phdr;
741 int cnt;
742
743 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
744 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700745 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800746 return (unsigned)-1;
747 }
748
749 req_base = (unsigned) is_prelinked(fd, name);
750 if (req_base == (unsigned)-1)
751 return -1;
752 else if (req_base != 0) {
753 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
754 pid, name, req_base);
755 } else {
756 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
757 }
758
759 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
760
761 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
762 * get the range. */
763 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
764 if (phdr->p_type == PT_LOAD) {
765 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
766 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
767 if (phdr->p_vaddr < min_vaddr)
768 min_vaddr = phdr->p_vaddr;
769 }
770 }
771
772 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700773 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800774 return (unsigned)-1;
775 }
776
777 /* truncate min_vaddr down to page boundary */
778 min_vaddr &= ~PAGE_MASK;
779
780 /* round max_vaddr up to the next page */
781 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
782
783 *total_sz = (max_vaddr - min_vaddr);
784 return (unsigned)req_base;
785}
786
787/* alloc_mem_region
788 *
789 * This function reserves a chunk of memory to be used for mapping in
790 * the shared library. We reserve the entire memory region here, and
791 * then the rest of the linker will relocate the individual loadable
792 * segments into the correct locations within this memory range.
793 *
794 * Args:
795 * si->base: The requested base of the allocation. If 0, a sane one will be
796 * chosen in the range LIBBASE <= base < LIBLAST.
797 * si->size: The size of the allocation.
798 *
799 * Returns:
800 * -1 on failure, and 0 on success. On success, si->base will contain
801 * the virtual address at which the library will be mapped.
802 */
803
804static int reserve_mem_region(soinfo *si)
805{
806 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
807 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
808 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700809 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700810 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800811 pid, (si->base ? "" : "non-"), si->name, si->base,
812 errno, strerror(errno));
813 return -1;
814 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700815 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700816 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800817 si->name, (unsigned)base, si->base);
818 munmap(base, si->size);
819 return -1;
820 }
821 return 0;
822}
823
824static int
825alloc_mem_region(soinfo *si)
826{
827 if (si->base) {
828 /* Attempt to mmap a prelinked library. */
829 si->ba_index = -1;
830 return reserve_mem_region(si);
831 }
832
833 /* This is not a prelinked library, so we attempt to allocate space
834 for it from the buddy allocator, which manages the area between
835 LIBBASE and LIBLAST.
836 */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700837 si->ba_index = ba_allocate(&ba_prelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800838 if(si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700839 si->base = ba_start_addr(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800840 PRINT("%5d mapping library '%s' at %08x (index %d) " \
841 "through buddy allocator.\n",
842 pid, si->name, si->base, si->ba_index);
843 if (reserve_mem_region(si) < 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700844 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800845 si->ba_index = -1;
846 si->base = 0;
847 goto err;
848 }
849 return 0;
850 }
851
852err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700853 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800854 pid, si->name);
855 return -1;
856}
857
858#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
859#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
860 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
861 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
862/* load_segments
863 *
864 * This function loads all the loadable (PT_LOAD) segments into memory
865 * at their appropriate memory offsets off the base address.
866 *
867 * Args:
868 * fd: Open file descriptor to the library to load.
869 * header: Pointer to a header page that contains the ELF header.
870 * This is needed since we haven't mapped in the real file yet.
871 * si: ptr to soinfo struct describing the shared object.
872 *
873 * Returns:
874 * 0 on success, -1 on failure.
875 */
876static int
877load_segments(int fd, void *header, soinfo *si)
878{
879 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
880 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
881 unsigned char *base = (unsigned char *)si->base;
882 int cnt;
883 unsigned len;
884 unsigned char *tmp;
885 unsigned char *pbase;
886 unsigned char *extra_base;
887 unsigned extra_len;
888 unsigned total_sz = 0;
889
890 si->wrprotect_start = 0xffffffff;
891 si->wrprotect_end = 0;
892
893 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
894 pid, si->name, (unsigned)si->base);
895 /* Now go through all the PT_LOAD segments and map them into memory
896 * at the appropriate locations. */
897 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
898 if (phdr->p_type == PT_LOAD) {
899 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
900 /* we want to map in the segment on a page boundary */
901 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
902 /* add the # of bytes we masked off above to the total length. */
903 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
904
905 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
906 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
907 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
908 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
909 MAP_PRIVATE | MAP_FIXED, fd,
910 phdr->p_offset & (~PAGE_MASK));
911 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700912 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700913 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800914 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
915 goto fail;
916 }
917
918 /* If 'len' didn't end on page boundary, and it's a writable
919 * segment, zero-fill the rest. */
920 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
921 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
922
923 /* Check to see if we need to extend the map for this segment to
924 * cover the diff between filesz and memsz (i.e. for bss).
925 *
926 * base _+---------------------+ page boundary
927 * . .
928 * | |
929 * . .
930 * pbase _+---------------------+ page boundary
931 * | |
932 * . .
933 * base + p_vaddr _| |
934 * . \ \ .
935 * . | filesz | .
936 * pbase + len _| / | |
937 * <0 pad> . . .
938 * extra_base _+------------|--------+ page boundary
939 * / . . .
940 * | . . .
941 * | +------------|--------+ page boundary
942 * extra_len-> | | | |
943 * | . | memsz .
944 * | . | .
945 * \ _| / |
946 * . .
947 * | |
948 * _+---------------------+ page boundary
949 */
950 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
951 (~PAGE_MASK));
952 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
953 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
954 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
955 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
956 /* map in the extra page(s) as anonymous into the range.
957 * This is probably not necessary as we already mapped in
958 * the entire region previously, but we just want to be
959 * sure. This will also set the right flags on the region
960 * (though we can probably accomplish the same thing with
961 * mprotect).
962 */
963 extra_base = mmap((void *)tmp, extra_len,
964 PFLAGS_TO_PROT(phdr->p_flags),
965 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
966 -1, 0);
967 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700968 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700969 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800970 extra_len);
971 goto fail;
972 }
973 /* TODO: Check if we need to memset-0 this region.
974 * Anonymous mappings are zero-filled copy-on-writes, so we
975 * shouldn't need to. */
976 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
977 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
978 extra_len);
979 }
980 /* set the len here to show the full extent of the segment we
981 * just loaded, mostly for debugging */
982 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
983 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
984 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
985 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
986 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
987 total_sz += len;
988 /* Make the section writable just in case we'll have to write to
989 * it during relocation (i.e. text segment). However, we will
990 * remember what range of addresses should be write protected.
991 *
992 */
993 if (!(phdr->p_flags & PF_W)) {
994 if ((unsigned)pbase < si->wrprotect_start)
995 si->wrprotect_start = (unsigned)pbase;
996 if (((unsigned)pbase + len) > si->wrprotect_end)
997 si->wrprotect_end = (unsigned)pbase + len;
998 mprotect(pbase, len,
999 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1000 }
1001 } else if (phdr->p_type == PT_DYNAMIC) {
1002 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1003 /* this segment contains the dynamic linking information */
1004 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
1005 } else {
1006#ifdef ANDROID_ARM_LINKER
1007 if (phdr->p_type == PT_ARM_EXIDX) {
1008 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1009 /* exidx entries (used for stack unwinding) are 8 bytes each.
1010 */
1011 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1012 si->ARM_exidx_count = phdr->p_memsz / 8;
1013 }
1014#endif
1015 }
1016
1017 }
1018
1019 /* Sanity check */
1020 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001021 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001022 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001023 pid, total_sz, si->name, si->size);
1024 goto fail;
1025 }
1026
1027 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1028 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1029 (unsigned)si->base, si->size);
1030 return 0;
1031
1032fail:
1033 /* We can just blindly unmap the entire region even though some things
1034 * were mapped in originally with anonymous and others could have been
1035 * been mapped in from the file before we failed. The kernel will unmap
1036 * all the pages in the range, irrespective of how they got there.
1037 */
1038 munmap((void *)si->base, si->size);
1039 si->flags |= FLAG_ERROR;
1040 return -1;
1041}
1042
1043/* TODO: Implement this to take care of the fact that Android ARM
1044 * ELF objects shove everything into a single loadable segment that has the
1045 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1046 * non-writable.
1047 */
1048#if 0
1049static unsigned
1050get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1051{
1052 Elf32_Shdr *shdr_start;
1053 Elf32_Shdr *shdr;
1054 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1055 int cnt;
1056 unsigned wr_offset = 0xffffffff;
1057
1058 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1059 ehdr->e_shoff & (~PAGE_MASK));
1060 if (shdr_start == MAP_FAILED) {
1061 WARN("%5d - Could not read section header info from '%s'. Will not "
1062 "not be able to determine write-protect offset.\n", pid, name);
1063 return (unsigned)-1;
1064 }
1065
1066 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1067 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1068 (shdr->sh_addr < wr_offset)) {
1069 wr_offset = shdr->sh_addr;
1070 }
1071 }
1072
1073 munmap(shdr_start, shdr_sz);
1074 return wr_offset;
1075}
1076#endif
1077
1078static soinfo *
1079load_library(const char *name)
1080{
1081 int fd = open_library(name);
1082 int cnt;
1083 unsigned ext_sz;
1084 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001085 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001086 soinfo *si = NULL;
1087 Elf32_Ehdr *hdr;
1088
Dima Zavin2e855792009-05-20 18:28:09 -07001089 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001090 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001091 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001092 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001093
1094 /* We have to read the ELF header to figure out what to do with this image
1095 */
1096 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001097 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001098 goto fail;
1099 }
1100
1101 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001102 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103 goto fail;
1104 }
1105
1106 /* Parse the ELF header and get the size of the memory footprint for
1107 * the library */
1108 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1109 if (req_base == (unsigned)-1)
1110 goto fail;
1111 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1112 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1113
1114 /* Now configure the soinfo struct where we'll store all of our data
1115 * for the ELF object. If the loading fails, we waste the entry, but
1116 * same thing would happen if we failed during linking. Configuring the
1117 * soinfo struct here is a lot more convenient.
1118 */
Erik Gillingfde86422009-07-28 20:28:19 -07001119 bname = strrchr(name, '/');
1120 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001121 if (si == NULL)
1122 goto fail;
1123
1124 /* Carve out a chunk of memory where we will map in the individual
1125 * segments */
1126 si->base = req_base;
1127 si->size = ext_sz;
1128 si->flags = 0;
1129 si->entry = 0;
1130 si->dynamic = (unsigned *)-1;
1131 if (alloc_mem_region(si) < 0)
1132 goto fail;
1133
1134 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1135 pid, name, (void *)si->base, (unsigned) ext_sz);
1136
1137 /* Now actually load the library's segments into right places in memory */
1138 if (load_segments(fd, &__header[0], si) < 0) {
1139 if (si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001140 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001141 si->ba_index = -1;
1142 }
1143 goto fail;
1144 }
1145
1146 /* this might not be right. Technically, we don't even need this info
1147 * once we go through 'load_segments'. */
1148 hdr = (Elf32_Ehdr *)si->base;
1149 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1150 si->phnum = hdr->e_phnum;
1151 /**/
1152
1153 close(fd);
1154 return si;
1155
1156fail:
1157 if (si) free_info(si);
1158 close(fd);
1159 return NULL;
1160}
1161
1162static soinfo *
1163init_library(soinfo *si)
1164{
1165 unsigned wr_offset = 0xffffffff;
1166
1167 /* At this point we know that whatever is loaded @ base is a valid ELF
1168 * shared library whose segments are properly mapped in. */
1169 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1170 pid, si->base, si->size, si->name);
1171
1172 if (si->base < LIBBASE || si->base >= LIBLAST)
1173 si->flags |= FLAG_PRELINKED;
1174
1175 if(link_image(si, wr_offset)) {
1176 /* We failed to link. However, we can only restore libbase
1177 ** if no additional libraries have moved it since we updated it.
1178 */
1179 munmap((void *)si->base, si->size);
1180 return NULL;
1181 }
1182
1183 return si;
1184}
1185
1186soinfo *find_library(const char *name)
1187{
1188 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001189 const char *bname = strrchr(name, '/');
1190 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191
1192 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001193 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001194 if(si->flags & FLAG_ERROR) {
1195 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1196 return NULL;
1197 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001198 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001199 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001200 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001201 }
1202 }
1203
1204 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1205 si = load_library(name);
1206 if(si == NULL)
1207 return NULL;
1208 return init_library(si);
1209}
1210
1211/* TODO:
1212 * notify gdb of unload
1213 * for non-prelinked libraries, find a way to decrement libbase
1214 */
1215static void call_destructors(soinfo *si);
1216unsigned unload_library(soinfo *si)
1217{
1218 unsigned *d;
1219 if (si->refcount == 1) {
1220 TRACE("%5d unloading '%s'\n", pid, si->name);
1221 call_destructors(si);
1222
1223 for(d = si->dynamic; *d; d += 2) {
1224 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001225 soinfo *lsi = (soinfo *)d[1];
1226 d[1] = 0;
1227 if (validate_soinfo(lsi)) {
1228 TRACE("%5d %s needs to unload %s\n", pid,
1229 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001230 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001231 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001232 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001233 DL_ERR("%5d %s: could not unload dependent library",
1234 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001235 }
1236 }
1237
1238 munmap((char *)si->base, si->size);
1239 if (si->ba_index >= 0) {
1240 PRINT("%5d releasing library '%s' address space at %08x "\
1241 "through buddy allocator.\n",
1242 pid, si->name, si->base);
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001243 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001245 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246 free_info(si);
1247 si->refcount = 0;
1248 }
1249 else {
1250 si->refcount--;
1251 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1252 pid, si->name, si->refcount);
1253 }
1254 return si->refcount;
1255}
1256
1257/* TODO: don't use unsigned for addrs below. It works, but is not
1258 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1259 * long.
1260 */
1261static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1262{
1263 Elf32_Sym *symtab = si->symtab;
1264 const char *strtab = si->strtab;
1265 Elf32_Sym *s;
1266 unsigned base;
1267 Elf32_Rel *start = rel;
1268 unsigned idx;
1269
1270 for (idx = 0; idx < count; ++idx) {
1271 unsigned type = ELF32_R_TYPE(rel->r_info);
1272 unsigned sym = ELF32_R_SYM(rel->r_info);
1273 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1274 unsigned sym_addr = 0;
1275 char *sym_name = NULL;
1276
1277 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1278 si->name, idx);
1279 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001280 sym_name = (char *)(strtab + symtab[sym].st_name);
1281 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001282 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001283 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001284 return -1;
1285 }
1286#if 0
1287 if((base == 0) && (si->base != 0)){
1288 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001289 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001290 pid, strtab + symtab[sym].st_name);
1291 return -1;
1292 }
1293#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001294 // st_shndx==SHN_UNDEF means an undefined symbol.
1295 // st_value should be 0 then, except that the low bit of st_value is
1296 // used to indicate whether the symbol points to an ARM or thumb function,
1297 // and should be ignored in the following check.
1298 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1299 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1300 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001301 s->st_value);
1302 return -1;
1303 }
1304 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001305 COUNT_RELOC(RELOC_SYMBOL);
1306 } else {
1307 s = 0;
1308 }
1309
1310/* TODO: This is ugly. Split up the relocations by arch into
1311 * different files.
1312 */
1313 switch(type){
1314#if defined(ANDROID_ARM_LINKER)
1315 case R_ARM_JUMP_SLOT:
1316 COUNT_RELOC(RELOC_ABSOLUTE);
1317 MARK(rel->r_offset);
1318 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1319 reloc, sym_addr, sym_name);
1320 *((unsigned*)reloc) = sym_addr;
1321 break;
1322 case R_ARM_GLOB_DAT:
1323 COUNT_RELOC(RELOC_ABSOLUTE);
1324 MARK(rel->r_offset);
1325 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1326 reloc, sym_addr, sym_name);
1327 *((unsigned*)reloc) = sym_addr;
1328 break;
1329 case R_ARM_ABS32:
1330 COUNT_RELOC(RELOC_ABSOLUTE);
1331 MARK(rel->r_offset);
1332 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1333 reloc, sym_addr, sym_name);
1334 *((unsigned*)reloc) += sym_addr;
1335 break;
David 'Digit' Turnerfe62de12009-12-02 10:54:53 -08001336 case R_ARM_REL32:
1337 COUNT_RELOC(RELOC_RELATIVE);
1338 MARK(rel->r_offset);
1339 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1340 reloc, sym_addr, rel->r_offset, sym_name);
1341 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1342 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001343#elif defined(ANDROID_X86_LINKER)
1344 case R_386_JUMP_SLOT:
1345 COUNT_RELOC(RELOC_ABSOLUTE);
1346 MARK(rel->r_offset);
1347 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1348 reloc, sym_addr, sym_name);
1349 *((unsigned*)reloc) = sym_addr;
1350 break;
1351 case R_386_GLOB_DAT:
1352 COUNT_RELOC(RELOC_ABSOLUTE);
1353 MARK(rel->r_offset);
1354 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1355 reloc, sym_addr, sym_name);
1356 *((unsigned*)reloc) = sym_addr;
1357 break;
1358#endif /* ANDROID_*_LINKER */
1359
1360#if defined(ANDROID_ARM_LINKER)
1361 case R_ARM_RELATIVE:
1362#elif defined(ANDROID_X86_LINKER)
1363 case R_386_RELATIVE:
1364#endif /* ANDROID_*_LINKER */
1365 COUNT_RELOC(RELOC_RELATIVE);
1366 MARK(rel->r_offset);
1367 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001368 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001369 return -1;
1370 }
1371 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1372 reloc, si->base);
1373 *((unsigned*)reloc) += si->base;
1374 break;
1375
1376#if defined(ANDROID_X86_LINKER)
1377 case R_386_32:
1378 COUNT_RELOC(RELOC_RELATIVE);
1379 MARK(rel->r_offset);
1380
1381 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1382 reloc, sym_addr, sym_name);
1383 *((unsigned *)reloc) += (unsigned)sym_addr;
1384 break;
1385
1386 case R_386_PC32:
1387 COUNT_RELOC(RELOC_RELATIVE);
1388 MARK(rel->r_offset);
1389 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1390 "+%08x (%08x - %08x) %s\n", pid, reloc,
1391 (sym_addr - reloc), sym_addr, reloc, sym_name);
1392 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1393 break;
1394#endif /* ANDROID_X86_LINKER */
1395
1396#ifdef ANDROID_ARM_LINKER
1397 case R_ARM_COPY:
1398 COUNT_RELOC(RELOC_COPY);
1399 MARK(rel->r_offset);
1400 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1401 reloc, s->st_size, sym_addr, sym_name);
1402 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1403 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001404 case R_ARM_NONE:
1405 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406#endif /* ANDROID_ARM_LINKER */
1407
1408 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001409 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001410 pid, type, rel, (int) (rel - start));
1411 return -1;
1412 }
1413 rel++;
1414 }
1415 return 0;
1416}
1417
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001418#if defined(ANDROID_SH_LINKER)
1419static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1420{
1421 Elf32_Sym *symtab = si->symtab;
1422 const char *strtab = si->strtab;
1423 Elf32_Sym *s;
1424 unsigned base;
1425 Elf32_Rela *start = rela;
1426 unsigned idx;
1427
1428 for (idx = 0; idx < count; ++idx) {
1429 unsigned type = ELF32_R_TYPE(rela->r_info);
1430 unsigned sym = ELF32_R_SYM(rela->r_info);
1431 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1432 unsigned sym_addr = 0;
1433 char *sym_name = NULL;
1434
1435 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1436 si->name, idx);
1437 if(sym != 0) {
1438 sym_name = (char *)(strtab + symtab[sym].st_name);
1439 s = _do_lookup(si, sym_name, &base);
1440 if(s == 0) {
1441 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1442 return -1;
1443 }
1444#if 0
1445 if((base == 0) && (si->base != 0)){
1446 /* linking from libraries to main image is bad */
1447 DL_ERR("%5d cannot locate '%s'...",
1448 pid, strtab + symtab[sym].st_name);
1449 return -1;
1450 }
1451#endif
1452 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1453 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1454 "handle this yet", pid, si->name, s->st_shndx,
1455 s->st_value);
1456 return -1;
1457 }
1458 sym_addr = (unsigned)(s->st_value + base);
1459 COUNT_RELOC(RELOC_SYMBOL);
1460 } else {
1461 s = 0;
1462 }
1463
1464/* TODO: This is ugly. Split up the relocations by arch into
1465 * different files.
1466 */
1467 switch(type){
1468 case R_SH_JUMP_SLOT:
1469 COUNT_RELOC(RELOC_ABSOLUTE);
1470 MARK(rela->r_offset);
1471 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1472 reloc, sym_addr, sym_name);
1473 *((unsigned*)reloc) = sym_addr;
1474 break;
1475 case R_SH_GLOB_DAT:
1476 COUNT_RELOC(RELOC_ABSOLUTE);
1477 MARK(rela->r_offset);
1478 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1479 reloc, sym_addr, sym_name);
1480 *((unsigned*)reloc) = sym_addr;
1481 break;
1482 case R_SH_DIR32:
1483 COUNT_RELOC(RELOC_ABSOLUTE);
1484 MARK(rela->r_offset);
1485 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1486 reloc, sym_addr, sym_name);
1487 *((unsigned*)reloc) += sym_addr;
1488 break;
1489 case R_SH_RELATIVE:
1490 COUNT_RELOC(RELOC_RELATIVE);
1491 MARK(rela->r_offset);
1492 if(sym){
1493 DL_ERR("%5d odd RELATIVE form...", pid);
1494 return -1;
1495 }
1496 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1497 reloc, si->base);
1498 *((unsigned*)reloc) += si->base;
1499 break;
1500
1501 default:
1502 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1503 pid, type, rela, (int) (rela - start));
1504 return -1;
1505 }
1506 rela++;
1507 }
1508 return 0;
1509}
1510#endif /* ANDROID_SH_LINKER */
1511
David 'Digit' Turner82156792009-05-18 14:37:41 +02001512
1513/* Please read the "Initialization and Termination functions" functions.
1514 * of the linker design note in bionic/linker/README.TXT to understand
1515 * what the following code is doing.
1516 *
1517 * The important things to remember are:
1518 *
1519 * DT_PREINIT_ARRAY must be called first for executables, and should
1520 * not appear in shared libraries.
1521 *
1522 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1523 *
1524 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1525 *
1526 * DT_FINI_ARRAY must be parsed in reverse order.
1527 */
1528
1529static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001530{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001531 int n, inc = 1;
1532
1533 if (reverse) {
1534 ctor += (count-1);
1535 inc = -1;
1536 }
1537
1538 for(n = count; n > 0; n--) {
1539 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1540 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001541 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001542 void (*func)() = (void (*)()) *ctor;
1543 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001544 if(((int) func == 0) || ((int) func == -1)) continue;
1545 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1546 func();
1547 }
1548}
1549
1550static void call_constructors(soinfo *si)
1551{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001552 if (si->flags & FLAG_EXE) {
1553 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1554 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1555 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001556 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001557 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1558 } else {
1559 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001560 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001561 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001562 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001563 }
1564 }
1565
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001566 if (si->init_func) {
1567 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1568 (unsigned)si->init_func, si->name);
1569 si->init_func();
1570 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1571 }
1572
1573 if (si->init_array) {
1574 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1575 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001576 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001577 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1578 }
1579}
1580
David 'Digit' Turner82156792009-05-18 14:37:41 +02001581
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001582static void call_destructors(soinfo *si)
1583{
1584 if (si->fini_array) {
1585 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1586 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001587 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001588 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1589 }
1590
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001591 if (si->fini_func) {
1592 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1593 (unsigned)si->fini_func, si->name);
1594 si->fini_func();
1595 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1596 }
1597}
1598
1599/* Force any of the closed stdin, stdout and stderr to be associated with
1600 /dev/null. */
1601static int nullify_closed_stdio (void)
1602{
1603 int dev_null, i, status;
1604 int return_value = 0;
1605
1606 dev_null = open("/dev/null", O_RDWR);
1607 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001608 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001609 return -1;
1610 }
1611 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1612
1613 /* If any of the stdio file descriptors is valid and not associated
1614 with /dev/null, dup /dev/null to it. */
1615 for (i = 0; i < 3; i++) {
1616 /* If it is /dev/null already, we are done. */
1617 if (i == dev_null)
1618 continue;
1619
1620 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1621 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1622 can be interrupted but we do this just to be safe. */
1623 do {
1624 status = fcntl(i, F_GETFL);
1625 } while (status < 0 && errno == EINTR);
1626
1627 /* If file is openned, we are good. */
1628 if (status >= 0)
1629 continue;
1630
1631 /* The only error we allow is that the file descriptor does not
1632 exist, in which case we dup /dev/null to it. */
1633 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001634 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001635 return_value = -1;
1636 continue;
1637 }
1638
1639 /* Try dupping /dev/null to this stdio file descriptor and
1640 repeat if there is a signal. Note that any errors in closing
1641 the stdio descriptor are lost. */
1642 do {
1643 status = dup2(dev_null, i);
1644 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001645
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001646 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001647 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001648 return_value = -1;
1649 continue;
1650 }
1651 }
1652
1653 /* If /dev/null is not one of the stdio file descriptors, close it. */
1654 if (dev_null > 2) {
1655 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001656 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001657 status = close(dev_null);
1658 } while (status < 0 && errno == EINTR);
1659
1660 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001661 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001662 return_value = -1;
1663 }
1664 }
1665
1666 return return_value;
1667}
1668
1669static int link_image(soinfo *si, unsigned wr_offset)
1670{
1671 unsigned *d;
1672 Elf32_Phdr *phdr = si->phdr;
1673 int phnum = si->phnum;
1674
1675 INFO("[ %5d linking %s ]\n", pid, si->name);
1676 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1677 si->base, si->flags);
1678
1679 if (si->flags & FLAG_EXE) {
1680 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1681 * linkage info if this is the executable. If this was a
1682 * dynamic lib, that would have been done at load time.
1683 *
1684 * TODO: It's unfortunate that small pieces of this are
1685 * repeated from the load_library routine. Refactor this just
1686 * slightly to reuse these bits.
1687 */
1688 si->size = 0;
1689 for(; phnum > 0; --phnum, ++phdr) {
1690#ifdef ANDROID_ARM_LINKER
1691 if(phdr->p_type == PT_ARM_EXIDX) {
1692 /* exidx entries (used for stack unwinding) are 8 bytes each.
1693 */
1694 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1695 si->ARM_exidx_count = phdr->p_memsz / 8;
1696 }
1697#endif
1698 if (phdr->p_type == PT_LOAD) {
1699 /* For the executable, we use the si->size field only in
1700 dl_unwind_find_exidx(), so the meaning of si->size
1701 is not the size of the executable; it is the last
1702 virtual address of the loadable part of the executable;
1703 since si->base == 0 for an executable, we use the
1704 range [0, si->size) to determine whether a PC value
1705 falls within the executable section. Of course, if
1706 a value is below phdr->p_vaddr, it's not in the
1707 executable section, but a) we shouldn't be asking for
1708 such a value anyway, and b) if we have to provide
1709 an EXIDX for such a value, then the executable's
1710 EXIDX is probably the better choice.
1711 */
1712 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1713 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1714 si->size = phdr->p_vaddr + phdr->p_memsz;
1715 /* try to remember what range of addresses should be write
1716 * protected */
1717 if (!(phdr->p_flags & PF_W)) {
1718 unsigned _end;
1719
1720 if (phdr->p_vaddr < si->wrprotect_start)
1721 si->wrprotect_start = phdr->p_vaddr;
1722 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1723 (~PAGE_MASK)));
1724 if (_end > si->wrprotect_end)
1725 si->wrprotect_end = _end;
1726 }
1727 } else if (phdr->p_type == PT_DYNAMIC) {
1728 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001729 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001730 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001731 pid, si->name, si->base + phdr->p_vaddr,
1732 (unsigned)si->dynamic);
1733 goto fail;
1734 }
1735 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1736 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1737 }
1738 }
1739 }
1740
1741 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001742 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001743 goto fail;
1744 }
1745
1746 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1747
1748 /* extract useful information from dynamic section */
1749 for(d = si->dynamic; *d; d++){
1750 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1751 switch(*d++){
1752 case DT_HASH:
1753 si->nbucket = ((unsigned *) (si->base + *d))[0];
1754 si->nchain = ((unsigned *) (si->base + *d))[1];
1755 si->bucket = (unsigned *) (si->base + *d + 8);
1756 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1757 break;
1758 case DT_STRTAB:
1759 si->strtab = (const char *) (si->base + *d);
1760 break;
1761 case DT_SYMTAB:
1762 si->symtab = (Elf32_Sym *) (si->base + *d);
1763 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001764#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001765 case DT_PLTREL:
1766 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001767 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001768 goto fail;
1769 }
1770 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001771#endif
1772#ifdef ANDROID_SH_LINKER
1773 case DT_JMPREL:
1774 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1775 break;
1776 case DT_PLTRELSZ:
1777 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1778 break;
1779#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001780 case DT_JMPREL:
1781 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1782 break;
1783 case DT_PLTRELSZ:
1784 si->plt_rel_count = *d / 8;
1785 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001786#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001787 case DT_REL:
1788 si->rel = (Elf32_Rel*) (si->base + *d);
1789 break;
1790 case DT_RELSZ:
1791 si->rel_count = *d / 8;
1792 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001793#ifdef ANDROID_SH_LINKER
1794 case DT_RELASZ:
1795 si->rela_count = *d / sizeof(Elf32_Rela);
1796 break;
1797#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001798 case DT_PLTGOT:
1799 /* Save this in case we decide to do lazy binding. We don't yet. */
1800 si->plt_got = (unsigned *)(si->base + *d);
1801 break;
1802 case DT_DEBUG:
1803 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1804 *d = (int) &_r_debug;
1805 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001806#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001807 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001808 si->rela = (Elf32_Rela *) (si->base + *d);
1809 break;
1810#else
1811 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001812 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001813 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001814#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001815 case DT_INIT:
1816 si->init_func = (void (*)(void))(si->base + *d);
1817 DEBUG("%5d %s constructors (init func) found at %p\n",
1818 pid, si->name, si->init_func);
1819 break;
1820 case DT_FINI:
1821 si->fini_func = (void (*)(void))(si->base + *d);
1822 DEBUG("%5d %s destructors (fini func) found at %p\n",
1823 pid, si->name, si->fini_func);
1824 break;
1825 case DT_INIT_ARRAY:
1826 si->init_array = (unsigned *)(si->base + *d);
1827 DEBUG("%5d %s constructors (init_array) found at %p\n",
1828 pid, si->name, si->init_array);
1829 break;
1830 case DT_INIT_ARRAYSZ:
1831 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1832 break;
1833 case DT_FINI_ARRAY:
1834 si->fini_array = (unsigned *)(si->base + *d);
1835 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1836 pid, si->name, si->fini_array);
1837 break;
1838 case DT_FINI_ARRAYSZ:
1839 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1840 break;
1841 case DT_PREINIT_ARRAY:
1842 si->preinit_array = (unsigned *)(si->base + *d);
1843 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1844 pid, si->name, si->preinit_array);
1845 break;
1846 case DT_PREINIT_ARRAYSZ:
1847 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1848 break;
1849 case DT_TEXTREL:
1850 /* TODO: make use of this. */
1851 /* this means that we might have to write into where the text
1852 * segment was loaded during relocation... Do something with
1853 * it.
1854 */
1855 DEBUG("%5d Text segment should be writable during relocation.\n",
1856 pid);
1857 break;
1858 }
1859 }
1860
1861 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1862 pid, si->base, si->strtab, si->symtab);
1863
1864 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001865 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001866 goto fail;
1867 }
1868
1869 for(d = si->dynamic; *d; d += 2) {
1870 if(d[0] == DT_NEEDED){
1871 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001872 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001873 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001874 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001875 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001876 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001877 goto fail;
1878 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001879 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1880 of the DT_NEEDED entry itself, so that we can retrieve the
1881 soinfo directly later from the dynamic segment. This is a hack,
1882 but it allows us to map from DT_NEEDED to soinfo efficiently
1883 later on when we resolve relocations, trying to look up a symgol
1884 with dlsym().
1885 */
1886 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001887 lsi->refcount++;
1888 }
1889 }
1890
1891 if(si->plt_rel) {
1892 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1893 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1894 goto fail;
1895 }
1896 if(si->rel) {
1897 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1898 if(reloc_library(si, si->rel, si->rel_count))
1899 goto fail;
1900 }
1901
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001902#ifdef ANDROID_SH_LINKER
1903 if(si->plt_rela) {
1904 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1905 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1906 goto fail;
1907 }
1908 if(si->rela) {
1909 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1910 if(reloc_library_a(si, si->rela, si->rela_count))
1911 goto fail;
1912 }
1913#endif /* ANDROID_SH_LINKER */
1914
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001915 si->flags |= FLAG_LINKED;
1916 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1917
1918#if 0
1919 /* This is the way that the old dynamic linker did protection of
1920 * non-writable areas. It would scan section headers and find where
1921 * .text ended (rather where .data/.bss began) and assume that this is
1922 * the upper range of the non-writable area. This is too coarse,
1923 * and is kept here for reference until we fully move away from single
1924 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1925 * that made this possible.
1926 */
1927 if(wr_offset < 0xffffffff){
1928 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1929 }
1930#else
1931 /* TODO: Verify that this does the right thing in all cases, as it
1932 * presently probably does not. It is possible that an ELF image will
1933 * come with multiple read-only segments. What we ought to do is scan
1934 * the program headers again and mprotect all the read-only segments.
1935 * To prevent re-scanning the program header, we would have to build a
1936 * list of loadable segments in si, and then scan that instead. */
1937 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1938 mprotect((void *)si->wrprotect_start,
1939 si->wrprotect_end - si->wrprotect_start,
1940 PROT_READ | PROT_EXEC);
1941 }
1942#endif
1943
1944 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1945 stdout and stderr to close a security hole described in:
1946
1947 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1948
1949 */
1950 if (getuid() != geteuid() || getgid() != getegid())
1951 nullify_closed_stdio ();
1952 call_constructors(si);
1953 notify_gdb_of_load(si);
1954 return 0;
1955
1956fail:
1957 ERROR("failed to link %s\n", si->name);
1958 si->flags |= FLAG_ERROR;
1959 return -1;
1960}
1961
David Bartleybc3a5c22009-06-02 18:27:28 -07001962static void parse_library_path(char *path, char *delim)
1963{
1964 size_t len;
1965 char *ldpaths_bufp = ldpaths_buf;
1966 int i = 0;
1967
1968 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1969
1970 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1971 if (*ldpaths[i] != '\0')
1972 ++i;
1973 }
1974
1975 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1976 * last char isn't '\0' (i.e. not originally a delim). */
1977 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1978 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1979 ldpaths[i - 1] = NULL;
1980 } else {
1981 ldpaths[i] = NULL;
1982 }
1983}
1984
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001985int main(int argc, char **argv)
1986{
1987 return 0;
1988}
1989
1990#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1991
1992static void * __tls_area[ANDROID_TLS_SLOTS];
1993
1994unsigned __linker_init(unsigned **elfdata)
1995{
1996 static soinfo linker_soinfo;
1997
1998 int argc = (int) *elfdata;
1999 char **argv = (char**) (elfdata + 1);
2000 unsigned *vecs = (unsigned*) (argv + argc + 1);
2001 soinfo *si;
2002 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07002003 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002004
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002005 /* Setup a temporary TLS area that is used to get a working
2006 * errno for system calls.
2007 */
2008 __set_tls(__tls_area);
2009
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002010 pid = getpid();
2011
2012#if TIMING
2013 struct timeval t0, t1;
2014 gettimeofday(&t0, 0);
2015#endif
2016
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002017 /* NOTE: we store the elfdata pointer on a special location
2018 * of the temporary TLS area in order to pass it to
2019 * the C Library's runtime initializer.
2020 *
2021 * The initializer must clear the slot and reset the TLS
2022 * to point to a different location to ensure that no other
2023 * shared library constructor can access it.
2024 */
2025 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002026
2027 debugger_init();
2028
2029 /* skip past the environment */
2030 while(vecs[0] != 0) {
2031 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
2032 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07002033 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
2034 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002035 }
2036 vecs++;
2037 }
2038 vecs++;
2039
2040 INFO("[ android linker & debugger ]\n");
2041 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2042
2043 si = alloc_info(argv[0]);
2044 if(si == 0) {
2045 exit(-1);
2046 }
2047
2048 /* bootstrap the link map, the main exe always needs to be first */
2049 si->flags |= FLAG_EXE;
2050 map = &(si->linkmap);
2051
2052 map->l_addr = 0;
2053 map->l_name = argv[0];
2054 map->l_prev = NULL;
2055 map->l_next = NULL;
2056
2057 _r_debug.r_map = map;
2058 r_debug_tail = map;
2059
2060 /* gdb expects the linker to be in the debug shared object list,
2061 * and we need to make sure that the reported load address is zero.
2062 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2063 * is. Don't use alloc_info(), because the linker shouldn't
2064 * be on the soinfo list.
2065 */
2066 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
2067 linker_soinfo.flags = 0;
2068 linker_soinfo.base = 0; // This is the important part; must be zero.
2069 insert_soinfo_into_debug_map(&linker_soinfo);
2070
2071 /* extract information passed from the kernel */
2072 while(vecs[0] != 0){
2073 switch(vecs[0]){
2074 case AT_PHDR:
2075 si->phdr = (Elf32_Phdr*) vecs[1];
2076 break;
2077 case AT_PHNUM:
2078 si->phnum = (int) vecs[1];
2079 break;
2080 case AT_ENTRY:
2081 si->entry = vecs[1];
2082 break;
2083 }
2084 vecs += 2;
2085 }
2086
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07002087 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002088
2089 si->base = 0;
2090 si->dynamic = (unsigned *)-1;
2091 si->wrprotect_start = 0xffffffff;
2092 si->wrprotect_end = 0;
2093
David Bartleybc3a5c22009-06-02 18:27:28 -07002094 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
2095 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
2096 parse_library_path(ldpath_env, ":");
2097
Dima Zavin2e855792009-05-20 18:28:09 -07002098 if(link_image(si, 0)) {
2099 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2100 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2101 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002102 exit(-1);
2103 }
2104
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002105#if ALLOW_SYMBOLS_FROM_MAIN
2106 /* Set somain after we've loaded all the libraries in order to prevent
2107 * linking of symbols back to the main image, which is not set up at that
2108 * point yet.
2109 */
2110 somain = si;
2111#endif
2112
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002113#if TIMING
2114 gettimeofday(&t1,NULL);
2115 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2116 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2117 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2118 ));
2119#endif
2120#if STATS
2121 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2122 linker_stats.reloc[RELOC_ABSOLUTE],
2123 linker_stats.reloc[RELOC_RELATIVE],
2124 linker_stats.reloc[RELOC_COPY],
2125 linker_stats.reloc[RELOC_SYMBOL]);
2126#endif
2127#if COUNT_PAGES
2128 {
2129 unsigned n;
2130 unsigned i;
2131 unsigned count = 0;
2132 for(n = 0; n < 4096; n++){
2133 if(bitmask[n]){
2134 unsigned x = bitmask[n];
2135 for(i = 0; i < 8; i++){
2136 if(x & 1) count++;
2137 x >>= 1;
2138 }
2139 }
2140 }
2141 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2142 }
2143#endif
2144
2145#if TIMING || STATS || COUNT_PAGES
2146 fflush(stdout);
2147#endif
2148
2149 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2150 si->entry);
2151 return si->entry;
2152}