blob: 5f93bd3ce8b923b63941dfb508772f04ce85980d [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
Doug Kwan94304352009-10-23 18:11:40 -07002 * Copyright (C) 2008, 2009 The Android Open Source Project
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <linux/auxvec.h>
30
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35#include <fcntl.h>
36#include <errno.h>
37#include <dlfcn.h>
38#include <sys/stat.h>
39
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -070040#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
42#include <sys/mman.h>
43
44#include <sys/atomics.h>
45
46/* special private C library header - see Android.mk */
47#include <bionic_tls.h>
48
49#include "linker.h"
50#include "linker_debug.h"
51
52#include "ba.h"
53
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070054#define ALLOW_SYMBOLS_FROM_MAIN 1
James Dongba52b302009-04-30 20:37:36 -070055#define SO_MAX 96
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056
David Bartleybc3a5c22009-06-02 18:27:28 -070057/* Assume average path length of 64 and max 8 paths */
58#define LDPATH_BUFSIZE 512
59#define LDPATH_MAX 8
60
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080061/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
62 *
63 * Do NOT use malloc() and friends or pthread_*() code here.
64 * Don't use printf() either; it's caused mysterious memory
65 * corruption in the past.
66 * The linker runs before we bring up libc and it's easiest
67 * to make sure it does not depend on any complex libc features
68 *
69 * open issues / todo:
70 *
71 * - should we do anything special for STB_WEAK symbols?
72 * - are we doing everything we should for ARM_COPY relocations?
73 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080074 * - after linking, set as much stuff as possible to READONLY
75 * and NOEXEC
76 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
77 * headers provide versions that are negative...
78 * - allocate space for soinfo structs dynamically instead of
79 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080*/
81
82
83static int link_image(soinfo *si, unsigned wr_offset);
84
85static int socount = 0;
86static soinfo sopool[SO_MAX];
87static soinfo *freelist = NULL;
88static soinfo *solist = &libdl_info;
89static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070090#if ALLOW_SYMBOLS_FROM_MAIN
91static soinfo *somain; /* main process, always the one after libdl_info */
92#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080093
Iliyan Malchevaf7315a2009-10-16 17:50:42 -070094
95/* Set up for the buddy allocator managing the prelinked libraries. */
96static struct ba_bits ba_prelink_bitmap[(LIBLAST - LIBBASE) / LIBINC];
97static struct ba ba_prelink = {
98 .base = LIBBASE,
99 .size = LIBLAST - LIBBASE,
100 .min_alloc = LIBINC,
Iliyan Malchevbb9eede2009-10-19 14:25:17 -0700101 /* max_order will be determined automatically */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700102 .bitmap = ba_prelink_bitmap,
103 .num_entries = sizeof(ba_prelink_bitmap)/sizeof(ba_prelink_bitmap[0]),
104};
105
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700106static inline int validate_soinfo(soinfo *si)
107{
108 return (si >= sopool && si < sopool + SO_MAX) ||
109 si == &libdl_info;
110}
111
David Bartleybc3a5c22009-06-02 18:27:28 -0700112static char ldpaths_buf[LDPATH_BUFSIZE];
113static const char *ldpaths[LDPATH_MAX + 1];
114
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800115int debug_verbosity;
116static int pid;
117
118#if STATS
119struct _link_stats linker_stats;
120#endif
121
122#if COUNT_PAGES
123unsigned bitmask[4096];
124#endif
125
126#ifndef PT_ARM_EXIDX
127#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
128#endif
129
Dima Zavin2e855792009-05-20 18:28:09 -0700130#define HOODLUM(name, ret, ...) \
131 ret name __VA_ARGS__ \
132 { \
133 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
134 write(2, errstr, sizeof(errstr)); \
135 abort(); \
136 }
137HOODLUM(malloc, void *, (size_t size));
138HOODLUM(free, void, (void *ptr));
139HOODLUM(realloc, void *, (void *ptr, size_t size));
140HOODLUM(calloc, void *, (size_t cnt, size_t size));
141
Dima Zavin03531952009-05-29 17:30:25 -0700142static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700143static char __linker_dl_err_buf[768];
144#define DL_ERR(fmt, x...) \
145 do { \
146 snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
147 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700148 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700149 } while(0)
150
151const char *linker_get_error(void)
152{
153 return (const char *)&__linker_dl_err_buf[0];
154}
155
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800156/*
157 * This function is an empty stub where GDB locates a breakpoint to get notified
158 * about linker activity.
159 */
160extern void __attribute__((noinline)) rtld_db_dlactivity(void);
161
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800162static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
163 RT_CONSISTENT, 0};
164static struct link_map *r_debug_tail = 0;
165
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700166static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800167
168static void insert_soinfo_into_debug_map(soinfo * info)
169{
170 struct link_map * map;
171
172 /* Copy the necessary fields into the debug structure.
173 */
174 map = &(info->linkmap);
175 map->l_addr = info->base;
176 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800177 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800178
179 /* Stick the new library at the end of the list.
180 * gdb tends to care more about libc than it does
181 * about leaf libraries, and ordering it this way
182 * reduces the back-and-forth over the wire.
183 */
184 if (r_debug_tail) {
185 r_debug_tail->l_next = map;
186 map->l_prev = r_debug_tail;
187 map->l_next = 0;
188 } else {
189 _r_debug.r_map = map;
190 map->l_prev = 0;
191 map->l_next = 0;
192 }
193 r_debug_tail = map;
194}
195
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700196static void remove_soinfo_from_debug_map(soinfo * info)
197{
198 struct link_map * map = &(info->linkmap);
199
200 if (r_debug_tail == map)
201 r_debug_tail = map->l_prev;
202
203 if (map->l_prev) map->l_prev->l_next = map->l_next;
204 if (map->l_next) map->l_next->l_prev = map->l_prev;
205}
206
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800207void notify_gdb_of_load(soinfo * info)
208{
209 if (info->flags & FLAG_EXE) {
210 // GDB already knows about the main executable
211 return;
212 }
213
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700214 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800215
216 _r_debug.r_state = RT_ADD;
217 rtld_db_dlactivity();
218
219 insert_soinfo_into_debug_map(info);
220
221 _r_debug.r_state = RT_CONSISTENT;
222 rtld_db_dlactivity();
223
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700224 pthread_mutex_unlock(&_r_debug_lock);
225}
226
227void notify_gdb_of_unload(soinfo * info)
228{
229 if (info->flags & FLAG_EXE) {
230 // GDB already knows about the main executable
231 return;
232 }
233
234 pthread_mutex_lock(&_r_debug_lock);
235
236 _r_debug.r_state = RT_DELETE;
237 rtld_db_dlactivity();
238
239 remove_soinfo_from_debug_map(info);
240
241 _r_debug.r_state = RT_CONSISTENT;
242 rtld_db_dlactivity();
243
244 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800245}
246
247void notify_gdb_of_libraries()
248{
249 _r_debug.r_state = RT_ADD;
250 rtld_db_dlactivity();
251 _r_debug.r_state = RT_CONSISTENT;
252 rtld_db_dlactivity();
253}
254
255static soinfo *alloc_info(const char *name)
256{
257 soinfo *si;
258
259 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700260 DL_ERR("%5d library name %s too long", pid, name);
Doug Kwan94304352009-10-23 18:11:40 -0700261 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800262 }
263
264 /* The freelist is populated when we call free_info(), which in turn is
265 done only by dlclose(), which is not likely to be used.
266 */
267 if (!freelist) {
268 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700269 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800270 return NULL;
271 }
272 freelist = sopool + socount++;
273 freelist->next = NULL;
274 }
275
276 si = freelist;
277 freelist = freelist->next;
278
279 /* Make sure we get a clean block of soinfo */
280 memset(si, 0, sizeof(soinfo));
281 strcpy((char*) si->name, name);
282 sonext->next = si;
283 si->ba_index = -1; /* by default, prelinked */
284 si->next = NULL;
285 si->refcount = 0;
286 sonext = si;
287
288 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
289 return si;
290}
291
292static void free_info(soinfo *si)
293{
294 soinfo *prev = NULL, *trav;
295
296 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
297
298 for(trav = solist; trav != NULL; trav = trav->next){
299 if (trav == si)
300 break;
301 prev = trav;
302 }
303 if (trav == NULL) {
304 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700305 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800306 return;
307 }
308
309 /* prev will never be NULL, because the first entry in solist is
310 always the static libdl_info.
311 */
312 prev->next = si->next;
313 if (si == sonext) sonext = prev;
314 si->next = freelist;
315 freelist = si;
316}
317
318#ifndef LINKER_TEXT_BASE
319#error "linker's makefile must define LINKER_TEXT_BASE"
320#endif
321#ifndef LINKER_AREA_SIZE
322#error "linker's makefile must define LINKER_AREA_SIZE"
323#endif
324#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
325#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
326
327const char *addr_to_name(unsigned addr)
328{
329 soinfo *si;
330
331 for(si = solist; si != 0; si = si->next){
332 if((addr >= si->base) && (addr < (si->base + si->size))) {
333 return si->name;
334 }
335 }
336
337 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
338 return "linker";
339 }
340
341 return "";
342}
343
344/* For a given PC, find the .so that it belongs to.
345 * Returns the base address of the .ARM.exidx section
346 * for that .so, and the number of 8-byte entries
347 * in that section (via *pcount).
348 *
349 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
350 *
351 * This function is exposed via dlfcn.c and libdl.so.
352 */
353#ifdef ANDROID_ARM_LINKER
354_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
355{
356 soinfo *si;
357 unsigned addr = (unsigned)pc;
358
359 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
360 for (si = solist; si != 0; si = si->next){
361 if ((addr >= si->base) && (addr < (si->base + si->size))) {
362 *pcount = si->ARM_exidx_count;
363 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
364 }
365 }
366 }
367 *pcount = 0;
368 return NULL;
369}
370#elif defined(ANDROID_X86_LINKER)
371/* Here, we only have to provide a callback to iterate across all the
372 * loaded libraries. gcc_eh does the rest. */
373int
374dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
375 void *data)
376{
377 soinfo *si;
378 struct dl_phdr_info dl_info;
379 int rv = 0;
380
381 for (si = solist; si != NULL; si = si->next) {
382 dl_info.dlpi_addr = si->linkmap.l_addr;
383 dl_info.dlpi_name = si->linkmap.l_name;
384 dl_info.dlpi_phdr = si->phdr;
385 dl_info.dlpi_phnum = si->phnum;
386 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
387 if (rv != 0)
388 break;
389 }
390 return rv;
391}
392#endif
393
394static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
395{
396 Elf32_Sym *s;
397 Elf32_Sym *symtab = si->symtab;
398 const char *strtab = si->strtab;
399 unsigned n;
400
401 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
402 name, si->name, si->base, hash, hash % si->nbucket);
403 n = hash % si->nbucket;
404
405 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
406 s = symtab + n;
407 if(strcmp(strtab + s->st_name, name)) continue;
408
409 /* only concern ourselves with global symbols */
410 switch(ELF32_ST_BIND(s->st_info)){
411 case STB_GLOBAL:
412 /* no section == undefined */
413 if(s->st_shndx == 0) continue;
414
415 case STB_WEAK:
416 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
417 name, si->name, s->st_value, s->st_size);
418 return s;
419 }
420 }
421
Doug Kwan94304352009-10-23 18:11:40 -0700422 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800423}
424
425static unsigned elfhash(const char *_name)
426{
427 const unsigned char *name = (const unsigned char *) _name;
428 unsigned h = 0, g;
429
430 while(*name) {
431 h = (h << 4) + *name++;
432 g = h & 0xf0000000;
433 h ^= g;
434 h ^= g >> 24;
435 }
436 return h;
437}
438
439static Elf32_Sym *
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700440_do_lookup(soinfo *si, const char *name, unsigned *base)
441{
Doug Kwan94304352009-10-23 18:11:40 -0700442 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700443 Elf32_Sym *s;
444 unsigned *d;
445 soinfo *lsi = si;
446
447 /* Look for symbols in the local scope first (the object who is
448 * searching). This happens with C++ templates on i386 for some
449 * reason. */
Doug Kwan94304352009-10-23 18:11:40 -0700450 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700451 if(s != NULL)
452 goto done;
453
454 for(d = si->dynamic; *d; d += 2) {
455 if(d[0] == DT_NEEDED){
456 lsi = (soinfo *)d[1];
457 if (!validate_soinfo(lsi)) {
458 DL_ERR("%5d bad DT_NEEDED pointer in %s",
459 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700460 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700461 }
462
463 DEBUG("%5d %s: looking up %s in %s\n",
464 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700465 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700466 if(s != NULL)
467 goto done;
468 }
469 }
470
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700471#if ALLOW_SYMBOLS_FROM_MAIN
472 /* If we are resolving relocations while dlopen()ing a library, it's OK for
473 * the library to resolve a symbol that's defined in the executable itself,
474 * although this is rare and is generally a bad idea.
475 */
476 if (somain) {
477 lsi = somain;
478 DEBUG("%5d %s: looking up %s in executable %s\n",
479 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700480 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700481 }
482#endif
483
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700484done:
485 if(s != NULL) {
486 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
487 "found in %s, base = 0x%08x\n",
488 pid, si->name, name, s->st_value, lsi->name, lsi->base);
489 *base = lsi->base;
490 return s;
491 }
492
Doug Kwan94304352009-10-23 18:11:40 -0700493 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700494}
495
496/* This is used by dl_sym(). It performs symbol lookup only within the
497 specified soinfo object and not in any of its dependencies.
498 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800499Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
500{
Doug Kwan94304352009-10-23 18:11:40 -0700501 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800502}
503
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700504/* This is used by dl_sym(). It performs a global symbol lookup.
505 */
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700506Elf32_Sym *lookup(const char *name, soinfo **found)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800507{
Doug Kwan94304352009-10-23 18:11:40 -0700508 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800509 Elf32_Sym *s = NULL;
510 soinfo *si;
511
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800512 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
513 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700514 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800515 continue;
Doug Kwan94304352009-10-23 18:11:40 -0700516 s = _elf_lookup(si, elfhash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800517 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700518 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800519 break;
520 }
521 }
522
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700523 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800524 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
525 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
526 return s;
527 }
528
Doug Kwan94304352009-10-23 18:11:40 -0700529 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800530}
531
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800532#if 0
533static void dump(soinfo *si)
534{
535 Elf32_Sym *s = si->symtab;
536 unsigned n;
537
538 for(n = 0; n < si->nchain; n++) {
539 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
540 s->st_info, s->st_shndx, s->st_value, s->st_size,
541 si->strtab + s->st_name);
542 s++;
543 }
544}
545#endif
546
547static const char *sopaths[] = {
548 "/system/lib",
549 "/lib",
550 0
551};
552
553static int _open_lib(const char *name)
554{
555 int fd;
556 struct stat filestat;
557
558 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
559 if ((fd = open(name, O_RDONLY)) >= 0)
560 return fd;
561 }
562
563 return -1;
564}
565
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800566static int open_library(const char *name)
567{
568 int fd;
569 char buf[512];
570 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700571 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800572
573 TRACE("[ %5d opening %s ]\n", pid, name);
574
575 if(name == 0) return -1;
576 if(strlen(name) > 256) return -1;
577
578 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
579 return fd;
580
David Bartleybc3a5c22009-06-02 18:27:28 -0700581 for (path = ldpaths; *path; path++) {
582 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
583 if (n < 0 || n >= (int)sizeof(buf)) {
584 WARN("Ignoring very long library path: %s/%s\n", *path, name);
585 continue;
586 }
587 if ((fd = _open_lib(buf)) >= 0)
588 return fd;
589 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800590 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700591 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
592 if (n < 0 || n >= (int)sizeof(buf)) {
593 WARN("Ignoring very long library path: %s/%s\n", *path, name);
594 continue;
595 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800596 if ((fd = _open_lib(buf)) >= 0)
597 return fd;
598 }
599
600 return -1;
601}
602
603/* temporary space for holding the first page of the shared lib
604 * which contains the elf header (with the pht). */
605static unsigned char __header[PAGE_SIZE];
606
607typedef struct {
608 long mmap_addr;
609 char tag[4]; /* 'P', 'R', 'E', ' ' */
610} prelink_info_t;
611
612/* Returns the requested base address if the library is prelinked,
613 * and 0 otherwise. */
614static unsigned long
615is_prelinked(int fd, const char *name)
616{
617 off_t sz;
618 prelink_info_t info;
619
620 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
621 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700622 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800623 return 0;
624 }
625
626 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
627 WARN("Could not read prelink_info_t structure for `%s`\n", name);
628 return 0;
629 }
630
631 if (strncmp(info.tag, "PRE ", 4)) {
632 WARN("`%s` is not a prelinked library\n", name);
633 return 0;
634 }
635
636 return (unsigned long)info.mmap_addr;
637}
638
639/* verify_elf_object
640 * Verifies if the object @ base is a valid ELF object
641 *
642 * Args:
643 *
644 * Returns:
645 * 0 on success
646 * -1 if no valid ELF object is found @ base.
647 */
648static int
649verify_elf_object(void *base, const char *name)
650{
651 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
652
653 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
654 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
655 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
656 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
657
658 /* TODO: Should we verify anything else in the header? */
659
660 return 0;
661}
662
663
664/* get_lib_extents
665 * Retrieves the base (*base) address where the ELF object should be
666 * mapped and its overall memory size (*total_sz).
667 *
668 * Args:
669 * fd: Opened file descriptor for the library
670 * name: The name of the library
671 * _hdr: Pointer to the header page of the library
672 * total_sz: Total size of the memory that should be allocated for
673 * this library
674 *
675 * Returns:
676 * -1 if there was an error while trying to get the lib extents.
677 * The possible reasons are:
678 * - Could not determine if the library was prelinked.
679 * - The library provided is not a valid ELF object
680 * 0 if the library did not request a specific base offset (normal
681 * for non-prelinked libs)
682 * > 0 if the library requests a specific address to be mapped to.
683 * This indicates a pre-linked library.
684 */
685static unsigned
686get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
687{
688 unsigned req_base;
689 unsigned min_vaddr = 0xffffffff;
690 unsigned max_vaddr = 0;
691 unsigned char *_hdr = (unsigned char *)__hdr;
692 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
693 Elf32_Phdr *phdr;
694 int cnt;
695
696 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
697 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700698 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800699 return (unsigned)-1;
700 }
701
702 req_base = (unsigned) is_prelinked(fd, name);
703 if (req_base == (unsigned)-1)
704 return -1;
705 else if (req_base != 0) {
706 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
707 pid, name, req_base);
708 } else {
709 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
710 }
711
712 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
713
714 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
715 * get the range. */
716 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
717 if (phdr->p_type == PT_LOAD) {
718 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
719 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
720 if (phdr->p_vaddr < min_vaddr)
721 min_vaddr = phdr->p_vaddr;
722 }
723 }
724
725 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700726 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800727 return (unsigned)-1;
728 }
729
730 /* truncate min_vaddr down to page boundary */
731 min_vaddr &= ~PAGE_MASK;
732
733 /* round max_vaddr up to the next page */
734 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
735
736 *total_sz = (max_vaddr - min_vaddr);
737 return (unsigned)req_base;
738}
739
740/* alloc_mem_region
741 *
742 * This function reserves a chunk of memory to be used for mapping in
743 * the shared library. We reserve the entire memory region here, and
744 * then the rest of the linker will relocate the individual loadable
745 * segments into the correct locations within this memory range.
746 *
747 * Args:
748 * si->base: The requested base of the allocation. If 0, a sane one will be
749 * chosen in the range LIBBASE <= base < LIBLAST.
750 * si->size: The size of the allocation.
751 *
752 * Returns:
753 * -1 on failure, and 0 on success. On success, si->base will contain
754 * the virtual address at which the library will be mapped.
755 */
756
757static int reserve_mem_region(soinfo *si)
758{
759 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
760 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
761 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700762 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700763 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800764 pid, (si->base ? "" : "non-"), si->name, si->base,
765 errno, strerror(errno));
766 return -1;
767 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700768 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700769 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800770 si->name, (unsigned)base, si->base);
771 munmap(base, si->size);
772 return -1;
773 }
774 return 0;
775}
776
777static int
778alloc_mem_region(soinfo *si)
779{
780 if (si->base) {
781 /* Attempt to mmap a prelinked library. */
782 si->ba_index = -1;
783 return reserve_mem_region(si);
784 }
785
786 /* This is not a prelinked library, so we attempt to allocate space
787 for it from the buddy allocator, which manages the area between
788 LIBBASE and LIBLAST.
789 */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700790 si->ba_index = ba_allocate(&ba_prelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800791 if(si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700792 si->base = ba_start_addr(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800793 PRINT("%5d mapping library '%s' at %08x (index %d) " \
794 "through buddy allocator.\n",
795 pid, si->name, si->base, si->ba_index);
796 if (reserve_mem_region(si) < 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700797 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800798 si->ba_index = -1;
799 si->base = 0;
800 goto err;
801 }
802 return 0;
803 }
804
805err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700806 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800807 pid, si->name);
808 return -1;
809}
810
811#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
812#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
813 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
814 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
815/* load_segments
816 *
817 * This function loads all the loadable (PT_LOAD) segments into memory
818 * at their appropriate memory offsets off the base address.
819 *
820 * Args:
821 * fd: Open file descriptor to the library to load.
822 * header: Pointer to a header page that contains the ELF header.
823 * This is needed since we haven't mapped in the real file yet.
824 * si: ptr to soinfo struct describing the shared object.
825 *
826 * Returns:
827 * 0 on success, -1 on failure.
828 */
829static int
830load_segments(int fd, void *header, soinfo *si)
831{
832 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
833 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
834 unsigned char *base = (unsigned char *)si->base;
835 int cnt;
836 unsigned len;
837 unsigned char *tmp;
838 unsigned char *pbase;
839 unsigned char *extra_base;
840 unsigned extra_len;
841 unsigned total_sz = 0;
842
843 si->wrprotect_start = 0xffffffff;
844 si->wrprotect_end = 0;
845
846 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
847 pid, si->name, (unsigned)si->base);
848 /* Now go through all the PT_LOAD segments and map them into memory
849 * at the appropriate locations. */
850 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
851 if (phdr->p_type == PT_LOAD) {
852 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
853 /* we want to map in the segment on a page boundary */
854 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
855 /* add the # of bytes we masked off above to the total length. */
856 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
857
858 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
859 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
860 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
861 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
862 MAP_PRIVATE | MAP_FIXED, fd,
863 phdr->p_offset & (~PAGE_MASK));
864 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700865 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700866 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800867 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
868 goto fail;
869 }
870
871 /* If 'len' didn't end on page boundary, and it's a writable
872 * segment, zero-fill the rest. */
873 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
874 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
875
876 /* Check to see if we need to extend the map for this segment to
877 * cover the diff between filesz and memsz (i.e. for bss).
878 *
879 * base _+---------------------+ page boundary
880 * . .
881 * | |
882 * . .
883 * pbase _+---------------------+ page boundary
884 * | |
885 * . .
886 * base + p_vaddr _| |
887 * . \ \ .
888 * . | filesz | .
889 * pbase + len _| / | |
890 * <0 pad> . . .
891 * extra_base _+------------|--------+ page boundary
892 * / . . .
893 * | . . .
894 * | +------------|--------+ page boundary
895 * extra_len-> | | | |
896 * | . | memsz .
897 * | . | .
898 * \ _| / |
899 * . .
900 * | |
901 * _+---------------------+ page boundary
902 */
903 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
904 (~PAGE_MASK));
905 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
906 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
907 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
908 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
909 /* map in the extra page(s) as anonymous into the range.
910 * This is probably not necessary as we already mapped in
911 * the entire region previously, but we just want to be
912 * sure. This will also set the right flags on the region
913 * (though we can probably accomplish the same thing with
914 * mprotect).
915 */
916 extra_base = mmap((void *)tmp, extra_len,
917 PFLAGS_TO_PROT(phdr->p_flags),
918 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
919 -1, 0);
920 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700921 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700922 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800923 extra_len);
924 goto fail;
925 }
926 /* TODO: Check if we need to memset-0 this region.
927 * Anonymous mappings are zero-filled copy-on-writes, so we
928 * shouldn't need to. */
929 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
930 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
931 extra_len);
932 }
933 /* set the len here to show the full extent of the segment we
934 * just loaded, mostly for debugging */
935 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
936 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
937 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
938 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
939 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
940 total_sz += len;
941 /* Make the section writable just in case we'll have to write to
942 * it during relocation (i.e. text segment). However, we will
943 * remember what range of addresses should be write protected.
944 *
945 */
946 if (!(phdr->p_flags & PF_W)) {
947 if ((unsigned)pbase < si->wrprotect_start)
948 si->wrprotect_start = (unsigned)pbase;
949 if (((unsigned)pbase + len) > si->wrprotect_end)
950 si->wrprotect_end = (unsigned)pbase + len;
951 mprotect(pbase, len,
952 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
953 }
954 } else if (phdr->p_type == PT_DYNAMIC) {
955 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
956 /* this segment contains the dynamic linking information */
957 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
958 } else {
959#ifdef ANDROID_ARM_LINKER
960 if (phdr->p_type == PT_ARM_EXIDX) {
961 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
962 /* exidx entries (used for stack unwinding) are 8 bytes each.
963 */
964 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
965 si->ARM_exidx_count = phdr->p_memsz / 8;
966 }
967#endif
968 }
969
970 }
971
972 /* Sanity check */
973 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700974 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700975 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800976 pid, total_sz, si->name, si->size);
977 goto fail;
978 }
979
980 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
981 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
982 (unsigned)si->base, si->size);
983 return 0;
984
985fail:
986 /* We can just blindly unmap the entire region even though some things
987 * were mapped in originally with anonymous and others could have been
988 * been mapped in from the file before we failed. The kernel will unmap
989 * all the pages in the range, irrespective of how they got there.
990 */
991 munmap((void *)si->base, si->size);
992 si->flags |= FLAG_ERROR;
993 return -1;
994}
995
996/* TODO: Implement this to take care of the fact that Android ARM
997 * ELF objects shove everything into a single loadable segment that has the
998 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
999 * non-writable.
1000 */
1001#if 0
1002static unsigned
1003get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1004{
1005 Elf32_Shdr *shdr_start;
1006 Elf32_Shdr *shdr;
1007 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1008 int cnt;
1009 unsigned wr_offset = 0xffffffff;
1010
1011 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1012 ehdr->e_shoff & (~PAGE_MASK));
1013 if (shdr_start == MAP_FAILED) {
1014 WARN("%5d - Could not read section header info from '%s'. Will not "
1015 "not be able to determine write-protect offset.\n", pid, name);
1016 return (unsigned)-1;
1017 }
1018
1019 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1020 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1021 (shdr->sh_addr < wr_offset)) {
1022 wr_offset = shdr->sh_addr;
1023 }
1024 }
1025
1026 munmap(shdr_start, shdr_sz);
1027 return wr_offset;
1028}
1029#endif
1030
1031static soinfo *
1032load_library(const char *name)
1033{
1034 int fd = open_library(name);
1035 int cnt;
1036 unsigned ext_sz;
1037 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001038 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001039 soinfo *si = NULL;
1040 Elf32_Ehdr *hdr;
1041
Dima Zavin2e855792009-05-20 18:28:09 -07001042 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001043 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001044 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001045 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001046
1047 /* We have to read the ELF header to figure out what to do with this image
1048 */
1049 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001050 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001051 goto fail;
1052 }
1053
1054 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001055 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001056 goto fail;
1057 }
1058
1059 /* Parse the ELF header and get the size of the memory footprint for
1060 * the library */
1061 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1062 if (req_base == (unsigned)-1)
1063 goto fail;
1064 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1065 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1066
1067 /* Now configure the soinfo struct where we'll store all of our data
1068 * for the ELF object. If the loading fails, we waste the entry, but
1069 * same thing would happen if we failed during linking. Configuring the
1070 * soinfo struct here is a lot more convenient.
1071 */
Erik Gillingfde86422009-07-28 20:28:19 -07001072 bname = strrchr(name, '/');
1073 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001074 if (si == NULL)
1075 goto fail;
1076
1077 /* Carve out a chunk of memory where we will map in the individual
1078 * segments */
1079 si->base = req_base;
1080 si->size = ext_sz;
1081 si->flags = 0;
1082 si->entry = 0;
1083 si->dynamic = (unsigned *)-1;
1084 if (alloc_mem_region(si) < 0)
1085 goto fail;
1086
1087 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1088 pid, name, (void *)si->base, (unsigned) ext_sz);
1089
1090 /* Now actually load the library's segments into right places in memory */
1091 if (load_segments(fd, &__header[0], si) < 0) {
1092 if (si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001093 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001094 si->ba_index = -1;
1095 }
1096 goto fail;
1097 }
1098
1099 /* this might not be right. Technically, we don't even need this info
1100 * once we go through 'load_segments'. */
1101 hdr = (Elf32_Ehdr *)si->base;
1102 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1103 si->phnum = hdr->e_phnum;
1104 /**/
1105
1106 close(fd);
1107 return si;
1108
1109fail:
1110 if (si) free_info(si);
1111 close(fd);
1112 return NULL;
1113}
1114
1115static soinfo *
1116init_library(soinfo *si)
1117{
1118 unsigned wr_offset = 0xffffffff;
1119
1120 /* At this point we know that whatever is loaded @ base is a valid ELF
1121 * shared library whose segments are properly mapped in. */
1122 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1123 pid, si->base, si->size, si->name);
1124
1125 if (si->base < LIBBASE || si->base >= LIBLAST)
1126 si->flags |= FLAG_PRELINKED;
1127
1128 if(link_image(si, wr_offset)) {
1129 /* We failed to link. However, we can only restore libbase
1130 ** if no additional libraries have moved it since we updated it.
1131 */
1132 munmap((void *)si->base, si->size);
1133 return NULL;
1134 }
1135
1136 return si;
1137}
1138
1139soinfo *find_library(const char *name)
1140{
1141 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001142 const char *bname = strrchr(name, '/');
1143 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144
1145 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001146 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001147 if(si->flags & FLAG_ERROR) {
1148 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1149 return NULL;
1150 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001151 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001152 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001153 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001154 }
1155 }
1156
1157 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1158 si = load_library(name);
1159 if(si == NULL)
1160 return NULL;
1161 return init_library(si);
1162}
1163
1164/* TODO:
1165 * notify gdb of unload
1166 * for non-prelinked libraries, find a way to decrement libbase
1167 */
1168static void call_destructors(soinfo *si);
1169unsigned unload_library(soinfo *si)
1170{
1171 unsigned *d;
1172 if (si->refcount == 1) {
1173 TRACE("%5d unloading '%s'\n", pid, si->name);
1174 call_destructors(si);
1175
1176 for(d = si->dynamic; *d; d += 2) {
1177 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001178 soinfo *lsi = (soinfo *)d[1];
1179 d[1] = 0;
1180 if (validate_soinfo(lsi)) {
1181 TRACE("%5d %s needs to unload %s\n", pid,
1182 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001183 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001184 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001185 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001186 DL_ERR("%5d %s: could not unload dependent library",
1187 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001188 }
1189 }
1190
1191 munmap((char *)si->base, si->size);
1192 if (si->ba_index >= 0) {
1193 PRINT("%5d releasing library '%s' address space at %08x "\
1194 "through buddy allocator.\n",
1195 pid, si->name, si->base);
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001196 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001197 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001198 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001199 free_info(si);
1200 si->refcount = 0;
1201 }
1202 else {
1203 si->refcount--;
1204 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1205 pid, si->name, si->refcount);
1206 }
1207 return si->refcount;
1208}
1209
1210/* TODO: don't use unsigned for addrs below. It works, but is not
1211 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1212 * long.
1213 */
1214static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1215{
1216 Elf32_Sym *symtab = si->symtab;
1217 const char *strtab = si->strtab;
1218 Elf32_Sym *s;
1219 unsigned base;
1220 Elf32_Rel *start = rel;
1221 unsigned idx;
1222
1223 for (idx = 0; idx < count; ++idx) {
1224 unsigned type = ELF32_R_TYPE(rel->r_info);
1225 unsigned sym = ELF32_R_SYM(rel->r_info);
1226 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1227 unsigned sym_addr = 0;
1228 char *sym_name = NULL;
1229
1230 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1231 si->name, idx);
1232 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001233 sym_name = (char *)(strtab + symtab[sym].st_name);
1234 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001235 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001236 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001237 return -1;
1238 }
1239#if 0
1240 if((base == 0) && (si->base != 0)){
1241 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001242 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001243 pid, strtab + symtab[sym].st_name);
1244 return -1;
1245 }
1246#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001247 // st_shndx==SHN_UNDEF means an undefined symbol.
1248 // st_value should be 0 then, except that the low bit of st_value is
1249 // used to indicate whether the symbol points to an ARM or thumb function,
1250 // and should be ignored in the following check.
1251 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1252 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1253 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001254 s->st_value);
1255 return -1;
1256 }
1257 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001258 COUNT_RELOC(RELOC_SYMBOL);
1259 } else {
1260 s = 0;
1261 }
1262
1263/* TODO: This is ugly. Split up the relocations by arch into
1264 * different files.
1265 */
1266 switch(type){
1267#if defined(ANDROID_ARM_LINKER)
1268 case R_ARM_JUMP_SLOT:
1269 COUNT_RELOC(RELOC_ABSOLUTE);
1270 MARK(rel->r_offset);
1271 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1272 reloc, sym_addr, sym_name);
1273 *((unsigned*)reloc) = sym_addr;
1274 break;
1275 case R_ARM_GLOB_DAT:
1276 COUNT_RELOC(RELOC_ABSOLUTE);
1277 MARK(rel->r_offset);
1278 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1279 reloc, sym_addr, sym_name);
1280 *((unsigned*)reloc) = sym_addr;
1281 break;
1282 case R_ARM_ABS32:
1283 COUNT_RELOC(RELOC_ABSOLUTE);
1284 MARK(rel->r_offset);
1285 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1286 reloc, sym_addr, sym_name);
1287 *((unsigned*)reloc) += sym_addr;
1288 break;
1289#elif defined(ANDROID_X86_LINKER)
1290 case R_386_JUMP_SLOT:
1291 COUNT_RELOC(RELOC_ABSOLUTE);
1292 MARK(rel->r_offset);
1293 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1294 reloc, sym_addr, sym_name);
1295 *((unsigned*)reloc) = sym_addr;
1296 break;
1297 case R_386_GLOB_DAT:
1298 COUNT_RELOC(RELOC_ABSOLUTE);
1299 MARK(rel->r_offset);
1300 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1301 reloc, sym_addr, sym_name);
1302 *((unsigned*)reloc) = sym_addr;
1303 break;
1304#endif /* ANDROID_*_LINKER */
1305
1306#if defined(ANDROID_ARM_LINKER)
1307 case R_ARM_RELATIVE:
1308#elif defined(ANDROID_X86_LINKER)
1309 case R_386_RELATIVE:
1310#endif /* ANDROID_*_LINKER */
1311 COUNT_RELOC(RELOC_RELATIVE);
1312 MARK(rel->r_offset);
1313 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001314 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001315 return -1;
1316 }
1317 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1318 reloc, si->base);
1319 *((unsigned*)reloc) += si->base;
1320 break;
1321
1322#if defined(ANDROID_X86_LINKER)
1323 case R_386_32:
1324 COUNT_RELOC(RELOC_RELATIVE);
1325 MARK(rel->r_offset);
1326
1327 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1328 reloc, sym_addr, sym_name);
1329 *((unsigned *)reloc) += (unsigned)sym_addr;
1330 break;
1331
1332 case R_386_PC32:
1333 COUNT_RELOC(RELOC_RELATIVE);
1334 MARK(rel->r_offset);
1335 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1336 "+%08x (%08x - %08x) %s\n", pid, reloc,
1337 (sym_addr - reloc), sym_addr, reloc, sym_name);
1338 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1339 break;
1340#endif /* ANDROID_X86_LINKER */
1341
1342#ifdef ANDROID_ARM_LINKER
1343 case R_ARM_COPY:
1344 COUNT_RELOC(RELOC_COPY);
1345 MARK(rel->r_offset);
1346 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1347 reloc, s->st_size, sym_addr, sym_name);
1348 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1349 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001350 case R_ARM_NONE:
1351 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001352#endif /* ANDROID_ARM_LINKER */
1353
1354 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001355 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001356 pid, type, rel, (int) (rel - start));
1357 return -1;
1358 }
1359 rel++;
1360 }
1361 return 0;
1362}
1363
David 'Digit' Turner82156792009-05-18 14:37:41 +02001364
1365/* Please read the "Initialization and Termination functions" functions.
1366 * of the linker design note in bionic/linker/README.TXT to understand
1367 * what the following code is doing.
1368 *
1369 * The important things to remember are:
1370 *
1371 * DT_PREINIT_ARRAY must be called first for executables, and should
1372 * not appear in shared libraries.
1373 *
1374 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1375 *
1376 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1377 *
1378 * DT_FINI_ARRAY must be parsed in reverse order.
1379 */
1380
1381static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001382{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001383 int n, inc = 1;
1384
1385 if (reverse) {
1386 ctor += (count-1);
1387 inc = -1;
1388 }
1389
1390 for(n = count; n > 0; n--) {
1391 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1392 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001393 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001394 void (*func)() = (void (*)()) *ctor;
1395 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001396 if(((int) func == 0) || ((int) func == -1)) continue;
1397 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1398 func();
1399 }
1400}
1401
1402static void call_constructors(soinfo *si)
1403{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001404 if (si->flags & FLAG_EXE) {
1405 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1406 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1407 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001408 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001409 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1410 } else {
1411 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001412 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001413 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001414 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001415 }
1416 }
1417
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001418 if (si->init_func) {
1419 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1420 (unsigned)si->init_func, si->name);
1421 si->init_func();
1422 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1423 }
1424
1425 if (si->init_array) {
1426 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1427 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001428 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001429 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1430 }
1431}
1432
David 'Digit' Turner82156792009-05-18 14:37:41 +02001433
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001434static void call_destructors(soinfo *si)
1435{
1436 if (si->fini_array) {
1437 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1438 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001439 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001440 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1441 }
1442
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001443 if (si->fini_func) {
1444 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1445 (unsigned)si->fini_func, si->name);
1446 si->fini_func();
1447 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1448 }
1449}
1450
1451/* Force any of the closed stdin, stdout and stderr to be associated with
1452 /dev/null. */
1453static int nullify_closed_stdio (void)
1454{
1455 int dev_null, i, status;
1456 int return_value = 0;
1457
1458 dev_null = open("/dev/null", O_RDWR);
1459 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001460 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001461 return -1;
1462 }
1463 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1464
1465 /* If any of the stdio file descriptors is valid and not associated
1466 with /dev/null, dup /dev/null to it. */
1467 for (i = 0; i < 3; i++) {
1468 /* If it is /dev/null already, we are done. */
1469 if (i == dev_null)
1470 continue;
1471
1472 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1473 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1474 can be interrupted but we do this just to be safe. */
1475 do {
1476 status = fcntl(i, F_GETFL);
1477 } while (status < 0 && errno == EINTR);
1478
1479 /* If file is openned, we are good. */
1480 if (status >= 0)
1481 continue;
1482
1483 /* The only error we allow is that the file descriptor does not
1484 exist, in which case we dup /dev/null to it. */
1485 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001486 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001487 return_value = -1;
1488 continue;
1489 }
1490
1491 /* Try dupping /dev/null to this stdio file descriptor and
1492 repeat if there is a signal. Note that any errors in closing
1493 the stdio descriptor are lost. */
1494 do {
1495 status = dup2(dev_null, i);
1496 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001497
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001498 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001499 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001500 return_value = -1;
1501 continue;
1502 }
1503 }
1504
1505 /* If /dev/null is not one of the stdio file descriptors, close it. */
1506 if (dev_null > 2) {
1507 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001508 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001509 status = close(dev_null);
1510 } while (status < 0 && errno == EINTR);
1511
1512 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001513 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001514 return_value = -1;
1515 }
1516 }
1517
1518 return return_value;
1519}
1520
1521static int link_image(soinfo *si, unsigned wr_offset)
1522{
1523 unsigned *d;
1524 Elf32_Phdr *phdr = si->phdr;
1525 int phnum = si->phnum;
1526
1527 INFO("[ %5d linking %s ]\n", pid, si->name);
1528 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1529 si->base, si->flags);
1530
1531 if (si->flags & FLAG_EXE) {
1532 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1533 * linkage info if this is the executable. If this was a
1534 * dynamic lib, that would have been done at load time.
1535 *
1536 * TODO: It's unfortunate that small pieces of this are
1537 * repeated from the load_library routine. Refactor this just
1538 * slightly to reuse these bits.
1539 */
1540 si->size = 0;
1541 for(; phnum > 0; --phnum, ++phdr) {
1542#ifdef ANDROID_ARM_LINKER
1543 if(phdr->p_type == PT_ARM_EXIDX) {
1544 /* exidx entries (used for stack unwinding) are 8 bytes each.
1545 */
1546 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1547 si->ARM_exidx_count = phdr->p_memsz / 8;
1548 }
1549#endif
1550 if (phdr->p_type == PT_LOAD) {
1551 /* For the executable, we use the si->size field only in
1552 dl_unwind_find_exidx(), so the meaning of si->size
1553 is not the size of the executable; it is the last
1554 virtual address of the loadable part of the executable;
1555 since si->base == 0 for an executable, we use the
1556 range [0, si->size) to determine whether a PC value
1557 falls within the executable section. Of course, if
1558 a value is below phdr->p_vaddr, it's not in the
1559 executable section, but a) we shouldn't be asking for
1560 such a value anyway, and b) if we have to provide
1561 an EXIDX for such a value, then the executable's
1562 EXIDX is probably the better choice.
1563 */
1564 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1565 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1566 si->size = phdr->p_vaddr + phdr->p_memsz;
1567 /* try to remember what range of addresses should be write
1568 * protected */
1569 if (!(phdr->p_flags & PF_W)) {
1570 unsigned _end;
1571
1572 if (phdr->p_vaddr < si->wrprotect_start)
1573 si->wrprotect_start = phdr->p_vaddr;
1574 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1575 (~PAGE_MASK)));
1576 if (_end > si->wrprotect_end)
1577 si->wrprotect_end = _end;
1578 }
1579 } else if (phdr->p_type == PT_DYNAMIC) {
1580 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001581 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001582 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001583 pid, si->name, si->base + phdr->p_vaddr,
1584 (unsigned)si->dynamic);
1585 goto fail;
1586 }
1587 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1588 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1589 }
1590 }
1591 }
1592
1593 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001594 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001595 goto fail;
1596 }
1597
1598 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1599
1600 /* extract useful information from dynamic section */
1601 for(d = si->dynamic; *d; d++){
1602 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1603 switch(*d++){
1604 case DT_HASH:
1605 si->nbucket = ((unsigned *) (si->base + *d))[0];
1606 si->nchain = ((unsigned *) (si->base + *d))[1];
1607 si->bucket = (unsigned *) (si->base + *d + 8);
1608 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1609 break;
1610 case DT_STRTAB:
1611 si->strtab = (const char *) (si->base + *d);
1612 break;
1613 case DT_SYMTAB:
1614 si->symtab = (Elf32_Sym *) (si->base + *d);
1615 break;
1616 case DT_PLTREL:
1617 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001618 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001619 goto fail;
1620 }
1621 break;
1622 case DT_JMPREL:
1623 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1624 break;
1625 case DT_PLTRELSZ:
1626 si->plt_rel_count = *d / 8;
1627 break;
1628 case DT_REL:
1629 si->rel = (Elf32_Rel*) (si->base + *d);
1630 break;
1631 case DT_RELSZ:
1632 si->rel_count = *d / 8;
1633 break;
1634 case DT_PLTGOT:
1635 /* Save this in case we decide to do lazy binding. We don't yet. */
1636 si->plt_got = (unsigned *)(si->base + *d);
1637 break;
1638 case DT_DEBUG:
1639 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1640 *d = (int) &_r_debug;
1641 break;
1642 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001643 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001644 goto fail;
1645 case DT_INIT:
1646 si->init_func = (void (*)(void))(si->base + *d);
1647 DEBUG("%5d %s constructors (init func) found at %p\n",
1648 pid, si->name, si->init_func);
1649 break;
1650 case DT_FINI:
1651 si->fini_func = (void (*)(void))(si->base + *d);
1652 DEBUG("%5d %s destructors (fini func) found at %p\n",
1653 pid, si->name, si->fini_func);
1654 break;
1655 case DT_INIT_ARRAY:
1656 si->init_array = (unsigned *)(si->base + *d);
1657 DEBUG("%5d %s constructors (init_array) found at %p\n",
1658 pid, si->name, si->init_array);
1659 break;
1660 case DT_INIT_ARRAYSZ:
1661 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1662 break;
1663 case DT_FINI_ARRAY:
1664 si->fini_array = (unsigned *)(si->base + *d);
1665 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1666 pid, si->name, si->fini_array);
1667 break;
1668 case DT_FINI_ARRAYSZ:
1669 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1670 break;
1671 case DT_PREINIT_ARRAY:
1672 si->preinit_array = (unsigned *)(si->base + *d);
1673 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1674 pid, si->name, si->preinit_array);
1675 break;
1676 case DT_PREINIT_ARRAYSZ:
1677 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1678 break;
1679 case DT_TEXTREL:
1680 /* TODO: make use of this. */
1681 /* this means that we might have to write into where the text
1682 * segment was loaded during relocation... Do something with
1683 * it.
1684 */
1685 DEBUG("%5d Text segment should be writable during relocation.\n",
1686 pid);
1687 break;
1688 }
1689 }
1690
1691 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1692 pid, si->base, si->strtab, si->symtab);
1693
1694 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001695 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001696 goto fail;
1697 }
1698
1699 for(d = si->dynamic; *d; d += 2) {
1700 if(d[0] == DT_NEEDED){
1701 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001702 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001703 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001704 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001705 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001706 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001707 goto fail;
1708 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001709 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1710 of the DT_NEEDED entry itself, so that we can retrieve the
1711 soinfo directly later from the dynamic segment. This is a hack,
1712 but it allows us to map from DT_NEEDED to soinfo efficiently
1713 later on when we resolve relocations, trying to look up a symgol
1714 with dlsym().
1715 */
1716 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717 lsi->refcount++;
1718 }
1719 }
1720
1721 if(si->plt_rel) {
1722 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1723 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1724 goto fail;
1725 }
1726 if(si->rel) {
1727 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1728 if(reloc_library(si, si->rel, si->rel_count))
1729 goto fail;
1730 }
1731
1732 si->flags |= FLAG_LINKED;
1733 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1734
1735#if 0
1736 /* This is the way that the old dynamic linker did protection of
1737 * non-writable areas. It would scan section headers and find where
1738 * .text ended (rather where .data/.bss began) and assume that this is
1739 * the upper range of the non-writable area. This is too coarse,
1740 * and is kept here for reference until we fully move away from single
1741 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1742 * that made this possible.
1743 */
1744 if(wr_offset < 0xffffffff){
1745 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1746 }
1747#else
1748 /* TODO: Verify that this does the right thing in all cases, as it
1749 * presently probably does not. It is possible that an ELF image will
1750 * come with multiple read-only segments. What we ought to do is scan
1751 * the program headers again and mprotect all the read-only segments.
1752 * To prevent re-scanning the program header, we would have to build a
1753 * list of loadable segments in si, and then scan that instead. */
1754 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1755 mprotect((void *)si->wrprotect_start,
1756 si->wrprotect_end - si->wrprotect_start,
1757 PROT_READ | PROT_EXEC);
1758 }
1759#endif
1760
1761 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1762 stdout and stderr to close a security hole described in:
1763
1764 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1765
1766 */
1767 if (getuid() != geteuid() || getgid() != getegid())
1768 nullify_closed_stdio ();
1769 call_constructors(si);
1770 notify_gdb_of_load(si);
1771 return 0;
1772
1773fail:
Doug Kwan94304352009-10-23 18:11:40 -07001774 DL_ERR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775 si->flags |= FLAG_ERROR;
1776 return -1;
1777}
1778
David Bartleybc3a5c22009-06-02 18:27:28 -07001779static void parse_library_path(char *path, char *delim)
1780{
1781 size_t len;
1782 char *ldpaths_bufp = ldpaths_buf;
1783 int i = 0;
1784
1785 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1786
1787 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1788 if (*ldpaths[i] != '\0')
1789 ++i;
1790 }
1791
1792 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1793 * last char isn't '\0' (i.e. not originally a delim). */
1794 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1795 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1796 ldpaths[i - 1] = NULL;
1797 } else {
1798 ldpaths[i] = NULL;
1799 }
1800}
1801
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001802int main(int argc, char **argv)
1803{
1804 return 0;
1805}
1806
1807#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1808
1809static void * __tls_area[ANDROID_TLS_SLOTS];
1810
1811unsigned __linker_init(unsigned **elfdata)
1812{
1813 static soinfo linker_soinfo;
1814
1815 int argc = (int) *elfdata;
1816 char **argv = (char**) (elfdata + 1);
1817 unsigned *vecs = (unsigned*) (argv + argc + 1);
1818 soinfo *si;
1819 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001820 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001821
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001822 /* Setup a temporary TLS area that is used to get a working
1823 * errno for system calls.
1824 */
1825 __set_tls(__tls_area);
1826
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001827 pid = getpid();
1828
1829#if TIMING
1830 struct timeval t0, t1;
1831 gettimeofday(&t0, 0);
1832#endif
1833
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001834 /* NOTE: we store the elfdata pointer on a special location
1835 * of the temporary TLS area in order to pass it to
1836 * the C Library's runtime initializer.
1837 *
1838 * The initializer must clear the slot and reset the TLS
1839 * to point to a different location to ensure that no other
1840 * shared library constructor can access it.
1841 */
1842 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001843
1844 debugger_init();
1845
1846 /* skip past the environment */
1847 while(vecs[0] != 0) {
1848 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1849 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001850 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1851 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001852 }
1853 vecs++;
1854 }
1855 vecs++;
1856
1857 INFO("[ android linker & debugger ]\n");
1858 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1859
1860 si = alloc_info(argv[0]);
1861 if(si == 0) {
1862 exit(-1);
1863 }
1864
1865 /* bootstrap the link map, the main exe always needs to be first */
1866 si->flags |= FLAG_EXE;
1867 map = &(si->linkmap);
1868
1869 map->l_addr = 0;
1870 map->l_name = argv[0];
1871 map->l_prev = NULL;
1872 map->l_next = NULL;
1873
1874 _r_debug.r_map = map;
1875 r_debug_tail = map;
1876
1877 /* gdb expects the linker to be in the debug shared object list,
1878 * and we need to make sure that the reported load address is zero.
1879 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1880 * is. Don't use alloc_info(), because the linker shouldn't
1881 * be on the soinfo list.
1882 */
1883 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1884 linker_soinfo.flags = 0;
1885 linker_soinfo.base = 0; // This is the important part; must be zero.
1886 insert_soinfo_into_debug_map(&linker_soinfo);
1887
1888 /* extract information passed from the kernel */
1889 while(vecs[0] != 0){
1890 switch(vecs[0]){
1891 case AT_PHDR:
1892 si->phdr = (Elf32_Phdr*) vecs[1];
1893 break;
1894 case AT_PHNUM:
1895 si->phnum = (int) vecs[1];
1896 break;
1897 case AT_ENTRY:
1898 si->entry = vecs[1];
1899 break;
1900 }
1901 vecs += 2;
1902 }
1903
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001904 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001905
1906 si->base = 0;
1907 si->dynamic = (unsigned *)-1;
1908 si->wrprotect_start = 0xffffffff;
1909 si->wrprotect_end = 0;
1910
David Bartleybc3a5c22009-06-02 18:27:28 -07001911 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1912 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1913 parse_library_path(ldpath_env, ":");
1914
Dima Zavin2e855792009-05-20 18:28:09 -07001915 if(link_image(si, 0)) {
1916 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1917 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1918 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001919 exit(-1);
1920 }
1921
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001922#if ALLOW_SYMBOLS_FROM_MAIN
1923 /* Set somain after we've loaded all the libraries in order to prevent
1924 * linking of symbols back to the main image, which is not set up at that
1925 * point yet.
1926 */
1927 somain = si;
1928#endif
1929
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001930#if TIMING
1931 gettimeofday(&t1,NULL);
1932 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1933 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1934 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1935 ));
1936#endif
1937#if STATS
1938 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1939 linker_stats.reloc[RELOC_ABSOLUTE],
1940 linker_stats.reloc[RELOC_RELATIVE],
1941 linker_stats.reloc[RELOC_COPY],
1942 linker_stats.reloc[RELOC_SYMBOL]);
1943#endif
1944#if COUNT_PAGES
1945 {
1946 unsigned n;
1947 unsigned i;
1948 unsigned count = 0;
1949 for(n = 0; n < 4096; n++){
1950 if(bitmask[n]){
1951 unsigned x = bitmask[n];
1952 for(i = 0; i < 8; i++){
1953 if(x & 1) count++;
1954 x >>= 1;
1955 }
1956 }
1957 }
1958 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1959 }
1960#endif
1961
1962#if TIMING || STATS || COUNT_PAGES
1963 fflush(stdout);
1964#endif
1965
1966 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1967 si->entry);
1968 return si->entry;
1969}