blob: 15a22f8bd2090a1990180bb092db35607a5eb104 [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"
David 'Digit' Turner5c734642010-01-20 12:36:51 -080051#include "linker_format.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052
53#include "ba.h"
54
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070055#define ALLOW_SYMBOLS_FROM_MAIN 1
James Dongba52b302009-04-30 20:37:36 -070056#define SO_MAX 96
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080057
David Bartleybc3a5c22009-06-02 18:27:28 -070058/* Assume average path length of 64 and max 8 paths */
59#define LDPATH_BUFSIZE 512
60#define LDPATH_MAX 8
61
Matt Fischer4fd42c12009-12-31 12:09:10 -060062#define LDPRELOAD_BUFSIZE 512
63#define LDPRELOAD_MAX 8
64
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080065/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
66 *
67 * Do NOT use malloc() and friends or pthread_*() code here.
68 * Don't use printf() either; it's caused mysterious memory
69 * corruption in the past.
70 * The linker runs before we bring up libc and it's easiest
71 * to make sure it does not depend on any complex libc features
72 *
73 * open issues / todo:
74 *
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080075 * - are we doing everything we should for ARM_COPY relocations?
76 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080077 * - after linking, set as much stuff as possible to READONLY
78 * and NOEXEC
79 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
80 * headers provide versions that are negative...
81 * - allocate space for soinfo structs dynamically instead of
82 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080083*/
84
85
86static int link_image(soinfo *si, unsigned wr_offset);
87
88static int socount = 0;
89static soinfo sopool[SO_MAX];
90static soinfo *freelist = NULL;
91static soinfo *solist = &libdl_info;
92static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070093#if ALLOW_SYMBOLS_FROM_MAIN
94static soinfo *somain; /* main process, always the one after libdl_info */
95#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080096
Iliyan Malchevaf7315a2009-10-16 17:50:42 -070097
Iliyan Malcheve100f522010-02-10 15:19:37 -080098/* Set up for the buddy allocator managing the non-prelinked libraries. */
99static struct ba_bits ba_nonprelink_bitmap[(LIBLAST - LIBBASE) / LIBINC];
100static struct ba ba_nonprelink = {
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700101 .base = LIBBASE,
102 .size = LIBLAST - LIBBASE,
103 .min_alloc = LIBINC,
Iliyan Malchevbb9eede2009-10-19 14:25:17 -0700104 /* max_order will be determined automatically */
Iliyan Malcheve100f522010-02-10 15:19:37 -0800105 .bitmap = ba_nonprelink_bitmap,
106 .num_entries = sizeof(ba_nonprelink_bitmap)/sizeof(ba_nonprelink_bitmap[0]),
Iliyan Malchevaf7315a2009-10-16 17:50:42 -0700107};
108
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700109static inline int validate_soinfo(soinfo *si)
110{
111 return (si >= sopool && si < sopool + SO_MAX) ||
112 si == &libdl_info;
113}
114
David Bartleybc3a5c22009-06-02 18:27:28 -0700115static char ldpaths_buf[LDPATH_BUFSIZE];
116static const char *ldpaths[LDPATH_MAX + 1];
117
Matt Fischer4fd42c12009-12-31 12:09:10 -0600118static char ldpreloads_buf[LDPRELOAD_BUFSIZE];
119static const char *ldpreload_names[LDPRELOAD_MAX + 1];
120
121static soinfo *preloads[LDPRELOAD_MAX + 1];
122
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800123int debug_verbosity;
124static int pid;
125
126#if STATS
127struct _link_stats linker_stats;
128#endif
129
130#if COUNT_PAGES
131unsigned bitmask[4096];
132#endif
133
134#ifndef PT_ARM_EXIDX
135#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
136#endif
137
Dima Zavin2e855792009-05-20 18:28:09 -0700138#define HOODLUM(name, ret, ...) \
139 ret name __VA_ARGS__ \
140 { \
141 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
142 write(2, errstr, sizeof(errstr)); \
143 abort(); \
144 }
145HOODLUM(malloc, void *, (size_t size));
146HOODLUM(free, void, (void *ptr));
147HOODLUM(realloc, void *, (void *ptr, size_t size));
148HOODLUM(calloc, void *, (size_t cnt, size_t size));
149
Dima Zavin03531952009-05-29 17:30:25 -0700150static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700151static char __linker_dl_err_buf[768];
152#define DL_ERR(fmt, x...) \
153 do { \
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800154 format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
Dima Zavin2e855792009-05-20 18:28:09 -0700155 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700156 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700157 } while(0)
158
159const char *linker_get_error(void)
160{
161 return (const char *)&__linker_dl_err_buf[0];
162}
163
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800164/*
165 * This function is an empty stub where GDB locates a breakpoint to get notified
166 * about linker activity.
167 */
168extern void __attribute__((noinline)) rtld_db_dlactivity(void);
169
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800170static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
171 RT_CONSISTENT, 0};
172static struct link_map *r_debug_tail = 0;
173
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700174static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800175
176static void insert_soinfo_into_debug_map(soinfo * info)
177{
178 struct link_map * map;
179
180 /* Copy the necessary fields into the debug structure.
181 */
182 map = &(info->linkmap);
183 map->l_addr = info->base;
184 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800185 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800186
187 /* Stick the new library at the end of the list.
188 * gdb tends to care more about libc than it does
189 * about leaf libraries, and ordering it this way
190 * reduces the back-and-forth over the wire.
191 */
192 if (r_debug_tail) {
193 r_debug_tail->l_next = map;
194 map->l_prev = r_debug_tail;
195 map->l_next = 0;
196 } else {
197 _r_debug.r_map = map;
198 map->l_prev = 0;
199 map->l_next = 0;
200 }
201 r_debug_tail = map;
202}
203
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700204static void remove_soinfo_from_debug_map(soinfo * info)
205{
206 struct link_map * map = &(info->linkmap);
207
208 if (r_debug_tail == map)
209 r_debug_tail = map->l_prev;
210
211 if (map->l_prev) map->l_prev->l_next = map->l_next;
212 if (map->l_next) map->l_next->l_prev = map->l_prev;
213}
214
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800215void notify_gdb_of_load(soinfo * info)
216{
217 if (info->flags & FLAG_EXE) {
218 // GDB already knows about the main executable
219 return;
220 }
221
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700222 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800223
224 _r_debug.r_state = RT_ADD;
225 rtld_db_dlactivity();
226
227 insert_soinfo_into_debug_map(info);
228
229 _r_debug.r_state = RT_CONSISTENT;
230 rtld_db_dlactivity();
231
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700232 pthread_mutex_unlock(&_r_debug_lock);
233}
234
235void notify_gdb_of_unload(soinfo * info)
236{
237 if (info->flags & FLAG_EXE) {
238 // GDB already knows about the main executable
239 return;
240 }
241
242 pthread_mutex_lock(&_r_debug_lock);
243
244 _r_debug.r_state = RT_DELETE;
245 rtld_db_dlactivity();
246
247 remove_soinfo_from_debug_map(info);
248
249 _r_debug.r_state = RT_CONSISTENT;
250 rtld_db_dlactivity();
251
252 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800253}
254
255void notify_gdb_of_libraries()
256{
257 _r_debug.r_state = RT_ADD;
258 rtld_db_dlactivity();
259 _r_debug.r_state = RT_CONSISTENT;
260 rtld_db_dlactivity();
261}
262
263static soinfo *alloc_info(const char *name)
264{
265 soinfo *si;
266
267 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700268 DL_ERR("%5d library name %s too long", pid, name);
Doug Kwan94304352009-10-23 18:11:40 -0700269 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800270 }
271
272 /* The freelist is populated when we call free_info(), which in turn is
273 done only by dlclose(), which is not likely to be used.
274 */
275 if (!freelist) {
276 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700277 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800278 return NULL;
279 }
280 freelist = sopool + socount++;
281 freelist->next = NULL;
282 }
283
284 si = freelist;
285 freelist = freelist->next;
286
287 /* Make sure we get a clean block of soinfo */
288 memset(si, 0, sizeof(soinfo));
289 strcpy((char*) si->name, name);
290 sonext->next = si;
291 si->ba_index = -1; /* by default, prelinked */
292 si->next = NULL;
293 si->refcount = 0;
294 sonext = si;
295
296 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
297 return si;
298}
299
300static void free_info(soinfo *si)
301{
302 soinfo *prev = NULL, *trav;
303
304 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
305
306 for(trav = solist; trav != NULL; trav = trav->next){
307 if (trav == si)
308 break;
309 prev = trav;
310 }
311 if (trav == NULL) {
312 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700313 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800314 return;
315 }
316
317 /* prev will never be NULL, because the first entry in solist is
318 always the static libdl_info.
319 */
320 prev->next = si->next;
321 if (si == sonext) sonext = prev;
322 si->next = freelist;
323 freelist = si;
324}
325
326#ifndef LINKER_TEXT_BASE
327#error "linker's makefile must define LINKER_TEXT_BASE"
328#endif
329#ifndef LINKER_AREA_SIZE
330#error "linker's makefile must define LINKER_AREA_SIZE"
331#endif
332#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
333#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
334
335const char *addr_to_name(unsigned addr)
336{
337 soinfo *si;
338
339 for(si = solist; si != 0; si = si->next){
340 if((addr >= si->base) && (addr < (si->base + si->size))) {
341 return si->name;
342 }
343 }
344
345 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
346 return "linker";
347 }
348
349 return "";
350}
351
352/* For a given PC, find the .so that it belongs to.
353 * Returns the base address of the .ARM.exidx section
354 * for that .so, and the number of 8-byte entries
355 * in that section (via *pcount).
356 *
357 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
358 *
359 * This function is exposed via dlfcn.c and libdl.so.
360 */
361#ifdef ANDROID_ARM_LINKER
362_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
363{
364 soinfo *si;
365 unsigned addr = (unsigned)pc;
366
367 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
368 for (si = solist; si != 0; si = si->next){
369 if ((addr >= si->base) && (addr < (si->base + si->size))) {
370 *pcount = si->ARM_exidx_count;
371 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
372 }
373 }
374 }
375 *pcount = 0;
376 return NULL;
377}
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +0900378#elif defined(ANDROID_X86_LINKER) || defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800379/* Here, we only have to provide a callback to iterate across all the
380 * loaded libraries. gcc_eh does the rest. */
381int
382dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
383 void *data)
384{
385 soinfo *si;
386 struct dl_phdr_info dl_info;
387 int rv = 0;
388
389 for (si = solist; si != NULL; si = si->next) {
390 dl_info.dlpi_addr = si->linkmap.l_addr;
391 dl_info.dlpi_name = si->linkmap.l_name;
392 dl_info.dlpi_phdr = si->phdr;
393 dl_info.dlpi_phnum = si->phnum;
394 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
395 if (rv != 0)
396 break;
397 }
398 return rv;
399}
400#endif
401
402static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
403{
404 Elf32_Sym *s;
405 Elf32_Sym *symtab = si->symtab;
406 const char *strtab = si->strtab;
407 unsigned n;
408
409 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
410 name, si->name, si->base, hash, hash % si->nbucket);
411 n = hash % si->nbucket;
412
413 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
414 s = symtab + n;
415 if(strcmp(strtab + s->st_name, name)) continue;
416
Doug Kwane8238072009-10-26 12:05:23 -0700417 /* only concern ourselves with global and weak symbol definitions */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800418 switch(ELF32_ST_BIND(s->st_info)){
419 case STB_GLOBAL:
Doug Kwane8238072009-10-26 12:05:23 -0700420 case STB_WEAK:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800421 /* no section == undefined */
422 if(s->st_shndx == 0) continue;
423
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800424 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
425 name, si->name, s->st_value, s->st_size);
426 return s;
427 }
428 }
429
Doug Kwan94304352009-10-23 18:11:40 -0700430 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800431}
432
433static unsigned elfhash(const char *_name)
434{
435 const unsigned char *name = (const unsigned char *) _name;
436 unsigned h = 0, g;
437
438 while(*name) {
439 h = (h << 4) + *name++;
440 g = h & 0xf0000000;
441 h ^= g;
442 h ^= g >> 24;
443 }
444 return h;
445}
446
447static Elf32_Sym *
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700448_do_lookup(soinfo *si, const char *name, unsigned *base)
449{
Doug Kwan94304352009-10-23 18:11:40 -0700450 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700451 Elf32_Sym *s;
452 unsigned *d;
453 soinfo *lsi = si;
Matt Fischer4fd42c12009-12-31 12:09:10 -0600454 int i;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700455
456 /* Look for symbols in the local scope first (the object who is
457 * searching). This happens with C++ templates on i386 for some
Doug Kwane8238072009-10-26 12:05:23 -0700458 * reason.
459 *
460 * Notes on weak symbols:
461 * The ELF specs are ambigious about treatment of weak definitions in
462 * dynamic linking. Some systems return the first definition found
463 * and some the first non-weak definition. This is system dependent.
464 * Here we return the first definition found for simplicity. */
Doug Kwan94304352009-10-23 18:11:40 -0700465 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700466 if(s != NULL)
467 goto done;
468
Matt Fischer4fd42c12009-12-31 12:09:10 -0600469 /* Next, look for it in the preloads list */
470 for(i = 0; preloads[i] != NULL; i++) {
471 lsi = preloads[i];
Jean-Baptiste Queruf4394452010-05-12 10:05:59 -0700472 s = _elf_lookup(lsi, elf_hash, name);
Matt Fischer4fd42c12009-12-31 12:09:10 -0600473 if(s != NULL)
474 goto done;
475 }
476
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700477 for(d = si->dynamic; *d; d += 2) {
478 if(d[0] == DT_NEEDED){
479 lsi = (soinfo *)d[1];
480 if (!validate_soinfo(lsi)) {
481 DL_ERR("%5d bad DT_NEEDED pointer in %s",
482 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700483 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700484 }
485
486 DEBUG("%5d %s: looking up %s in %s\n",
487 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700488 s = _elf_lookup(lsi, elf_hash, name);
Min-su, Kim3cab22c2010-01-19 10:05:33 +0900489 if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700490 goto done;
491 }
492 }
493
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700494#if ALLOW_SYMBOLS_FROM_MAIN
495 /* If we are resolving relocations while dlopen()ing a library, it's OK for
496 * the library to resolve a symbol that's defined in the executable itself,
497 * although this is rare and is generally a bad idea.
498 */
499 if (somain) {
500 lsi = somain;
501 DEBUG("%5d %s: looking up %s in executable %s\n",
502 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700503 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700504 }
505#endif
506
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700507done:
508 if(s != NULL) {
509 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
510 "found in %s, base = 0x%08x\n",
511 pid, si->name, name, s->st_value, lsi->name, lsi->base);
512 *base = lsi->base;
513 return s;
514 }
515
Doug Kwan94304352009-10-23 18:11:40 -0700516 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700517}
518
519/* This is used by dl_sym(). It performs symbol lookup only within the
520 specified soinfo object and not in any of its dependencies.
521 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800522Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
523{
Doug Kwan94304352009-10-23 18:11:40 -0700524 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800525}
526
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700527/* This is used by dl_sym(). It performs a global symbol lookup.
528 */
Matt Fischer1698d9e2009-12-31 12:17:56 -0600529Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800530{
Doug Kwan94304352009-10-23 18:11:40 -0700531 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800532 Elf32_Sym *s = NULL;
533 soinfo *si;
534
Matt Fischer1698d9e2009-12-31 12:17:56 -0600535 if(start == NULL) {
536 start = solist;
537 }
538
539 for(si = start; (s == NULL) && (si != NULL); si = si->next)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800540 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700541 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800542 continue;
Doug Kwane8238072009-10-26 12:05:23 -0700543 s = _elf_lookup(si, elf_hash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800544 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700545 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800546 break;
547 }
548 }
549
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700550 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800551 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
552 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
553 return s;
554 }
555
Doug Kwan94304352009-10-23 18:11:40 -0700556 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800557}
558
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600559soinfo *find_containing_library(void *addr)
560{
561 soinfo *si;
562
563 for(si = solist; si != NULL; si = si->next)
564 {
565 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
566 return si;
567 }
568 }
569
570 return NULL;
571}
572
573Elf32_Sym *find_containing_symbol(void *addr, soinfo *si)
574{
575 unsigned int i;
576 unsigned soaddr = (unsigned)addr - si->base;
577
578 /* Search the library's symbol table for any defined symbol which
579 * contains this address */
580 for(i=0; i<si->nchain; i++) {
581 Elf32_Sym *sym = &si->symtab[i];
582
583 if(sym->st_shndx != SHN_UNDEF &&
584 soaddr >= sym->st_value &&
585 soaddr < sym->st_value + sym->st_size) {
586 return sym;
587 }
588 }
589
590 return NULL;
591}
592
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800593#if 0
594static void dump(soinfo *si)
595{
596 Elf32_Sym *s = si->symtab;
597 unsigned n;
598
599 for(n = 0; n < si->nchain; n++) {
600 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
601 s->st_info, s->st_shndx, s->st_value, s->st_size,
602 si->strtab + s->st_name);
603 s++;
604 }
605}
606#endif
607
608static const char *sopaths[] = {
609 "/system/lib",
610 "/lib",
611 0
612};
613
614static int _open_lib(const char *name)
615{
616 int fd;
617 struct stat filestat;
618
619 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
620 if ((fd = open(name, O_RDONLY)) >= 0)
621 return fd;
622 }
623
624 return -1;
625}
626
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800627static int open_library(const char *name)
628{
629 int fd;
630 char buf[512];
631 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700632 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800633
634 TRACE("[ %5d opening %s ]\n", pid, name);
635
636 if(name == 0) return -1;
637 if(strlen(name) > 256) return -1;
638
639 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
640 return fd;
641
David Bartleybc3a5c22009-06-02 18:27:28 -0700642 for (path = ldpaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800643 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700644 if (n < 0 || n >= (int)sizeof(buf)) {
645 WARN("Ignoring very long library path: %s/%s\n", *path, name);
646 continue;
647 }
648 if ((fd = _open_lib(buf)) >= 0)
649 return fd;
650 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800651 for (path = sopaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800652 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700653 if (n < 0 || n >= (int)sizeof(buf)) {
654 WARN("Ignoring very long library path: %s/%s\n", *path, name);
655 continue;
656 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800657 if ((fd = _open_lib(buf)) >= 0)
658 return fd;
659 }
660
661 return -1;
662}
663
664/* temporary space for holding the first page of the shared lib
665 * which contains the elf header (with the pht). */
666static unsigned char __header[PAGE_SIZE];
667
668typedef struct {
669 long mmap_addr;
670 char tag[4]; /* 'P', 'R', 'E', ' ' */
671} prelink_info_t;
672
673/* Returns the requested base address if the library is prelinked,
674 * and 0 otherwise. */
675static unsigned long
676is_prelinked(int fd, const char *name)
677{
678 off_t sz;
679 prelink_info_t info;
680
681 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
682 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700683 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800684 return 0;
685 }
686
687 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
688 WARN("Could not read prelink_info_t structure for `%s`\n", name);
689 return 0;
690 }
691
692 if (strncmp(info.tag, "PRE ", 4)) {
693 WARN("`%s` is not a prelinked library\n", name);
694 return 0;
695 }
696
697 return (unsigned long)info.mmap_addr;
698}
699
700/* verify_elf_object
701 * Verifies if the object @ base is a valid ELF object
702 *
703 * Args:
704 *
705 * Returns:
706 * 0 on success
707 * -1 if no valid ELF object is found @ base.
708 */
709static int
710verify_elf_object(void *base, const char *name)
711{
712 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
713
714 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
715 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
716 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
717 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
718
719 /* TODO: Should we verify anything else in the header? */
720
721 return 0;
722}
723
724
725/* get_lib_extents
726 * Retrieves the base (*base) address where the ELF object should be
727 * mapped and its overall memory size (*total_sz).
728 *
729 * Args:
730 * fd: Opened file descriptor for the library
731 * name: The name of the library
732 * _hdr: Pointer to the header page of the library
733 * total_sz: Total size of the memory that should be allocated for
734 * this library
735 *
736 * Returns:
737 * -1 if there was an error while trying to get the lib extents.
738 * The possible reasons are:
739 * - Could not determine if the library was prelinked.
740 * - The library provided is not a valid ELF object
741 * 0 if the library did not request a specific base offset (normal
742 * for non-prelinked libs)
743 * > 0 if the library requests a specific address to be mapped to.
744 * This indicates a pre-linked library.
745 */
746static unsigned
747get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
748{
749 unsigned req_base;
750 unsigned min_vaddr = 0xffffffff;
751 unsigned max_vaddr = 0;
752 unsigned char *_hdr = (unsigned char *)__hdr;
753 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
754 Elf32_Phdr *phdr;
755 int cnt;
756
757 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
758 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700759 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800760 return (unsigned)-1;
761 }
762
763 req_base = (unsigned) is_prelinked(fd, name);
764 if (req_base == (unsigned)-1)
765 return -1;
766 else if (req_base != 0) {
767 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
768 pid, name, req_base);
769 } else {
770 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
771 }
772
773 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
774
775 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
776 * get the range. */
777 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
778 if (phdr->p_type == PT_LOAD) {
779 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
780 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
781 if (phdr->p_vaddr < min_vaddr)
782 min_vaddr = phdr->p_vaddr;
783 }
784 }
785
786 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700787 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800788 return (unsigned)-1;
789 }
790
791 /* truncate min_vaddr down to page boundary */
792 min_vaddr &= ~PAGE_MASK;
793
794 /* round max_vaddr up to the next page */
795 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
796
797 *total_sz = (max_vaddr - min_vaddr);
798 return (unsigned)req_base;
799}
800
801/* alloc_mem_region
802 *
803 * This function reserves a chunk of memory to be used for mapping in
804 * the shared library. We reserve the entire memory region here, and
805 * then the rest of the linker will relocate the individual loadable
806 * segments into the correct locations within this memory range.
807 *
808 * Args:
809 * si->base: The requested base of the allocation. If 0, a sane one will be
810 * chosen in the range LIBBASE <= base < LIBLAST.
811 * si->size: The size of the allocation.
812 *
813 * Returns:
814 * -1 on failure, and 0 on success. On success, si->base will contain
815 * the virtual address at which the library will be mapped.
816 */
817
818static int reserve_mem_region(soinfo *si)
819{
820 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
821 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
822 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700823 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700824 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800825 pid, (si->base ? "" : "non-"), si->name, si->base,
826 errno, strerror(errno));
827 return -1;
828 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700829 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700830 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800831 si->name, (unsigned)base, si->base);
832 munmap(base, si->size);
833 return -1;
834 }
835 return 0;
836}
837
838static int
839alloc_mem_region(soinfo *si)
840{
841 if (si->base) {
842 /* Attempt to mmap a prelinked library. */
843 si->ba_index = -1;
844 return reserve_mem_region(si);
845 }
846
847 /* This is not a prelinked library, so we attempt to allocate space
848 for it from the buddy allocator, which manages the area between
849 LIBBASE and LIBLAST.
850 */
Iliyan Malcheve100f522010-02-10 15:19:37 -0800851 si->ba_index = ba_allocate(&ba_nonprelink, si->size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800852 if(si->ba_index >= 0) {
Iliyan Malcheve100f522010-02-10 15:19:37 -0800853 si->base = ba_start_addr(&ba_nonprelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800854 PRINT("%5d mapping library '%s' at %08x (index %d) " \
855 "through buddy allocator.\n",
856 pid, si->name, si->base, si->ba_index);
857 if (reserve_mem_region(si) < 0) {
Iliyan Malcheve100f522010-02-10 15:19:37 -0800858 ba_free(&ba_nonprelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800859 si->ba_index = -1;
860 si->base = 0;
861 goto err;
862 }
863 return 0;
864 }
865
866err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700867 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800868 pid, si->name);
869 return -1;
870}
871
872#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
873#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
874 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
875 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
876/* load_segments
877 *
878 * This function loads all the loadable (PT_LOAD) segments into memory
879 * at their appropriate memory offsets off the base address.
880 *
881 * Args:
882 * fd: Open file descriptor to the library to load.
883 * header: Pointer to a header page that contains the ELF header.
884 * This is needed since we haven't mapped in the real file yet.
885 * si: ptr to soinfo struct describing the shared object.
886 *
887 * Returns:
888 * 0 on success, -1 on failure.
889 */
890static int
891load_segments(int fd, void *header, soinfo *si)
892{
893 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
894 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
895 unsigned char *base = (unsigned char *)si->base;
896 int cnt;
897 unsigned len;
898 unsigned char *tmp;
899 unsigned char *pbase;
900 unsigned char *extra_base;
901 unsigned extra_len;
902 unsigned total_sz = 0;
903
904 si->wrprotect_start = 0xffffffff;
905 si->wrprotect_end = 0;
906
907 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
908 pid, si->name, (unsigned)si->base);
909 /* Now go through all the PT_LOAD segments and map them into memory
910 * at the appropriate locations. */
911 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
912 if (phdr->p_type == PT_LOAD) {
913 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
914 /* we want to map in the segment on a page boundary */
915 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
916 /* add the # of bytes we masked off above to the total length. */
917 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
918
919 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
920 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
921 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
922 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
923 MAP_PRIVATE | MAP_FIXED, fd,
924 phdr->p_offset & (~PAGE_MASK));
925 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700926 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700927 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800928 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
929 goto fail;
930 }
931
932 /* If 'len' didn't end on page boundary, and it's a writable
933 * segment, zero-fill the rest. */
934 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
935 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
936
937 /* Check to see if we need to extend the map for this segment to
938 * cover the diff between filesz and memsz (i.e. for bss).
939 *
940 * base _+---------------------+ page boundary
941 * . .
942 * | |
943 * . .
944 * pbase _+---------------------+ page boundary
945 * | |
946 * . .
947 * base + p_vaddr _| |
948 * . \ \ .
949 * . | filesz | .
950 * pbase + len _| / | |
951 * <0 pad> . . .
952 * extra_base _+------------|--------+ page boundary
953 * / . . .
954 * | . . .
955 * | +------------|--------+ page boundary
956 * extra_len-> | | | |
957 * | . | memsz .
958 * | . | .
959 * \ _| / |
960 * . .
961 * | |
962 * _+---------------------+ page boundary
963 */
964 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
965 (~PAGE_MASK));
966 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
967 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
968 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
969 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
970 /* map in the extra page(s) as anonymous into the range.
971 * This is probably not necessary as we already mapped in
972 * the entire region previously, but we just want to be
973 * sure. This will also set the right flags on the region
974 * (though we can probably accomplish the same thing with
975 * mprotect).
976 */
977 extra_base = mmap((void *)tmp, extra_len,
978 PFLAGS_TO_PROT(phdr->p_flags),
979 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
980 -1, 0);
981 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700982 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700983 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800984 extra_len);
985 goto fail;
986 }
987 /* TODO: Check if we need to memset-0 this region.
988 * Anonymous mappings are zero-filled copy-on-writes, so we
989 * shouldn't need to. */
990 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
991 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
992 extra_len);
993 }
994 /* set the len here to show the full extent of the segment we
995 * just loaded, mostly for debugging */
996 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
997 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
998 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
999 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
1000 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
1001 total_sz += len;
1002 /* Make the section writable just in case we'll have to write to
1003 * it during relocation (i.e. text segment). However, we will
1004 * remember what range of addresses should be write protected.
1005 *
1006 */
1007 if (!(phdr->p_flags & PF_W)) {
1008 if ((unsigned)pbase < si->wrprotect_start)
1009 si->wrprotect_start = (unsigned)pbase;
1010 if (((unsigned)pbase + len) > si->wrprotect_end)
1011 si->wrprotect_end = (unsigned)pbase + len;
1012 mprotect(pbase, len,
1013 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1014 }
1015 } else if (phdr->p_type == PT_DYNAMIC) {
1016 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1017 /* this segment contains the dynamic linking information */
1018 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
1019 } else {
1020#ifdef ANDROID_ARM_LINKER
1021 if (phdr->p_type == PT_ARM_EXIDX) {
1022 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1023 /* exidx entries (used for stack unwinding) are 8 bytes each.
1024 */
1025 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1026 si->ARM_exidx_count = phdr->p_memsz / 8;
1027 }
1028#endif
1029 }
1030
1031 }
1032
1033 /* Sanity check */
1034 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001035 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001036 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001037 pid, total_sz, si->name, si->size);
1038 goto fail;
1039 }
1040
1041 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1042 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1043 (unsigned)si->base, si->size);
1044 return 0;
1045
1046fail:
1047 /* We can just blindly unmap the entire region even though some things
1048 * were mapped in originally with anonymous and others could have been
1049 * been mapped in from the file before we failed. The kernel will unmap
1050 * all the pages in the range, irrespective of how they got there.
1051 */
1052 munmap((void *)si->base, si->size);
1053 si->flags |= FLAG_ERROR;
1054 return -1;
1055}
1056
1057/* TODO: Implement this to take care of the fact that Android ARM
1058 * ELF objects shove everything into a single loadable segment that has the
1059 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1060 * non-writable.
1061 */
1062#if 0
1063static unsigned
1064get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1065{
1066 Elf32_Shdr *shdr_start;
1067 Elf32_Shdr *shdr;
1068 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1069 int cnt;
1070 unsigned wr_offset = 0xffffffff;
1071
1072 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1073 ehdr->e_shoff & (~PAGE_MASK));
1074 if (shdr_start == MAP_FAILED) {
1075 WARN("%5d - Could not read section header info from '%s'. Will not "
1076 "not be able to determine write-protect offset.\n", pid, name);
1077 return (unsigned)-1;
1078 }
1079
1080 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1081 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1082 (shdr->sh_addr < wr_offset)) {
1083 wr_offset = shdr->sh_addr;
1084 }
1085 }
1086
1087 munmap(shdr_start, shdr_sz);
1088 return wr_offset;
1089}
1090#endif
1091
1092static soinfo *
1093load_library(const char *name)
1094{
1095 int fd = open_library(name);
1096 int cnt;
1097 unsigned ext_sz;
1098 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001099 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001100 soinfo *si = NULL;
1101 Elf32_Ehdr *hdr;
1102
Dima Zavin2e855792009-05-20 18:28:09 -07001103 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001104 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001105 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001106 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001107
1108 /* We have to read the ELF header to figure out what to do with this image
1109 */
1110 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001111 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001112 goto fail;
1113 }
1114
1115 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001116 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001117 goto fail;
1118 }
1119
1120 /* Parse the ELF header and get the size of the memory footprint for
1121 * the library */
1122 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1123 if (req_base == (unsigned)-1)
1124 goto fail;
1125 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1126 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1127
1128 /* Now configure the soinfo struct where we'll store all of our data
1129 * for the ELF object. If the loading fails, we waste the entry, but
1130 * same thing would happen if we failed during linking. Configuring the
1131 * soinfo struct here is a lot more convenient.
1132 */
Erik Gillingfde86422009-07-28 20:28:19 -07001133 bname = strrchr(name, '/');
1134 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001135 if (si == NULL)
1136 goto fail;
1137
1138 /* Carve out a chunk of memory where we will map in the individual
1139 * segments */
1140 si->base = req_base;
1141 si->size = ext_sz;
1142 si->flags = 0;
1143 si->entry = 0;
1144 si->dynamic = (unsigned *)-1;
1145 if (alloc_mem_region(si) < 0)
1146 goto fail;
1147
1148 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1149 pid, name, (void *)si->base, (unsigned) ext_sz);
1150
1151 /* Now actually load the library's segments into right places in memory */
1152 if (load_segments(fd, &__header[0], si) < 0) {
1153 if (si->ba_index >= 0) {
Iliyan Malcheve100f522010-02-10 15:19:37 -08001154 ba_free(&ba_nonprelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001155 si->ba_index = -1;
1156 }
1157 goto fail;
1158 }
1159
1160 /* this might not be right. Technically, we don't even need this info
1161 * once we go through 'load_segments'. */
1162 hdr = (Elf32_Ehdr *)si->base;
1163 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1164 si->phnum = hdr->e_phnum;
1165 /**/
1166
1167 close(fd);
1168 return si;
1169
1170fail:
1171 if (si) free_info(si);
1172 close(fd);
1173 return NULL;
1174}
1175
1176static soinfo *
1177init_library(soinfo *si)
1178{
1179 unsigned wr_offset = 0xffffffff;
1180
1181 /* At this point we know that whatever is loaded @ base is a valid ELF
1182 * shared library whose segments are properly mapped in. */
1183 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1184 pid, si->base, si->size, si->name);
1185
1186 if (si->base < LIBBASE || si->base >= LIBLAST)
1187 si->flags |= FLAG_PRELINKED;
1188
1189 if(link_image(si, wr_offset)) {
1190 /* We failed to link. However, we can only restore libbase
1191 ** if no additional libraries have moved it since we updated it.
1192 */
1193 munmap((void *)si->base, si->size);
1194 return NULL;
1195 }
1196
1197 return si;
1198}
1199
1200soinfo *find_library(const char *name)
1201{
1202 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001203 const char *bname;
1204
1205#if ALLOW_SYMBOLS_FROM_MAIN
1206 if (name == NULL)
1207 return somain;
1208#else
1209 if (name == NULL)
1210 return NULL;
1211#endif
1212
1213 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001214 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001215
1216 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001217 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001218 if(si->flags & FLAG_ERROR) {
1219 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1220 return NULL;
1221 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001222 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001223 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001224 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001225 }
1226 }
1227
1228 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1229 si = load_library(name);
1230 if(si == NULL)
1231 return NULL;
1232 return init_library(si);
1233}
1234
1235/* TODO:
1236 * notify gdb of unload
1237 * for non-prelinked libraries, find a way to decrement libbase
1238 */
1239static void call_destructors(soinfo *si);
1240unsigned unload_library(soinfo *si)
1241{
1242 unsigned *d;
1243 if (si->refcount == 1) {
1244 TRACE("%5d unloading '%s'\n", pid, si->name);
1245 call_destructors(si);
1246
1247 for(d = si->dynamic; *d; d += 2) {
1248 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001249 soinfo *lsi = (soinfo *)d[1];
1250 d[1] = 0;
1251 if (validate_soinfo(lsi)) {
1252 TRACE("%5d %s needs to unload %s\n", pid,
1253 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001254 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001255 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001256 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001257 DL_ERR("%5d %s: could not unload dependent library",
1258 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001259 }
1260 }
1261
1262 munmap((char *)si->base, si->size);
1263 if (si->ba_index >= 0) {
1264 PRINT("%5d releasing library '%s' address space at %08x "\
1265 "through buddy allocator.\n",
1266 pid, si->name, si->base);
Iliyan Malcheve100f522010-02-10 15:19:37 -08001267 ba_free(&ba_nonprelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001268 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001269 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001270 free_info(si);
1271 si->refcount = 0;
1272 }
1273 else {
1274 si->refcount--;
1275 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1276 pid, si->name, si->refcount);
1277 }
1278 return si->refcount;
1279}
1280
1281/* TODO: don't use unsigned for addrs below. It works, but is not
1282 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1283 * long.
1284 */
1285static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1286{
1287 Elf32_Sym *symtab = si->symtab;
1288 const char *strtab = si->strtab;
1289 Elf32_Sym *s;
1290 unsigned base;
1291 Elf32_Rel *start = rel;
1292 unsigned idx;
1293
1294 for (idx = 0; idx < count; ++idx) {
1295 unsigned type = ELF32_R_TYPE(rel->r_info);
1296 unsigned sym = ELF32_R_SYM(rel->r_info);
1297 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1298 unsigned sym_addr = 0;
1299 char *sym_name = NULL;
1300
1301 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1302 si->name, idx);
1303 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001304 sym_name = (char *)(strtab + symtab[sym].st_name);
1305 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001306 if(s == NULL) {
1307 /* We only allow an undefined symbol if this is a weak
1308 reference.. */
1309 s = &symtab[sym];
1310 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1311 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1312 return -1;
1313 }
1314
1315 /* IHI0044C AAELF 4.5.1.1:
1316
1317 Libraries are not searched to resolve weak references.
1318 It is not an error for a weak reference to remain
1319 unsatisfied.
1320
1321 During linking, the value of an undefined weak reference is:
1322 - Zero if the relocation type is absolute
1323 - The address of the place if the relocation is pc-relative
1324 - The address of nominial base address if the relocation
1325 type is base-relative.
1326 */
1327
1328 switch (type) {
1329#if defined(ANDROID_ARM_LINKER)
1330 case R_ARM_JUMP_SLOT:
1331 case R_ARM_GLOB_DAT:
1332 case R_ARM_ABS32:
1333 case R_ARM_RELATIVE: /* Don't care. */
1334 case R_ARM_NONE: /* Don't care. */
1335#elif defined(ANDROID_X86_LINKER)
1336 case R_386_JUMP_SLOT:
1337 case R_386_GLOB_DAT:
1338 case R_386_32:
1339 case R_386_RELATIVE: /* Dont' care. */
1340#endif /* ANDROID_*_LINKER */
1341 /* sym_addr was initialized to be zero above or relocation
1342 code below does not care about value of sym_addr.
1343 No need to do anything. */
1344 break;
1345
1346#if defined(ANDROID_X86_LINKER)
1347 case R_386_PC32:
1348 sym_addr = reloc;
1349 break;
1350#endif /* ANDROID_X86_LINKER */
1351
1352#if defined(ANDROID_ARM_LINKER)
1353 case R_ARM_COPY:
1354 /* Fall through. Can't really copy if weak symbol is
1355 not found in run-time. */
1356#endif /* ANDROID_ARM_LINKER */
1357 default:
1358 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1359 pid, type, rel, (int) (rel - start));
1360 return -1;
1361 }
1362 } else {
1363 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001364#if 0
1365 if((base == 0) && (si->base != 0)){
1366 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001367 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001368 pid, strtab + symtab[sym].st_name);
1369 return -1;
1370 }
1371#endif
Doug Kwane8238072009-10-26 12:05:23 -07001372 sym_addr = (unsigned)(s->st_value + base);
1373 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001374 COUNT_RELOC(RELOC_SYMBOL);
1375 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001376 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001377 }
1378
1379/* TODO: This is ugly. Split up the relocations by arch into
1380 * different files.
1381 */
1382 switch(type){
1383#if defined(ANDROID_ARM_LINKER)
1384 case R_ARM_JUMP_SLOT:
1385 COUNT_RELOC(RELOC_ABSOLUTE);
1386 MARK(rel->r_offset);
1387 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1388 reloc, sym_addr, sym_name);
1389 *((unsigned*)reloc) = sym_addr;
1390 break;
1391 case R_ARM_GLOB_DAT:
1392 COUNT_RELOC(RELOC_ABSOLUTE);
1393 MARK(rel->r_offset);
1394 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1395 reloc, sym_addr, sym_name);
1396 *((unsigned*)reloc) = sym_addr;
1397 break;
1398 case R_ARM_ABS32:
1399 COUNT_RELOC(RELOC_ABSOLUTE);
1400 MARK(rel->r_offset);
1401 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1402 reloc, sym_addr, sym_name);
1403 *((unsigned*)reloc) += sym_addr;
1404 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001405 case R_ARM_REL32:
1406 COUNT_RELOC(RELOC_RELATIVE);
1407 MARK(rel->r_offset);
1408 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1409 reloc, sym_addr, rel->r_offset, sym_name);
1410 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1411 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001412#elif defined(ANDROID_X86_LINKER)
1413 case R_386_JUMP_SLOT:
1414 COUNT_RELOC(RELOC_ABSOLUTE);
1415 MARK(rel->r_offset);
1416 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1417 reloc, sym_addr, sym_name);
1418 *((unsigned*)reloc) = sym_addr;
1419 break;
1420 case R_386_GLOB_DAT:
1421 COUNT_RELOC(RELOC_ABSOLUTE);
1422 MARK(rel->r_offset);
1423 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1424 reloc, sym_addr, sym_name);
1425 *((unsigned*)reloc) = sym_addr;
1426 break;
1427#endif /* ANDROID_*_LINKER */
1428
1429#if defined(ANDROID_ARM_LINKER)
1430 case R_ARM_RELATIVE:
1431#elif defined(ANDROID_X86_LINKER)
1432 case R_386_RELATIVE:
1433#endif /* ANDROID_*_LINKER */
1434 COUNT_RELOC(RELOC_RELATIVE);
1435 MARK(rel->r_offset);
1436 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001437 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001438 return -1;
1439 }
1440 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1441 reloc, si->base);
1442 *((unsigned*)reloc) += si->base;
1443 break;
1444
1445#if defined(ANDROID_X86_LINKER)
1446 case R_386_32:
1447 COUNT_RELOC(RELOC_RELATIVE);
1448 MARK(rel->r_offset);
1449
1450 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1451 reloc, sym_addr, sym_name);
1452 *((unsigned *)reloc) += (unsigned)sym_addr;
1453 break;
1454
1455 case R_386_PC32:
1456 COUNT_RELOC(RELOC_RELATIVE);
1457 MARK(rel->r_offset);
1458 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1459 "+%08x (%08x - %08x) %s\n", pid, reloc,
1460 (sym_addr - reloc), sym_addr, reloc, sym_name);
1461 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1462 break;
1463#endif /* ANDROID_X86_LINKER */
1464
1465#ifdef ANDROID_ARM_LINKER
1466 case R_ARM_COPY:
1467 COUNT_RELOC(RELOC_COPY);
1468 MARK(rel->r_offset);
1469 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1470 reloc, s->st_size, sym_addr, sym_name);
1471 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1472 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001473 case R_ARM_NONE:
1474 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001475#endif /* ANDROID_ARM_LINKER */
1476
1477 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001478 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001479 pid, type, rel, (int) (rel - start));
1480 return -1;
1481 }
1482 rel++;
1483 }
1484 return 0;
1485}
1486
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001487#if defined(ANDROID_SH_LINKER)
1488static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1489{
1490 Elf32_Sym *symtab = si->symtab;
1491 const char *strtab = si->strtab;
1492 Elf32_Sym *s;
1493 unsigned base;
1494 Elf32_Rela *start = rela;
1495 unsigned idx;
1496
1497 for (idx = 0; idx < count; ++idx) {
1498 unsigned type = ELF32_R_TYPE(rela->r_info);
1499 unsigned sym = ELF32_R_SYM(rela->r_info);
1500 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1501 unsigned sym_addr = 0;
1502 char *sym_name = NULL;
1503
1504 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1505 si->name, idx);
1506 if(sym != 0) {
1507 sym_name = (char *)(strtab + symtab[sym].st_name);
1508 s = _do_lookup(si, sym_name, &base);
1509 if(s == 0) {
1510 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1511 return -1;
1512 }
1513#if 0
1514 if((base == 0) && (si->base != 0)){
1515 /* linking from libraries to main image is bad */
1516 DL_ERR("%5d cannot locate '%s'...",
1517 pid, strtab + symtab[sym].st_name);
1518 return -1;
1519 }
1520#endif
1521 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1522 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1523 "handle this yet", pid, si->name, s->st_shndx,
1524 s->st_value);
1525 return -1;
1526 }
1527 sym_addr = (unsigned)(s->st_value + base);
1528 COUNT_RELOC(RELOC_SYMBOL);
1529 } else {
1530 s = 0;
1531 }
1532
1533/* TODO: This is ugly. Split up the relocations by arch into
1534 * different files.
1535 */
1536 switch(type){
1537 case R_SH_JUMP_SLOT:
1538 COUNT_RELOC(RELOC_ABSOLUTE);
1539 MARK(rela->r_offset);
1540 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1541 reloc, sym_addr, sym_name);
1542 *((unsigned*)reloc) = sym_addr;
1543 break;
1544 case R_SH_GLOB_DAT:
1545 COUNT_RELOC(RELOC_ABSOLUTE);
1546 MARK(rela->r_offset);
1547 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1548 reloc, sym_addr, sym_name);
1549 *((unsigned*)reloc) = sym_addr;
1550 break;
1551 case R_SH_DIR32:
1552 COUNT_RELOC(RELOC_ABSOLUTE);
1553 MARK(rela->r_offset);
1554 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1555 reloc, sym_addr, sym_name);
1556 *((unsigned*)reloc) += sym_addr;
1557 break;
1558 case R_SH_RELATIVE:
1559 COUNT_RELOC(RELOC_RELATIVE);
1560 MARK(rela->r_offset);
1561 if(sym){
1562 DL_ERR("%5d odd RELATIVE form...", pid);
1563 return -1;
1564 }
1565 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1566 reloc, si->base);
1567 *((unsigned*)reloc) += si->base;
1568 break;
1569
1570 default:
1571 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1572 pid, type, rela, (int) (rela - start));
1573 return -1;
1574 }
1575 rela++;
1576 }
1577 return 0;
1578}
1579#endif /* ANDROID_SH_LINKER */
1580
David 'Digit' Turner82156792009-05-18 14:37:41 +02001581
1582/* Please read the "Initialization and Termination functions" functions.
1583 * of the linker design note in bionic/linker/README.TXT to understand
1584 * what the following code is doing.
1585 *
1586 * The important things to remember are:
1587 *
1588 * DT_PREINIT_ARRAY must be called first for executables, and should
1589 * not appear in shared libraries.
1590 *
1591 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1592 *
1593 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1594 *
1595 * DT_FINI_ARRAY must be parsed in reverse order.
1596 */
1597
1598static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001599{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001600 int n, inc = 1;
1601
1602 if (reverse) {
1603 ctor += (count-1);
1604 inc = -1;
1605 }
1606
1607 for(n = count; n > 0; n--) {
1608 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1609 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001610 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001611 void (*func)() = (void (*)()) *ctor;
1612 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001613 if(((int) func == 0) || ((int) func == -1)) continue;
1614 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1615 func();
1616 }
1617}
1618
1619static void call_constructors(soinfo *si)
1620{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001621 if (si->flags & FLAG_EXE) {
1622 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1623 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1624 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001625 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001626 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1627 } else {
1628 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001629 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001630 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001631 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001632 }
1633 }
1634
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001635 if (si->init_func) {
1636 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1637 (unsigned)si->init_func, si->name);
1638 si->init_func();
1639 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1640 }
1641
1642 if (si->init_array) {
1643 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1644 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001645 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001646 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1647 }
1648}
1649
David 'Digit' Turner82156792009-05-18 14:37:41 +02001650
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001651static void call_destructors(soinfo *si)
1652{
1653 if (si->fini_array) {
1654 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1655 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001656 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001657 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1658 }
1659
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001660 if (si->fini_func) {
1661 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1662 (unsigned)si->fini_func, si->name);
1663 si->fini_func();
1664 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1665 }
1666}
1667
1668/* Force any of the closed stdin, stdout and stderr to be associated with
1669 /dev/null. */
1670static int nullify_closed_stdio (void)
1671{
1672 int dev_null, i, status;
1673 int return_value = 0;
1674
1675 dev_null = open("/dev/null", O_RDWR);
1676 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001677 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001678 return -1;
1679 }
1680 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1681
1682 /* If any of the stdio file descriptors is valid and not associated
1683 with /dev/null, dup /dev/null to it. */
1684 for (i = 0; i < 3; i++) {
1685 /* If it is /dev/null already, we are done. */
1686 if (i == dev_null)
1687 continue;
1688
1689 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1690 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1691 can be interrupted but we do this just to be safe. */
1692 do {
1693 status = fcntl(i, F_GETFL);
1694 } while (status < 0 && errno == EINTR);
1695
1696 /* If file is openned, we are good. */
1697 if (status >= 0)
1698 continue;
1699
1700 /* The only error we allow is that the file descriptor does not
1701 exist, in which case we dup /dev/null to it. */
1702 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001703 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001704 return_value = -1;
1705 continue;
1706 }
1707
1708 /* Try dupping /dev/null to this stdio file descriptor and
1709 repeat if there is a signal. Note that any errors in closing
1710 the stdio descriptor are lost. */
1711 do {
1712 status = dup2(dev_null, i);
1713 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001714
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001715 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001716 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717 return_value = -1;
1718 continue;
1719 }
1720 }
1721
1722 /* If /dev/null is not one of the stdio file descriptors, close it. */
1723 if (dev_null > 2) {
1724 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001725 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001726 status = close(dev_null);
1727 } while (status < 0 && errno == EINTR);
1728
1729 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001730 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001731 return_value = -1;
1732 }
1733 }
1734
1735 return return_value;
1736}
1737
1738static int link_image(soinfo *si, unsigned wr_offset)
1739{
1740 unsigned *d;
1741 Elf32_Phdr *phdr = si->phdr;
1742 int phnum = si->phnum;
1743
1744 INFO("[ %5d linking %s ]\n", pid, si->name);
1745 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1746 si->base, si->flags);
1747
1748 if (si->flags & FLAG_EXE) {
1749 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1750 * linkage info if this is the executable. If this was a
1751 * dynamic lib, that would have been done at load time.
1752 *
1753 * TODO: It's unfortunate that small pieces of this are
1754 * repeated from the load_library routine. Refactor this just
1755 * slightly to reuse these bits.
1756 */
1757 si->size = 0;
1758 for(; phnum > 0; --phnum, ++phdr) {
1759#ifdef ANDROID_ARM_LINKER
1760 if(phdr->p_type == PT_ARM_EXIDX) {
1761 /* exidx entries (used for stack unwinding) are 8 bytes each.
1762 */
1763 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1764 si->ARM_exidx_count = phdr->p_memsz / 8;
1765 }
1766#endif
1767 if (phdr->p_type == PT_LOAD) {
1768 /* For the executable, we use the si->size field only in
1769 dl_unwind_find_exidx(), so the meaning of si->size
1770 is not the size of the executable; it is the last
1771 virtual address of the loadable part of the executable;
1772 since si->base == 0 for an executable, we use the
1773 range [0, si->size) to determine whether a PC value
1774 falls within the executable section. Of course, if
1775 a value is below phdr->p_vaddr, it's not in the
1776 executable section, but a) we shouldn't be asking for
1777 such a value anyway, and b) if we have to provide
1778 an EXIDX for such a value, then the executable's
1779 EXIDX is probably the better choice.
1780 */
1781 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1782 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1783 si->size = phdr->p_vaddr + phdr->p_memsz;
1784 /* try to remember what range of addresses should be write
1785 * protected */
1786 if (!(phdr->p_flags & PF_W)) {
1787 unsigned _end;
1788
1789 if (phdr->p_vaddr < si->wrprotect_start)
1790 si->wrprotect_start = phdr->p_vaddr;
1791 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1792 (~PAGE_MASK)));
1793 if (_end > si->wrprotect_end)
1794 si->wrprotect_end = _end;
1795 }
1796 } else if (phdr->p_type == PT_DYNAMIC) {
1797 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001798 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001799 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001800 pid, si->name, si->base + phdr->p_vaddr,
1801 (unsigned)si->dynamic);
1802 goto fail;
1803 }
1804 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1805 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1806 }
1807 }
1808 }
1809
1810 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001811 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001812 goto fail;
1813 }
1814
1815 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1816
1817 /* extract useful information from dynamic section */
1818 for(d = si->dynamic; *d; d++){
1819 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1820 switch(*d++){
1821 case DT_HASH:
1822 si->nbucket = ((unsigned *) (si->base + *d))[0];
1823 si->nchain = ((unsigned *) (si->base + *d))[1];
1824 si->bucket = (unsigned *) (si->base + *d + 8);
1825 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1826 break;
1827 case DT_STRTAB:
1828 si->strtab = (const char *) (si->base + *d);
1829 break;
1830 case DT_SYMTAB:
1831 si->symtab = (Elf32_Sym *) (si->base + *d);
1832 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001833#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001834 case DT_PLTREL:
1835 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001836 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001837 goto fail;
1838 }
1839 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001840#endif
1841#ifdef ANDROID_SH_LINKER
1842 case DT_JMPREL:
1843 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1844 break;
1845 case DT_PLTRELSZ:
1846 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1847 break;
1848#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001849 case DT_JMPREL:
1850 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1851 break;
1852 case DT_PLTRELSZ:
1853 si->plt_rel_count = *d / 8;
1854 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001855#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001856 case DT_REL:
1857 si->rel = (Elf32_Rel*) (si->base + *d);
1858 break;
1859 case DT_RELSZ:
1860 si->rel_count = *d / 8;
1861 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001862#ifdef ANDROID_SH_LINKER
1863 case DT_RELASZ:
1864 si->rela_count = *d / sizeof(Elf32_Rela);
1865 break;
1866#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001867 case DT_PLTGOT:
1868 /* Save this in case we decide to do lazy binding. We don't yet. */
1869 si->plt_got = (unsigned *)(si->base + *d);
1870 break;
1871 case DT_DEBUG:
1872 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1873 *d = (int) &_r_debug;
1874 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001875#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001876 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001877 si->rela = (Elf32_Rela *) (si->base + *d);
1878 break;
1879#else
1880 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001881 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001882 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001883#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001884 case DT_INIT:
1885 si->init_func = (void (*)(void))(si->base + *d);
1886 DEBUG("%5d %s constructors (init func) found at %p\n",
1887 pid, si->name, si->init_func);
1888 break;
1889 case DT_FINI:
1890 si->fini_func = (void (*)(void))(si->base + *d);
1891 DEBUG("%5d %s destructors (fini func) found at %p\n",
1892 pid, si->name, si->fini_func);
1893 break;
1894 case DT_INIT_ARRAY:
1895 si->init_array = (unsigned *)(si->base + *d);
1896 DEBUG("%5d %s constructors (init_array) found at %p\n",
1897 pid, si->name, si->init_array);
1898 break;
1899 case DT_INIT_ARRAYSZ:
1900 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1901 break;
1902 case DT_FINI_ARRAY:
1903 si->fini_array = (unsigned *)(si->base + *d);
1904 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1905 pid, si->name, si->fini_array);
1906 break;
1907 case DT_FINI_ARRAYSZ:
1908 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1909 break;
1910 case DT_PREINIT_ARRAY:
1911 si->preinit_array = (unsigned *)(si->base + *d);
1912 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1913 pid, si->name, si->preinit_array);
1914 break;
1915 case DT_PREINIT_ARRAYSZ:
1916 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1917 break;
1918 case DT_TEXTREL:
1919 /* TODO: make use of this. */
1920 /* this means that we might have to write into where the text
1921 * segment was loaded during relocation... Do something with
1922 * it.
1923 */
1924 DEBUG("%5d Text segment should be writable during relocation.\n",
1925 pid);
1926 break;
1927 }
1928 }
1929
1930 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1931 pid, si->base, si->strtab, si->symtab);
1932
1933 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001934 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001935 goto fail;
1936 }
1937
Matt Fischer4fd42c12009-12-31 12:09:10 -06001938 /* if this is the main executable, then load all of the preloads now */
1939 if(si->flags & FLAG_EXE) {
1940 int i;
1941 memset(preloads, 0, sizeof(preloads));
1942 for(i = 0; ldpreload_names[i] != NULL; i++) {
1943 soinfo *lsi = find_library(ldpreload_names[i]);
1944 if(lsi == 0) {
1945 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1946 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1947 pid, ldpreload_names[i], si->name, tmp_err_buf);
1948 goto fail;
1949 }
1950 lsi->refcount++;
1951 preloads[i] = lsi;
1952 }
1953 }
1954
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001955 for(d = si->dynamic; *d; d += 2) {
1956 if(d[0] == DT_NEEDED){
1957 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001958 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001959 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001960 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001961 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001962 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001963 goto fail;
1964 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001965 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1966 of the DT_NEEDED entry itself, so that we can retrieve the
1967 soinfo directly later from the dynamic segment. This is a hack,
1968 but it allows us to map from DT_NEEDED to soinfo efficiently
1969 later on when we resolve relocations, trying to look up a symgol
1970 with dlsym().
1971 */
1972 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001973 lsi->refcount++;
1974 }
1975 }
1976
1977 if(si->plt_rel) {
1978 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1979 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1980 goto fail;
1981 }
1982 if(si->rel) {
1983 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1984 if(reloc_library(si, si->rel, si->rel_count))
1985 goto fail;
1986 }
1987
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001988#ifdef ANDROID_SH_LINKER
1989 if(si->plt_rela) {
1990 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1991 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1992 goto fail;
1993 }
1994 if(si->rela) {
1995 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1996 if(reloc_library_a(si, si->rela, si->rela_count))
1997 goto fail;
1998 }
1999#endif /* ANDROID_SH_LINKER */
2000
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002001 si->flags |= FLAG_LINKED;
2002 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
2003
2004#if 0
2005 /* This is the way that the old dynamic linker did protection of
2006 * non-writable areas. It would scan section headers and find where
2007 * .text ended (rather where .data/.bss began) and assume that this is
2008 * the upper range of the non-writable area. This is too coarse,
2009 * and is kept here for reference until we fully move away from single
2010 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
2011 * that made this possible.
2012 */
2013 if(wr_offset < 0xffffffff){
2014 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
2015 }
2016#else
2017 /* TODO: Verify that this does the right thing in all cases, as it
2018 * presently probably does not. It is possible that an ELF image will
2019 * come with multiple read-only segments. What we ought to do is scan
2020 * the program headers again and mprotect all the read-only segments.
2021 * To prevent re-scanning the program header, we would have to build a
2022 * list of loadable segments in si, and then scan that instead. */
2023 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
2024 mprotect((void *)si->wrprotect_start,
2025 si->wrprotect_end - si->wrprotect_start,
2026 PROT_READ | PROT_EXEC);
2027 }
2028#endif
2029
2030 /* If this is a SET?ID program, dup /dev/null to opened stdin,
2031 stdout and stderr to close a security hole described in:
2032
2033 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
2034
2035 */
2036 if (getuid() != geteuid() || getgid() != getegid())
2037 nullify_closed_stdio ();
2038 call_constructors(si);
2039 notify_gdb_of_load(si);
2040 return 0;
2041
2042fail:
Dima Zavina7161902010-08-17 15:56:40 -07002043 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002044 si->flags |= FLAG_ERROR;
2045 return -1;
2046}
2047
David Bartleybc3a5c22009-06-02 18:27:28 -07002048static void parse_library_path(char *path, char *delim)
2049{
2050 size_t len;
2051 char *ldpaths_bufp = ldpaths_buf;
2052 int i = 0;
2053
2054 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2055
2056 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2057 if (*ldpaths[i] != '\0')
2058 ++i;
2059 }
2060
2061 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2062 * last char isn't '\0' (i.e. not originally a delim). */
2063 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2064 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2065 ldpaths[i - 1] = NULL;
2066 } else {
2067 ldpaths[i] = NULL;
2068 }
2069}
2070
Matt Fischer4fd42c12009-12-31 12:09:10 -06002071static void parse_preloads(char *path, char *delim)
2072{
2073 size_t len;
2074 char *ldpreloads_bufp = ldpreloads_buf;
2075 int i = 0;
2076
2077 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2078
2079 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2080 if (*ldpreload_names[i] != '\0') {
2081 ++i;
2082 }
2083 }
2084
2085 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2086 * last char isn't '\0' (i.e. not originally a delim). */
2087 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2088 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2089 ldpreload_names[i - 1] = NULL;
2090 } else {
2091 ldpreload_names[i] = NULL;
2092 }
2093}
2094
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002095int main(int argc, char **argv)
2096{
2097 return 0;
2098}
2099
2100#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
2101
2102static void * __tls_area[ANDROID_TLS_SLOTS];
2103
2104unsigned __linker_init(unsigned **elfdata)
2105{
2106 static soinfo linker_soinfo;
2107
2108 int argc = (int) *elfdata;
2109 char **argv = (char**) (elfdata + 1);
2110 unsigned *vecs = (unsigned*) (argv + argc + 1);
2111 soinfo *si;
2112 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07002113 char *ldpath_env = NULL;
Matt Fischer4fd42c12009-12-31 12:09:10 -06002114 char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002115
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002116 /* Setup a temporary TLS area that is used to get a working
2117 * errno for system calls.
2118 */
2119 __set_tls(__tls_area);
2120
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002121 pid = getpid();
2122
2123#if TIMING
2124 struct timeval t0, t1;
2125 gettimeofday(&t0, 0);
2126#endif
2127
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002128 /* NOTE: we store the elfdata pointer on a special location
2129 * of the temporary TLS area in order to pass it to
2130 * the C Library's runtime initializer.
2131 *
2132 * The initializer must clear the slot and reset the TLS
2133 * to point to a different location to ensure that no other
2134 * shared library constructor can access it.
2135 */
2136 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002137
2138 debugger_init();
2139
2140 /* skip past the environment */
2141 while(vecs[0] != 0) {
2142 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
2143 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07002144 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
2145 ldpath_env = (char*) vecs[0] + 16;
Matt Fischer4fd42c12009-12-31 12:09:10 -06002146 } else if(!strncmp((char*) vecs[0], "LD_PRELOAD=", 11)) {
2147 ldpreload_env = (char*) vecs[0] + 11;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002148 }
2149 vecs++;
2150 }
2151 vecs++;
2152
2153 INFO("[ android linker & debugger ]\n");
2154 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2155
2156 si = alloc_info(argv[0]);
2157 if(si == 0) {
2158 exit(-1);
2159 }
2160
2161 /* bootstrap the link map, the main exe always needs to be first */
2162 si->flags |= FLAG_EXE;
2163 map = &(si->linkmap);
2164
2165 map->l_addr = 0;
2166 map->l_name = argv[0];
2167 map->l_prev = NULL;
2168 map->l_next = NULL;
2169
2170 _r_debug.r_map = map;
2171 r_debug_tail = map;
2172
2173 /* gdb expects the linker to be in the debug shared object list,
2174 * and we need to make sure that the reported load address is zero.
2175 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2176 * is. Don't use alloc_info(), because the linker shouldn't
2177 * be on the soinfo list.
2178 */
2179 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
2180 linker_soinfo.flags = 0;
2181 linker_soinfo.base = 0; // This is the important part; must be zero.
2182 insert_soinfo_into_debug_map(&linker_soinfo);
2183
2184 /* extract information passed from the kernel */
2185 while(vecs[0] != 0){
2186 switch(vecs[0]){
2187 case AT_PHDR:
2188 si->phdr = (Elf32_Phdr*) vecs[1];
2189 break;
2190 case AT_PHNUM:
2191 si->phnum = (int) vecs[1];
2192 break;
2193 case AT_ENTRY:
2194 si->entry = vecs[1];
2195 break;
2196 }
2197 vecs += 2;
2198 }
2199
Iliyan Malcheve100f522010-02-10 15:19:37 -08002200 ba_init(&ba_nonprelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002201
2202 si->base = 0;
2203 si->dynamic = (unsigned *)-1;
2204 si->wrprotect_start = 0xffffffff;
2205 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002206 si->refcount = 1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002207
David Bartleybc3a5c22009-06-02 18:27:28 -07002208 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
2209 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
2210 parse_library_path(ldpath_env, ":");
2211
Matt Fischer4fd42c12009-12-31 12:09:10 -06002212 if (ldpreload_env && getuid() == geteuid() && getgid() == getegid()) {
2213 parse_preloads(ldpreload_env, " :");
2214 }
2215
Dima Zavin2e855792009-05-20 18:28:09 -07002216 if(link_image(si, 0)) {
2217 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2218 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2219 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002220 exit(-1);
2221 }
2222
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002223#if ALLOW_SYMBOLS_FROM_MAIN
2224 /* Set somain after we've loaded all the libraries in order to prevent
2225 * linking of symbols back to the main image, which is not set up at that
2226 * point yet.
2227 */
2228 somain = si;
2229#endif
2230
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002231#if TIMING
2232 gettimeofday(&t1,NULL);
2233 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2234 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2235 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2236 ));
2237#endif
2238#if STATS
2239 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2240 linker_stats.reloc[RELOC_ABSOLUTE],
2241 linker_stats.reloc[RELOC_RELATIVE],
2242 linker_stats.reloc[RELOC_COPY],
2243 linker_stats.reloc[RELOC_SYMBOL]);
2244#endif
2245#if COUNT_PAGES
2246 {
2247 unsigned n;
2248 unsigned i;
2249 unsigned count = 0;
2250 for(n = 0; n < 4096; n++){
2251 if(bitmask[n]){
2252 unsigned x = bitmask[n];
2253 for(i = 0; i < 8; i++){
2254 if(x & 1) count++;
2255 x >>= 1;
2256 }
2257 }
2258 }
2259 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2260 }
2261#endif
2262
2263#if TIMING || STATS || COUNT_PAGES
2264 fflush(stdout);
2265#endif
2266
2267 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2268 si->entry);
2269 return si->entry;
2270}