blob: 6d57cbc2cfe21567dd7ebc32da4c469e78291344 [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);
474 if(s != NULL)
475 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
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800541#if 0
542static void dump(soinfo *si)
543{
544 Elf32_Sym *s = si->symtab;
545 unsigned n;
546
547 for(n = 0; n < si->nchain; n++) {
548 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
549 s->st_info, s->st_shndx, s->st_value, s->st_size,
550 si->strtab + s->st_name);
551 s++;
552 }
553}
554#endif
555
556static const char *sopaths[] = {
557 "/system/lib",
558 "/lib",
559 0
560};
561
562static int _open_lib(const char *name)
563{
564 int fd;
565 struct stat filestat;
566
567 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
568 if ((fd = open(name, O_RDONLY)) >= 0)
569 return fd;
570 }
571
572 return -1;
573}
574
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800575static int open_library(const char *name)
576{
577 int fd;
578 char buf[512];
579 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700580 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800581
582 TRACE("[ %5d opening %s ]\n", pid, name);
583
584 if(name == 0) return -1;
585 if(strlen(name) > 256) return -1;
586
587 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
588 return fd;
589
David Bartleybc3a5c22009-06-02 18:27:28 -0700590 for (path = ldpaths; *path; path++) {
591 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
592 if (n < 0 || n >= (int)sizeof(buf)) {
593 WARN("Ignoring very long library path: %s/%s\n", *path, name);
594 continue;
595 }
596 if ((fd = _open_lib(buf)) >= 0)
597 return fd;
598 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800599 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700600 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
601 if (n < 0 || n >= (int)sizeof(buf)) {
602 WARN("Ignoring very long library path: %s/%s\n", *path, name);
603 continue;
604 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800605 if ((fd = _open_lib(buf)) >= 0)
606 return fd;
607 }
608
609 return -1;
610}
611
612/* temporary space for holding the first page of the shared lib
613 * which contains the elf header (with the pht). */
614static unsigned char __header[PAGE_SIZE];
615
616typedef struct {
617 long mmap_addr;
618 char tag[4]; /* 'P', 'R', 'E', ' ' */
619} prelink_info_t;
620
621/* Returns the requested base address if the library is prelinked,
622 * and 0 otherwise. */
623static unsigned long
624is_prelinked(int fd, const char *name)
625{
626 off_t sz;
627 prelink_info_t info;
628
629 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
630 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700631 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800632 return 0;
633 }
634
635 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
636 WARN("Could not read prelink_info_t structure for `%s`\n", name);
637 return 0;
638 }
639
640 if (strncmp(info.tag, "PRE ", 4)) {
641 WARN("`%s` is not a prelinked library\n", name);
642 return 0;
643 }
644
645 return (unsigned long)info.mmap_addr;
646}
647
648/* verify_elf_object
649 * Verifies if the object @ base is a valid ELF object
650 *
651 * Args:
652 *
653 * Returns:
654 * 0 on success
655 * -1 if no valid ELF object is found @ base.
656 */
657static int
658verify_elf_object(void *base, const char *name)
659{
660 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
661
662 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
663 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
664 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
665 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
666
667 /* TODO: Should we verify anything else in the header? */
668
669 return 0;
670}
671
672
673/* get_lib_extents
674 * Retrieves the base (*base) address where the ELF object should be
675 * mapped and its overall memory size (*total_sz).
676 *
677 * Args:
678 * fd: Opened file descriptor for the library
679 * name: The name of the library
680 * _hdr: Pointer to the header page of the library
681 * total_sz: Total size of the memory that should be allocated for
682 * this library
683 *
684 * Returns:
685 * -1 if there was an error while trying to get the lib extents.
686 * The possible reasons are:
687 * - Could not determine if the library was prelinked.
688 * - The library provided is not a valid ELF object
689 * 0 if the library did not request a specific base offset (normal
690 * for non-prelinked libs)
691 * > 0 if the library requests a specific address to be mapped to.
692 * This indicates a pre-linked library.
693 */
694static unsigned
695get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
696{
697 unsigned req_base;
698 unsigned min_vaddr = 0xffffffff;
699 unsigned max_vaddr = 0;
700 unsigned char *_hdr = (unsigned char *)__hdr;
701 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
702 Elf32_Phdr *phdr;
703 int cnt;
704
705 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
706 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700707 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800708 return (unsigned)-1;
709 }
710
711 req_base = (unsigned) is_prelinked(fd, name);
712 if (req_base == (unsigned)-1)
713 return -1;
714 else if (req_base != 0) {
715 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
716 pid, name, req_base);
717 } else {
718 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
719 }
720
721 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
722
723 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
724 * get the range. */
725 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
726 if (phdr->p_type == PT_LOAD) {
727 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
728 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
729 if (phdr->p_vaddr < min_vaddr)
730 min_vaddr = phdr->p_vaddr;
731 }
732 }
733
734 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700735 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800736 return (unsigned)-1;
737 }
738
739 /* truncate min_vaddr down to page boundary */
740 min_vaddr &= ~PAGE_MASK;
741
742 /* round max_vaddr up to the next page */
743 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
744
745 *total_sz = (max_vaddr - min_vaddr);
746 return (unsigned)req_base;
747}
748
749/* alloc_mem_region
750 *
751 * This function reserves a chunk of memory to be used for mapping in
752 * the shared library. We reserve the entire memory region here, and
753 * then the rest of the linker will relocate the individual loadable
754 * segments into the correct locations within this memory range.
755 *
756 * Args:
757 * si->base: The requested base of the allocation. If 0, a sane one will be
758 * chosen in the range LIBBASE <= base < LIBLAST.
759 * si->size: The size of the allocation.
760 *
761 * Returns:
762 * -1 on failure, and 0 on success. On success, si->base will contain
763 * the virtual address at which the library will be mapped.
764 */
765
766static int reserve_mem_region(soinfo *si)
767{
768 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
769 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
770 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700771 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700772 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800773 pid, (si->base ? "" : "non-"), si->name, si->base,
774 errno, strerror(errno));
775 return -1;
776 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700777 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700778 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800779 si->name, (unsigned)base, si->base);
780 munmap(base, si->size);
781 return -1;
782 }
783 return 0;
784}
785
786static int
787alloc_mem_region(soinfo *si)
788{
789 if (si->base) {
790 /* Attempt to mmap a prelinked library. */
791 si->ba_index = -1;
792 return reserve_mem_region(si);
793 }
794
795 /* This is not a prelinked library, so we attempt to allocate space
796 for it from the buddy allocator, which manages the area between
797 LIBBASE and LIBLAST.
798 */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700799 si->ba_index = ba_allocate(&ba_prelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800800 if(si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700801 si->base = ba_start_addr(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800802 PRINT("%5d mapping library '%s' at %08x (index %d) " \
803 "through buddy allocator.\n",
804 pid, si->name, si->base, si->ba_index);
805 if (reserve_mem_region(si) < 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700806 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800807 si->ba_index = -1;
808 si->base = 0;
809 goto err;
810 }
811 return 0;
812 }
813
814err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700815 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800816 pid, si->name);
817 return -1;
818}
819
820#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
821#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
822 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
823 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
824/* load_segments
825 *
826 * This function loads all the loadable (PT_LOAD) segments into memory
827 * at their appropriate memory offsets off the base address.
828 *
829 * Args:
830 * fd: Open file descriptor to the library to load.
831 * header: Pointer to a header page that contains the ELF header.
832 * This is needed since we haven't mapped in the real file yet.
833 * si: ptr to soinfo struct describing the shared object.
834 *
835 * Returns:
836 * 0 on success, -1 on failure.
837 */
838static int
839load_segments(int fd, void *header, soinfo *si)
840{
841 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
842 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
843 unsigned char *base = (unsigned char *)si->base;
844 int cnt;
845 unsigned len;
846 unsigned char *tmp;
847 unsigned char *pbase;
848 unsigned char *extra_base;
849 unsigned extra_len;
850 unsigned total_sz = 0;
851
852 si->wrprotect_start = 0xffffffff;
853 si->wrprotect_end = 0;
854
855 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
856 pid, si->name, (unsigned)si->base);
857 /* Now go through all the PT_LOAD segments and map them into memory
858 * at the appropriate locations. */
859 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
860 if (phdr->p_type == PT_LOAD) {
861 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
862 /* we want to map in the segment on a page boundary */
863 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
864 /* add the # of bytes we masked off above to the total length. */
865 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
866
867 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
868 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
869 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
870 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
871 MAP_PRIVATE | MAP_FIXED, fd,
872 phdr->p_offset & (~PAGE_MASK));
873 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700874 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700875 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800876 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
877 goto fail;
878 }
879
880 /* If 'len' didn't end on page boundary, and it's a writable
881 * segment, zero-fill the rest. */
882 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
883 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
884
885 /* Check to see if we need to extend the map for this segment to
886 * cover the diff between filesz and memsz (i.e. for bss).
887 *
888 * base _+---------------------+ page boundary
889 * . .
890 * | |
891 * . .
892 * pbase _+---------------------+ page boundary
893 * | |
894 * . .
895 * base + p_vaddr _| |
896 * . \ \ .
897 * . | filesz | .
898 * pbase + len _| / | |
899 * <0 pad> . . .
900 * extra_base _+------------|--------+ page boundary
901 * / . . .
902 * | . . .
903 * | +------------|--------+ page boundary
904 * extra_len-> | | | |
905 * | . | memsz .
906 * | . | .
907 * \ _| / |
908 * . .
909 * | |
910 * _+---------------------+ page boundary
911 */
912 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
913 (~PAGE_MASK));
914 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
915 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
916 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
917 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
918 /* map in the extra page(s) as anonymous into the range.
919 * This is probably not necessary as we already mapped in
920 * the entire region previously, but we just want to be
921 * sure. This will also set the right flags on the region
922 * (though we can probably accomplish the same thing with
923 * mprotect).
924 */
925 extra_base = mmap((void *)tmp, extra_len,
926 PFLAGS_TO_PROT(phdr->p_flags),
927 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
928 -1, 0);
929 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700930 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700931 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800932 extra_len);
933 goto fail;
934 }
935 /* TODO: Check if we need to memset-0 this region.
936 * Anonymous mappings are zero-filled copy-on-writes, so we
937 * shouldn't need to. */
938 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
939 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
940 extra_len);
941 }
942 /* set the len here to show the full extent of the segment we
943 * just loaded, mostly for debugging */
944 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
945 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
946 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
947 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
948 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
949 total_sz += len;
950 /* Make the section writable just in case we'll have to write to
951 * it during relocation (i.e. text segment). However, we will
952 * remember what range of addresses should be write protected.
953 *
954 */
955 if (!(phdr->p_flags & PF_W)) {
956 if ((unsigned)pbase < si->wrprotect_start)
957 si->wrprotect_start = (unsigned)pbase;
958 if (((unsigned)pbase + len) > si->wrprotect_end)
959 si->wrprotect_end = (unsigned)pbase + len;
960 mprotect(pbase, len,
961 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
962 }
963 } else if (phdr->p_type == PT_DYNAMIC) {
964 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
965 /* this segment contains the dynamic linking information */
966 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
967 } else {
968#ifdef ANDROID_ARM_LINKER
969 if (phdr->p_type == PT_ARM_EXIDX) {
970 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
971 /* exidx entries (used for stack unwinding) are 8 bytes each.
972 */
973 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
974 si->ARM_exidx_count = phdr->p_memsz / 8;
975 }
976#endif
977 }
978
979 }
980
981 /* Sanity check */
982 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700983 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700984 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800985 pid, total_sz, si->name, si->size);
986 goto fail;
987 }
988
989 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
990 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
991 (unsigned)si->base, si->size);
992 return 0;
993
994fail:
995 /* We can just blindly unmap the entire region even though some things
996 * were mapped in originally with anonymous and others could have been
997 * been mapped in from the file before we failed. The kernel will unmap
998 * all the pages in the range, irrespective of how they got there.
999 */
1000 munmap((void *)si->base, si->size);
1001 si->flags |= FLAG_ERROR;
1002 return -1;
1003}
1004
1005/* TODO: Implement this to take care of the fact that Android ARM
1006 * ELF objects shove everything into a single loadable segment that has the
1007 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1008 * non-writable.
1009 */
1010#if 0
1011static unsigned
1012get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1013{
1014 Elf32_Shdr *shdr_start;
1015 Elf32_Shdr *shdr;
1016 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1017 int cnt;
1018 unsigned wr_offset = 0xffffffff;
1019
1020 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1021 ehdr->e_shoff & (~PAGE_MASK));
1022 if (shdr_start == MAP_FAILED) {
1023 WARN("%5d - Could not read section header info from '%s'. Will not "
1024 "not be able to determine write-protect offset.\n", pid, name);
1025 return (unsigned)-1;
1026 }
1027
1028 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1029 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1030 (shdr->sh_addr < wr_offset)) {
1031 wr_offset = shdr->sh_addr;
1032 }
1033 }
1034
1035 munmap(shdr_start, shdr_sz);
1036 return wr_offset;
1037}
1038#endif
1039
1040static soinfo *
1041load_library(const char *name)
1042{
1043 int fd = open_library(name);
1044 int cnt;
1045 unsigned ext_sz;
1046 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001047 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001048 soinfo *si = NULL;
1049 Elf32_Ehdr *hdr;
1050
Dima Zavin2e855792009-05-20 18:28:09 -07001051 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001052 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001053 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001054 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001055
1056 /* We have to read the ELF header to figure out what to do with this image
1057 */
1058 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001059 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001060 goto fail;
1061 }
1062
1063 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001064 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001065 goto fail;
1066 }
1067
1068 /* Parse the ELF header and get the size of the memory footprint for
1069 * the library */
1070 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1071 if (req_base == (unsigned)-1)
1072 goto fail;
1073 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1074 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1075
1076 /* Now configure the soinfo struct where we'll store all of our data
1077 * for the ELF object. If the loading fails, we waste the entry, but
1078 * same thing would happen if we failed during linking. Configuring the
1079 * soinfo struct here is a lot more convenient.
1080 */
Erik Gillingfde86422009-07-28 20:28:19 -07001081 bname = strrchr(name, '/');
1082 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001083 if (si == NULL)
1084 goto fail;
1085
1086 /* Carve out a chunk of memory where we will map in the individual
1087 * segments */
1088 si->base = req_base;
1089 si->size = ext_sz;
1090 si->flags = 0;
1091 si->entry = 0;
1092 si->dynamic = (unsigned *)-1;
1093 if (alloc_mem_region(si) < 0)
1094 goto fail;
1095
1096 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1097 pid, name, (void *)si->base, (unsigned) ext_sz);
1098
1099 /* Now actually load the library's segments into right places in memory */
1100 if (load_segments(fd, &__header[0], si) < 0) {
1101 if (si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001102 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001103 si->ba_index = -1;
1104 }
1105 goto fail;
1106 }
1107
1108 /* this might not be right. Technically, we don't even need this info
1109 * once we go through 'load_segments'. */
1110 hdr = (Elf32_Ehdr *)si->base;
1111 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1112 si->phnum = hdr->e_phnum;
1113 /**/
1114
1115 close(fd);
1116 return si;
1117
1118fail:
1119 if (si) free_info(si);
1120 close(fd);
1121 return NULL;
1122}
1123
1124static soinfo *
1125init_library(soinfo *si)
1126{
1127 unsigned wr_offset = 0xffffffff;
1128
1129 /* At this point we know that whatever is loaded @ base is a valid ELF
1130 * shared library whose segments are properly mapped in. */
1131 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1132 pid, si->base, si->size, si->name);
1133
1134 if (si->base < LIBBASE || si->base >= LIBLAST)
1135 si->flags |= FLAG_PRELINKED;
1136
1137 if(link_image(si, wr_offset)) {
1138 /* We failed to link. However, we can only restore libbase
1139 ** if no additional libraries have moved it since we updated it.
1140 */
1141 munmap((void *)si->base, si->size);
1142 return NULL;
1143 }
1144
1145 return si;
1146}
1147
1148soinfo *find_library(const char *name)
1149{
1150 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001151 const char *bname = strrchr(name, '/');
1152 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001153
1154 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001155 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001156 if(si->flags & FLAG_ERROR) {
1157 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1158 return NULL;
1159 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001160 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001161 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001162 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001163 }
1164 }
1165
1166 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1167 si = load_library(name);
1168 if(si == NULL)
1169 return NULL;
1170 return init_library(si);
1171}
1172
1173/* TODO:
1174 * notify gdb of unload
1175 * for non-prelinked libraries, find a way to decrement libbase
1176 */
1177static void call_destructors(soinfo *si);
1178unsigned unload_library(soinfo *si)
1179{
1180 unsigned *d;
1181 if (si->refcount == 1) {
1182 TRACE("%5d unloading '%s'\n", pid, si->name);
1183 call_destructors(si);
1184
1185 for(d = si->dynamic; *d; d += 2) {
1186 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001187 soinfo *lsi = (soinfo *)d[1];
1188 d[1] = 0;
1189 if (validate_soinfo(lsi)) {
1190 TRACE("%5d %s needs to unload %s\n", pid,
1191 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001192 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001193 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001194 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001195 DL_ERR("%5d %s: could not unload dependent library",
1196 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001197 }
1198 }
1199
1200 munmap((char *)si->base, si->size);
1201 if (si->ba_index >= 0) {
1202 PRINT("%5d releasing library '%s' address space at %08x "\
1203 "through buddy allocator.\n",
1204 pid, si->name, si->base);
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001205 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001206 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001207 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001208 free_info(si);
1209 si->refcount = 0;
1210 }
1211 else {
1212 si->refcount--;
1213 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1214 pid, si->name, si->refcount);
1215 }
1216 return si->refcount;
1217}
1218
1219/* TODO: don't use unsigned for addrs below. It works, but is not
1220 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1221 * long.
1222 */
1223static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1224{
1225 Elf32_Sym *symtab = si->symtab;
1226 const char *strtab = si->strtab;
1227 Elf32_Sym *s;
1228 unsigned base;
1229 Elf32_Rel *start = rel;
1230 unsigned idx;
1231
1232 for (idx = 0; idx < count; ++idx) {
1233 unsigned type = ELF32_R_TYPE(rel->r_info);
1234 unsigned sym = ELF32_R_SYM(rel->r_info);
1235 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1236 unsigned sym_addr = 0;
1237 char *sym_name = NULL;
1238
1239 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1240 si->name, idx);
1241 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001242 sym_name = (char *)(strtab + symtab[sym].st_name);
1243 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001245 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246 return -1;
1247 }
1248#if 0
1249 if((base == 0) && (si->base != 0)){
1250 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001251 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001252 pid, strtab + symtab[sym].st_name);
1253 return -1;
1254 }
1255#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001256 // st_shndx==SHN_UNDEF means an undefined symbol.
1257 // st_value should be 0 then, except that the low bit of st_value is
1258 // used to indicate whether the symbol points to an ARM or thumb function,
1259 // and should be ignored in the following check.
1260 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1261 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1262 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001263 s->st_value);
1264 return -1;
1265 }
1266 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001267 COUNT_RELOC(RELOC_SYMBOL);
1268 } else {
1269 s = 0;
1270 }
1271
1272/* TODO: This is ugly. Split up the relocations by arch into
1273 * different files.
1274 */
1275 switch(type){
1276#if defined(ANDROID_ARM_LINKER)
1277 case R_ARM_JUMP_SLOT:
1278 COUNT_RELOC(RELOC_ABSOLUTE);
1279 MARK(rel->r_offset);
1280 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1281 reloc, sym_addr, sym_name);
1282 *((unsigned*)reloc) = sym_addr;
1283 break;
1284 case R_ARM_GLOB_DAT:
1285 COUNT_RELOC(RELOC_ABSOLUTE);
1286 MARK(rel->r_offset);
1287 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1288 reloc, sym_addr, sym_name);
1289 *((unsigned*)reloc) = sym_addr;
1290 break;
1291 case R_ARM_ABS32:
1292 COUNT_RELOC(RELOC_ABSOLUTE);
1293 MARK(rel->r_offset);
1294 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1295 reloc, sym_addr, sym_name);
1296 *((unsigned*)reloc) += sym_addr;
1297 break;
David 'Digit' Turnerfe62de12009-12-02 10:54:53 -08001298 case R_ARM_REL32:
1299 COUNT_RELOC(RELOC_RELATIVE);
1300 MARK(rel->r_offset);
1301 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1302 reloc, sym_addr, rel->r_offset, sym_name);
1303 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1304 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001305#elif defined(ANDROID_X86_LINKER)
1306 case R_386_JUMP_SLOT:
1307 COUNT_RELOC(RELOC_ABSOLUTE);
1308 MARK(rel->r_offset);
1309 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1310 reloc, sym_addr, sym_name);
1311 *((unsigned*)reloc) = sym_addr;
1312 break;
1313 case R_386_GLOB_DAT:
1314 COUNT_RELOC(RELOC_ABSOLUTE);
1315 MARK(rel->r_offset);
1316 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1317 reloc, sym_addr, sym_name);
1318 *((unsigned*)reloc) = sym_addr;
1319 break;
1320#endif /* ANDROID_*_LINKER */
1321
1322#if defined(ANDROID_ARM_LINKER)
1323 case R_ARM_RELATIVE:
1324#elif defined(ANDROID_X86_LINKER)
1325 case R_386_RELATIVE:
1326#endif /* ANDROID_*_LINKER */
1327 COUNT_RELOC(RELOC_RELATIVE);
1328 MARK(rel->r_offset);
1329 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001330 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001331 return -1;
1332 }
1333 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1334 reloc, si->base);
1335 *((unsigned*)reloc) += si->base;
1336 break;
1337
1338#if defined(ANDROID_X86_LINKER)
1339 case R_386_32:
1340 COUNT_RELOC(RELOC_RELATIVE);
1341 MARK(rel->r_offset);
1342
1343 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1344 reloc, sym_addr, sym_name);
1345 *((unsigned *)reloc) += (unsigned)sym_addr;
1346 break;
1347
1348 case R_386_PC32:
1349 COUNT_RELOC(RELOC_RELATIVE);
1350 MARK(rel->r_offset);
1351 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1352 "+%08x (%08x - %08x) %s\n", pid, reloc,
1353 (sym_addr - reloc), sym_addr, reloc, sym_name);
1354 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1355 break;
1356#endif /* ANDROID_X86_LINKER */
1357
1358#ifdef ANDROID_ARM_LINKER
1359 case R_ARM_COPY:
1360 COUNT_RELOC(RELOC_COPY);
1361 MARK(rel->r_offset);
1362 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1363 reloc, s->st_size, sym_addr, sym_name);
1364 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1365 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001366 case R_ARM_NONE:
1367 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001368#endif /* ANDROID_ARM_LINKER */
1369
1370 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001371 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001372 pid, type, rel, (int) (rel - start));
1373 return -1;
1374 }
1375 rel++;
1376 }
1377 return 0;
1378}
1379
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001380#if defined(ANDROID_SH_LINKER)
1381static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1382{
1383 Elf32_Sym *symtab = si->symtab;
1384 const char *strtab = si->strtab;
1385 Elf32_Sym *s;
1386 unsigned base;
1387 Elf32_Rela *start = rela;
1388 unsigned idx;
1389
1390 for (idx = 0; idx < count; ++idx) {
1391 unsigned type = ELF32_R_TYPE(rela->r_info);
1392 unsigned sym = ELF32_R_SYM(rela->r_info);
1393 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1394 unsigned sym_addr = 0;
1395 char *sym_name = NULL;
1396
1397 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1398 si->name, idx);
1399 if(sym != 0) {
1400 sym_name = (char *)(strtab + symtab[sym].st_name);
1401 s = _do_lookup(si, sym_name, &base);
1402 if(s == 0) {
1403 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1404 return -1;
1405 }
1406#if 0
1407 if((base == 0) && (si->base != 0)){
1408 /* linking from libraries to main image is bad */
1409 DL_ERR("%5d cannot locate '%s'...",
1410 pid, strtab + symtab[sym].st_name);
1411 return -1;
1412 }
1413#endif
1414 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1415 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1416 "handle this yet", pid, si->name, s->st_shndx,
1417 s->st_value);
1418 return -1;
1419 }
1420 sym_addr = (unsigned)(s->st_value + base);
1421 COUNT_RELOC(RELOC_SYMBOL);
1422 } else {
1423 s = 0;
1424 }
1425
1426/* TODO: This is ugly. Split up the relocations by arch into
1427 * different files.
1428 */
1429 switch(type){
1430 case R_SH_JUMP_SLOT:
1431 COUNT_RELOC(RELOC_ABSOLUTE);
1432 MARK(rela->r_offset);
1433 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1434 reloc, sym_addr, sym_name);
1435 *((unsigned*)reloc) = sym_addr;
1436 break;
1437 case R_SH_GLOB_DAT:
1438 COUNT_RELOC(RELOC_ABSOLUTE);
1439 MARK(rela->r_offset);
1440 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1441 reloc, sym_addr, sym_name);
1442 *((unsigned*)reloc) = sym_addr;
1443 break;
1444 case R_SH_DIR32:
1445 COUNT_RELOC(RELOC_ABSOLUTE);
1446 MARK(rela->r_offset);
1447 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1448 reloc, sym_addr, sym_name);
1449 *((unsigned*)reloc) += sym_addr;
1450 break;
1451 case R_SH_RELATIVE:
1452 COUNT_RELOC(RELOC_RELATIVE);
1453 MARK(rela->r_offset);
1454 if(sym){
1455 DL_ERR("%5d odd RELATIVE form...", pid);
1456 return -1;
1457 }
1458 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1459 reloc, si->base);
1460 *((unsigned*)reloc) += si->base;
1461 break;
1462
1463 default:
1464 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1465 pid, type, rela, (int) (rela - start));
1466 return -1;
1467 }
1468 rela++;
1469 }
1470 return 0;
1471}
1472#endif /* ANDROID_SH_LINKER */
1473
David 'Digit' Turner82156792009-05-18 14:37:41 +02001474
1475/* Please read the "Initialization and Termination functions" functions.
1476 * of the linker design note in bionic/linker/README.TXT to understand
1477 * what the following code is doing.
1478 *
1479 * The important things to remember are:
1480 *
1481 * DT_PREINIT_ARRAY must be called first for executables, and should
1482 * not appear in shared libraries.
1483 *
1484 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1485 *
1486 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1487 *
1488 * DT_FINI_ARRAY must be parsed in reverse order.
1489 */
1490
1491static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001492{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001493 int n, inc = 1;
1494
1495 if (reverse) {
1496 ctor += (count-1);
1497 inc = -1;
1498 }
1499
1500 for(n = count; n > 0; n--) {
1501 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1502 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001503 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001504 void (*func)() = (void (*)()) *ctor;
1505 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001506 if(((int) func == 0) || ((int) func == -1)) continue;
1507 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1508 func();
1509 }
1510}
1511
1512static void call_constructors(soinfo *si)
1513{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001514 if (si->flags & FLAG_EXE) {
1515 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1516 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1517 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001518 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001519 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1520 } else {
1521 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001522 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001523 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001524 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001525 }
1526 }
1527
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001528 if (si->init_func) {
1529 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1530 (unsigned)si->init_func, si->name);
1531 si->init_func();
1532 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1533 }
1534
1535 if (si->init_array) {
1536 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1537 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001538 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001539 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1540 }
1541}
1542
David 'Digit' Turner82156792009-05-18 14:37:41 +02001543
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001544static void call_destructors(soinfo *si)
1545{
1546 if (si->fini_array) {
1547 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1548 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001549 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001550 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1551 }
1552
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001553 if (si->fini_func) {
1554 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1555 (unsigned)si->fini_func, si->name);
1556 si->fini_func();
1557 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1558 }
1559}
1560
1561/* Force any of the closed stdin, stdout and stderr to be associated with
1562 /dev/null. */
1563static int nullify_closed_stdio (void)
1564{
1565 int dev_null, i, status;
1566 int return_value = 0;
1567
1568 dev_null = open("/dev/null", O_RDWR);
1569 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001570 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001571 return -1;
1572 }
1573 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1574
1575 /* If any of the stdio file descriptors is valid and not associated
1576 with /dev/null, dup /dev/null to it. */
1577 for (i = 0; i < 3; i++) {
1578 /* If it is /dev/null already, we are done. */
1579 if (i == dev_null)
1580 continue;
1581
1582 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1583 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1584 can be interrupted but we do this just to be safe. */
1585 do {
1586 status = fcntl(i, F_GETFL);
1587 } while (status < 0 && errno == EINTR);
1588
1589 /* If file is openned, we are good. */
1590 if (status >= 0)
1591 continue;
1592
1593 /* The only error we allow is that the file descriptor does not
1594 exist, in which case we dup /dev/null to it. */
1595 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001596 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001597 return_value = -1;
1598 continue;
1599 }
1600
1601 /* Try dupping /dev/null to this stdio file descriptor and
1602 repeat if there is a signal. Note that any errors in closing
1603 the stdio descriptor are lost. */
1604 do {
1605 status = dup2(dev_null, i);
1606 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001607
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001608 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001609 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001610 return_value = -1;
1611 continue;
1612 }
1613 }
1614
1615 /* If /dev/null is not one of the stdio file descriptors, close it. */
1616 if (dev_null > 2) {
1617 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001618 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001619 status = close(dev_null);
1620 } while (status < 0 && errno == EINTR);
1621
1622 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001623 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001624 return_value = -1;
1625 }
1626 }
1627
1628 return return_value;
1629}
1630
1631static int link_image(soinfo *si, unsigned wr_offset)
1632{
1633 unsigned *d;
1634 Elf32_Phdr *phdr = si->phdr;
1635 int phnum = si->phnum;
1636
1637 INFO("[ %5d linking %s ]\n", pid, si->name);
1638 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1639 si->base, si->flags);
1640
1641 if (si->flags & FLAG_EXE) {
1642 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1643 * linkage info if this is the executable. If this was a
1644 * dynamic lib, that would have been done at load time.
1645 *
1646 * TODO: It's unfortunate that small pieces of this are
1647 * repeated from the load_library routine. Refactor this just
1648 * slightly to reuse these bits.
1649 */
1650 si->size = 0;
1651 for(; phnum > 0; --phnum, ++phdr) {
1652#ifdef ANDROID_ARM_LINKER
1653 if(phdr->p_type == PT_ARM_EXIDX) {
1654 /* exidx entries (used for stack unwinding) are 8 bytes each.
1655 */
1656 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1657 si->ARM_exidx_count = phdr->p_memsz / 8;
1658 }
1659#endif
1660 if (phdr->p_type == PT_LOAD) {
1661 /* For the executable, we use the si->size field only in
1662 dl_unwind_find_exidx(), so the meaning of si->size
1663 is not the size of the executable; it is the last
1664 virtual address of the loadable part of the executable;
1665 since si->base == 0 for an executable, we use the
1666 range [0, si->size) to determine whether a PC value
1667 falls within the executable section. Of course, if
1668 a value is below phdr->p_vaddr, it's not in the
1669 executable section, but a) we shouldn't be asking for
1670 such a value anyway, and b) if we have to provide
1671 an EXIDX for such a value, then the executable's
1672 EXIDX is probably the better choice.
1673 */
1674 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1675 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1676 si->size = phdr->p_vaddr + phdr->p_memsz;
1677 /* try to remember what range of addresses should be write
1678 * protected */
1679 if (!(phdr->p_flags & PF_W)) {
1680 unsigned _end;
1681
1682 if (phdr->p_vaddr < si->wrprotect_start)
1683 si->wrprotect_start = phdr->p_vaddr;
1684 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1685 (~PAGE_MASK)));
1686 if (_end > si->wrprotect_end)
1687 si->wrprotect_end = _end;
1688 }
1689 } else if (phdr->p_type == PT_DYNAMIC) {
1690 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001691 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001692 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001693 pid, si->name, si->base + phdr->p_vaddr,
1694 (unsigned)si->dynamic);
1695 goto fail;
1696 }
1697 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1698 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1699 }
1700 }
1701 }
1702
1703 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001704 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001705 goto fail;
1706 }
1707
1708 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1709
1710 /* extract useful information from dynamic section */
1711 for(d = si->dynamic; *d; d++){
1712 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1713 switch(*d++){
1714 case DT_HASH:
1715 si->nbucket = ((unsigned *) (si->base + *d))[0];
1716 si->nchain = ((unsigned *) (si->base + *d))[1];
1717 si->bucket = (unsigned *) (si->base + *d + 8);
1718 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1719 break;
1720 case DT_STRTAB:
1721 si->strtab = (const char *) (si->base + *d);
1722 break;
1723 case DT_SYMTAB:
1724 si->symtab = (Elf32_Sym *) (si->base + *d);
1725 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001726#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001727 case DT_PLTREL:
1728 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001729 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001730 goto fail;
1731 }
1732 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001733#endif
1734#ifdef ANDROID_SH_LINKER
1735 case DT_JMPREL:
1736 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1737 break;
1738 case DT_PLTRELSZ:
1739 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1740 break;
1741#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001742 case DT_JMPREL:
1743 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1744 break;
1745 case DT_PLTRELSZ:
1746 si->plt_rel_count = *d / 8;
1747 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001748#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001749 case DT_REL:
1750 si->rel = (Elf32_Rel*) (si->base + *d);
1751 break;
1752 case DT_RELSZ:
1753 si->rel_count = *d / 8;
1754 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001755#ifdef ANDROID_SH_LINKER
1756 case DT_RELASZ:
1757 si->rela_count = *d / sizeof(Elf32_Rela);
1758 break;
1759#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001760 case DT_PLTGOT:
1761 /* Save this in case we decide to do lazy binding. We don't yet. */
1762 si->plt_got = (unsigned *)(si->base + *d);
1763 break;
1764 case DT_DEBUG:
1765 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1766 *d = (int) &_r_debug;
1767 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001768#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001769 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001770 si->rela = (Elf32_Rela *) (si->base + *d);
1771 break;
1772#else
1773 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001774 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001776#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001777 case DT_INIT:
1778 si->init_func = (void (*)(void))(si->base + *d);
1779 DEBUG("%5d %s constructors (init func) found at %p\n",
1780 pid, si->name, si->init_func);
1781 break;
1782 case DT_FINI:
1783 si->fini_func = (void (*)(void))(si->base + *d);
1784 DEBUG("%5d %s destructors (fini func) found at %p\n",
1785 pid, si->name, si->fini_func);
1786 break;
1787 case DT_INIT_ARRAY:
1788 si->init_array = (unsigned *)(si->base + *d);
1789 DEBUG("%5d %s constructors (init_array) found at %p\n",
1790 pid, si->name, si->init_array);
1791 break;
1792 case DT_INIT_ARRAYSZ:
1793 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1794 break;
1795 case DT_FINI_ARRAY:
1796 si->fini_array = (unsigned *)(si->base + *d);
1797 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1798 pid, si->name, si->fini_array);
1799 break;
1800 case DT_FINI_ARRAYSZ:
1801 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1802 break;
1803 case DT_PREINIT_ARRAY:
1804 si->preinit_array = (unsigned *)(si->base + *d);
1805 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1806 pid, si->name, si->preinit_array);
1807 break;
1808 case DT_PREINIT_ARRAYSZ:
1809 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1810 break;
1811 case DT_TEXTREL:
1812 /* TODO: make use of this. */
1813 /* this means that we might have to write into where the text
1814 * segment was loaded during relocation... Do something with
1815 * it.
1816 */
1817 DEBUG("%5d Text segment should be writable during relocation.\n",
1818 pid);
1819 break;
1820 }
1821 }
1822
1823 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1824 pid, si->base, si->strtab, si->symtab);
1825
1826 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001827 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001828 goto fail;
1829 }
1830
1831 for(d = si->dynamic; *d; d += 2) {
1832 if(d[0] == DT_NEEDED){
1833 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001834 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001835 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001836 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001837 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001838 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001839 goto fail;
1840 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001841 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1842 of the DT_NEEDED entry itself, so that we can retrieve the
1843 soinfo directly later from the dynamic segment. This is a hack,
1844 but it allows us to map from DT_NEEDED to soinfo efficiently
1845 later on when we resolve relocations, trying to look up a symgol
1846 with dlsym().
1847 */
1848 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001849 lsi->refcount++;
1850 }
1851 }
1852
1853 if(si->plt_rel) {
1854 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1855 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1856 goto fail;
1857 }
1858 if(si->rel) {
1859 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1860 if(reloc_library(si, si->rel, si->rel_count))
1861 goto fail;
1862 }
1863
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001864#ifdef ANDROID_SH_LINKER
1865 if(si->plt_rela) {
1866 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1867 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1868 goto fail;
1869 }
1870 if(si->rela) {
1871 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1872 if(reloc_library_a(si, si->rela, si->rela_count))
1873 goto fail;
1874 }
1875#endif /* ANDROID_SH_LINKER */
1876
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001877 si->flags |= FLAG_LINKED;
1878 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1879
1880#if 0
1881 /* This is the way that the old dynamic linker did protection of
1882 * non-writable areas. It would scan section headers and find where
1883 * .text ended (rather where .data/.bss began) and assume that this is
1884 * the upper range of the non-writable area. This is too coarse,
1885 * and is kept here for reference until we fully move away from single
1886 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1887 * that made this possible.
1888 */
1889 if(wr_offset < 0xffffffff){
1890 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1891 }
1892#else
1893 /* TODO: Verify that this does the right thing in all cases, as it
1894 * presently probably does not. It is possible that an ELF image will
1895 * come with multiple read-only segments. What we ought to do is scan
1896 * the program headers again and mprotect all the read-only segments.
1897 * To prevent re-scanning the program header, we would have to build a
1898 * list of loadable segments in si, and then scan that instead. */
1899 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1900 mprotect((void *)si->wrprotect_start,
1901 si->wrprotect_end - si->wrprotect_start,
1902 PROT_READ | PROT_EXEC);
1903 }
1904#endif
1905
1906 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1907 stdout and stderr to close a security hole described in:
1908
1909 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1910
1911 */
1912 if (getuid() != geteuid() || getgid() != getegid())
1913 nullify_closed_stdio ();
1914 call_constructors(si);
1915 notify_gdb_of_load(si);
1916 return 0;
1917
1918fail:
1919 ERROR("failed to link %s\n", si->name);
1920 si->flags |= FLAG_ERROR;
1921 return -1;
1922}
1923
David Bartleybc3a5c22009-06-02 18:27:28 -07001924static void parse_library_path(char *path, char *delim)
1925{
1926 size_t len;
1927 char *ldpaths_bufp = ldpaths_buf;
1928 int i = 0;
1929
1930 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1931
1932 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1933 if (*ldpaths[i] != '\0')
1934 ++i;
1935 }
1936
1937 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1938 * last char isn't '\0' (i.e. not originally a delim). */
1939 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1940 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1941 ldpaths[i - 1] = NULL;
1942 } else {
1943 ldpaths[i] = NULL;
1944 }
1945}
1946
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001947int main(int argc, char **argv)
1948{
1949 return 0;
1950}
1951
1952#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1953
1954static void * __tls_area[ANDROID_TLS_SLOTS];
1955
1956unsigned __linker_init(unsigned **elfdata)
1957{
1958 static soinfo linker_soinfo;
1959
1960 int argc = (int) *elfdata;
1961 char **argv = (char**) (elfdata + 1);
1962 unsigned *vecs = (unsigned*) (argv + argc + 1);
1963 soinfo *si;
1964 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001965 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001966
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001967 /* Setup a temporary TLS area that is used to get a working
1968 * errno for system calls.
1969 */
1970 __set_tls(__tls_area);
1971
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001972 pid = getpid();
1973
1974#if TIMING
1975 struct timeval t0, t1;
1976 gettimeofday(&t0, 0);
1977#endif
1978
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001979 /* NOTE: we store the elfdata pointer on a special location
1980 * of the temporary TLS area in order to pass it to
1981 * the C Library's runtime initializer.
1982 *
1983 * The initializer must clear the slot and reset the TLS
1984 * to point to a different location to ensure that no other
1985 * shared library constructor can access it.
1986 */
1987 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001988
1989 debugger_init();
1990
1991 /* skip past the environment */
1992 while(vecs[0] != 0) {
1993 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1994 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001995 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1996 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001997 }
1998 vecs++;
1999 }
2000 vecs++;
2001
2002 INFO("[ android linker & debugger ]\n");
2003 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2004
2005 si = alloc_info(argv[0]);
2006 if(si == 0) {
2007 exit(-1);
2008 }
2009
2010 /* bootstrap the link map, the main exe always needs to be first */
2011 si->flags |= FLAG_EXE;
2012 map = &(si->linkmap);
2013
2014 map->l_addr = 0;
2015 map->l_name = argv[0];
2016 map->l_prev = NULL;
2017 map->l_next = NULL;
2018
2019 _r_debug.r_map = map;
2020 r_debug_tail = map;
2021
2022 /* gdb expects the linker to be in the debug shared object list,
2023 * and we need to make sure that the reported load address is zero.
2024 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2025 * is. Don't use alloc_info(), because the linker shouldn't
2026 * be on the soinfo list.
2027 */
2028 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
2029 linker_soinfo.flags = 0;
2030 linker_soinfo.base = 0; // This is the important part; must be zero.
2031 insert_soinfo_into_debug_map(&linker_soinfo);
2032
2033 /* extract information passed from the kernel */
2034 while(vecs[0] != 0){
2035 switch(vecs[0]){
2036 case AT_PHDR:
2037 si->phdr = (Elf32_Phdr*) vecs[1];
2038 break;
2039 case AT_PHNUM:
2040 si->phnum = (int) vecs[1];
2041 break;
2042 case AT_ENTRY:
2043 si->entry = vecs[1];
2044 break;
2045 }
2046 vecs += 2;
2047 }
2048
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07002049 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002050
2051 si->base = 0;
2052 si->dynamic = (unsigned *)-1;
2053 si->wrprotect_start = 0xffffffff;
2054 si->wrprotect_end = 0;
2055
David Bartleybc3a5c22009-06-02 18:27:28 -07002056 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
2057 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
2058 parse_library_path(ldpath_env, ":");
2059
Dima Zavin2e855792009-05-20 18:28:09 -07002060 if(link_image(si, 0)) {
2061 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2062 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2063 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002064 exit(-1);
2065 }
2066
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002067#if ALLOW_SYMBOLS_FROM_MAIN
2068 /* Set somain after we've loaded all the libraries in order to prevent
2069 * linking of symbols back to the main image, which is not set up at that
2070 * point yet.
2071 */
2072 somain = si;
2073#endif
2074
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002075#if TIMING
2076 gettimeofday(&t1,NULL);
2077 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2078 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2079 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2080 ));
2081#endif
2082#if STATS
2083 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2084 linker_stats.reloc[RELOC_ABSOLUTE],
2085 linker_stats.reloc[RELOC_RELATIVE],
2086 linker_stats.reloc[RELOC_COPY],
2087 linker_stats.reloc[RELOC_SYMBOL]);
2088#endif
2089#if COUNT_PAGES
2090 {
2091 unsigned n;
2092 unsigned i;
2093 unsigned count = 0;
2094 for(n = 0; n < 4096; n++){
2095 if(bitmask[n]){
2096 unsigned x = bitmask[n];
2097 for(i = 0; i < 8; i++){
2098 if(x & 1) count++;
2099 x >>= 1;
2100 }
2101 }
2102 }
2103 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2104 }
2105#endif
2106
2107#if TIMING || STATS || COUNT_PAGES
2108 fflush(stdout);
2109#endif
2110
2111 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2112 si->entry);
2113 return si->entry;
2114}