blob: 53d3b01d5f2ab2d0c94ad47dc7eff62740f8d079 [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}
370#elif defined(ANDROID_X86_LINKER)
371/* 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;
1298#elif defined(ANDROID_X86_LINKER)
1299 case R_386_JUMP_SLOT:
1300 COUNT_RELOC(RELOC_ABSOLUTE);
1301 MARK(rel->r_offset);
1302 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1303 reloc, sym_addr, sym_name);
1304 *((unsigned*)reloc) = sym_addr;
1305 break;
1306 case R_386_GLOB_DAT:
1307 COUNT_RELOC(RELOC_ABSOLUTE);
1308 MARK(rel->r_offset);
1309 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1310 reloc, sym_addr, sym_name);
1311 *((unsigned*)reloc) = sym_addr;
1312 break;
1313#endif /* ANDROID_*_LINKER */
1314
1315#if defined(ANDROID_ARM_LINKER)
1316 case R_ARM_RELATIVE:
1317#elif defined(ANDROID_X86_LINKER)
1318 case R_386_RELATIVE:
1319#endif /* ANDROID_*_LINKER */
1320 COUNT_RELOC(RELOC_RELATIVE);
1321 MARK(rel->r_offset);
1322 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001323 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001324 return -1;
1325 }
1326 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1327 reloc, si->base);
1328 *((unsigned*)reloc) += si->base;
1329 break;
1330
1331#if defined(ANDROID_X86_LINKER)
1332 case R_386_32:
1333 COUNT_RELOC(RELOC_RELATIVE);
1334 MARK(rel->r_offset);
1335
1336 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1337 reloc, sym_addr, sym_name);
1338 *((unsigned *)reloc) += (unsigned)sym_addr;
1339 break;
1340
1341 case R_386_PC32:
1342 COUNT_RELOC(RELOC_RELATIVE);
1343 MARK(rel->r_offset);
1344 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1345 "+%08x (%08x - %08x) %s\n", pid, reloc,
1346 (sym_addr - reloc), sym_addr, reloc, sym_name);
1347 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1348 break;
1349#endif /* ANDROID_X86_LINKER */
1350
1351#ifdef ANDROID_ARM_LINKER
1352 case R_ARM_COPY:
1353 COUNT_RELOC(RELOC_COPY);
1354 MARK(rel->r_offset);
1355 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1356 reloc, s->st_size, sym_addr, sym_name);
1357 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1358 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001359 case R_ARM_NONE:
1360 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001361#endif /* ANDROID_ARM_LINKER */
1362
1363 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001364 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365 pid, type, rel, (int) (rel - start));
1366 return -1;
1367 }
1368 rel++;
1369 }
1370 return 0;
1371}
1372
David 'Digit' Turner82156792009-05-18 14:37:41 +02001373
1374/* Please read the "Initialization and Termination functions" functions.
1375 * of the linker design note in bionic/linker/README.TXT to understand
1376 * what the following code is doing.
1377 *
1378 * The important things to remember are:
1379 *
1380 * DT_PREINIT_ARRAY must be called first for executables, and should
1381 * not appear in shared libraries.
1382 *
1383 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1384 *
1385 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1386 *
1387 * DT_FINI_ARRAY must be parsed in reverse order.
1388 */
1389
1390static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001391{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001392 int n, inc = 1;
1393
1394 if (reverse) {
1395 ctor += (count-1);
1396 inc = -1;
1397 }
1398
1399 for(n = count; n > 0; n--) {
1400 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1401 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001403 void (*func)() = (void (*)()) *ctor;
1404 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001405 if(((int) func == 0) || ((int) func == -1)) continue;
1406 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1407 func();
1408 }
1409}
1410
1411static void call_constructors(soinfo *si)
1412{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001413 if (si->flags & FLAG_EXE) {
1414 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1415 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1416 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001417 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001418 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1419 } else {
1420 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001421 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001422 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001423 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001424 }
1425 }
1426
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001427 if (si->init_func) {
1428 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1429 (unsigned)si->init_func, si->name);
1430 si->init_func();
1431 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1432 }
1433
1434 if (si->init_array) {
1435 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1436 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001437 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001438 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1439 }
1440}
1441
David 'Digit' Turner82156792009-05-18 14:37:41 +02001442
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001443static void call_destructors(soinfo *si)
1444{
1445 if (si->fini_array) {
1446 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1447 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001448 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001449 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1450 }
1451
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001452 if (si->fini_func) {
1453 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1454 (unsigned)si->fini_func, si->name);
1455 si->fini_func();
1456 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1457 }
1458}
1459
1460/* Force any of the closed stdin, stdout and stderr to be associated with
1461 /dev/null. */
1462static int nullify_closed_stdio (void)
1463{
1464 int dev_null, i, status;
1465 int return_value = 0;
1466
1467 dev_null = open("/dev/null", O_RDWR);
1468 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001469 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001470 return -1;
1471 }
1472 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1473
1474 /* If any of the stdio file descriptors is valid and not associated
1475 with /dev/null, dup /dev/null to it. */
1476 for (i = 0; i < 3; i++) {
1477 /* If it is /dev/null already, we are done. */
1478 if (i == dev_null)
1479 continue;
1480
1481 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1482 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1483 can be interrupted but we do this just to be safe. */
1484 do {
1485 status = fcntl(i, F_GETFL);
1486 } while (status < 0 && errno == EINTR);
1487
1488 /* If file is openned, we are good. */
1489 if (status >= 0)
1490 continue;
1491
1492 /* The only error we allow is that the file descriptor does not
1493 exist, in which case we dup /dev/null to it. */
1494 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001495 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001496 return_value = -1;
1497 continue;
1498 }
1499
1500 /* Try dupping /dev/null to this stdio file descriptor and
1501 repeat if there is a signal. Note that any errors in closing
1502 the stdio descriptor are lost. */
1503 do {
1504 status = dup2(dev_null, i);
1505 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001506
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001507 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001508 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001509 return_value = -1;
1510 continue;
1511 }
1512 }
1513
1514 /* If /dev/null is not one of the stdio file descriptors, close it. */
1515 if (dev_null > 2) {
1516 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001517 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001518 status = close(dev_null);
1519 } while (status < 0 && errno == EINTR);
1520
1521 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001522 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001523 return_value = -1;
1524 }
1525 }
1526
1527 return return_value;
1528}
1529
1530static int link_image(soinfo *si, unsigned wr_offset)
1531{
1532 unsigned *d;
1533 Elf32_Phdr *phdr = si->phdr;
1534 int phnum = si->phnum;
1535
1536 INFO("[ %5d linking %s ]\n", pid, si->name);
1537 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1538 si->base, si->flags);
1539
1540 if (si->flags & FLAG_EXE) {
1541 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1542 * linkage info if this is the executable. If this was a
1543 * dynamic lib, that would have been done at load time.
1544 *
1545 * TODO: It's unfortunate that small pieces of this are
1546 * repeated from the load_library routine. Refactor this just
1547 * slightly to reuse these bits.
1548 */
1549 si->size = 0;
1550 for(; phnum > 0; --phnum, ++phdr) {
1551#ifdef ANDROID_ARM_LINKER
1552 if(phdr->p_type == PT_ARM_EXIDX) {
1553 /* exidx entries (used for stack unwinding) are 8 bytes each.
1554 */
1555 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1556 si->ARM_exidx_count = phdr->p_memsz / 8;
1557 }
1558#endif
1559 if (phdr->p_type == PT_LOAD) {
1560 /* For the executable, we use the si->size field only in
1561 dl_unwind_find_exidx(), so the meaning of si->size
1562 is not the size of the executable; it is the last
1563 virtual address of the loadable part of the executable;
1564 since si->base == 0 for an executable, we use the
1565 range [0, si->size) to determine whether a PC value
1566 falls within the executable section. Of course, if
1567 a value is below phdr->p_vaddr, it's not in the
1568 executable section, but a) we shouldn't be asking for
1569 such a value anyway, and b) if we have to provide
1570 an EXIDX for such a value, then the executable's
1571 EXIDX is probably the better choice.
1572 */
1573 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1574 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1575 si->size = phdr->p_vaddr + phdr->p_memsz;
1576 /* try to remember what range of addresses should be write
1577 * protected */
1578 if (!(phdr->p_flags & PF_W)) {
1579 unsigned _end;
1580
1581 if (phdr->p_vaddr < si->wrprotect_start)
1582 si->wrprotect_start = phdr->p_vaddr;
1583 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1584 (~PAGE_MASK)));
1585 if (_end > si->wrprotect_end)
1586 si->wrprotect_end = _end;
1587 }
1588 } else if (phdr->p_type == PT_DYNAMIC) {
1589 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001590 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001591 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001592 pid, si->name, si->base + phdr->p_vaddr,
1593 (unsigned)si->dynamic);
1594 goto fail;
1595 }
1596 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1597 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1598 }
1599 }
1600 }
1601
1602 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001603 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001604 goto fail;
1605 }
1606
1607 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1608
1609 /* extract useful information from dynamic section */
1610 for(d = si->dynamic; *d; d++){
1611 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1612 switch(*d++){
1613 case DT_HASH:
1614 si->nbucket = ((unsigned *) (si->base + *d))[0];
1615 si->nchain = ((unsigned *) (si->base + *d))[1];
1616 si->bucket = (unsigned *) (si->base + *d + 8);
1617 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1618 break;
1619 case DT_STRTAB:
1620 si->strtab = (const char *) (si->base + *d);
1621 break;
1622 case DT_SYMTAB:
1623 si->symtab = (Elf32_Sym *) (si->base + *d);
1624 break;
1625 case DT_PLTREL:
1626 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001627 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001628 goto fail;
1629 }
1630 break;
1631 case DT_JMPREL:
1632 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1633 break;
1634 case DT_PLTRELSZ:
1635 si->plt_rel_count = *d / 8;
1636 break;
1637 case DT_REL:
1638 si->rel = (Elf32_Rel*) (si->base + *d);
1639 break;
1640 case DT_RELSZ:
1641 si->rel_count = *d / 8;
1642 break;
1643 case DT_PLTGOT:
1644 /* Save this in case we decide to do lazy binding. We don't yet. */
1645 si->plt_got = (unsigned *)(si->base + *d);
1646 break;
1647 case DT_DEBUG:
1648 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1649 *d = (int) &_r_debug;
1650 break;
1651 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001652 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001653 goto fail;
1654 case DT_INIT:
1655 si->init_func = (void (*)(void))(si->base + *d);
1656 DEBUG("%5d %s constructors (init func) found at %p\n",
1657 pid, si->name, si->init_func);
1658 break;
1659 case DT_FINI:
1660 si->fini_func = (void (*)(void))(si->base + *d);
1661 DEBUG("%5d %s destructors (fini func) found at %p\n",
1662 pid, si->name, si->fini_func);
1663 break;
1664 case DT_INIT_ARRAY:
1665 si->init_array = (unsigned *)(si->base + *d);
1666 DEBUG("%5d %s constructors (init_array) found at %p\n",
1667 pid, si->name, si->init_array);
1668 break;
1669 case DT_INIT_ARRAYSZ:
1670 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1671 break;
1672 case DT_FINI_ARRAY:
1673 si->fini_array = (unsigned *)(si->base + *d);
1674 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1675 pid, si->name, si->fini_array);
1676 break;
1677 case DT_FINI_ARRAYSZ:
1678 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1679 break;
1680 case DT_PREINIT_ARRAY:
1681 si->preinit_array = (unsigned *)(si->base + *d);
1682 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1683 pid, si->name, si->preinit_array);
1684 break;
1685 case DT_PREINIT_ARRAYSZ:
1686 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1687 break;
1688 case DT_TEXTREL:
1689 /* TODO: make use of this. */
1690 /* this means that we might have to write into where the text
1691 * segment was loaded during relocation... Do something with
1692 * it.
1693 */
1694 DEBUG("%5d Text segment should be writable during relocation.\n",
1695 pid);
1696 break;
1697 }
1698 }
1699
1700 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1701 pid, si->base, si->strtab, si->symtab);
1702
1703 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001704 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001705 goto fail;
1706 }
1707
1708 for(d = si->dynamic; *d; d += 2) {
1709 if(d[0] == DT_NEEDED){
1710 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001711 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001712 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001713 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001714 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001715 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001716 goto fail;
1717 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001718 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1719 of the DT_NEEDED entry itself, so that we can retrieve the
1720 soinfo directly later from the dynamic segment. This is a hack,
1721 but it allows us to map from DT_NEEDED to soinfo efficiently
1722 later on when we resolve relocations, trying to look up a symgol
1723 with dlsym().
1724 */
1725 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001726 lsi->refcount++;
1727 }
1728 }
1729
1730 if(si->plt_rel) {
1731 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1732 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1733 goto fail;
1734 }
1735 if(si->rel) {
1736 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1737 if(reloc_library(si, si->rel, si->rel_count))
1738 goto fail;
1739 }
1740
1741 si->flags |= FLAG_LINKED;
1742 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1743
1744#if 0
1745 /* This is the way that the old dynamic linker did protection of
1746 * non-writable areas. It would scan section headers and find where
1747 * .text ended (rather where .data/.bss began) and assume that this is
1748 * the upper range of the non-writable area. This is too coarse,
1749 * and is kept here for reference until we fully move away from single
1750 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1751 * that made this possible.
1752 */
1753 if(wr_offset < 0xffffffff){
1754 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1755 }
1756#else
1757 /* TODO: Verify that this does the right thing in all cases, as it
1758 * presently probably does not. It is possible that an ELF image will
1759 * come with multiple read-only segments. What we ought to do is scan
1760 * the program headers again and mprotect all the read-only segments.
1761 * To prevent re-scanning the program header, we would have to build a
1762 * list of loadable segments in si, and then scan that instead. */
1763 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1764 mprotect((void *)si->wrprotect_start,
1765 si->wrprotect_end - si->wrprotect_start,
1766 PROT_READ | PROT_EXEC);
1767 }
1768#endif
1769
1770 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1771 stdout and stderr to close a security hole described in:
1772
1773 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1774
1775 */
1776 if (getuid() != geteuid() || getgid() != getegid())
1777 nullify_closed_stdio ();
1778 call_constructors(si);
1779 notify_gdb_of_load(si);
1780 return 0;
1781
1782fail:
1783 ERROR("failed to link %s\n", si->name);
1784 si->flags |= FLAG_ERROR;
1785 return -1;
1786}
1787
David Bartleybc3a5c22009-06-02 18:27:28 -07001788static void parse_library_path(char *path, char *delim)
1789{
1790 size_t len;
1791 char *ldpaths_bufp = ldpaths_buf;
1792 int i = 0;
1793
1794 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1795
1796 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1797 if (*ldpaths[i] != '\0')
1798 ++i;
1799 }
1800
1801 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1802 * last char isn't '\0' (i.e. not originally a delim). */
1803 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1804 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1805 ldpaths[i - 1] = NULL;
1806 } else {
1807 ldpaths[i] = NULL;
1808 }
1809}
1810
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001811int main(int argc, char **argv)
1812{
1813 return 0;
1814}
1815
1816#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1817
1818static void * __tls_area[ANDROID_TLS_SLOTS];
1819
1820unsigned __linker_init(unsigned **elfdata)
1821{
1822 static soinfo linker_soinfo;
1823
1824 int argc = (int) *elfdata;
1825 char **argv = (char**) (elfdata + 1);
1826 unsigned *vecs = (unsigned*) (argv + argc + 1);
1827 soinfo *si;
1828 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001829 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001830
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001831 /* Setup a temporary TLS area that is used to get a working
1832 * errno for system calls.
1833 */
1834 __set_tls(__tls_area);
1835
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001836 pid = getpid();
1837
1838#if TIMING
1839 struct timeval t0, t1;
1840 gettimeofday(&t0, 0);
1841#endif
1842
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001843 /* NOTE: we store the elfdata pointer on a special location
1844 * of the temporary TLS area in order to pass it to
1845 * the C Library's runtime initializer.
1846 *
1847 * The initializer must clear the slot and reset the TLS
1848 * to point to a different location to ensure that no other
1849 * shared library constructor can access it.
1850 */
1851 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001852
1853 debugger_init();
1854
1855 /* skip past the environment */
1856 while(vecs[0] != 0) {
1857 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1858 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001859 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1860 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001861 }
1862 vecs++;
1863 }
1864 vecs++;
1865
1866 INFO("[ android linker & debugger ]\n");
1867 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1868
1869 si = alloc_info(argv[0]);
1870 if(si == 0) {
1871 exit(-1);
1872 }
1873
1874 /* bootstrap the link map, the main exe always needs to be first */
1875 si->flags |= FLAG_EXE;
1876 map = &(si->linkmap);
1877
1878 map->l_addr = 0;
1879 map->l_name = argv[0];
1880 map->l_prev = NULL;
1881 map->l_next = NULL;
1882
1883 _r_debug.r_map = map;
1884 r_debug_tail = map;
1885
1886 /* gdb expects the linker to be in the debug shared object list,
1887 * and we need to make sure that the reported load address is zero.
1888 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1889 * is. Don't use alloc_info(), because the linker shouldn't
1890 * be on the soinfo list.
1891 */
1892 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1893 linker_soinfo.flags = 0;
1894 linker_soinfo.base = 0; // This is the important part; must be zero.
1895 insert_soinfo_into_debug_map(&linker_soinfo);
1896
1897 /* extract information passed from the kernel */
1898 while(vecs[0] != 0){
1899 switch(vecs[0]){
1900 case AT_PHDR:
1901 si->phdr = (Elf32_Phdr*) vecs[1];
1902 break;
1903 case AT_PHNUM:
1904 si->phnum = (int) vecs[1];
1905 break;
1906 case AT_ENTRY:
1907 si->entry = vecs[1];
1908 break;
1909 }
1910 vecs += 2;
1911 }
1912
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001913 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001914
1915 si->base = 0;
1916 si->dynamic = (unsigned *)-1;
1917 si->wrprotect_start = 0xffffffff;
1918 si->wrprotect_end = 0;
1919
David Bartleybc3a5c22009-06-02 18:27:28 -07001920 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1921 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1922 parse_library_path(ldpath_env, ":");
1923
Dima Zavin2e855792009-05-20 18:28:09 -07001924 if(link_image(si, 0)) {
1925 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1926 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1927 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001928 exit(-1);
1929 }
1930
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001931#if ALLOW_SYMBOLS_FROM_MAIN
1932 /* Set somain after we've loaded all the libraries in order to prevent
1933 * linking of symbols back to the main image, which is not set up at that
1934 * point yet.
1935 */
1936 somain = si;
1937#endif
1938
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001939#if TIMING
1940 gettimeofday(&t1,NULL);
1941 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1942 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1943 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1944 ));
1945#endif
1946#if STATS
1947 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1948 linker_stats.reloc[RELOC_ABSOLUTE],
1949 linker_stats.reloc[RELOC_RELATIVE],
1950 linker_stats.reloc[RELOC_COPY],
1951 linker_stats.reloc[RELOC_SYMBOL]);
1952#endif
1953#if COUNT_PAGES
1954 {
1955 unsigned n;
1956 unsigned i;
1957 unsigned count = 0;
1958 for(n = 0; n < 4096; n++){
1959 if(bitmask[n]){
1960 unsigned x = bitmask[n];
1961 for(i = 0; i < 8; i++){
1962 if(x & 1) count++;
1963 x >>= 1;
1964 }
1965 }
1966 }
1967 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1968 }
1969#endif
1970
1971#if TIMING || STATS || COUNT_PAGES
1972 fflush(stdout);
1973#endif
1974
1975 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1976 si->entry);
1977 return si->entry;
1978}