blob: 6e421458bc01317219c9b76f6b8145f6fd3f91d3 [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 *
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080071 * - are we doing everything we should for ARM_COPY relocations?
72 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080073 * - after linking, set as much stuff as possible to READONLY
74 * and NOEXEC
75 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
76 * headers provide versions that are negative...
77 * - allocate space for soinfo structs dynamically instead of
78 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080079*/
80
81
82static int link_image(soinfo *si, unsigned wr_offset);
83
84static int socount = 0;
85static soinfo sopool[SO_MAX];
86static soinfo *freelist = NULL;
87static soinfo *solist = &libdl_info;
88static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070089#if ALLOW_SYMBOLS_FROM_MAIN
90static soinfo *somain; /* main process, always the one after libdl_info */
91#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080092
Iliyan Malchevaf7315a2009-10-16 17:50:42 -070093
94/* Set up for the buddy allocator managing the prelinked libraries. */
95static struct ba_bits ba_prelink_bitmap[(LIBLAST - LIBBASE) / LIBINC];
96static struct ba ba_prelink = {
97 .base = LIBBASE,
98 .size = LIBLAST - LIBBASE,
99 .min_alloc = LIBINC,
Iliyan Malchevbb9eede2009-10-19 14:25:17 -0700100 /* max_order will be determined automatically */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700101 .bitmap = ba_prelink_bitmap,
102 .num_entries = sizeof(ba_prelink_bitmap)/sizeof(ba_prelink_bitmap[0]),
103};
104
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700105static inline int validate_soinfo(soinfo *si)
106{
107 return (si >= sopool && si < sopool + SO_MAX) ||
108 si == &libdl_info;
109}
110
David Bartleybc3a5c22009-06-02 18:27:28 -0700111static char ldpaths_buf[LDPATH_BUFSIZE];
112static const char *ldpaths[LDPATH_MAX + 1];
113
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800114int debug_verbosity;
115static int pid;
116
117#if STATS
118struct _link_stats linker_stats;
119#endif
120
121#if COUNT_PAGES
122unsigned bitmask[4096];
123#endif
124
125#ifndef PT_ARM_EXIDX
126#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
127#endif
128
Dima Zavin2e855792009-05-20 18:28:09 -0700129#define HOODLUM(name, ret, ...) \
130 ret name __VA_ARGS__ \
131 { \
132 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
133 write(2, errstr, sizeof(errstr)); \
134 abort(); \
135 }
136HOODLUM(malloc, void *, (size_t size));
137HOODLUM(free, void, (void *ptr));
138HOODLUM(realloc, void *, (void *ptr, size_t size));
139HOODLUM(calloc, void *, (size_t cnt, size_t size));
140
Dima Zavin03531952009-05-29 17:30:25 -0700141static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700142static char __linker_dl_err_buf[768];
143#define DL_ERR(fmt, x...) \
144 do { \
145 snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
146 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700147 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700148 } while(0)
149
150const char *linker_get_error(void)
151{
152 return (const char *)&__linker_dl_err_buf[0];
153}
154
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800155/*
156 * This function is an empty stub where GDB locates a breakpoint to get notified
157 * about linker activity.
158 */
159extern void __attribute__((noinline)) rtld_db_dlactivity(void);
160
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800161static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
162 RT_CONSISTENT, 0};
163static struct link_map *r_debug_tail = 0;
164
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700165static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166
167static void insert_soinfo_into_debug_map(soinfo * info)
168{
169 struct link_map * map;
170
171 /* Copy the necessary fields into the debug structure.
172 */
173 map = &(info->linkmap);
174 map->l_addr = info->base;
175 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800176 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800177
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);
Doug Kwan94304352009-10-23 18:11:40 -0700260 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261 }
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
Doug Kwane8238072009-10-26 12:05:23 -0700408 /* only concern ourselves with global and weak symbol definitions */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800409 switch(ELF32_ST_BIND(s->st_info)){
410 case STB_GLOBAL:
Doug Kwane8238072009-10-26 12:05:23 -0700411 case STB_WEAK:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800412 /* no section == undefined */
413 if(s->st_shndx == 0) continue;
414
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800415 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
Doug Kwan94304352009-10-23 18:11:40 -0700421 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800422}
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 *
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700439_do_lookup(soinfo *si, const char *name, unsigned *base)
440{
Doug Kwan94304352009-10-23 18:11:40 -0700441 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700442 Elf32_Sym *s;
443 unsigned *d;
444 soinfo *lsi = si;
445
446 /* Look for symbols in the local scope first (the object who is
447 * searching). This happens with C++ templates on i386 for some
Doug Kwane8238072009-10-26 12:05:23 -0700448 * reason.
449 *
450 * Notes on weak symbols:
451 * The ELF specs are ambigious about treatment of weak definitions in
452 * dynamic linking. Some systems return the first definition found
453 * and some the first non-weak definition. This is system dependent.
454 * Here we return the first definition found for simplicity. */
Doug Kwan94304352009-10-23 18:11:40 -0700455 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700456 if(s != NULL)
457 goto done;
458
459 for(d = si->dynamic; *d; d += 2) {
460 if(d[0] == DT_NEEDED){
461 lsi = (soinfo *)d[1];
462 if (!validate_soinfo(lsi)) {
463 DL_ERR("%5d bad DT_NEEDED pointer in %s",
464 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700465 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700466 }
467
468 DEBUG("%5d %s: looking up %s in %s\n",
469 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700470 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700471 if(s != NULL)
472 goto done;
473 }
474 }
475
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700476#if ALLOW_SYMBOLS_FROM_MAIN
477 /* If we are resolving relocations while dlopen()ing a library, it's OK for
478 * the library to resolve a symbol that's defined in the executable itself,
479 * although this is rare and is generally a bad idea.
480 */
481 if (somain) {
482 lsi = somain;
483 DEBUG("%5d %s: looking up %s in executable %s\n",
484 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700485 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700486 }
487#endif
488
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700489done:
490 if(s != NULL) {
491 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
492 "found in %s, base = 0x%08x\n",
493 pid, si->name, name, s->st_value, lsi->name, lsi->base);
494 *base = lsi->base;
495 return s;
496 }
497
Doug Kwan94304352009-10-23 18:11:40 -0700498 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700499}
500
501/* This is used by dl_sym(). It performs symbol lookup only within the
502 specified soinfo object and not in any of its dependencies.
503 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800504Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
505{
Doug Kwan94304352009-10-23 18:11:40 -0700506 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800507}
508
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700509/* This is used by dl_sym(). It performs a global symbol lookup.
510 */
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700511Elf32_Sym *lookup(const char *name, soinfo **found)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800512{
Doug Kwan94304352009-10-23 18:11:40 -0700513 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800514 Elf32_Sym *s = NULL;
515 soinfo *si;
516
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800517 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
518 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700519 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800520 continue;
Doug Kwane8238072009-10-26 12:05:23 -0700521 s = _elf_lookup(si, elf_hash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800522 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700523 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800524 break;
525 }
526 }
527
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700528 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800529 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
530 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
531 return s;
532 }
533
Doug Kwan94304352009-10-23 18:11:40 -0700534 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800535}
536
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800537#if 0
538static void dump(soinfo *si)
539{
540 Elf32_Sym *s = si->symtab;
541 unsigned n;
542
543 for(n = 0; n < si->nchain; n++) {
544 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
545 s->st_info, s->st_shndx, s->st_value, s->st_size,
546 si->strtab + s->st_name);
547 s++;
548 }
549}
550#endif
551
552static const char *sopaths[] = {
553 "/system/lib",
554 "/lib",
555 0
556};
557
558static int _open_lib(const char *name)
559{
560 int fd;
561 struct stat filestat;
562
563 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
564 if ((fd = open(name, O_RDONLY)) >= 0)
565 return fd;
566 }
567
568 return -1;
569}
570
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800571static int open_library(const char *name)
572{
573 int fd;
574 char buf[512];
575 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700576 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800577
578 TRACE("[ %5d opening %s ]\n", pid, name);
579
580 if(name == 0) return -1;
581 if(strlen(name) > 256) return -1;
582
583 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
584 return fd;
585
David Bartleybc3a5c22009-06-02 18:27:28 -0700586 for (path = ldpaths; *path; path++) {
587 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
588 if (n < 0 || n >= (int)sizeof(buf)) {
589 WARN("Ignoring very long library path: %s/%s\n", *path, name);
590 continue;
591 }
592 if ((fd = _open_lib(buf)) >= 0)
593 return fd;
594 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800595 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700596 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
597 if (n < 0 || n >= (int)sizeof(buf)) {
598 WARN("Ignoring very long library path: %s/%s\n", *path, name);
599 continue;
600 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800601 if ((fd = _open_lib(buf)) >= 0)
602 return fd;
603 }
604
605 return -1;
606}
607
608/* temporary space for holding the first page of the shared lib
609 * which contains the elf header (with the pht). */
610static unsigned char __header[PAGE_SIZE];
611
612typedef struct {
613 long mmap_addr;
614 char tag[4]; /* 'P', 'R', 'E', ' ' */
615} prelink_info_t;
616
617/* Returns the requested base address if the library is prelinked,
618 * and 0 otherwise. */
619static unsigned long
620is_prelinked(int fd, const char *name)
621{
622 off_t sz;
623 prelink_info_t info;
624
625 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
626 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700627 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800628 return 0;
629 }
630
631 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
632 WARN("Could not read prelink_info_t structure for `%s`\n", name);
633 return 0;
634 }
635
636 if (strncmp(info.tag, "PRE ", 4)) {
637 WARN("`%s` is not a prelinked library\n", name);
638 return 0;
639 }
640
641 return (unsigned long)info.mmap_addr;
642}
643
644/* verify_elf_object
645 * Verifies if the object @ base is a valid ELF object
646 *
647 * Args:
648 *
649 * Returns:
650 * 0 on success
651 * -1 if no valid ELF object is found @ base.
652 */
653static int
654verify_elf_object(void *base, const char *name)
655{
656 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
657
658 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
659 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
660 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
661 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
662
663 /* TODO: Should we verify anything else in the header? */
664
665 return 0;
666}
667
668
669/* get_lib_extents
670 * Retrieves the base (*base) address where the ELF object should be
671 * mapped and its overall memory size (*total_sz).
672 *
673 * Args:
674 * fd: Opened file descriptor for the library
675 * name: The name of the library
676 * _hdr: Pointer to the header page of the library
677 * total_sz: Total size of the memory that should be allocated for
678 * this library
679 *
680 * Returns:
681 * -1 if there was an error while trying to get the lib extents.
682 * The possible reasons are:
683 * - Could not determine if the library was prelinked.
684 * - The library provided is not a valid ELF object
685 * 0 if the library did not request a specific base offset (normal
686 * for non-prelinked libs)
687 * > 0 if the library requests a specific address to be mapped to.
688 * This indicates a pre-linked library.
689 */
690static unsigned
691get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
692{
693 unsigned req_base;
694 unsigned min_vaddr = 0xffffffff;
695 unsigned max_vaddr = 0;
696 unsigned char *_hdr = (unsigned char *)__hdr;
697 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
698 Elf32_Phdr *phdr;
699 int cnt;
700
701 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
702 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700703 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800704 return (unsigned)-1;
705 }
706
707 req_base = (unsigned) is_prelinked(fd, name);
708 if (req_base == (unsigned)-1)
709 return -1;
710 else if (req_base != 0) {
711 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
712 pid, name, req_base);
713 } else {
714 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
715 }
716
717 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
718
719 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
720 * get the range. */
721 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
722 if (phdr->p_type == PT_LOAD) {
723 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
724 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
725 if (phdr->p_vaddr < min_vaddr)
726 min_vaddr = phdr->p_vaddr;
727 }
728 }
729
730 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700731 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800732 return (unsigned)-1;
733 }
734
735 /* truncate min_vaddr down to page boundary */
736 min_vaddr &= ~PAGE_MASK;
737
738 /* round max_vaddr up to the next page */
739 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
740
741 *total_sz = (max_vaddr - min_vaddr);
742 return (unsigned)req_base;
743}
744
745/* alloc_mem_region
746 *
747 * This function reserves a chunk of memory to be used for mapping in
748 * the shared library. We reserve the entire memory region here, and
749 * then the rest of the linker will relocate the individual loadable
750 * segments into the correct locations within this memory range.
751 *
752 * Args:
753 * si->base: The requested base of the allocation. If 0, a sane one will be
754 * chosen in the range LIBBASE <= base < LIBLAST.
755 * si->size: The size of the allocation.
756 *
757 * Returns:
758 * -1 on failure, and 0 on success. On success, si->base will contain
759 * the virtual address at which the library will be mapped.
760 */
761
762static int reserve_mem_region(soinfo *si)
763{
764 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
765 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
766 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700767 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700768 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800769 pid, (si->base ? "" : "non-"), si->name, si->base,
770 errno, strerror(errno));
771 return -1;
772 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700773 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700774 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800775 si->name, (unsigned)base, si->base);
776 munmap(base, si->size);
777 return -1;
778 }
779 return 0;
780}
781
782static int
783alloc_mem_region(soinfo *si)
784{
785 if (si->base) {
786 /* Attempt to mmap a prelinked library. */
787 si->ba_index = -1;
788 return reserve_mem_region(si);
789 }
790
791 /* This is not a prelinked library, so we attempt to allocate space
792 for it from the buddy allocator, which manages the area between
793 LIBBASE and LIBLAST.
794 */
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700795 si->ba_index = ba_allocate(&ba_prelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800796 if(si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700797 si->base = ba_start_addr(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800798 PRINT("%5d mapping library '%s' at %08x (index %d) " \
799 "through buddy allocator.\n",
800 pid, si->name, si->base, si->ba_index);
801 if (reserve_mem_region(si) < 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700802 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800803 si->ba_index = -1;
804 si->base = 0;
805 goto err;
806 }
807 return 0;
808 }
809
810err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700811 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800812 pid, si->name);
813 return -1;
814}
815
816#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
817#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
818 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
819 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
820/* load_segments
821 *
822 * This function loads all the loadable (PT_LOAD) segments into memory
823 * at their appropriate memory offsets off the base address.
824 *
825 * Args:
826 * fd: Open file descriptor to the library to load.
827 * header: Pointer to a header page that contains the ELF header.
828 * This is needed since we haven't mapped in the real file yet.
829 * si: ptr to soinfo struct describing the shared object.
830 *
831 * Returns:
832 * 0 on success, -1 on failure.
833 */
834static int
835load_segments(int fd, void *header, soinfo *si)
836{
837 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
838 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
839 unsigned char *base = (unsigned char *)si->base;
840 int cnt;
841 unsigned len;
842 unsigned char *tmp;
843 unsigned char *pbase;
844 unsigned char *extra_base;
845 unsigned extra_len;
846 unsigned total_sz = 0;
847
848 si->wrprotect_start = 0xffffffff;
849 si->wrprotect_end = 0;
850
851 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
852 pid, si->name, (unsigned)si->base);
853 /* Now go through all the PT_LOAD segments and map them into memory
854 * at the appropriate locations. */
855 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
856 if (phdr->p_type == PT_LOAD) {
857 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
858 /* we want to map in the segment on a page boundary */
859 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
860 /* add the # of bytes we masked off above to the total length. */
861 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
862
863 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
864 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
865 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
866 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
867 MAP_PRIVATE | MAP_FIXED, fd,
868 phdr->p_offset & (~PAGE_MASK));
869 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700870 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700871 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800872 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
873 goto fail;
874 }
875
876 /* If 'len' didn't end on page boundary, and it's a writable
877 * segment, zero-fill the rest. */
878 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
879 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
880
881 /* Check to see if we need to extend the map for this segment to
882 * cover the diff between filesz and memsz (i.e. for bss).
883 *
884 * base _+---------------------+ page boundary
885 * . .
886 * | |
887 * . .
888 * pbase _+---------------------+ page boundary
889 * | |
890 * . .
891 * base + p_vaddr _| |
892 * . \ \ .
893 * . | filesz | .
894 * pbase + len _| / | |
895 * <0 pad> . . .
896 * extra_base _+------------|--------+ page boundary
897 * / . . .
898 * | . . .
899 * | +------------|--------+ page boundary
900 * extra_len-> | | | |
901 * | . | memsz .
902 * | . | .
903 * \ _| / |
904 * . .
905 * | |
906 * _+---------------------+ page boundary
907 */
908 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
909 (~PAGE_MASK));
910 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
911 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
912 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
913 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
914 /* map in the extra page(s) as anonymous into the range.
915 * This is probably not necessary as we already mapped in
916 * the entire region previously, but we just want to be
917 * sure. This will also set the right flags on the region
918 * (though we can probably accomplish the same thing with
919 * mprotect).
920 */
921 extra_base = mmap((void *)tmp, extra_len,
922 PFLAGS_TO_PROT(phdr->p_flags),
923 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
924 -1, 0);
925 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700926 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700927 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800928 extra_len);
929 goto fail;
930 }
931 /* TODO: Check if we need to memset-0 this region.
932 * Anonymous mappings are zero-filled copy-on-writes, so we
933 * shouldn't need to. */
934 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
935 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
936 extra_len);
937 }
938 /* set the len here to show the full extent of the segment we
939 * just loaded, mostly for debugging */
940 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
941 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
942 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
943 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
944 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
945 total_sz += len;
946 /* Make the section writable just in case we'll have to write to
947 * it during relocation (i.e. text segment). However, we will
948 * remember what range of addresses should be write protected.
949 *
950 */
951 if (!(phdr->p_flags & PF_W)) {
952 if ((unsigned)pbase < si->wrprotect_start)
953 si->wrprotect_start = (unsigned)pbase;
954 if (((unsigned)pbase + len) > si->wrprotect_end)
955 si->wrprotect_end = (unsigned)pbase + len;
956 mprotect(pbase, len,
957 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
958 }
959 } else if (phdr->p_type == PT_DYNAMIC) {
960 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
961 /* this segment contains the dynamic linking information */
962 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
963 } else {
964#ifdef ANDROID_ARM_LINKER
965 if (phdr->p_type == PT_ARM_EXIDX) {
966 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
967 /* exidx entries (used for stack unwinding) are 8 bytes each.
968 */
969 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
970 si->ARM_exidx_count = phdr->p_memsz / 8;
971 }
972#endif
973 }
974
975 }
976
977 /* Sanity check */
978 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700979 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700980 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800981 pid, total_sz, si->name, si->size);
982 goto fail;
983 }
984
985 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
986 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
987 (unsigned)si->base, si->size);
988 return 0;
989
990fail:
991 /* We can just blindly unmap the entire region even though some things
992 * were mapped in originally with anonymous and others could have been
993 * been mapped in from the file before we failed. The kernel will unmap
994 * all the pages in the range, irrespective of how they got there.
995 */
996 munmap((void *)si->base, si->size);
997 si->flags |= FLAG_ERROR;
998 return -1;
999}
1000
1001/* TODO: Implement this to take care of the fact that Android ARM
1002 * ELF objects shove everything into a single loadable segment that has the
1003 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1004 * non-writable.
1005 */
1006#if 0
1007static unsigned
1008get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1009{
1010 Elf32_Shdr *shdr_start;
1011 Elf32_Shdr *shdr;
1012 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1013 int cnt;
1014 unsigned wr_offset = 0xffffffff;
1015
1016 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1017 ehdr->e_shoff & (~PAGE_MASK));
1018 if (shdr_start == MAP_FAILED) {
1019 WARN("%5d - Could not read section header info from '%s'. Will not "
1020 "not be able to determine write-protect offset.\n", pid, name);
1021 return (unsigned)-1;
1022 }
1023
1024 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1025 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1026 (shdr->sh_addr < wr_offset)) {
1027 wr_offset = shdr->sh_addr;
1028 }
1029 }
1030
1031 munmap(shdr_start, shdr_sz);
1032 return wr_offset;
1033}
1034#endif
1035
1036static soinfo *
1037load_library(const char *name)
1038{
1039 int fd = open_library(name);
1040 int cnt;
1041 unsigned ext_sz;
1042 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001043 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001044 soinfo *si = NULL;
1045 Elf32_Ehdr *hdr;
1046
Dima Zavin2e855792009-05-20 18:28:09 -07001047 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001048 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001049 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001050 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001051
1052 /* We have to read the ELF header to figure out what to do with this image
1053 */
1054 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001055 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001056 goto fail;
1057 }
1058
1059 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001060 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001061 goto fail;
1062 }
1063
1064 /* Parse the ELF header and get the size of the memory footprint for
1065 * the library */
1066 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1067 if (req_base == (unsigned)-1)
1068 goto fail;
1069 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1070 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1071
1072 /* Now configure the soinfo struct where we'll store all of our data
1073 * for the ELF object. If the loading fails, we waste the entry, but
1074 * same thing would happen if we failed during linking. Configuring the
1075 * soinfo struct here is a lot more convenient.
1076 */
Erik Gillingfde86422009-07-28 20:28:19 -07001077 bname = strrchr(name, '/');
1078 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001079 if (si == NULL)
1080 goto fail;
1081
1082 /* Carve out a chunk of memory where we will map in the individual
1083 * segments */
1084 si->base = req_base;
1085 si->size = ext_sz;
1086 si->flags = 0;
1087 si->entry = 0;
1088 si->dynamic = (unsigned *)-1;
1089 if (alloc_mem_region(si) < 0)
1090 goto fail;
1091
1092 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1093 pid, name, (void *)si->base, (unsigned) ext_sz);
1094
1095 /* Now actually load the library's segments into right places in memory */
1096 if (load_segments(fd, &__header[0], si) < 0) {
1097 if (si->ba_index >= 0) {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001098 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001099 si->ba_index = -1;
1100 }
1101 goto fail;
1102 }
1103
1104 /* this might not be right. Technically, we don't even need this info
1105 * once we go through 'load_segments'. */
1106 hdr = (Elf32_Ehdr *)si->base;
1107 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1108 si->phnum = hdr->e_phnum;
1109 /**/
1110
1111 close(fd);
1112 return si;
1113
1114fail:
1115 if (si) free_info(si);
1116 close(fd);
1117 return NULL;
1118}
1119
1120static soinfo *
1121init_library(soinfo *si)
1122{
1123 unsigned wr_offset = 0xffffffff;
1124
1125 /* At this point we know that whatever is loaded @ base is a valid ELF
1126 * shared library whose segments are properly mapped in. */
1127 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1128 pid, si->base, si->size, si->name);
1129
1130 if (si->base < LIBBASE || si->base >= LIBLAST)
1131 si->flags |= FLAG_PRELINKED;
1132
1133 if(link_image(si, wr_offset)) {
1134 /* We failed to link. However, we can only restore libbase
1135 ** if no additional libraries have moved it since we updated it.
1136 */
1137 munmap((void *)si->base, si->size);
1138 return NULL;
1139 }
1140
1141 return si;
1142}
1143
1144soinfo *find_library(const char *name)
1145{
1146 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001147 const char *bname = strrchr(name, '/');
1148 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001149
1150 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001151 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001152 if(si->flags & FLAG_ERROR) {
1153 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1154 return NULL;
1155 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001156 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001157 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001158 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001159 }
1160 }
1161
1162 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1163 si = load_library(name);
1164 if(si == NULL)
1165 return NULL;
1166 return init_library(si);
1167}
1168
1169/* TODO:
1170 * notify gdb of unload
1171 * for non-prelinked libraries, find a way to decrement libbase
1172 */
1173static void call_destructors(soinfo *si);
1174unsigned unload_library(soinfo *si)
1175{
1176 unsigned *d;
1177 if (si->refcount == 1) {
1178 TRACE("%5d unloading '%s'\n", pid, si->name);
1179 call_destructors(si);
1180
1181 for(d = si->dynamic; *d; d += 2) {
1182 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001183 soinfo *lsi = (soinfo *)d[1];
1184 d[1] = 0;
1185 if (validate_soinfo(lsi)) {
1186 TRACE("%5d %s needs to unload %s\n", pid,
1187 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001188 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001189 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001190 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001191 DL_ERR("%5d %s: could not unload dependent library",
1192 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001193 }
1194 }
1195
1196 munmap((char *)si->base, si->size);
1197 if (si->ba_index >= 0) {
1198 PRINT("%5d releasing library '%s' address space at %08x "\
1199 "through buddy allocator.\n",
1200 pid, si->name, si->base);
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001201 ba_free(&ba_prelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001202 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001203 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001204 free_info(si);
1205 si->refcount = 0;
1206 }
1207 else {
1208 si->refcount--;
1209 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1210 pid, si->name, si->refcount);
1211 }
1212 return si->refcount;
1213}
1214
1215/* TODO: don't use unsigned for addrs below. It works, but is not
1216 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1217 * long.
1218 */
1219static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1220{
1221 Elf32_Sym *symtab = si->symtab;
1222 const char *strtab = si->strtab;
1223 Elf32_Sym *s;
1224 unsigned base;
1225 Elf32_Rel *start = rel;
1226 unsigned idx;
1227
1228 for (idx = 0; idx < count; ++idx) {
1229 unsigned type = ELF32_R_TYPE(rel->r_info);
1230 unsigned sym = ELF32_R_SYM(rel->r_info);
1231 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1232 unsigned sym_addr = 0;
1233 char *sym_name = NULL;
1234
1235 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1236 si->name, idx);
1237 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001238 sym_name = (char *)(strtab + symtab[sym].st_name);
1239 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001240 if(s == NULL) {
1241 /* We only allow an undefined symbol if this is a weak
1242 reference.. */
1243 s = &symtab[sym];
1244 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1245 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1246 return -1;
1247 }
1248
1249 /* IHI0044C AAELF 4.5.1.1:
1250
1251 Libraries are not searched to resolve weak references.
1252 It is not an error for a weak reference to remain
1253 unsatisfied.
1254
1255 During linking, the value of an undefined weak reference is:
1256 - Zero if the relocation type is absolute
1257 - The address of the place if the relocation is pc-relative
1258 - The address of nominial base address if the relocation
1259 type is base-relative.
1260 */
1261
1262 switch (type) {
1263#if defined(ANDROID_ARM_LINKER)
1264 case R_ARM_JUMP_SLOT:
1265 case R_ARM_GLOB_DAT:
1266 case R_ARM_ABS32:
1267 case R_ARM_RELATIVE: /* Don't care. */
1268 case R_ARM_NONE: /* Don't care. */
1269#elif defined(ANDROID_X86_LINKER)
1270 case R_386_JUMP_SLOT:
1271 case R_386_GLOB_DAT:
1272 case R_386_32:
1273 case R_386_RELATIVE: /* Dont' care. */
1274#endif /* ANDROID_*_LINKER */
1275 /* sym_addr was initialized to be zero above or relocation
1276 code below does not care about value of sym_addr.
1277 No need to do anything. */
1278 break;
1279
1280#if defined(ANDROID_X86_LINKER)
1281 case R_386_PC32:
1282 sym_addr = reloc;
1283 break;
1284#endif /* ANDROID_X86_LINKER */
1285
1286#if defined(ANDROID_ARM_LINKER)
1287 case R_ARM_COPY:
1288 /* Fall through. Can't really copy if weak symbol is
1289 not found in run-time. */
1290#endif /* ANDROID_ARM_LINKER */
1291 default:
1292 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1293 pid, type, rel, (int) (rel - start));
1294 return -1;
1295 }
1296 } else {
1297 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001298#if 0
1299 if((base == 0) && (si->base != 0)){
1300 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001301 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001302 pid, strtab + symtab[sym].st_name);
1303 return -1;
1304 }
1305#endif
Doug Kwane8238072009-10-26 12:05:23 -07001306 sym_addr = (unsigned)(s->st_value + base);
1307 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001308 COUNT_RELOC(RELOC_SYMBOL);
1309 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001310 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001311 }
1312
1313/* TODO: This is ugly. Split up the relocations by arch into
1314 * different files.
1315 */
1316 switch(type){
1317#if defined(ANDROID_ARM_LINKER)
1318 case R_ARM_JUMP_SLOT:
1319 COUNT_RELOC(RELOC_ABSOLUTE);
1320 MARK(rel->r_offset);
1321 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1322 reloc, sym_addr, sym_name);
1323 *((unsigned*)reloc) = sym_addr;
1324 break;
1325 case R_ARM_GLOB_DAT:
1326 COUNT_RELOC(RELOC_ABSOLUTE);
1327 MARK(rel->r_offset);
1328 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1329 reloc, sym_addr, sym_name);
1330 *((unsigned*)reloc) = sym_addr;
1331 break;
1332 case R_ARM_ABS32:
1333 COUNT_RELOC(RELOC_ABSOLUTE);
1334 MARK(rel->r_offset);
1335 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1336 reloc, sym_addr, sym_name);
1337 *((unsigned*)reloc) += sym_addr;
1338 break;
1339#elif defined(ANDROID_X86_LINKER)
1340 case R_386_JUMP_SLOT:
1341 COUNT_RELOC(RELOC_ABSOLUTE);
1342 MARK(rel->r_offset);
1343 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1344 reloc, sym_addr, sym_name);
1345 *((unsigned*)reloc) = sym_addr;
1346 break;
1347 case R_386_GLOB_DAT:
1348 COUNT_RELOC(RELOC_ABSOLUTE);
1349 MARK(rel->r_offset);
1350 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1351 reloc, sym_addr, sym_name);
1352 *((unsigned*)reloc) = sym_addr;
1353 break;
1354#endif /* ANDROID_*_LINKER */
1355
1356#if defined(ANDROID_ARM_LINKER)
1357 case R_ARM_RELATIVE:
1358#elif defined(ANDROID_X86_LINKER)
1359 case R_386_RELATIVE:
1360#endif /* ANDROID_*_LINKER */
1361 COUNT_RELOC(RELOC_RELATIVE);
1362 MARK(rel->r_offset);
1363 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001364 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365 return -1;
1366 }
1367 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1368 reloc, si->base);
1369 *((unsigned*)reloc) += si->base;
1370 break;
1371
1372#if defined(ANDROID_X86_LINKER)
1373 case R_386_32:
1374 COUNT_RELOC(RELOC_RELATIVE);
1375 MARK(rel->r_offset);
1376
1377 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1378 reloc, sym_addr, sym_name);
1379 *((unsigned *)reloc) += (unsigned)sym_addr;
1380 break;
1381
1382 case R_386_PC32:
1383 COUNT_RELOC(RELOC_RELATIVE);
1384 MARK(rel->r_offset);
1385 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1386 "+%08x (%08x - %08x) %s\n", pid, reloc,
1387 (sym_addr - reloc), sym_addr, reloc, sym_name);
1388 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1389 break;
1390#endif /* ANDROID_X86_LINKER */
1391
1392#ifdef ANDROID_ARM_LINKER
1393 case R_ARM_COPY:
1394 COUNT_RELOC(RELOC_COPY);
1395 MARK(rel->r_offset);
1396 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1397 reloc, s->st_size, sym_addr, sym_name);
1398 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1399 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001400 case R_ARM_NONE:
1401 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402#endif /* ANDROID_ARM_LINKER */
1403
1404 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001405 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 pid, type, rel, (int) (rel - start));
1407 return -1;
1408 }
1409 rel++;
1410 }
1411 return 0;
1412}
1413
David 'Digit' Turner82156792009-05-18 14:37:41 +02001414
1415/* Please read the "Initialization and Termination functions" functions.
1416 * of the linker design note in bionic/linker/README.TXT to understand
1417 * what the following code is doing.
1418 *
1419 * The important things to remember are:
1420 *
1421 * DT_PREINIT_ARRAY must be called first for executables, and should
1422 * not appear in shared libraries.
1423 *
1424 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1425 *
1426 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1427 *
1428 * DT_FINI_ARRAY must be parsed in reverse order.
1429 */
1430
1431static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001432{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001433 int n, inc = 1;
1434
1435 if (reverse) {
1436 ctor += (count-1);
1437 inc = -1;
1438 }
1439
1440 for(n = count; n > 0; n--) {
1441 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1442 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001443 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001444 void (*func)() = (void (*)()) *ctor;
1445 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001446 if(((int) func == 0) || ((int) func == -1)) continue;
1447 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1448 func();
1449 }
1450}
1451
1452static void call_constructors(soinfo *si)
1453{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001454 if (si->flags & FLAG_EXE) {
1455 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1456 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1457 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001458 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001459 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1460 } else {
1461 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001462 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001463 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001464 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001465 }
1466 }
1467
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001468 if (si->init_func) {
1469 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1470 (unsigned)si->init_func, si->name);
1471 si->init_func();
1472 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1473 }
1474
1475 if (si->init_array) {
1476 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1477 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001478 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001479 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1480 }
1481}
1482
David 'Digit' Turner82156792009-05-18 14:37:41 +02001483
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001484static void call_destructors(soinfo *si)
1485{
1486 if (si->fini_array) {
1487 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1488 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001489 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001490 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1491 }
1492
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001493 if (si->fini_func) {
1494 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1495 (unsigned)si->fini_func, si->name);
1496 si->fini_func();
1497 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1498 }
1499}
1500
1501/* Force any of the closed stdin, stdout and stderr to be associated with
1502 /dev/null. */
1503static int nullify_closed_stdio (void)
1504{
1505 int dev_null, i, status;
1506 int return_value = 0;
1507
1508 dev_null = open("/dev/null", O_RDWR);
1509 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001510 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511 return -1;
1512 }
1513 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1514
1515 /* If any of the stdio file descriptors is valid and not associated
1516 with /dev/null, dup /dev/null to it. */
1517 for (i = 0; i < 3; i++) {
1518 /* If it is /dev/null already, we are done. */
1519 if (i == dev_null)
1520 continue;
1521
1522 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1523 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1524 can be interrupted but we do this just to be safe. */
1525 do {
1526 status = fcntl(i, F_GETFL);
1527 } while (status < 0 && errno == EINTR);
1528
1529 /* If file is openned, we are good. */
1530 if (status >= 0)
1531 continue;
1532
1533 /* The only error we allow is that the file descriptor does not
1534 exist, in which case we dup /dev/null to it. */
1535 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001536 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001537 return_value = -1;
1538 continue;
1539 }
1540
1541 /* Try dupping /dev/null to this stdio file descriptor and
1542 repeat if there is a signal. Note that any errors in closing
1543 the stdio descriptor are lost. */
1544 do {
1545 status = dup2(dev_null, i);
1546 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001547
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001548 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001549 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001550 return_value = -1;
1551 continue;
1552 }
1553 }
1554
1555 /* If /dev/null is not one of the stdio file descriptors, close it. */
1556 if (dev_null > 2) {
1557 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001558 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001559 status = close(dev_null);
1560 } while (status < 0 && errno == EINTR);
1561
1562 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001563 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001564 return_value = -1;
1565 }
1566 }
1567
1568 return return_value;
1569}
1570
1571static int link_image(soinfo *si, unsigned wr_offset)
1572{
1573 unsigned *d;
1574 Elf32_Phdr *phdr = si->phdr;
1575 int phnum = si->phnum;
1576
1577 INFO("[ %5d linking %s ]\n", pid, si->name);
1578 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1579 si->base, si->flags);
1580
1581 if (si->flags & FLAG_EXE) {
1582 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1583 * linkage info if this is the executable. If this was a
1584 * dynamic lib, that would have been done at load time.
1585 *
1586 * TODO: It's unfortunate that small pieces of this are
1587 * repeated from the load_library routine. Refactor this just
1588 * slightly to reuse these bits.
1589 */
1590 si->size = 0;
1591 for(; phnum > 0; --phnum, ++phdr) {
1592#ifdef ANDROID_ARM_LINKER
1593 if(phdr->p_type == PT_ARM_EXIDX) {
1594 /* exidx entries (used for stack unwinding) are 8 bytes each.
1595 */
1596 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1597 si->ARM_exidx_count = phdr->p_memsz / 8;
1598 }
1599#endif
1600 if (phdr->p_type == PT_LOAD) {
1601 /* For the executable, we use the si->size field only in
1602 dl_unwind_find_exidx(), so the meaning of si->size
1603 is not the size of the executable; it is the last
1604 virtual address of the loadable part of the executable;
1605 since si->base == 0 for an executable, we use the
1606 range [0, si->size) to determine whether a PC value
1607 falls within the executable section. Of course, if
1608 a value is below phdr->p_vaddr, it's not in the
1609 executable section, but a) we shouldn't be asking for
1610 such a value anyway, and b) if we have to provide
1611 an EXIDX for such a value, then the executable's
1612 EXIDX is probably the better choice.
1613 */
1614 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1615 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1616 si->size = phdr->p_vaddr + phdr->p_memsz;
1617 /* try to remember what range of addresses should be write
1618 * protected */
1619 if (!(phdr->p_flags & PF_W)) {
1620 unsigned _end;
1621
1622 if (phdr->p_vaddr < si->wrprotect_start)
1623 si->wrprotect_start = phdr->p_vaddr;
1624 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1625 (~PAGE_MASK)));
1626 if (_end > si->wrprotect_end)
1627 si->wrprotect_end = _end;
1628 }
1629 } else if (phdr->p_type == PT_DYNAMIC) {
1630 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001631 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001632 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001633 pid, si->name, si->base + phdr->p_vaddr,
1634 (unsigned)si->dynamic);
1635 goto fail;
1636 }
1637 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1638 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1639 }
1640 }
1641 }
1642
1643 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001644 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001645 goto fail;
1646 }
1647
1648 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1649
1650 /* extract useful information from dynamic section */
1651 for(d = si->dynamic; *d; d++){
1652 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1653 switch(*d++){
1654 case DT_HASH:
1655 si->nbucket = ((unsigned *) (si->base + *d))[0];
1656 si->nchain = ((unsigned *) (si->base + *d))[1];
1657 si->bucket = (unsigned *) (si->base + *d + 8);
1658 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1659 break;
1660 case DT_STRTAB:
1661 si->strtab = (const char *) (si->base + *d);
1662 break;
1663 case DT_SYMTAB:
1664 si->symtab = (Elf32_Sym *) (si->base + *d);
1665 break;
1666 case DT_PLTREL:
1667 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001668 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001669 goto fail;
1670 }
1671 break;
1672 case DT_JMPREL:
1673 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1674 break;
1675 case DT_PLTRELSZ:
1676 si->plt_rel_count = *d / 8;
1677 break;
1678 case DT_REL:
1679 si->rel = (Elf32_Rel*) (si->base + *d);
1680 break;
1681 case DT_RELSZ:
1682 si->rel_count = *d / 8;
1683 break;
1684 case DT_PLTGOT:
1685 /* Save this in case we decide to do lazy binding. We don't yet. */
1686 si->plt_got = (unsigned *)(si->base + *d);
1687 break;
1688 case DT_DEBUG:
1689 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1690 *d = (int) &_r_debug;
1691 break;
1692 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001693 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001694 goto fail;
1695 case DT_INIT:
1696 si->init_func = (void (*)(void))(si->base + *d);
1697 DEBUG("%5d %s constructors (init func) found at %p\n",
1698 pid, si->name, si->init_func);
1699 break;
1700 case DT_FINI:
1701 si->fini_func = (void (*)(void))(si->base + *d);
1702 DEBUG("%5d %s destructors (fini func) found at %p\n",
1703 pid, si->name, si->fini_func);
1704 break;
1705 case DT_INIT_ARRAY:
1706 si->init_array = (unsigned *)(si->base + *d);
1707 DEBUG("%5d %s constructors (init_array) found at %p\n",
1708 pid, si->name, si->init_array);
1709 break;
1710 case DT_INIT_ARRAYSZ:
1711 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1712 break;
1713 case DT_FINI_ARRAY:
1714 si->fini_array = (unsigned *)(si->base + *d);
1715 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1716 pid, si->name, si->fini_array);
1717 break;
1718 case DT_FINI_ARRAYSZ:
1719 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1720 break;
1721 case DT_PREINIT_ARRAY:
1722 si->preinit_array = (unsigned *)(si->base + *d);
1723 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1724 pid, si->name, si->preinit_array);
1725 break;
1726 case DT_PREINIT_ARRAYSZ:
1727 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1728 break;
1729 case DT_TEXTREL:
1730 /* TODO: make use of this. */
1731 /* this means that we might have to write into where the text
1732 * segment was loaded during relocation... Do something with
1733 * it.
1734 */
1735 DEBUG("%5d Text segment should be writable during relocation.\n",
1736 pid);
1737 break;
1738 }
1739 }
1740
1741 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1742 pid, si->base, si->strtab, si->symtab);
1743
1744 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001745 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001746 goto fail;
1747 }
1748
1749 for(d = si->dynamic; *d; d += 2) {
1750 if(d[0] == DT_NEEDED){
1751 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001752 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001753 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001754 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001755 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001756 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001757 goto fail;
1758 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001759 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1760 of the DT_NEEDED entry itself, so that we can retrieve the
1761 soinfo directly later from the dynamic segment. This is a hack,
1762 but it allows us to map from DT_NEEDED to soinfo efficiently
1763 later on when we resolve relocations, trying to look up a symgol
1764 with dlsym().
1765 */
1766 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001767 lsi->refcount++;
1768 }
1769 }
1770
1771 if(si->plt_rel) {
1772 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1773 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1774 goto fail;
1775 }
1776 if(si->rel) {
1777 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1778 if(reloc_library(si, si->rel, si->rel_count))
1779 goto fail;
1780 }
1781
1782 si->flags |= FLAG_LINKED;
1783 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1784
1785#if 0
1786 /* This is the way that the old dynamic linker did protection of
1787 * non-writable areas. It would scan section headers and find where
1788 * .text ended (rather where .data/.bss began) and assume that this is
1789 * the upper range of the non-writable area. This is too coarse,
1790 * and is kept here for reference until we fully move away from single
1791 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1792 * that made this possible.
1793 */
1794 if(wr_offset < 0xffffffff){
1795 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1796 }
1797#else
1798 /* TODO: Verify that this does the right thing in all cases, as it
1799 * presently probably does not. It is possible that an ELF image will
1800 * come with multiple read-only segments. What we ought to do is scan
1801 * the program headers again and mprotect all the read-only segments.
1802 * To prevent re-scanning the program header, we would have to build a
1803 * list of loadable segments in si, and then scan that instead. */
1804 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1805 mprotect((void *)si->wrprotect_start,
1806 si->wrprotect_end - si->wrprotect_start,
1807 PROT_READ | PROT_EXEC);
1808 }
1809#endif
1810
1811 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1812 stdout and stderr to close a security hole described in:
1813
1814 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1815
1816 */
1817 if (getuid() != geteuid() || getgid() != getegid())
1818 nullify_closed_stdio ();
1819 call_constructors(si);
1820 notify_gdb_of_load(si);
1821 return 0;
1822
1823fail:
Doug Kwan94304352009-10-23 18:11:40 -07001824 DL_ERR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001825 si->flags |= FLAG_ERROR;
1826 return -1;
1827}
1828
David Bartleybc3a5c22009-06-02 18:27:28 -07001829static void parse_library_path(char *path, char *delim)
1830{
1831 size_t len;
1832 char *ldpaths_bufp = ldpaths_buf;
1833 int i = 0;
1834
1835 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1836
1837 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1838 if (*ldpaths[i] != '\0')
1839 ++i;
1840 }
1841
1842 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1843 * last char isn't '\0' (i.e. not originally a delim). */
1844 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1845 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1846 ldpaths[i - 1] = NULL;
1847 } else {
1848 ldpaths[i] = NULL;
1849 }
1850}
1851
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001852int main(int argc, char **argv)
1853{
1854 return 0;
1855}
1856
1857#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1858
1859static void * __tls_area[ANDROID_TLS_SLOTS];
1860
1861unsigned __linker_init(unsigned **elfdata)
1862{
1863 static soinfo linker_soinfo;
1864
1865 int argc = (int) *elfdata;
1866 char **argv = (char**) (elfdata + 1);
1867 unsigned *vecs = (unsigned*) (argv + argc + 1);
1868 soinfo *si;
1869 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001870 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001871
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001872 /* Setup a temporary TLS area that is used to get a working
1873 * errno for system calls.
1874 */
1875 __set_tls(__tls_area);
1876
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001877 pid = getpid();
1878
1879#if TIMING
1880 struct timeval t0, t1;
1881 gettimeofday(&t0, 0);
1882#endif
1883
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001884 /* NOTE: we store the elfdata pointer on a special location
1885 * of the temporary TLS area in order to pass it to
1886 * the C Library's runtime initializer.
1887 *
1888 * The initializer must clear the slot and reset the TLS
1889 * to point to a different location to ensure that no other
1890 * shared library constructor can access it.
1891 */
1892 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001893
1894 debugger_init();
1895
1896 /* skip past the environment */
1897 while(vecs[0] != 0) {
1898 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1899 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001900 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1901 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001902 }
1903 vecs++;
1904 }
1905 vecs++;
1906
1907 INFO("[ android linker & debugger ]\n");
1908 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1909
1910 si = alloc_info(argv[0]);
1911 if(si == 0) {
1912 exit(-1);
1913 }
1914
1915 /* bootstrap the link map, the main exe always needs to be first */
1916 si->flags |= FLAG_EXE;
1917 map = &(si->linkmap);
1918
1919 map->l_addr = 0;
1920 map->l_name = argv[0];
1921 map->l_prev = NULL;
1922 map->l_next = NULL;
1923
1924 _r_debug.r_map = map;
1925 r_debug_tail = map;
1926
1927 /* gdb expects the linker to be in the debug shared object list,
1928 * and we need to make sure that the reported load address is zero.
1929 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1930 * is. Don't use alloc_info(), because the linker shouldn't
1931 * be on the soinfo list.
1932 */
1933 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1934 linker_soinfo.flags = 0;
1935 linker_soinfo.base = 0; // This is the important part; must be zero.
1936 insert_soinfo_into_debug_map(&linker_soinfo);
1937
1938 /* extract information passed from the kernel */
1939 while(vecs[0] != 0){
1940 switch(vecs[0]){
1941 case AT_PHDR:
1942 si->phdr = (Elf32_Phdr*) vecs[1];
1943 break;
1944 case AT_PHNUM:
1945 si->phnum = (int) vecs[1];
1946 break;
1947 case AT_ENTRY:
1948 si->entry = vecs[1];
1949 break;
1950 }
1951 vecs += 2;
1952 }
1953
Iliyan Malchevaf7315a2009-10-16 17:50:42 -07001954 ba_init(&ba_prelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001955
1956 si->base = 0;
1957 si->dynamic = (unsigned *)-1;
1958 si->wrprotect_start = 0xffffffff;
1959 si->wrprotect_end = 0;
1960
David Bartleybc3a5c22009-06-02 18:27:28 -07001961 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1962 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1963 parse_library_path(ldpath_env, ":");
1964
Dima Zavin2e855792009-05-20 18:28:09 -07001965 if(link_image(si, 0)) {
1966 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1967 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1968 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001969 exit(-1);
1970 }
1971
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001972#if ALLOW_SYMBOLS_FROM_MAIN
1973 /* Set somain after we've loaded all the libraries in order to prevent
1974 * linking of symbols back to the main image, which is not set up at that
1975 * point yet.
1976 */
1977 somain = si;
1978#endif
1979
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001980#if TIMING
1981 gettimeofday(&t1,NULL);
1982 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1983 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1984 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1985 ));
1986#endif
1987#if STATS
1988 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1989 linker_stats.reloc[RELOC_ABSOLUTE],
1990 linker_stats.reloc[RELOC_RELATIVE],
1991 linker_stats.reloc[RELOC_COPY],
1992 linker_stats.reloc[RELOC_SYMBOL]);
1993#endif
1994#if COUNT_PAGES
1995 {
1996 unsigned n;
1997 unsigned i;
1998 unsigned count = 0;
1999 for(n = 0; n < 4096; n++){
2000 if(bitmask[n]){
2001 unsigned x = bitmask[n];
2002 for(i = 0; i < 8; i++){
2003 if(x & 1) count++;
2004 x >>= 1;
2005 }
2006 }
2007 }
2008 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2009 }
2010#endif
2011
2012#if TIMING || STATS || COUNT_PAGES
2013 fflush(stdout);
2014#endif
2015
2016 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2017 si->entry);
2018 return si->entry;
2019}