blob: 80b5d00faf2b292abaa8cd965cc39ca16b0e8a16 [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;
177
178 /* Stick the new library at the end of the list.
179 * gdb tends to care more about libc than it does
180 * about leaf libraries, and ordering it this way
181 * reduces the back-and-forth over the wire.
182 */
183 if (r_debug_tail) {
184 r_debug_tail->l_next = map;
185 map->l_prev = r_debug_tail;
186 map->l_next = 0;
187 } else {
188 _r_debug.r_map = map;
189 map->l_prev = 0;
190 map->l_next = 0;
191 }
192 r_debug_tail = map;
193}
194
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700195static void remove_soinfo_from_debug_map(soinfo * info)
196{
197 struct link_map * map = &(info->linkmap);
198
199 if (r_debug_tail == map)
200 r_debug_tail = map->l_prev;
201
202 if (map->l_prev) map->l_prev->l_next = map->l_next;
203 if (map->l_next) map->l_next->l_prev = map->l_prev;
204}
205
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800206void notify_gdb_of_load(soinfo * info)
207{
208 if (info->flags & FLAG_EXE) {
209 // GDB already knows about the main executable
210 return;
211 }
212
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700213 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800214
215 _r_debug.r_state = RT_ADD;
216 rtld_db_dlactivity();
217
218 insert_soinfo_into_debug_map(info);
219
220 _r_debug.r_state = RT_CONSISTENT;
221 rtld_db_dlactivity();
222
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700223 pthread_mutex_unlock(&_r_debug_lock);
224}
225
226void notify_gdb_of_unload(soinfo * info)
227{
228 if (info->flags & FLAG_EXE) {
229 // GDB already knows about the main executable
230 return;
231 }
232
233 pthread_mutex_lock(&_r_debug_lock);
234
235 _r_debug.r_state = RT_DELETE;
236 rtld_db_dlactivity();
237
238 remove_soinfo_from_debug_map(info);
239
240 _r_debug.r_state = RT_CONSISTENT;
241 rtld_db_dlactivity();
242
243 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800244}
245
246void notify_gdb_of_libraries()
247{
248 _r_debug.r_state = RT_ADD;
249 rtld_db_dlactivity();
250 _r_debug.r_state = RT_CONSISTENT;
251 rtld_db_dlactivity();
252}
253
254static soinfo *alloc_info(const char *name)
255{
256 soinfo *si;
257
258 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700259 DL_ERR("%5d library name %s too long", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800260 return 0;
261 }
262
263 /* The freelist is populated when we call free_info(), which in turn is
264 done only by dlclose(), which is not likely to be used.
265 */
266 if (!freelist) {
267 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700268 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800269 return NULL;
270 }
271 freelist = sopool + socount++;
272 freelist->next = NULL;
273 }
274
275 si = freelist;
276 freelist = freelist->next;
277
278 /* Make sure we get a clean block of soinfo */
279 memset(si, 0, sizeof(soinfo));
280 strcpy((char*) si->name, name);
281 sonext->next = si;
282 si->ba_index = -1; /* by default, prelinked */
283 si->next = NULL;
284 si->refcount = 0;
285 sonext = si;
286
287 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
288 return si;
289}
290
291static void free_info(soinfo *si)
292{
293 soinfo *prev = NULL, *trav;
294
295 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
296
297 for(trav = solist; trav != NULL; trav = trav->next){
298 if (trav == si)
299 break;
300 prev = trav;
301 }
302 if (trav == NULL) {
303 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700304 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800305 return;
306 }
307
308 /* prev will never be NULL, because the first entry in solist is
309 always the static libdl_info.
310 */
311 prev->next = si->next;
312 if (si == sonext) sonext = prev;
313 si->next = freelist;
314 freelist = si;
315}
316
317#ifndef LINKER_TEXT_BASE
318#error "linker's makefile must define LINKER_TEXT_BASE"
319#endif
320#ifndef LINKER_AREA_SIZE
321#error "linker's makefile must define LINKER_AREA_SIZE"
322#endif
323#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
324#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
325
326const char *addr_to_name(unsigned addr)
327{
328 soinfo *si;
329
330 for(si = solist; si != 0; si = si->next){
331 if((addr >= si->base) && (addr < (si->base + si->size))) {
332 return si->name;
333 }
334 }
335
336 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
337 return "linker";
338 }
339
340 return "";
341}
342
343/* For a given PC, find the .so that it belongs to.
344 * Returns the base address of the .ARM.exidx section
345 * for that .so, and the number of 8-byte entries
346 * in that section (via *pcount).
347 *
348 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
349 *
350 * This function is exposed via dlfcn.c and libdl.so.
351 */
352#ifdef ANDROID_ARM_LINKER
353_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
354{
355 soinfo *si;
356 unsigned addr = (unsigned)pc;
357
358 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
359 for (si = solist; si != 0; si = si->next){
360 if ((addr >= si->base) && (addr < (si->base + si->size))) {
361 *pcount = si->ARM_exidx_count;
362 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
363 }
364 }
365 }
366 *pcount = 0;
367 return NULL;
368}
369#elif defined(ANDROID_X86_LINKER)
370/* Here, we only have to provide a callback to iterate across all the
371 * loaded libraries. gcc_eh does the rest. */
372int
373dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
374 void *data)
375{
376 soinfo *si;
377 struct dl_phdr_info dl_info;
378 int rv = 0;
379
380 for (si = solist; si != NULL; si = si->next) {
381 dl_info.dlpi_addr = si->linkmap.l_addr;
382 dl_info.dlpi_name = si->linkmap.l_name;
383 dl_info.dlpi_phdr = si->phdr;
384 dl_info.dlpi_phnum = si->phnum;
385 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
386 if (rv != 0)
387 break;
388 }
389 return rv;
390}
391#endif
392
393static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
394{
395 Elf32_Sym *s;
396 Elf32_Sym *symtab = si->symtab;
397 const char *strtab = si->strtab;
398 unsigned n;
399
400 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
401 name, si->name, si->base, hash, hash % si->nbucket);
402 n = hash % si->nbucket;
403
404 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
405 s = symtab + n;
406 if(strcmp(strtab + s->st_name, name)) continue;
407
408 /* only concern ourselves with global symbols */
409 switch(ELF32_ST_BIND(s->st_info)){
410 case STB_GLOBAL:
411 /* no section == undefined */
412 if(s->st_shndx == 0) continue;
413
414 case STB_WEAK:
415 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
416 name, si->name, s->st_value, s->st_size);
417 return s;
418 }
419 }
420
421 return 0;
422}
423
424static unsigned elfhash(const char *_name)
425{
426 const unsigned char *name = (const unsigned char *) _name;
427 unsigned h = 0, g;
428
429 while(*name) {
430 h = (h << 4) + *name++;
431 g = h & 0xf0000000;
432 h ^= g;
433 h ^= g >> 24;
434 }
435 return h;
436}
437
438static Elf32_Sym *
439_do_lookup_in_so(soinfo *si, const char *name, unsigned *elf_hash)
440{
441 if (*elf_hash == 0)
442 *elf_hash = elfhash(name);
443 return _elf_lookup (si, *elf_hash, name);
444}
445
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700446static Elf32_Sym *
447_do_lookup(soinfo *si, const char *name, unsigned *base)
448{
449 unsigned elf_hash = 0;
450 Elf32_Sym *s;
451 unsigned *d;
452 soinfo *lsi = si;
453
454 /* Look for symbols in the local scope first (the object who is
455 * searching). This happens with C++ templates on i386 for some
456 * reason. */
457 s = _do_lookup_in_so(si, name, &elf_hash);
458 if(s != NULL)
459 goto done;
460
461 for(d = si->dynamic; *d; d += 2) {
462 if(d[0] == DT_NEEDED){
463 lsi = (soinfo *)d[1];
464 if (!validate_soinfo(lsi)) {
465 DL_ERR("%5d bad DT_NEEDED pointer in %s",
466 pid, si->name);
467 return 0;
468 }
469
470 DEBUG("%5d %s: looking up %s in %s\n",
471 pid, si->name, name, lsi->name);
472 s = _do_lookup_in_so(lsi, name, &elf_hash);
473 if(s != NULL)
474 goto done;
475 }
476 }
477
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700478#if ALLOW_SYMBOLS_FROM_MAIN
479 /* If we are resolving relocations while dlopen()ing a library, it's OK for
480 * the library to resolve a symbol that's defined in the executable itself,
481 * although this is rare and is generally a bad idea.
482 */
483 if (somain) {
484 lsi = somain;
485 DEBUG("%5d %s: looking up %s in executable %s\n",
486 pid, si->name, name, lsi->name);
487 s = _do_lookup_in_so(lsi, name, &elf_hash);
488 }
489#endif
490
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700491done:
492 if(s != NULL) {
493 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
494 "found in %s, base = 0x%08x\n",
495 pid, si->name, name, s->st_value, lsi->name, lsi->base);
496 *base = lsi->base;
497 return s;
498 }
499
500 return 0;
501}
502
503/* This is used by dl_sym(). It performs symbol lookup only within the
504 specified soinfo object and not in any of its dependencies.
505 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800506Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
507{
508 unsigned unused = 0;
509 return _do_lookup_in_so(si, name, &unused);
510}
511
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700512/* This is used by dl_sym(). It performs a global symbol lookup.
513 */
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700514Elf32_Sym *lookup(const char *name, soinfo **found)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800515{
516 unsigned elf_hash = 0;
517 Elf32_Sym *s = NULL;
518 soinfo *si;
519
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800520 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
521 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700522 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800523 continue;
524 s = _do_lookup_in_so(si, name, &elf_hash);
525 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700526 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800527 break;
528 }
529 }
530
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700531 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800532 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
533 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
534 return s;
535 }
536
537 return 0;
538}
539
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800540#if 0
541static void dump(soinfo *si)
542{
543 Elf32_Sym *s = si->symtab;
544 unsigned n;
545
546 for(n = 0; n < si->nchain; n++) {
547 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
548 s->st_info, s->st_shndx, s->st_value, s->st_size,
549 si->strtab + s->st_name);
550 s++;
551 }
552}
553#endif
554
555static const char *sopaths[] = {
556 "/system/lib",
557 "/lib",
558 0
559};
560
561static int _open_lib(const char *name)
562{
563 int fd;
564 struct stat filestat;
565
566 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
567 if ((fd = open(name, O_RDONLY)) >= 0)
568 return fd;
569 }
570
571 return -1;
572}
573
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800574static int open_library(const char *name)
575{
576 int fd;
577 char buf[512];
578 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700579 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800580
581 TRACE("[ %5d opening %s ]\n", pid, name);
582
583 if(name == 0) return -1;
584 if(strlen(name) > 256) return -1;
585
586 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
587 return fd;
588
David Bartleybc3a5c22009-06-02 18:27:28 -0700589 for (path = ldpaths; *path; path++) {
590 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
591 if (n < 0 || n >= (int)sizeof(buf)) {
592 WARN("Ignoring very long library path: %s/%s\n", *path, name);
593 continue;
594 }
595 if ((fd = _open_lib(buf)) >= 0)
596 return fd;
597 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800598 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700599 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
600 if (n < 0 || n >= (int)sizeof(buf)) {
601 WARN("Ignoring very long library path: %s/%s\n", *path, name);
602 continue;
603 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800604 if ((fd = _open_lib(buf)) >= 0)
605 return fd;
606 }
607
608 return -1;
609}
610
611/* temporary space for holding the first page of the shared lib
612 * which contains the elf header (with the pht). */
613static unsigned char __header[PAGE_SIZE];
614
615typedef struct {
616 long mmap_addr;
617 char tag[4]; /* 'P', 'R', 'E', ' ' */
618} prelink_info_t;
619
620/* Returns the requested base address if the library is prelinked,
621 * and 0 otherwise. */
622static unsigned long
623is_prelinked(int fd, const char *name)
624{
625 off_t sz;
626 prelink_info_t info;
627
628 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
629 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700630 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800631 return 0;
632 }
633
634 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
635 WARN("Could not read prelink_info_t structure for `%s`\n", name);
636 return 0;
637 }
638
639 if (strncmp(info.tag, "PRE ", 4)) {
640 WARN("`%s` is not a prelinked library\n", name);
641 return 0;
642 }
643
644 return (unsigned long)info.mmap_addr;
645}
646
647/* verify_elf_object
648 * Verifies if the object @ base is a valid ELF object
649 *
650 * Args:
651 *
652 * Returns:
653 * 0 on success
654 * -1 if no valid ELF object is found @ base.
655 */
656static int
657verify_elf_object(void *base, const char *name)
658{
659 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
660
661 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
662 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
663 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
664 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
665
666 /* TODO: Should we verify anything else in the header? */
667
668 return 0;
669}
670
671
672/* get_lib_extents
673 * Retrieves the base (*base) address where the ELF object should be
674 * mapped and its overall memory size (*total_sz).
675 *
676 * Args:
677 * fd: Opened file descriptor for the library
678 * name: The name of the library
679 * _hdr: Pointer to the header page of the library
680 * total_sz: Total size of the memory that should be allocated for
681 * this library
682 *
683 * Returns:
684 * -1 if there was an error while trying to get the lib extents.
685 * The possible reasons are:
686 * - Could not determine if the library was prelinked.
687 * - The library provided is not a valid ELF object
688 * 0 if the library did not request a specific base offset (normal
689 * for non-prelinked libs)
690 * > 0 if the library requests a specific address to be mapped to.
691 * This indicates a pre-linked library.
692 */
693static unsigned
694get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
695{
696 unsigned req_base;
697 unsigned min_vaddr = 0xffffffff;
698 unsigned max_vaddr = 0;
699 unsigned char *_hdr = (unsigned char *)__hdr;
700 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
701 Elf32_Phdr *phdr;
702 int cnt;
703
704 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
705 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700706 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800707 return (unsigned)-1;
708 }
709
710 req_base = (unsigned) is_prelinked(fd, name);
711 if (req_base == (unsigned)-1)
712 return -1;
713 else if (req_base != 0) {
714 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
715 pid, name, req_base);
716 } else {
717 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
718 }
719
720 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
721
722 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
723 * get the range. */
724 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
725 if (phdr->p_type == PT_LOAD) {
726 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
727 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
728 if (phdr->p_vaddr < min_vaddr)
729 min_vaddr = phdr->p_vaddr;
730 }
731 }
732
733 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700734 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800735 return (unsigned)-1;
736 }
737
738 /* truncate min_vaddr down to page boundary */
739 min_vaddr &= ~PAGE_MASK;
740
741 /* round max_vaddr up to the next page */
742 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
743
744 *total_sz = (max_vaddr - min_vaddr);
745 return (unsigned)req_base;
746}
747
748/* alloc_mem_region
749 *
750 * This function reserves a chunk of memory to be used for mapping in
751 * the shared library. We reserve the entire memory region here, and
752 * then the rest of the linker will relocate the individual loadable
753 * segments into the correct locations within this memory range.
754 *
755 * Args:
756 * si->base: The requested base of the allocation. If 0, a sane one will be
757 * chosen in the range LIBBASE <= base < LIBLAST.
758 * si->size: The size of the allocation.
759 *
760 * Returns:
761 * -1 on failure, and 0 on success. On success, si->base will contain
762 * the virtual address at which the library will be mapped.
763 */
764
765static int reserve_mem_region(soinfo *si)
766{
767 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
768 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
769 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700770 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700771 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800772 pid, (si->base ? "" : "non-"), si->name, si->base,
773 errno, strerror(errno));
774 return -1;
775 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700776 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700777 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800778 si->name, (unsigned)base, si->base);
779 munmap(base, si->size);
780 return -1;
781 }
782 return 0;
783}
784
785static int
786alloc_mem_region(soinfo *si)
787{
788 if (si->base) {
789 /* Attempt to mmap a prelinked library. */
790 si->ba_index = -1;
791 return reserve_mem_region(si);
792 }
793
794 /* This is not a prelinked library, so we attempt to allocate space
795 for it from the buddy allocator, which manages the area between
796 LIBBASE and LIBLAST.
797 */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700798 si->ba_index = ba_allocate(&ba_prelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800799 if(si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700800 si->base = ba_start_addr(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800801 PRINT("%5d mapping library '%s' at %08x (index %d) " \
802 "through buddy allocator.\n",
803 pid, si->name, si->base, si->ba_index);
804 if (reserve_mem_region(si) < 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700805 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800806 si->ba_index = -1;
807 si->base = 0;
808 goto err;
809 }
810 return 0;
811 }
812
813err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700814 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800815 pid, si->name);
816 return -1;
817}
818
819#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
820#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
821 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
822 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
823/* load_segments
824 *
825 * This function loads all the loadable (PT_LOAD) segments into memory
826 * at their appropriate memory offsets off the base address.
827 *
828 * Args:
829 * fd: Open file descriptor to the library to load.
830 * header: Pointer to a header page that contains the ELF header.
831 * This is needed since we haven't mapped in the real file yet.
832 * si: ptr to soinfo struct describing the shared object.
833 *
834 * Returns:
835 * 0 on success, -1 on failure.
836 */
837static int
838load_segments(int fd, void *header, soinfo *si)
839{
840 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
841 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
842 unsigned char *base = (unsigned char *)si->base;
843 int cnt;
844 unsigned len;
845 unsigned char *tmp;
846 unsigned char *pbase;
847 unsigned char *extra_base;
848 unsigned extra_len;
849 unsigned total_sz = 0;
850
851 si->wrprotect_start = 0xffffffff;
852 si->wrprotect_end = 0;
853
854 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
855 pid, si->name, (unsigned)si->base);
856 /* Now go through all the PT_LOAD segments and map them into memory
857 * at the appropriate locations. */
858 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
859 if (phdr->p_type == PT_LOAD) {
860 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
861 /* we want to map in the segment on a page boundary */
862 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
863 /* add the # of bytes we masked off above to the total length. */
864 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
865
866 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
867 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
868 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
869 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
870 MAP_PRIVATE | MAP_FIXED, fd,
871 phdr->p_offset & (~PAGE_MASK));
872 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700873 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700874 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800875 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
876 goto fail;
877 }
878
879 /* If 'len' didn't end on page boundary, and it's a writable
880 * segment, zero-fill the rest. */
881 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
882 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
883
884 /* Check to see if we need to extend the map for this segment to
885 * cover the diff between filesz and memsz (i.e. for bss).
886 *
887 * base _+---------------------+ page boundary
888 * . .
889 * | |
890 * . .
891 * pbase _+---------------------+ page boundary
892 * | |
893 * . .
894 * base + p_vaddr _| |
895 * . \ \ .
896 * . | filesz | .
897 * pbase + len _| / | |
898 * <0 pad> . . .
899 * extra_base _+------------|--------+ page boundary
900 * / . . .
901 * | . . .
902 * | +------------|--------+ page boundary
903 * extra_len-> | | | |
904 * | . | memsz .
905 * | . | .
906 * \ _| / |
907 * . .
908 * | |
909 * _+---------------------+ page boundary
910 */
911 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
912 (~PAGE_MASK));
913 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
914 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
915 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
916 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
917 /* map in the extra page(s) as anonymous into the range.
918 * This is probably not necessary as we already mapped in
919 * the entire region previously, but we just want to be
920 * sure. This will also set the right flags on the region
921 * (though we can probably accomplish the same thing with
922 * mprotect).
923 */
924 extra_base = mmap((void *)tmp, extra_len,
925 PFLAGS_TO_PROT(phdr->p_flags),
926 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
927 -1, 0);
928 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700929 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700930 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800931 extra_len);
932 goto fail;
933 }
934 /* TODO: Check if we need to memset-0 this region.
935 * Anonymous mappings are zero-filled copy-on-writes, so we
936 * shouldn't need to. */
937 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
938 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
939 extra_len);
940 }
941 /* set the len here to show the full extent of the segment we
942 * just loaded, mostly for debugging */
943 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
944 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
945 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
946 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
947 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
948 total_sz += len;
949 /* Make the section writable just in case we'll have to write to
950 * it during relocation (i.e. text segment). However, we will
951 * remember what range of addresses should be write protected.
952 *
953 */
954 if (!(phdr->p_flags & PF_W)) {
955 if ((unsigned)pbase < si->wrprotect_start)
956 si->wrprotect_start = (unsigned)pbase;
957 if (((unsigned)pbase + len) > si->wrprotect_end)
958 si->wrprotect_end = (unsigned)pbase + len;
959 mprotect(pbase, len,
960 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
961 }
962 } else if (phdr->p_type == PT_DYNAMIC) {
963 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
964 /* this segment contains the dynamic linking information */
965 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
966 } else {
967#ifdef ANDROID_ARM_LINKER
968 if (phdr->p_type == PT_ARM_EXIDX) {
969 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
970 /* exidx entries (used for stack unwinding) are 8 bytes each.
971 */
972 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
973 si->ARM_exidx_count = phdr->p_memsz / 8;
974 }
975#endif
976 }
977
978 }
979
980 /* Sanity check */
981 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700982 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700983 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800984 pid, total_sz, si->name, si->size);
985 goto fail;
986 }
987
988 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
989 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
990 (unsigned)si->base, si->size);
991 return 0;
992
993fail:
994 /* We can just blindly unmap the entire region even though some things
995 * were mapped in originally with anonymous and others could have been
996 * been mapped in from the file before we failed. The kernel will unmap
997 * all the pages in the range, irrespective of how they got there.
998 */
999 munmap((void *)si->base, si->size);
1000 si->flags |= FLAG_ERROR;
1001 return -1;
1002}
1003
1004/* TODO: Implement this to take care of the fact that Android ARM
1005 * ELF objects shove everything into a single loadable segment that has the
1006 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1007 * non-writable.
1008 */
1009#if 0
1010static unsigned
1011get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1012{
1013 Elf32_Shdr *shdr_start;
1014 Elf32_Shdr *shdr;
1015 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1016 int cnt;
1017 unsigned wr_offset = 0xffffffff;
1018
1019 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1020 ehdr->e_shoff & (~PAGE_MASK));
1021 if (shdr_start == MAP_FAILED) {
1022 WARN("%5d - Could not read section header info from '%s'. Will not "
1023 "not be able to determine write-protect offset.\n", pid, name);
1024 return (unsigned)-1;
1025 }
1026
1027 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1028 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1029 (shdr->sh_addr < wr_offset)) {
1030 wr_offset = shdr->sh_addr;
1031 }
1032 }
1033
1034 munmap(shdr_start, shdr_sz);
1035 return wr_offset;
1036}
1037#endif
1038
1039static soinfo *
1040load_library(const char *name)
1041{
1042 int fd = open_library(name);
1043 int cnt;
1044 unsigned ext_sz;
1045 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001046 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001047 soinfo *si = NULL;
1048 Elf32_Ehdr *hdr;
1049
Dima Zavin2e855792009-05-20 18:28:09 -07001050 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001051 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001052 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001053 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001054
1055 /* We have to read the ELF header to figure out what to do with this image
1056 */
1057 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001058 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001059 goto fail;
1060 }
1061
1062 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001063 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001064 goto fail;
1065 }
1066
1067 /* Parse the ELF header and get the size of the memory footprint for
1068 * the library */
1069 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1070 if (req_base == (unsigned)-1)
1071 goto fail;
1072 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1073 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1074
1075 /* Now configure the soinfo struct where we'll store all of our data
1076 * for the ELF object. If the loading fails, we waste the entry, but
1077 * same thing would happen if we failed during linking. Configuring the
1078 * soinfo struct here is a lot more convenient.
1079 */
Erik Gillingfde86422009-07-28 20:28:19 -07001080 bname = strrchr(name, '/');
1081 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001082 if (si == NULL)
1083 goto fail;
1084
1085 /* Carve out a chunk of memory where we will map in the individual
1086 * segments */
1087 si->base = req_base;
1088 si->size = ext_sz;
1089 si->flags = 0;
1090 si->entry = 0;
1091 si->dynamic = (unsigned *)-1;
1092 if (alloc_mem_region(si) < 0)
1093 goto fail;
1094
1095 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1096 pid, name, (void *)si->base, (unsigned) ext_sz);
1097
1098 /* Now actually load the library's segments into right places in memory */
1099 if (load_segments(fd, &__header[0], si) < 0) {
1100 if (si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001101 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001102 si->ba_index = -1;
1103 }
1104 goto fail;
1105 }
1106
1107 /* this might not be right. Technically, we don't even need this info
1108 * once we go through 'load_segments'. */
1109 hdr = (Elf32_Ehdr *)si->base;
1110 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1111 si->phnum = hdr->e_phnum;
1112 /**/
1113
1114 close(fd);
1115 return si;
1116
1117fail:
1118 if (si) free_info(si);
1119 close(fd);
1120 return NULL;
1121}
1122
1123static soinfo *
1124init_library(soinfo *si)
1125{
1126 unsigned wr_offset = 0xffffffff;
1127
1128 /* At this point we know that whatever is loaded @ base is a valid ELF
1129 * shared library whose segments are properly mapped in. */
1130 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1131 pid, si->base, si->size, si->name);
1132
1133 if (si->base < LIBBASE || si->base >= LIBLAST)
1134 si->flags |= FLAG_PRELINKED;
1135
1136 if(link_image(si, wr_offset)) {
1137 /* We failed to link. However, we can only restore libbase
1138 ** if no additional libraries have moved it since we updated it.
1139 */
1140 munmap((void *)si->base, si->size);
1141 return NULL;
1142 }
1143
1144 return si;
1145}
1146
1147soinfo *find_library(const char *name)
1148{
1149 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001150 const char *bname = strrchr(name, '/');
1151 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001152
1153 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001154 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001155 if(si->flags & FLAG_ERROR) {
1156 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1157 return NULL;
1158 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001159 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001160 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001161 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001162 }
1163 }
1164
1165 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1166 si = load_library(name);
1167 if(si == NULL)
1168 return NULL;
1169 return init_library(si);
1170}
1171
1172/* TODO:
1173 * notify gdb of unload
1174 * for non-prelinked libraries, find a way to decrement libbase
1175 */
1176static void call_destructors(soinfo *si);
1177unsigned unload_library(soinfo *si)
1178{
1179 unsigned *d;
1180 if (si->refcount == 1) {
1181 TRACE("%5d unloading '%s'\n", pid, si->name);
1182 call_destructors(si);
1183
1184 for(d = si->dynamic; *d; d += 2) {
1185 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001186 soinfo *lsi = (soinfo *)d[1];
1187 d[1] = 0;
1188 if (validate_soinfo(lsi)) {
1189 TRACE("%5d %s needs to unload %s\n", pid,
1190 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001192 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001193 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001194 DL_ERR("%5d %s: could not unload dependent library",
1195 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001196 }
1197 }
1198
1199 munmap((char *)si->base, si->size);
1200 if (si->ba_index >= 0) {
1201 PRINT("%5d releasing library '%s' address space at %08x "\
1202 "through buddy allocator.\n",
1203 pid, si->name, si->base);
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001204 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001205 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001206 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001207 free_info(si);
1208 si->refcount = 0;
1209 }
1210 else {
1211 si->refcount--;
1212 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1213 pid, si->name, si->refcount);
1214 }
1215 return si->refcount;
1216}
1217
1218/* TODO: don't use unsigned for addrs below. It works, but is not
1219 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1220 * long.
1221 */
1222static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1223{
1224 Elf32_Sym *symtab = si->symtab;
1225 const char *strtab = si->strtab;
1226 Elf32_Sym *s;
1227 unsigned base;
1228 Elf32_Rel *start = rel;
1229 unsigned idx;
1230
1231 for (idx = 0; idx < count; ++idx) {
1232 unsigned type = ELF32_R_TYPE(rel->r_info);
1233 unsigned sym = ELF32_R_SYM(rel->r_info);
1234 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1235 unsigned sym_addr = 0;
1236 char *sym_name = NULL;
1237
1238 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1239 si->name, idx);
1240 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001241 sym_name = (char *)(strtab + symtab[sym].st_name);
1242 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001243 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001244 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001245 return -1;
1246 }
1247#if 0
1248 if((base == 0) && (si->base != 0)){
1249 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001250 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001251 pid, strtab + symtab[sym].st_name);
1252 return -1;
1253 }
1254#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001255 // st_shndx==SHN_UNDEF means an undefined symbol.
1256 // st_value should be 0 then, except that the low bit of st_value is
1257 // used to indicate whether the symbol points to an ARM or thumb function,
1258 // and should be ignored in the following check.
1259 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1260 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1261 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001262 s->st_value);
1263 return -1;
1264 }
1265 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001266 COUNT_RELOC(RELOC_SYMBOL);
1267 } else {
1268 s = 0;
1269 }
1270
1271/* TODO: This is ugly. Split up the relocations by arch into
1272 * different files.
1273 */
1274 switch(type){
1275#if defined(ANDROID_ARM_LINKER)
1276 case R_ARM_JUMP_SLOT:
1277 COUNT_RELOC(RELOC_ABSOLUTE);
1278 MARK(rel->r_offset);
1279 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1280 reloc, sym_addr, sym_name);
1281 *((unsigned*)reloc) = sym_addr;
1282 break;
1283 case R_ARM_GLOB_DAT:
1284 COUNT_RELOC(RELOC_ABSOLUTE);
1285 MARK(rel->r_offset);
1286 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1287 reloc, sym_addr, sym_name);
1288 *((unsigned*)reloc) = sym_addr;
1289 break;
1290 case R_ARM_ABS32:
1291 COUNT_RELOC(RELOC_ABSOLUTE);
1292 MARK(rel->r_offset);
1293 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1294 reloc, sym_addr, sym_name);
1295 *((unsigned*)reloc) += sym_addr;
1296 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001297 case R_ARM_REL32:
1298 COUNT_RELOC(RELOC_RELATIVE);
1299 MARK(rel->r_offset);
1300 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1301 reloc, sym_addr, rel->r_offset, sym_name);
1302 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1303 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001304#elif defined(ANDROID_X86_LINKER)
1305 case R_386_JUMP_SLOT:
1306 COUNT_RELOC(RELOC_ABSOLUTE);
1307 MARK(rel->r_offset);
1308 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1309 reloc, sym_addr, sym_name);
1310 *((unsigned*)reloc) = sym_addr;
1311 break;
1312 case R_386_GLOB_DAT:
1313 COUNT_RELOC(RELOC_ABSOLUTE);
1314 MARK(rel->r_offset);
1315 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1316 reloc, sym_addr, sym_name);
1317 *((unsigned*)reloc) = sym_addr;
1318 break;
1319#endif /* ANDROID_*_LINKER */
1320
1321#if defined(ANDROID_ARM_LINKER)
1322 case R_ARM_RELATIVE:
1323#elif defined(ANDROID_X86_LINKER)
1324 case R_386_RELATIVE:
1325#endif /* ANDROID_*_LINKER */
1326 COUNT_RELOC(RELOC_RELATIVE);
1327 MARK(rel->r_offset);
1328 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001329 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001330 return -1;
1331 }
1332 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1333 reloc, si->base);
1334 *((unsigned*)reloc) += si->base;
1335 break;
1336
1337#if defined(ANDROID_X86_LINKER)
1338 case R_386_32:
1339 COUNT_RELOC(RELOC_RELATIVE);
1340 MARK(rel->r_offset);
1341
1342 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1343 reloc, sym_addr, sym_name);
1344 *((unsigned *)reloc) += (unsigned)sym_addr;
1345 break;
1346
1347 case R_386_PC32:
1348 COUNT_RELOC(RELOC_RELATIVE);
1349 MARK(rel->r_offset);
1350 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1351 "+%08x (%08x - %08x) %s\n", pid, reloc,
1352 (sym_addr - reloc), sym_addr, reloc, sym_name);
1353 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1354 break;
1355#endif /* ANDROID_X86_LINKER */
1356
1357#ifdef ANDROID_ARM_LINKER
1358 case R_ARM_COPY:
1359 COUNT_RELOC(RELOC_COPY);
1360 MARK(rel->r_offset);
1361 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1362 reloc, s->st_size, sym_addr, sym_name);
1363 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1364 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001365 case R_ARM_NONE:
1366 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001367#endif /* ANDROID_ARM_LINKER */
1368
1369 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001370 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001371 pid, type, rel, (int) (rel - start));
1372 return -1;
1373 }
1374 rel++;
1375 }
1376 return 0;
1377}
1378
David 'Digit' Turner82156792009-05-18 14:37:41 +02001379
1380/* Please read the "Initialization and Termination functions" functions.
1381 * of the linker design note in bionic/linker/README.TXT to understand
1382 * what the following code is doing.
1383 *
1384 * The important things to remember are:
1385 *
1386 * DT_PREINIT_ARRAY must be called first for executables, and should
1387 * not appear in shared libraries.
1388 *
1389 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1390 *
1391 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1392 *
1393 * DT_FINI_ARRAY must be parsed in reverse order.
1394 */
1395
1396static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001398 int n, inc = 1;
1399
1400 if (reverse) {
1401 ctor += (count-1);
1402 inc = -1;
1403 }
1404
1405 for(n = count; n > 0; n--) {
1406 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1407 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001408 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001409 void (*func)() = (void (*)()) *ctor;
1410 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001411 if(((int) func == 0) || ((int) func == -1)) continue;
1412 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1413 func();
1414 }
1415}
1416
1417static void call_constructors(soinfo *si)
1418{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001419 if (si->flags & FLAG_EXE) {
1420 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1421 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1422 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001423 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001424 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1425 } else {
1426 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001427 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001428 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001429 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001430 }
1431 }
1432
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001433 if (si->init_func) {
1434 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1435 (unsigned)si->init_func, si->name);
1436 si->init_func();
1437 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1438 }
1439
1440 if (si->init_array) {
1441 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1442 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001443 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001444 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1445 }
1446}
1447
David 'Digit' Turner82156792009-05-18 14:37:41 +02001448
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001449static void call_destructors(soinfo *si)
1450{
1451 if (si->fini_array) {
1452 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1453 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001454 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001455 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1456 }
1457
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001458 if (si->fini_func) {
1459 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1460 (unsigned)si->fini_func, si->name);
1461 si->fini_func();
1462 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1463 }
1464}
1465
1466/* Force any of the closed stdin, stdout and stderr to be associated with
1467 /dev/null. */
1468static int nullify_closed_stdio (void)
1469{
1470 int dev_null, i, status;
1471 int return_value = 0;
1472
1473 dev_null = open("/dev/null", O_RDWR);
1474 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001475 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001476 return -1;
1477 }
1478 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1479
1480 /* If any of the stdio file descriptors is valid and not associated
1481 with /dev/null, dup /dev/null to it. */
1482 for (i = 0; i < 3; i++) {
1483 /* If it is /dev/null already, we are done. */
1484 if (i == dev_null)
1485 continue;
1486
1487 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1488 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1489 can be interrupted but we do this just to be safe. */
1490 do {
1491 status = fcntl(i, F_GETFL);
1492 } while (status < 0 && errno == EINTR);
1493
1494 /* If file is openned, we are good. */
1495 if (status >= 0)
1496 continue;
1497
1498 /* The only error we allow is that the file descriptor does not
1499 exist, in which case we dup /dev/null to it. */
1500 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001501 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001502 return_value = -1;
1503 continue;
1504 }
1505
1506 /* Try dupping /dev/null to this stdio file descriptor and
1507 repeat if there is a signal. Note that any errors in closing
1508 the stdio descriptor are lost. */
1509 do {
1510 status = dup2(dev_null, i);
1511 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001512
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001513 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001514 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001515 return_value = -1;
1516 continue;
1517 }
1518 }
1519
1520 /* If /dev/null is not one of the stdio file descriptors, close it. */
1521 if (dev_null > 2) {
1522 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001523 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001524 status = close(dev_null);
1525 } while (status < 0 && errno == EINTR);
1526
1527 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001528 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001529 return_value = -1;
1530 }
1531 }
1532
1533 return return_value;
1534}
1535
1536static int link_image(soinfo *si, unsigned wr_offset)
1537{
1538 unsigned *d;
1539 Elf32_Phdr *phdr = si->phdr;
1540 int phnum = si->phnum;
1541
1542 INFO("[ %5d linking %s ]\n", pid, si->name);
1543 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1544 si->base, si->flags);
1545
1546 if (si->flags & FLAG_EXE) {
1547 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1548 * linkage info if this is the executable. If this was a
1549 * dynamic lib, that would have been done at load time.
1550 *
1551 * TODO: It's unfortunate that small pieces of this are
1552 * repeated from the load_library routine. Refactor this just
1553 * slightly to reuse these bits.
1554 */
1555 si->size = 0;
1556 for(; phnum > 0; --phnum, ++phdr) {
1557#ifdef ANDROID_ARM_LINKER
1558 if(phdr->p_type == PT_ARM_EXIDX) {
1559 /* exidx entries (used for stack unwinding) are 8 bytes each.
1560 */
1561 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1562 si->ARM_exidx_count = phdr->p_memsz / 8;
1563 }
1564#endif
1565 if (phdr->p_type == PT_LOAD) {
1566 /* For the executable, we use the si->size field only in
1567 dl_unwind_find_exidx(), so the meaning of si->size
1568 is not the size of the executable; it is the last
1569 virtual address of the loadable part of the executable;
1570 since si->base == 0 for an executable, we use the
1571 range [0, si->size) to determine whether a PC value
1572 falls within the executable section. Of course, if
1573 a value is below phdr->p_vaddr, it's not in the
1574 executable section, but a) we shouldn't be asking for
1575 such a value anyway, and b) if we have to provide
1576 an EXIDX for such a value, then the executable's
1577 EXIDX is probably the better choice.
1578 */
1579 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1580 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1581 si->size = phdr->p_vaddr + phdr->p_memsz;
1582 /* try to remember what range of addresses should be write
1583 * protected */
1584 if (!(phdr->p_flags & PF_W)) {
1585 unsigned _end;
1586
1587 if (phdr->p_vaddr < si->wrprotect_start)
1588 si->wrprotect_start = phdr->p_vaddr;
1589 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1590 (~PAGE_MASK)));
1591 if (_end > si->wrprotect_end)
1592 si->wrprotect_end = _end;
1593 }
1594 } else if (phdr->p_type == PT_DYNAMIC) {
1595 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001596 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001597 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001598 pid, si->name, si->base + phdr->p_vaddr,
1599 (unsigned)si->dynamic);
1600 goto fail;
1601 }
1602 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1603 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1604 }
1605 }
1606 }
1607
1608 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001609 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001610 goto fail;
1611 }
1612
1613 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1614
1615 /* extract useful information from dynamic section */
1616 for(d = si->dynamic; *d; d++){
1617 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1618 switch(*d++){
1619 case DT_HASH:
1620 si->nbucket = ((unsigned *) (si->base + *d))[0];
1621 si->nchain = ((unsigned *) (si->base + *d))[1];
1622 si->bucket = (unsigned *) (si->base + *d + 8);
1623 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1624 break;
1625 case DT_STRTAB:
1626 si->strtab = (const char *) (si->base + *d);
1627 break;
1628 case DT_SYMTAB:
1629 si->symtab = (Elf32_Sym *) (si->base + *d);
1630 break;
1631 case DT_PLTREL:
1632 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001633 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001634 goto fail;
1635 }
1636 break;
1637 case DT_JMPREL:
1638 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1639 break;
1640 case DT_PLTRELSZ:
1641 si->plt_rel_count = *d / 8;
1642 break;
1643 case DT_REL:
1644 si->rel = (Elf32_Rel*) (si->base + *d);
1645 break;
1646 case DT_RELSZ:
1647 si->rel_count = *d / 8;
1648 break;
1649 case DT_PLTGOT:
1650 /* Save this in case we decide to do lazy binding. We don't yet. */
1651 si->plt_got = (unsigned *)(si->base + *d);
1652 break;
1653 case DT_DEBUG:
1654 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1655 *d = (int) &_r_debug;
1656 break;
1657 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001658 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001659 goto fail;
1660 case DT_INIT:
1661 si->init_func = (void (*)(void))(si->base + *d);
1662 DEBUG("%5d %s constructors (init func) found at %p\n",
1663 pid, si->name, si->init_func);
1664 break;
1665 case DT_FINI:
1666 si->fini_func = (void (*)(void))(si->base + *d);
1667 DEBUG("%5d %s destructors (fini func) found at %p\n",
1668 pid, si->name, si->fini_func);
1669 break;
1670 case DT_INIT_ARRAY:
1671 si->init_array = (unsigned *)(si->base + *d);
1672 DEBUG("%5d %s constructors (init_array) found at %p\n",
1673 pid, si->name, si->init_array);
1674 break;
1675 case DT_INIT_ARRAYSZ:
1676 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1677 break;
1678 case DT_FINI_ARRAY:
1679 si->fini_array = (unsigned *)(si->base + *d);
1680 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1681 pid, si->name, si->fini_array);
1682 break;
1683 case DT_FINI_ARRAYSZ:
1684 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1685 break;
1686 case DT_PREINIT_ARRAY:
1687 si->preinit_array = (unsigned *)(si->base + *d);
1688 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1689 pid, si->name, si->preinit_array);
1690 break;
1691 case DT_PREINIT_ARRAYSZ:
1692 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1693 break;
1694 case DT_TEXTREL:
1695 /* TODO: make use of this. */
1696 /* this means that we might have to write into where the text
1697 * segment was loaded during relocation... Do something with
1698 * it.
1699 */
1700 DEBUG("%5d Text segment should be writable during relocation.\n",
1701 pid);
1702 break;
1703 }
1704 }
1705
1706 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1707 pid, si->base, si->strtab, si->symtab);
1708
1709 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001710 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001711 goto fail;
1712 }
1713
1714 for(d = si->dynamic; *d; d += 2) {
1715 if(d[0] == DT_NEEDED){
1716 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001717 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001718 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001719 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001720 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001721 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001722 goto fail;
1723 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001724 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1725 of the DT_NEEDED entry itself, so that we can retrieve the
1726 soinfo directly later from the dynamic segment. This is a hack,
1727 but it allows us to map from DT_NEEDED to soinfo efficiently
1728 later on when we resolve relocations, trying to look up a symgol
1729 with dlsym().
1730 */
1731 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001732 lsi->refcount++;
1733 }
1734 }
1735
1736 if(si->plt_rel) {
1737 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1738 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1739 goto fail;
1740 }
1741 if(si->rel) {
1742 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1743 if(reloc_library(si, si->rel, si->rel_count))
1744 goto fail;
1745 }
1746
1747 si->flags |= FLAG_LINKED;
1748 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1749
1750#if 0
1751 /* This is the way that the old dynamic linker did protection of
1752 * non-writable areas. It would scan section headers and find where
1753 * .text ended (rather where .data/.bss began) and assume that this is
1754 * the upper range of the non-writable area. This is too coarse,
1755 * and is kept here for reference until we fully move away from single
1756 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1757 * that made this possible.
1758 */
1759 if(wr_offset < 0xffffffff){
1760 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1761 }
1762#else
1763 /* TODO: Verify that this does the right thing in all cases, as it
1764 * presently probably does not. It is possible that an ELF image will
1765 * come with multiple read-only segments. What we ought to do is scan
1766 * the program headers again and mprotect all the read-only segments.
1767 * To prevent re-scanning the program header, we would have to build a
1768 * list of loadable segments in si, and then scan that instead. */
1769 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1770 mprotect((void *)si->wrprotect_start,
1771 si->wrprotect_end - si->wrprotect_start,
1772 PROT_READ | PROT_EXEC);
1773 }
1774#endif
1775
1776 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1777 stdout and stderr to close a security hole described in:
1778
1779 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1780
1781 */
1782 if (getuid() != geteuid() || getgid() != getegid())
1783 nullify_closed_stdio ();
1784 call_constructors(si);
1785 notify_gdb_of_load(si);
1786 return 0;
1787
1788fail:
1789 ERROR("failed to link %s\n", si->name);
1790 si->flags |= FLAG_ERROR;
1791 return -1;
1792}
1793
David Bartleybc3a5c22009-06-02 18:27:28 -07001794static void parse_library_path(char *path, char *delim)
1795{
1796 size_t len;
1797 char *ldpaths_bufp = ldpaths_buf;
1798 int i = 0;
1799
1800 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1801
1802 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1803 if (*ldpaths[i] != '\0')
1804 ++i;
1805 }
1806
1807 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1808 * last char isn't '\0' (i.e. not originally a delim). */
1809 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1810 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1811 ldpaths[i - 1] = NULL;
1812 } else {
1813 ldpaths[i] = NULL;
1814 }
1815}
1816
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001817int main(int argc, char **argv)
1818{
1819 return 0;
1820}
1821
1822#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1823
1824static void * __tls_area[ANDROID_TLS_SLOTS];
1825
1826unsigned __linker_init(unsigned **elfdata)
1827{
1828 static soinfo linker_soinfo;
1829
1830 int argc = (int) *elfdata;
1831 char **argv = (char**) (elfdata + 1);
1832 unsigned *vecs = (unsigned*) (argv + argc + 1);
1833 soinfo *si;
1834 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001835 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001836
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001837 /* Setup a temporary TLS area that is used to get a working
1838 * errno for system calls.
1839 */
1840 __set_tls(__tls_area);
1841
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001842 pid = getpid();
1843
1844#if TIMING
1845 struct timeval t0, t1;
1846 gettimeofday(&t0, 0);
1847#endif
1848
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001849 /* NOTE: we store the elfdata pointer on a special location
1850 * of the temporary TLS area in order to pass it to
1851 * the C Library's runtime initializer.
1852 *
1853 * The initializer must clear the slot and reset the TLS
1854 * to point to a different location to ensure that no other
1855 * shared library constructor can access it.
1856 */
1857 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001858
1859 debugger_init();
1860
1861 /* skip past the environment */
1862 while(vecs[0] != 0) {
1863 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1864 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001865 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1866 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001867 }
1868 vecs++;
1869 }
1870 vecs++;
1871
1872 INFO("[ android linker & debugger ]\n");
1873 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1874
1875 si = alloc_info(argv[0]);
1876 if(si == 0) {
1877 exit(-1);
1878 }
1879
1880 /* bootstrap the link map, the main exe always needs to be first */
1881 si->flags |= FLAG_EXE;
1882 map = &(si->linkmap);
1883
1884 map->l_addr = 0;
1885 map->l_name = argv[0];
1886 map->l_prev = NULL;
1887 map->l_next = NULL;
1888
1889 _r_debug.r_map = map;
1890 r_debug_tail = map;
1891
1892 /* gdb expects the linker to be in the debug shared object list,
1893 * and we need to make sure that the reported load address is zero.
1894 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1895 * is. Don't use alloc_info(), because the linker shouldn't
1896 * be on the soinfo list.
1897 */
1898 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1899 linker_soinfo.flags = 0;
1900 linker_soinfo.base = 0; // This is the important part; must be zero.
1901 insert_soinfo_into_debug_map(&linker_soinfo);
1902
1903 /* extract information passed from the kernel */
1904 while(vecs[0] != 0){
1905 switch(vecs[0]){
1906 case AT_PHDR:
1907 si->phdr = (Elf32_Phdr*) vecs[1];
1908 break;
1909 case AT_PHNUM:
1910 si->phnum = (int) vecs[1];
1911 break;
1912 case AT_ENTRY:
1913 si->entry = vecs[1];
1914 break;
1915 }
1916 vecs += 2;
1917 }
1918
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001919 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001920
1921 si->base = 0;
1922 si->dynamic = (unsigned *)-1;
1923 si->wrprotect_start = 0xffffffff;
1924 si->wrprotect_end = 0;
1925
David Bartleybc3a5c22009-06-02 18:27:28 -07001926 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1927 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1928 parse_library_path(ldpath_env, ":");
1929
Dima Zavin2e855792009-05-20 18:28:09 -07001930 if(link_image(si, 0)) {
1931 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1932 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1933 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001934 exit(-1);
1935 }
1936
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001937#if ALLOW_SYMBOLS_FROM_MAIN
1938 /* Set somain after we've loaded all the libraries in order to prevent
1939 * linking of symbols back to the main image, which is not set up at that
1940 * point yet.
1941 */
1942 somain = si;
1943#endif
1944
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001945#if TIMING
1946 gettimeofday(&t1,NULL);
1947 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1948 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1949 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1950 ));
1951#endif
1952#if STATS
1953 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1954 linker_stats.reloc[RELOC_ABSOLUTE],
1955 linker_stats.reloc[RELOC_RELATIVE],
1956 linker_stats.reloc[RELOC_COPY],
1957 linker_stats.reloc[RELOC_SYMBOL]);
1958#endif
1959#if COUNT_PAGES
1960 {
1961 unsigned n;
1962 unsigned i;
1963 unsigned count = 0;
1964 for(n = 0; n < 4096; n++){
1965 if(bitmask[n]){
1966 unsigned x = bitmask[n];
1967 for(i = 0; i < 8; i++){
1968 if(x & 1) count++;
1969 x >>= 1;
1970 }
1971 }
1972 }
1973 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1974 }
1975#endif
1976
1977#if TIMING || STATS || COUNT_PAGES
1978 fflush(stdout);
1979#endif
1980
1981 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1982 si->entry);
1983 return si->entry;
1984}