blob: 87fb19b59ad0cb9fd5b608e5d3caa03f9ef21952 [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 */
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700515Elf32_Sym *lookup(const char *name, soinfo **found)
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
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800521 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
522 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700523 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800524 continue;
525 s = _do_lookup_in_so(si, name, &elf_hash);
526 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700527 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800528 break;
529 }
530 }
531
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700532 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800533 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
534 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
535 return s;
536 }
537
538 return 0;
539}
540
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600541soinfo *find_containing_library(void *addr)
542{
543 soinfo *si;
544
545 for(si = solist; si != NULL; si = si->next)
546 {
547 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
548 return si;
549 }
550 }
551
552 return NULL;
553}
554
555Elf32_Sym *find_containing_symbol(void *addr, soinfo *si)
556{
557 unsigned int i;
558 unsigned soaddr = (unsigned)addr - si->base;
559
560 /* Search the library's symbol table for any defined symbol which
561 * contains this address */
562 for(i=0; i<si->nchain; i++) {
563 Elf32_Sym *sym = &si->symtab[i];
564
565 if(sym->st_shndx != SHN_UNDEF &&
566 soaddr >= sym->st_value &&
567 soaddr < sym->st_value + sym->st_size) {
568 return sym;
569 }
570 }
571
572 return NULL;
573}
574
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800575#if 0
576static void dump(soinfo *si)
577{
578 Elf32_Sym *s = si->symtab;
579 unsigned n;
580
581 for(n = 0; n < si->nchain; n++) {
582 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
583 s->st_info, s->st_shndx, s->st_value, s->st_size,
584 si->strtab + s->st_name);
585 s++;
586 }
587}
588#endif
589
590static const char *sopaths[] = {
591 "/system/lib",
592 "/lib",
593 0
594};
595
596static int _open_lib(const char *name)
597{
598 int fd;
599 struct stat filestat;
600
601 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
602 if ((fd = open(name, O_RDONLY)) >= 0)
603 return fd;
604 }
605
606 return -1;
607}
608
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800609static int open_library(const char *name)
610{
611 int fd;
612 char buf[512];
613 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700614 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800615
616 TRACE("[ %5d opening %s ]\n", pid, name);
617
618 if(name == 0) return -1;
619 if(strlen(name) > 256) return -1;
620
621 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
622 return fd;
623
David Bartleybc3a5c22009-06-02 18:27:28 -0700624 for (path = ldpaths; *path; path++) {
625 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
626 if (n < 0 || n >= (int)sizeof(buf)) {
627 WARN("Ignoring very long library path: %s/%s\n", *path, name);
628 continue;
629 }
630 if ((fd = _open_lib(buf)) >= 0)
631 return fd;
632 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800633 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700634 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
635 if (n < 0 || n >= (int)sizeof(buf)) {
636 WARN("Ignoring very long library path: %s/%s\n", *path, name);
637 continue;
638 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800639 if ((fd = _open_lib(buf)) >= 0)
640 return fd;
641 }
642
643 return -1;
644}
645
646/* temporary space for holding the first page of the shared lib
647 * which contains the elf header (with the pht). */
648static unsigned char __header[PAGE_SIZE];
649
650typedef struct {
651 long mmap_addr;
652 char tag[4]; /* 'P', 'R', 'E', ' ' */
653} prelink_info_t;
654
655/* Returns the requested base address if the library is prelinked,
656 * and 0 otherwise. */
657static unsigned long
658is_prelinked(int fd, const char *name)
659{
660 off_t sz;
661 prelink_info_t info;
662
663 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
664 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700665 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800666 return 0;
667 }
668
669 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
670 WARN("Could not read prelink_info_t structure for `%s`\n", name);
671 return 0;
672 }
673
674 if (strncmp(info.tag, "PRE ", 4)) {
675 WARN("`%s` is not a prelinked library\n", name);
676 return 0;
677 }
678
679 return (unsigned long)info.mmap_addr;
680}
681
682/* verify_elf_object
683 * Verifies if the object @ base is a valid ELF object
684 *
685 * Args:
686 *
687 * Returns:
688 * 0 on success
689 * -1 if no valid ELF object is found @ base.
690 */
691static int
692verify_elf_object(void *base, const char *name)
693{
694 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
695
696 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
697 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
698 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
699 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
700
701 /* TODO: Should we verify anything else in the header? */
702
703 return 0;
704}
705
706
707/* get_lib_extents
708 * Retrieves the base (*base) address where the ELF object should be
709 * mapped and its overall memory size (*total_sz).
710 *
711 * Args:
712 * fd: Opened file descriptor for the library
713 * name: The name of the library
714 * _hdr: Pointer to the header page of the library
715 * total_sz: Total size of the memory that should be allocated for
716 * this library
717 *
718 * Returns:
719 * -1 if there was an error while trying to get the lib extents.
720 * The possible reasons are:
721 * - Could not determine if the library was prelinked.
722 * - The library provided is not a valid ELF object
723 * 0 if the library did not request a specific base offset (normal
724 * for non-prelinked libs)
725 * > 0 if the library requests a specific address to be mapped to.
726 * This indicates a pre-linked library.
727 */
728static unsigned
729get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
730{
731 unsigned req_base;
732 unsigned min_vaddr = 0xffffffff;
733 unsigned max_vaddr = 0;
734 unsigned char *_hdr = (unsigned char *)__hdr;
735 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
736 Elf32_Phdr *phdr;
737 int cnt;
738
739 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
740 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700741 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800742 return (unsigned)-1;
743 }
744
745 req_base = (unsigned) is_prelinked(fd, name);
746 if (req_base == (unsigned)-1)
747 return -1;
748 else if (req_base != 0) {
749 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
750 pid, name, req_base);
751 } else {
752 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
753 }
754
755 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
756
757 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
758 * get the range. */
759 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
760 if (phdr->p_type == PT_LOAD) {
761 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
762 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
763 if (phdr->p_vaddr < min_vaddr)
764 min_vaddr = phdr->p_vaddr;
765 }
766 }
767
768 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700769 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800770 return (unsigned)-1;
771 }
772
773 /* truncate min_vaddr down to page boundary */
774 min_vaddr &= ~PAGE_MASK;
775
776 /* round max_vaddr up to the next page */
777 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
778
779 *total_sz = (max_vaddr - min_vaddr);
780 return (unsigned)req_base;
781}
782
783/* alloc_mem_region
784 *
785 * This function reserves a chunk of memory to be used for mapping in
786 * the shared library. We reserve the entire memory region here, and
787 * then the rest of the linker will relocate the individual loadable
788 * segments into the correct locations within this memory range.
789 *
790 * Args:
791 * si->base: The requested base of the allocation. If 0, a sane one will be
792 * chosen in the range LIBBASE <= base < LIBLAST.
793 * si->size: The size of the allocation.
794 *
795 * Returns:
796 * -1 on failure, and 0 on success. On success, si->base will contain
797 * the virtual address at which the library will be mapped.
798 */
799
800static int reserve_mem_region(soinfo *si)
801{
802 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
803 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
804 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700805 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700806 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800807 pid, (si->base ? "" : "non-"), si->name, si->base,
808 errno, strerror(errno));
809 return -1;
810 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700811 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700812 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800813 si->name, (unsigned)base, si->base);
814 munmap(base, si->size);
815 return -1;
816 }
817 return 0;
818}
819
820static int
821alloc_mem_region(soinfo *si)
822{
823 if (si->base) {
824 /* Attempt to mmap a prelinked library. */
825 si->ba_index = -1;
826 return reserve_mem_region(si);
827 }
828
829 /* This is not a prelinked library, so we attempt to allocate space
830 for it from the buddy allocator, which manages the area between
831 LIBBASE and LIBLAST.
832 */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700833 si->ba_index = ba_allocate(&ba_prelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800834 if(si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700835 si->base = ba_start_addr(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800836 PRINT("%5d mapping library '%s' at %08x (index %d) " \
837 "through buddy allocator.\n",
838 pid, si->name, si->base, si->ba_index);
839 if (reserve_mem_region(si) < 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700840 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800841 si->ba_index = -1;
842 si->base = 0;
843 goto err;
844 }
845 return 0;
846 }
847
848err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700849 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800850 pid, si->name);
851 return -1;
852}
853
854#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
855#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
856 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
857 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
858/* load_segments
859 *
860 * This function loads all the loadable (PT_LOAD) segments into memory
861 * at their appropriate memory offsets off the base address.
862 *
863 * Args:
864 * fd: Open file descriptor to the library to load.
865 * header: Pointer to a header page that contains the ELF header.
866 * This is needed since we haven't mapped in the real file yet.
867 * si: ptr to soinfo struct describing the shared object.
868 *
869 * Returns:
870 * 0 on success, -1 on failure.
871 */
872static int
873load_segments(int fd, void *header, soinfo *si)
874{
875 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
876 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
877 unsigned char *base = (unsigned char *)si->base;
878 int cnt;
879 unsigned len;
880 unsigned char *tmp;
881 unsigned char *pbase;
882 unsigned char *extra_base;
883 unsigned extra_len;
884 unsigned total_sz = 0;
885
886 si->wrprotect_start = 0xffffffff;
887 si->wrprotect_end = 0;
888
889 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
890 pid, si->name, (unsigned)si->base);
891 /* Now go through all the PT_LOAD segments and map them into memory
892 * at the appropriate locations. */
893 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
894 if (phdr->p_type == PT_LOAD) {
895 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
896 /* we want to map in the segment on a page boundary */
897 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
898 /* add the # of bytes we masked off above to the total length. */
899 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
900
901 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
902 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
903 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
904 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
905 MAP_PRIVATE | MAP_FIXED, fd,
906 phdr->p_offset & (~PAGE_MASK));
907 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700908 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700909 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800910 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
911 goto fail;
912 }
913
914 /* If 'len' didn't end on page boundary, and it's a writable
915 * segment, zero-fill the rest. */
916 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
917 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
918
919 /* Check to see if we need to extend the map for this segment to
920 * cover the diff between filesz and memsz (i.e. for bss).
921 *
922 * base _+---------------------+ page boundary
923 * . .
924 * | |
925 * . .
926 * pbase _+---------------------+ page boundary
927 * | |
928 * . .
929 * base + p_vaddr _| |
930 * . \ \ .
931 * . | filesz | .
932 * pbase + len _| / | |
933 * <0 pad> . . .
934 * extra_base _+------------|--------+ page boundary
935 * / . . .
936 * | . . .
937 * | +------------|--------+ page boundary
938 * extra_len-> | | | |
939 * | . | memsz .
940 * | . | .
941 * \ _| / |
942 * . .
943 * | |
944 * _+---------------------+ page boundary
945 */
946 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
947 (~PAGE_MASK));
948 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
949 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
950 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
951 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
952 /* map in the extra page(s) as anonymous into the range.
953 * This is probably not necessary as we already mapped in
954 * the entire region previously, but we just want to be
955 * sure. This will also set the right flags on the region
956 * (though we can probably accomplish the same thing with
957 * mprotect).
958 */
959 extra_base = mmap((void *)tmp, extra_len,
960 PFLAGS_TO_PROT(phdr->p_flags),
961 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
962 -1, 0);
963 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700964 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700965 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800966 extra_len);
967 goto fail;
968 }
969 /* TODO: Check if we need to memset-0 this region.
970 * Anonymous mappings are zero-filled copy-on-writes, so we
971 * shouldn't need to. */
972 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
973 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
974 extra_len);
975 }
976 /* set the len here to show the full extent of the segment we
977 * just loaded, mostly for debugging */
978 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
979 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
980 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
981 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
982 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
983 total_sz += len;
984 /* Make the section writable just in case we'll have to write to
985 * it during relocation (i.e. text segment). However, we will
986 * remember what range of addresses should be write protected.
987 *
988 */
989 if (!(phdr->p_flags & PF_W)) {
990 if ((unsigned)pbase < si->wrprotect_start)
991 si->wrprotect_start = (unsigned)pbase;
992 if (((unsigned)pbase + len) > si->wrprotect_end)
993 si->wrprotect_end = (unsigned)pbase + len;
994 mprotect(pbase, len,
995 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
996 }
997 } else if (phdr->p_type == PT_DYNAMIC) {
998 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
999 /* this segment contains the dynamic linking information */
1000 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
1001 } else {
1002#ifdef ANDROID_ARM_LINKER
1003 if (phdr->p_type == PT_ARM_EXIDX) {
1004 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1005 /* exidx entries (used for stack unwinding) are 8 bytes each.
1006 */
1007 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1008 si->ARM_exidx_count = phdr->p_memsz / 8;
1009 }
1010#endif
1011 }
1012
1013 }
1014
1015 /* Sanity check */
1016 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001017 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001018 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001019 pid, total_sz, si->name, si->size);
1020 goto fail;
1021 }
1022
1023 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1024 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1025 (unsigned)si->base, si->size);
1026 return 0;
1027
1028fail:
1029 /* We can just blindly unmap the entire region even though some things
1030 * were mapped in originally with anonymous and others could have been
1031 * been mapped in from the file before we failed. The kernel will unmap
1032 * all the pages in the range, irrespective of how they got there.
1033 */
1034 munmap((void *)si->base, si->size);
1035 si->flags |= FLAG_ERROR;
1036 return -1;
1037}
1038
1039/* TODO: Implement this to take care of the fact that Android ARM
1040 * ELF objects shove everything into a single loadable segment that has the
1041 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1042 * non-writable.
1043 */
1044#if 0
1045static unsigned
1046get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1047{
1048 Elf32_Shdr *shdr_start;
1049 Elf32_Shdr *shdr;
1050 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1051 int cnt;
1052 unsigned wr_offset = 0xffffffff;
1053
1054 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1055 ehdr->e_shoff & (~PAGE_MASK));
1056 if (shdr_start == MAP_FAILED) {
1057 WARN("%5d - Could not read section header info from '%s'. Will not "
1058 "not be able to determine write-protect offset.\n", pid, name);
1059 return (unsigned)-1;
1060 }
1061
1062 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1063 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1064 (shdr->sh_addr < wr_offset)) {
1065 wr_offset = shdr->sh_addr;
1066 }
1067 }
1068
1069 munmap(shdr_start, shdr_sz);
1070 return wr_offset;
1071}
1072#endif
1073
1074static soinfo *
1075load_library(const char *name)
1076{
1077 int fd = open_library(name);
1078 int cnt;
1079 unsigned ext_sz;
1080 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001081 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001082 soinfo *si = NULL;
1083 Elf32_Ehdr *hdr;
1084
Dima Zavin2e855792009-05-20 18:28:09 -07001085 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001086 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001087 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001088 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001089
1090 /* We have to read the ELF header to figure out what to do with this image
1091 */
1092 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001093 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001094 goto fail;
1095 }
1096
1097 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001098 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001099 goto fail;
1100 }
1101
1102 /* Parse the ELF header and get the size of the memory footprint for
1103 * the library */
1104 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1105 if (req_base == (unsigned)-1)
1106 goto fail;
1107 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1108 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1109
1110 /* Now configure the soinfo struct where we'll store all of our data
1111 * for the ELF object. If the loading fails, we waste the entry, but
1112 * same thing would happen if we failed during linking. Configuring the
1113 * soinfo struct here is a lot more convenient.
1114 */
Erik Gillingfde86422009-07-28 20:28:19 -07001115 bname = strrchr(name, '/');
1116 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001117 if (si == NULL)
1118 goto fail;
1119
1120 /* Carve out a chunk of memory where we will map in the individual
1121 * segments */
1122 si->base = req_base;
1123 si->size = ext_sz;
1124 si->flags = 0;
1125 si->entry = 0;
1126 si->dynamic = (unsigned *)-1;
1127 if (alloc_mem_region(si) < 0)
1128 goto fail;
1129
1130 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1131 pid, name, (void *)si->base, (unsigned) ext_sz);
1132
1133 /* Now actually load the library's segments into right places in memory */
1134 if (load_segments(fd, &__header[0], si) < 0) {
1135 if (si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001136 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001137 si->ba_index = -1;
1138 }
1139 goto fail;
1140 }
1141
1142 /* this might not be right. Technically, we don't even need this info
1143 * once we go through 'load_segments'. */
1144 hdr = (Elf32_Ehdr *)si->base;
1145 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1146 si->phnum = hdr->e_phnum;
1147 /**/
1148
1149 close(fd);
1150 return si;
1151
1152fail:
1153 if (si) free_info(si);
1154 close(fd);
1155 return NULL;
1156}
1157
1158static soinfo *
1159init_library(soinfo *si)
1160{
1161 unsigned wr_offset = 0xffffffff;
1162
1163 /* At this point we know that whatever is loaded @ base is a valid ELF
1164 * shared library whose segments are properly mapped in. */
1165 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1166 pid, si->base, si->size, si->name);
1167
1168 if (si->base < LIBBASE || si->base >= LIBLAST)
1169 si->flags |= FLAG_PRELINKED;
1170
1171 if(link_image(si, wr_offset)) {
1172 /* We failed to link. However, we can only restore libbase
1173 ** if no additional libraries have moved it since we updated it.
1174 */
1175 munmap((void *)si->base, si->size);
1176 return NULL;
1177 }
1178
1179 return si;
1180}
1181
1182soinfo *find_library(const char *name)
1183{
1184 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001185 const char *bname = strrchr(name, '/');
1186 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001187
1188 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001189 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001190 if(si->flags & FLAG_ERROR) {
1191 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1192 return NULL;
1193 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001194 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001195 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001196 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001197 }
1198 }
1199
1200 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1201 si = load_library(name);
1202 if(si == NULL)
1203 return NULL;
1204 return init_library(si);
1205}
1206
1207/* TODO:
1208 * notify gdb of unload
1209 * for non-prelinked libraries, find a way to decrement libbase
1210 */
1211static void call_destructors(soinfo *si);
1212unsigned unload_library(soinfo *si)
1213{
1214 unsigned *d;
1215 if (si->refcount == 1) {
1216 TRACE("%5d unloading '%s'\n", pid, si->name);
1217 call_destructors(si);
1218
1219 for(d = si->dynamic; *d; d += 2) {
1220 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001221 soinfo *lsi = (soinfo *)d[1];
1222 d[1] = 0;
1223 if (validate_soinfo(lsi)) {
1224 TRACE("%5d %s needs to unload %s\n", pid,
1225 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001226 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001227 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001228 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001229 DL_ERR("%5d %s: could not unload dependent library",
1230 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001231 }
1232 }
1233
1234 munmap((char *)si->base, si->size);
1235 if (si->ba_index >= 0) {
1236 PRINT("%5d releasing library '%s' address space at %08x "\
1237 "through buddy allocator.\n",
1238 pid, si->name, si->base);
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001239 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001241 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001242 free_info(si);
1243 si->refcount = 0;
1244 }
1245 else {
1246 si->refcount--;
1247 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1248 pid, si->name, si->refcount);
1249 }
1250 return si->refcount;
1251}
1252
1253/* TODO: don't use unsigned for addrs below. It works, but is not
1254 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1255 * long.
1256 */
1257static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1258{
1259 Elf32_Sym *symtab = si->symtab;
1260 const char *strtab = si->strtab;
1261 Elf32_Sym *s;
1262 unsigned base;
1263 Elf32_Rel *start = rel;
1264 unsigned idx;
1265
1266 for (idx = 0; idx < count; ++idx) {
1267 unsigned type = ELF32_R_TYPE(rel->r_info);
1268 unsigned sym = ELF32_R_SYM(rel->r_info);
1269 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1270 unsigned sym_addr = 0;
1271 char *sym_name = NULL;
1272
1273 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1274 si->name, idx);
1275 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001276 sym_name = (char *)(strtab + symtab[sym].st_name);
1277 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001278 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001279 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001280 return -1;
1281 }
1282#if 0
1283 if((base == 0) && (si->base != 0)){
1284 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001285 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001286 pid, strtab + symtab[sym].st_name);
1287 return -1;
1288 }
1289#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001290 // st_shndx==SHN_UNDEF means an undefined symbol.
1291 // st_value should be 0 then, except that the low bit of st_value is
1292 // used to indicate whether the symbol points to an ARM or thumb function,
1293 // and should be ignored in the following check.
1294 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1295 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1296 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001297 s->st_value);
1298 return -1;
1299 }
1300 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001301 COUNT_RELOC(RELOC_SYMBOL);
1302 } else {
1303 s = 0;
1304 }
1305
1306/* TODO: This is ugly. Split up the relocations by arch into
1307 * different files.
1308 */
1309 switch(type){
1310#if defined(ANDROID_ARM_LINKER)
1311 case R_ARM_JUMP_SLOT:
1312 COUNT_RELOC(RELOC_ABSOLUTE);
1313 MARK(rel->r_offset);
1314 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1315 reloc, sym_addr, sym_name);
1316 *((unsigned*)reloc) = sym_addr;
1317 break;
1318 case R_ARM_GLOB_DAT:
1319 COUNT_RELOC(RELOC_ABSOLUTE);
1320 MARK(rel->r_offset);
1321 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1322 reloc, sym_addr, sym_name);
1323 *((unsigned*)reloc) = sym_addr;
1324 break;
1325 case R_ARM_ABS32:
1326 COUNT_RELOC(RELOC_ABSOLUTE);
1327 MARK(rel->r_offset);
1328 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1329 reloc, sym_addr, sym_name);
1330 *((unsigned*)reloc) += sym_addr;
1331 break;
David 'Digit' Turnerfe62de12009-12-02 10:54:53 -08001332 case R_ARM_REL32:
1333 COUNT_RELOC(RELOC_RELATIVE);
1334 MARK(rel->r_offset);
1335 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1336 reloc, sym_addr, rel->r_offset, sym_name);
1337 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1338 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001339#elif defined(ANDROID_X86_LINKER)
1340 case R_386_JUMP_SLOT:
1341 COUNT_RELOC(RELOC_ABSOLUTE);
1342 MARK(rel->r_offset);
1343 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1344 reloc, sym_addr, sym_name);
1345 *((unsigned*)reloc) = sym_addr;
1346 break;
1347 case R_386_GLOB_DAT:
1348 COUNT_RELOC(RELOC_ABSOLUTE);
1349 MARK(rel->r_offset);
1350 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1351 reloc, sym_addr, sym_name);
1352 *((unsigned*)reloc) = sym_addr;
1353 break;
1354#endif /* ANDROID_*_LINKER */
1355
1356#if defined(ANDROID_ARM_LINKER)
1357 case R_ARM_RELATIVE:
1358#elif defined(ANDROID_X86_LINKER)
1359 case R_386_RELATIVE:
1360#endif /* ANDROID_*_LINKER */
1361 COUNT_RELOC(RELOC_RELATIVE);
1362 MARK(rel->r_offset);
1363 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001364 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365 return -1;
1366 }
1367 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1368 reloc, si->base);
1369 *((unsigned*)reloc) += si->base;
1370 break;
1371
1372#if defined(ANDROID_X86_LINKER)
1373 case R_386_32:
1374 COUNT_RELOC(RELOC_RELATIVE);
1375 MARK(rel->r_offset);
1376
1377 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1378 reloc, sym_addr, sym_name);
1379 *((unsigned *)reloc) += (unsigned)sym_addr;
1380 break;
1381
1382 case R_386_PC32:
1383 COUNT_RELOC(RELOC_RELATIVE);
1384 MARK(rel->r_offset);
1385 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1386 "+%08x (%08x - %08x) %s\n", pid, reloc,
1387 (sym_addr - reloc), sym_addr, reloc, sym_name);
1388 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1389 break;
1390#endif /* ANDROID_X86_LINKER */
1391
1392#ifdef ANDROID_ARM_LINKER
1393 case R_ARM_COPY:
1394 COUNT_RELOC(RELOC_COPY);
1395 MARK(rel->r_offset);
1396 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1397 reloc, s->st_size, sym_addr, sym_name);
1398 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1399 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001400 case R_ARM_NONE:
1401 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402#endif /* ANDROID_ARM_LINKER */
1403
1404 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001405 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 pid, type, rel, (int) (rel - start));
1407 return -1;
1408 }
1409 rel++;
1410 }
1411 return 0;
1412}
1413
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001414#if defined(ANDROID_SH_LINKER)
1415static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1416{
1417 Elf32_Sym *symtab = si->symtab;
1418 const char *strtab = si->strtab;
1419 Elf32_Sym *s;
1420 unsigned base;
1421 Elf32_Rela *start = rela;
1422 unsigned idx;
1423
1424 for (idx = 0; idx < count; ++idx) {
1425 unsigned type = ELF32_R_TYPE(rela->r_info);
1426 unsigned sym = ELF32_R_SYM(rela->r_info);
1427 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1428 unsigned sym_addr = 0;
1429 char *sym_name = NULL;
1430
1431 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1432 si->name, idx);
1433 if(sym != 0) {
1434 sym_name = (char *)(strtab + symtab[sym].st_name);
1435 s = _do_lookup(si, sym_name, &base);
1436 if(s == 0) {
1437 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1438 return -1;
1439 }
1440#if 0
1441 if((base == 0) && (si->base != 0)){
1442 /* linking from libraries to main image is bad */
1443 DL_ERR("%5d cannot locate '%s'...",
1444 pid, strtab + symtab[sym].st_name);
1445 return -1;
1446 }
1447#endif
1448 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1449 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1450 "handle this yet", pid, si->name, s->st_shndx,
1451 s->st_value);
1452 return -1;
1453 }
1454 sym_addr = (unsigned)(s->st_value + base);
1455 COUNT_RELOC(RELOC_SYMBOL);
1456 } else {
1457 s = 0;
1458 }
1459
1460/* TODO: This is ugly. Split up the relocations by arch into
1461 * different files.
1462 */
1463 switch(type){
1464 case R_SH_JUMP_SLOT:
1465 COUNT_RELOC(RELOC_ABSOLUTE);
1466 MARK(rela->r_offset);
1467 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1468 reloc, sym_addr, sym_name);
1469 *((unsigned*)reloc) = sym_addr;
1470 break;
1471 case R_SH_GLOB_DAT:
1472 COUNT_RELOC(RELOC_ABSOLUTE);
1473 MARK(rela->r_offset);
1474 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1475 reloc, sym_addr, sym_name);
1476 *((unsigned*)reloc) = sym_addr;
1477 break;
1478 case R_SH_DIR32:
1479 COUNT_RELOC(RELOC_ABSOLUTE);
1480 MARK(rela->r_offset);
1481 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1482 reloc, sym_addr, sym_name);
1483 *((unsigned*)reloc) += sym_addr;
1484 break;
1485 case R_SH_RELATIVE:
1486 COUNT_RELOC(RELOC_RELATIVE);
1487 MARK(rela->r_offset);
1488 if(sym){
1489 DL_ERR("%5d odd RELATIVE form...", pid);
1490 return -1;
1491 }
1492 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1493 reloc, si->base);
1494 *((unsigned*)reloc) += si->base;
1495 break;
1496
1497 default:
1498 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1499 pid, type, rela, (int) (rela - start));
1500 return -1;
1501 }
1502 rela++;
1503 }
1504 return 0;
1505}
1506#endif /* ANDROID_SH_LINKER */
1507
David 'Digit' Turner82156792009-05-18 14:37:41 +02001508
1509/* Please read the "Initialization and Termination functions" functions.
1510 * of the linker design note in bionic/linker/README.TXT to understand
1511 * what the following code is doing.
1512 *
1513 * The important things to remember are:
1514 *
1515 * DT_PREINIT_ARRAY must be called first for executables, and should
1516 * not appear in shared libraries.
1517 *
1518 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1519 *
1520 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1521 *
1522 * DT_FINI_ARRAY must be parsed in reverse order.
1523 */
1524
1525static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001526{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001527 int n, inc = 1;
1528
1529 if (reverse) {
1530 ctor += (count-1);
1531 inc = -1;
1532 }
1533
1534 for(n = count; n > 0; n--) {
1535 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1536 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001537 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001538 void (*func)() = (void (*)()) *ctor;
1539 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001540 if(((int) func == 0) || ((int) func == -1)) continue;
1541 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1542 func();
1543 }
1544}
1545
1546static void call_constructors(soinfo *si)
1547{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001548 if (si->flags & FLAG_EXE) {
1549 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1550 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1551 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001552 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001553 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1554 } else {
1555 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001556 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001557 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001558 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001559 }
1560 }
1561
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001562 if (si->init_func) {
1563 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1564 (unsigned)si->init_func, si->name);
1565 si->init_func();
1566 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1567 }
1568
1569 if (si->init_array) {
1570 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1571 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001572 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001573 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1574 }
1575}
1576
David 'Digit' Turner82156792009-05-18 14:37:41 +02001577
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001578static void call_destructors(soinfo *si)
1579{
1580 if (si->fini_array) {
1581 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1582 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001583 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001584 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1585 }
1586
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001587 if (si->fini_func) {
1588 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1589 (unsigned)si->fini_func, si->name);
1590 si->fini_func();
1591 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1592 }
1593}
1594
1595/* Force any of the closed stdin, stdout and stderr to be associated with
1596 /dev/null. */
1597static int nullify_closed_stdio (void)
1598{
1599 int dev_null, i, status;
1600 int return_value = 0;
1601
1602 dev_null = open("/dev/null", O_RDWR);
1603 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001604 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001605 return -1;
1606 }
1607 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1608
1609 /* If any of the stdio file descriptors is valid and not associated
1610 with /dev/null, dup /dev/null to it. */
1611 for (i = 0; i < 3; i++) {
1612 /* If it is /dev/null already, we are done. */
1613 if (i == dev_null)
1614 continue;
1615
1616 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1617 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1618 can be interrupted but we do this just to be safe. */
1619 do {
1620 status = fcntl(i, F_GETFL);
1621 } while (status < 0 && errno == EINTR);
1622
1623 /* If file is openned, we are good. */
1624 if (status >= 0)
1625 continue;
1626
1627 /* The only error we allow is that the file descriptor does not
1628 exist, in which case we dup /dev/null to it. */
1629 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001630 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001631 return_value = -1;
1632 continue;
1633 }
1634
1635 /* Try dupping /dev/null to this stdio file descriptor and
1636 repeat if there is a signal. Note that any errors in closing
1637 the stdio descriptor are lost. */
1638 do {
1639 status = dup2(dev_null, i);
1640 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001641
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001642 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001643 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001644 return_value = -1;
1645 continue;
1646 }
1647 }
1648
1649 /* If /dev/null is not one of the stdio file descriptors, close it. */
1650 if (dev_null > 2) {
1651 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001652 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001653 status = close(dev_null);
1654 } while (status < 0 && errno == EINTR);
1655
1656 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001657 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001658 return_value = -1;
1659 }
1660 }
1661
1662 return return_value;
1663}
1664
1665static int link_image(soinfo *si, unsigned wr_offset)
1666{
1667 unsigned *d;
1668 Elf32_Phdr *phdr = si->phdr;
1669 int phnum = si->phnum;
1670
1671 INFO("[ %5d linking %s ]\n", pid, si->name);
1672 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1673 si->base, si->flags);
1674
1675 if (si->flags & FLAG_EXE) {
1676 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1677 * linkage info if this is the executable. If this was a
1678 * dynamic lib, that would have been done at load time.
1679 *
1680 * TODO: It's unfortunate that small pieces of this are
1681 * repeated from the load_library routine. Refactor this just
1682 * slightly to reuse these bits.
1683 */
1684 si->size = 0;
1685 for(; phnum > 0; --phnum, ++phdr) {
1686#ifdef ANDROID_ARM_LINKER
1687 if(phdr->p_type == PT_ARM_EXIDX) {
1688 /* exidx entries (used for stack unwinding) are 8 bytes each.
1689 */
1690 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1691 si->ARM_exidx_count = phdr->p_memsz / 8;
1692 }
1693#endif
1694 if (phdr->p_type == PT_LOAD) {
1695 /* For the executable, we use the si->size field only in
1696 dl_unwind_find_exidx(), so the meaning of si->size
1697 is not the size of the executable; it is the last
1698 virtual address of the loadable part of the executable;
1699 since si->base == 0 for an executable, we use the
1700 range [0, si->size) to determine whether a PC value
1701 falls within the executable section. Of course, if
1702 a value is below phdr->p_vaddr, it's not in the
1703 executable section, but a) we shouldn't be asking for
1704 such a value anyway, and b) if we have to provide
1705 an EXIDX for such a value, then the executable's
1706 EXIDX is probably the better choice.
1707 */
1708 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1709 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1710 si->size = phdr->p_vaddr + phdr->p_memsz;
1711 /* try to remember what range of addresses should be write
1712 * protected */
1713 if (!(phdr->p_flags & PF_W)) {
1714 unsigned _end;
1715
1716 if (phdr->p_vaddr < si->wrprotect_start)
1717 si->wrprotect_start = phdr->p_vaddr;
1718 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1719 (~PAGE_MASK)));
1720 if (_end > si->wrprotect_end)
1721 si->wrprotect_end = _end;
1722 }
1723 } else if (phdr->p_type == PT_DYNAMIC) {
1724 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001725 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001726 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001727 pid, si->name, si->base + phdr->p_vaddr,
1728 (unsigned)si->dynamic);
1729 goto fail;
1730 }
1731 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1732 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1733 }
1734 }
1735 }
1736
1737 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001738 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001739 goto fail;
1740 }
1741
1742 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1743
1744 /* extract useful information from dynamic section */
1745 for(d = si->dynamic; *d; d++){
1746 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1747 switch(*d++){
1748 case DT_HASH:
1749 si->nbucket = ((unsigned *) (si->base + *d))[0];
1750 si->nchain = ((unsigned *) (si->base + *d))[1];
1751 si->bucket = (unsigned *) (si->base + *d + 8);
1752 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1753 break;
1754 case DT_STRTAB:
1755 si->strtab = (const char *) (si->base + *d);
1756 break;
1757 case DT_SYMTAB:
1758 si->symtab = (Elf32_Sym *) (si->base + *d);
1759 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001760#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001761 case DT_PLTREL:
1762 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001763 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001764 goto fail;
1765 }
1766 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001767#endif
1768#ifdef ANDROID_SH_LINKER
1769 case DT_JMPREL:
1770 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1771 break;
1772 case DT_PLTRELSZ:
1773 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1774 break;
1775#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001776 case DT_JMPREL:
1777 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1778 break;
1779 case DT_PLTRELSZ:
1780 si->plt_rel_count = *d / 8;
1781 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001782#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001783 case DT_REL:
1784 si->rel = (Elf32_Rel*) (si->base + *d);
1785 break;
1786 case DT_RELSZ:
1787 si->rel_count = *d / 8;
1788 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001789#ifdef ANDROID_SH_LINKER
1790 case DT_RELASZ:
1791 si->rela_count = *d / sizeof(Elf32_Rela);
1792 break;
1793#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001794 case DT_PLTGOT:
1795 /* Save this in case we decide to do lazy binding. We don't yet. */
1796 si->plt_got = (unsigned *)(si->base + *d);
1797 break;
1798 case DT_DEBUG:
1799 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1800 *d = (int) &_r_debug;
1801 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001802#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001803 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001804 si->rela = (Elf32_Rela *) (si->base + *d);
1805 break;
1806#else
1807 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001808 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001809 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001810#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001811 case DT_INIT:
1812 si->init_func = (void (*)(void))(si->base + *d);
1813 DEBUG("%5d %s constructors (init func) found at %p\n",
1814 pid, si->name, si->init_func);
1815 break;
1816 case DT_FINI:
1817 si->fini_func = (void (*)(void))(si->base + *d);
1818 DEBUG("%5d %s destructors (fini func) found at %p\n",
1819 pid, si->name, si->fini_func);
1820 break;
1821 case DT_INIT_ARRAY:
1822 si->init_array = (unsigned *)(si->base + *d);
1823 DEBUG("%5d %s constructors (init_array) found at %p\n",
1824 pid, si->name, si->init_array);
1825 break;
1826 case DT_INIT_ARRAYSZ:
1827 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1828 break;
1829 case DT_FINI_ARRAY:
1830 si->fini_array = (unsigned *)(si->base + *d);
1831 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1832 pid, si->name, si->fini_array);
1833 break;
1834 case DT_FINI_ARRAYSZ:
1835 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1836 break;
1837 case DT_PREINIT_ARRAY:
1838 si->preinit_array = (unsigned *)(si->base + *d);
1839 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1840 pid, si->name, si->preinit_array);
1841 break;
1842 case DT_PREINIT_ARRAYSZ:
1843 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1844 break;
1845 case DT_TEXTREL:
1846 /* TODO: make use of this. */
1847 /* this means that we might have to write into where the text
1848 * segment was loaded during relocation... Do something with
1849 * it.
1850 */
1851 DEBUG("%5d Text segment should be writable during relocation.\n",
1852 pid);
1853 break;
1854 }
1855 }
1856
1857 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1858 pid, si->base, si->strtab, si->symtab);
1859
1860 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001861 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001862 goto fail;
1863 }
1864
1865 for(d = si->dynamic; *d; d += 2) {
1866 if(d[0] == DT_NEEDED){
1867 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001868 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001869 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001870 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001871 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001872 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001873 goto fail;
1874 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001875 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1876 of the DT_NEEDED entry itself, so that we can retrieve the
1877 soinfo directly later from the dynamic segment. This is a hack,
1878 but it allows us to map from DT_NEEDED to soinfo efficiently
1879 later on when we resolve relocations, trying to look up a symgol
1880 with dlsym().
1881 */
1882 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001883 lsi->refcount++;
1884 }
1885 }
1886
1887 if(si->plt_rel) {
1888 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1889 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1890 goto fail;
1891 }
1892 if(si->rel) {
1893 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1894 if(reloc_library(si, si->rel, si->rel_count))
1895 goto fail;
1896 }
1897
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001898#ifdef ANDROID_SH_LINKER
1899 if(si->plt_rela) {
1900 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1901 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1902 goto fail;
1903 }
1904 if(si->rela) {
1905 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1906 if(reloc_library_a(si, si->rela, si->rela_count))
1907 goto fail;
1908 }
1909#endif /* ANDROID_SH_LINKER */
1910
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001911 si->flags |= FLAG_LINKED;
1912 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1913
1914#if 0
1915 /* This is the way that the old dynamic linker did protection of
1916 * non-writable areas. It would scan section headers and find where
1917 * .text ended (rather where .data/.bss began) and assume that this is
1918 * the upper range of the non-writable area. This is too coarse,
1919 * and is kept here for reference until we fully move away from single
1920 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1921 * that made this possible.
1922 */
1923 if(wr_offset < 0xffffffff){
1924 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1925 }
1926#else
1927 /* TODO: Verify that this does the right thing in all cases, as it
1928 * presently probably does not. It is possible that an ELF image will
1929 * come with multiple read-only segments. What we ought to do is scan
1930 * the program headers again and mprotect all the read-only segments.
1931 * To prevent re-scanning the program header, we would have to build a
1932 * list of loadable segments in si, and then scan that instead. */
1933 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1934 mprotect((void *)si->wrprotect_start,
1935 si->wrprotect_end - si->wrprotect_start,
1936 PROT_READ | PROT_EXEC);
1937 }
1938#endif
1939
1940 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1941 stdout and stderr to close a security hole described in:
1942
1943 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1944
1945 */
1946 if (getuid() != geteuid() || getgid() != getegid())
1947 nullify_closed_stdio ();
1948 call_constructors(si);
1949 notify_gdb_of_load(si);
1950 return 0;
1951
1952fail:
1953 ERROR("failed to link %s\n", si->name);
1954 si->flags |= FLAG_ERROR;
1955 return -1;
1956}
1957
David Bartleybc3a5c22009-06-02 18:27:28 -07001958static void parse_library_path(char *path, char *delim)
1959{
1960 size_t len;
1961 char *ldpaths_bufp = ldpaths_buf;
1962 int i = 0;
1963
1964 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1965
1966 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1967 if (*ldpaths[i] != '\0')
1968 ++i;
1969 }
1970
1971 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1972 * last char isn't '\0' (i.e. not originally a delim). */
1973 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1974 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1975 ldpaths[i - 1] = NULL;
1976 } else {
1977 ldpaths[i] = NULL;
1978 }
1979}
1980
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001981int main(int argc, char **argv)
1982{
1983 return 0;
1984}
1985
1986#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1987
1988static void * __tls_area[ANDROID_TLS_SLOTS];
1989
1990unsigned __linker_init(unsigned **elfdata)
1991{
1992 static soinfo linker_soinfo;
1993
1994 int argc = (int) *elfdata;
1995 char **argv = (char**) (elfdata + 1);
1996 unsigned *vecs = (unsigned*) (argv + argc + 1);
1997 soinfo *si;
1998 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001999 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002000
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002001 /* Setup a temporary TLS area that is used to get a working
2002 * errno for system calls.
2003 */
2004 __set_tls(__tls_area);
2005
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002006 pid = getpid();
2007
2008#if TIMING
2009 struct timeval t0, t1;
2010 gettimeofday(&t0, 0);
2011#endif
2012
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002013 /* NOTE: we store the elfdata pointer on a special location
2014 * of the temporary TLS area in order to pass it to
2015 * the C Library's runtime initializer.
2016 *
2017 * The initializer must clear the slot and reset the TLS
2018 * to point to a different location to ensure that no other
2019 * shared library constructor can access it.
2020 */
2021 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002022
2023 debugger_init();
2024
2025 /* skip past the environment */
2026 while(vecs[0] != 0) {
2027 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
2028 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07002029 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
2030 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002031 }
2032 vecs++;
2033 }
2034 vecs++;
2035
2036 INFO("[ android linker & debugger ]\n");
2037 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2038
2039 si = alloc_info(argv[0]);
2040 if(si == 0) {
2041 exit(-1);
2042 }
2043
2044 /* bootstrap the link map, the main exe always needs to be first */
2045 si->flags |= FLAG_EXE;
2046 map = &(si->linkmap);
2047
2048 map->l_addr = 0;
2049 map->l_name = argv[0];
2050 map->l_prev = NULL;
2051 map->l_next = NULL;
2052
2053 _r_debug.r_map = map;
2054 r_debug_tail = map;
2055
2056 /* gdb expects the linker to be in the debug shared object list,
2057 * and we need to make sure that the reported load address is zero.
2058 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2059 * is. Don't use alloc_info(), because the linker shouldn't
2060 * be on the soinfo list.
2061 */
2062 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
2063 linker_soinfo.flags = 0;
2064 linker_soinfo.base = 0; // This is the important part; must be zero.
2065 insert_soinfo_into_debug_map(&linker_soinfo);
2066
2067 /* extract information passed from the kernel */
2068 while(vecs[0] != 0){
2069 switch(vecs[0]){
2070 case AT_PHDR:
2071 si->phdr = (Elf32_Phdr*) vecs[1];
2072 break;
2073 case AT_PHNUM:
2074 si->phnum = (int) vecs[1];
2075 break;
2076 case AT_ENTRY:
2077 si->entry = vecs[1];
2078 break;
2079 }
2080 vecs += 2;
2081 }
2082
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07002083 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002084
2085 si->base = 0;
2086 si->dynamic = (unsigned *)-1;
2087 si->wrprotect_start = 0xffffffff;
2088 si->wrprotect_end = 0;
2089
David Bartleybc3a5c22009-06-02 18:27:28 -07002090 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
2091 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
2092 parse_library_path(ldpath_env, ":");
2093
Dima Zavin2e855792009-05-20 18:28:09 -07002094 if(link_image(si, 0)) {
2095 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2096 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2097 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002098 exit(-1);
2099 }
2100
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002101#if ALLOW_SYMBOLS_FROM_MAIN
2102 /* Set somain after we've loaded all the libraries in order to prevent
2103 * linking of symbols back to the main image, which is not set up at that
2104 * point yet.
2105 */
2106 somain = si;
2107#endif
2108
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002109#if TIMING
2110 gettimeofday(&t1,NULL);
2111 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2112 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2113 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2114 ));
2115#endif
2116#if STATS
2117 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2118 linker_stats.reloc[RELOC_ABSOLUTE],
2119 linker_stats.reloc[RELOC_RELATIVE],
2120 linker_stats.reloc[RELOC_COPY],
2121 linker_stats.reloc[RELOC_SYMBOL]);
2122#endif
2123#if COUNT_PAGES
2124 {
2125 unsigned n;
2126 unsigned i;
2127 unsigned count = 0;
2128 for(n = 0; n < 4096; n++){
2129 if(bitmask[n]){
2130 unsigned x = bitmask[n];
2131 for(i = 0; i < 8; i++){
2132 if(x & 1) count++;
2133 x >>= 1;
2134 }
2135 }
2136 }
2137 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2138 }
2139#endif
2140
2141#if TIMING || STATS || COUNT_PAGES
2142 fflush(stdout);
2143#endif
2144
2145 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2146 si->entry);
2147 return si->entry;
2148}