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