blob: 5e04e24d87d2eba106bd0196cc4be78c24736678 [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;
Erik Gillingfde86422009-07-28 20:28:19 -07001203 const char *bname = strrchr(name, '/');
1204 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001205
1206 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001207 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001208 if(si->flags & FLAG_ERROR) {
1209 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1210 return NULL;
1211 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001212 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001213 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001214 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001215 }
1216 }
1217
1218 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1219 si = load_library(name);
1220 if(si == NULL)
1221 return NULL;
1222 return init_library(si);
1223}
1224
1225/* TODO:
1226 * notify gdb of unload
1227 * for non-prelinked libraries, find a way to decrement libbase
1228 */
1229static void call_destructors(soinfo *si);
1230unsigned unload_library(soinfo *si)
1231{
1232 unsigned *d;
1233 if (si->refcount == 1) {
1234 TRACE("%5d unloading '%s'\n", pid, si->name);
1235 call_destructors(si);
1236
1237 for(d = si->dynamic; *d; d += 2) {
1238 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001239 soinfo *lsi = (soinfo *)d[1];
1240 d[1] = 0;
1241 if (validate_soinfo(lsi)) {
1242 TRACE("%5d %s needs to unload %s\n", pid,
1243 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001245 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001247 DL_ERR("%5d %s: could not unload dependent library",
1248 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001249 }
1250 }
1251
1252 munmap((char *)si->base, si->size);
1253 if (si->ba_index >= 0) {
1254 PRINT("%5d releasing library '%s' address space at %08x "\
1255 "through buddy allocator.\n",
1256 pid, si->name, si->base);
Iliyan Malcheve100f522010-02-10 15:19:37 -08001257 ba_free(&ba_nonprelink, si->ba_index);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001258 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001259 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001260 free_info(si);
1261 si->refcount = 0;
1262 }
1263 else {
1264 si->refcount--;
1265 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1266 pid, si->name, si->refcount);
1267 }
1268 return si->refcount;
1269}
1270
1271/* TODO: don't use unsigned for addrs below. It works, but is not
1272 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1273 * long.
1274 */
1275static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1276{
1277 Elf32_Sym *symtab = si->symtab;
1278 const char *strtab = si->strtab;
1279 Elf32_Sym *s;
1280 unsigned base;
1281 Elf32_Rel *start = rel;
1282 unsigned idx;
1283
1284 for (idx = 0; idx < count; ++idx) {
1285 unsigned type = ELF32_R_TYPE(rel->r_info);
1286 unsigned sym = ELF32_R_SYM(rel->r_info);
1287 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1288 unsigned sym_addr = 0;
1289 char *sym_name = NULL;
1290
1291 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1292 si->name, idx);
1293 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001294 sym_name = (char *)(strtab + symtab[sym].st_name);
1295 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001296 if(s == NULL) {
1297 /* We only allow an undefined symbol if this is a weak
1298 reference.. */
1299 s = &symtab[sym];
1300 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1301 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1302 return -1;
1303 }
1304
1305 /* IHI0044C AAELF 4.5.1.1:
1306
1307 Libraries are not searched to resolve weak references.
1308 It is not an error for a weak reference to remain
1309 unsatisfied.
1310
1311 During linking, the value of an undefined weak reference is:
1312 - Zero if the relocation type is absolute
1313 - The address of the place if the relocation is pc-relative
1314 - The address of nominial base address if the relocation
1315 type is base-relative.
1316 */
1317
1318 switch (type) {
1319#if defined(ANDROID_ARM_LINKER)
1320 case R_ARM_JUMP_SLOT:
1321 case R_ARM_GLOB_DAT:
1322 case R_ARM_ABS32:
1323 case R_ARM_RELATIVE: /* Don't care. */
1324 case R_ARM_NONE: /* Don't care. */
1325#elif defined(ANDROID_X86_LINKER)
1326 case R_386_JUMP_SLOT:
1327 case R_386_GLOB_DAT:
1328 case R_386_32:
1329 case R_386_RELATIVE: /* Dont' care. */
1330#endif /* ANDROID_*_LINKER */
1331 /* sym_addr was initialized to be zero above or relocation
1332 code below does not care about value of sym_addr.
1333 No need to do anything. */
1334 break;
1335
1336#if defined(ANDROID_X86_LINKER)
1337 case R_386_PC32:
1338 sym_addr = reloc;
1339 break;
1340#endif /* ANDROID_X86_LINKER */
1341
1342#if defined(ANDROID_ARM_LINKER)
1343 case R_ARM_COPY:
1344 /* Fall through. Can't really copy if weak symbol is
1345 not found in run-time. */
1346#endif /* ANDROID_ARM_LINKER */
1347 default:
1348 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1349 pid, type, rel, (int) (rel - start));
1350 return -1;
1351 }
1352 } else {
1353 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001354#if 0
1355 if((base == 0) && (si->base != 0)){
1356 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001357 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001358 pid, strtab + symtab[sym].st_name);
1359 return -1;
1360 }
1361#endif
Doug Kwane8238072009-10-26 12:05:23 -07001362 sym_addr = (unsigned)(s->st_value + base);
1363 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001364 COUNT_RELOC(RELOC_SYMBOL);
1365 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001366 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001367 }
1368
1369/* TODO: This is ugly. Split up the relocations by arch into
1370 * different files.
1371 */
1372 switch(type){
1373#if defined(ANDROID_ARM_LINKER)
1374 case R_ARM_JUMP_SLOT:
1375 COUNT_RELOC(RELOC_ABSOLUTE);
1376 MARK(rel->r_offset);
1377 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1378 reloc, sym_addr, sym_name);
1379 *((unsigned*)reloc) = sym_addr;
1380 break;
1381 case R_ARM_GLOB_DAT:
1382 COUNT_RELOC(RELOC_ABSOLUTE);
1383 MARK(rel->r_offset);
1384 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1385 reloc, sym_addr, sym_name);
1386 *((unsigned*)reloc) = sym_addr;
1387 break;
1388 case R_ARM_ABS32:
1389 COUNT_RELOC(RELOC_ABSOLUTE);
1390 MARK(rel->r_offset);
1391 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1392 reloc, sym_addr, sym_name);
1393 *((unsigned*)reloc) += sym_addr;
1394 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001395 case R_ARM_REL32:
1396 COUNT_RELOC(RELOC_RELATIVE);
1397 MARK(rel->r_offset);
1398 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1399 reloc, sym_addr, rel->r_offset, sym_name);
1400 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1401 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402#elif defined(ANDROID_X86_LINKER)
1403 case R_386_JUMP_SLOT:
1404 COUNT_RELOC(RELOC_ABSOLUTE);
1405 MARK(rel->r_offset);
1406 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1407 reloc, sym_addr, sym_name);
1408 *((unsigned*)reloc) = sym_addr;
1409 break;
1410 case R_386_GLOB_DAT:
1411 COUNT_RELOC(RELOC_ABSOLUTE);
1412 MARK(rel->r_offset);
1413 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1414 reloc, sym_addr, sym_name);
1415 *((unsigned*)reloc) = sym_addr;
1416 break;
1417#endif /* ANDROID_*_LINKER */
1418
1419#if defined(ANDROID_ARM_LINKER)
1420 case R_ARM_RELATIVE:
1421#elif defined(ANDROID_X86_LINKER)
1422 case R_386_RELATIVE:
1423#endif /* ANDROID_*_LINKER */
1424 COUNT_RELOC(RELOC_RELATIVE);
1425 MARK(rel->r_offset);
1426 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001427 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001428 return -1;
1429 }
1430 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1431 reloc, si->base);
1432 *((unsigned*)reloc) += si->base;
1433 break;
1434
1435#if defined(ANDROID_X86_LINKER)
1436 case R_386_32:
1437 COUNT_RELOC(RELOC_RELATIVE);
1438 MARK(rel->r_offset);
1439
1440 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1441 reloc, sym_addr, sym_name);
1442 *((unsigned *)reloc) += (unsigned)sym_addr;
1443 break;
1444
1445 case R_386_PC32:
1446 COUNT_RELOC(RELOC_RELATIVE);
1447 MARK(rel->r_offset);
1448 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1449 "+%08x (%08x - %08x) %s\n", pid, reloc,
1450 (sym_addr - reloc), sym_addr, reloc, sym_name);
1451 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1452 break;
1453#endif /* ANDROID_X86_LINKER */
1454
1455#ifdef ANDROID_ARM_LINKER
1456 case R_ARM_COPY:
1457 COUNT_RELOC(RELOC_COPY);
1458 MARK(rel->r_offset);
1459 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1460 reloc, s->st_size, sym_addr, sym_name);
1461 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1462 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001463 case R_ARM_NONE:
1464 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001465#endif /* ANDROID_ARM_LINKER */
1466
1467 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001468 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001469 pid, type, rel, (int) (rel - start));
1470 return -1;
1471 }
1472 rel++;
1473 }
1474 return 0;
1475}
1476
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001477#if defined(ANDROID_SH_LINKER)
1478static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1479{
1480 Elf32_Sym *symtab = si->symtab;
1481 const char *strtab = si->strtab;
1482 Elf32_Sym *s;
1483 unsigned base;
1484 Elf32_Rela *start = rela;
1485 unsigned idx;
1486
1487 for (idx = 0; idx < count; ++idx) {
1488 unsigned type = ELF32_R_TYPE(rela->r_info);
1489 unsigned sym = ELF32_R_SYM(rela->r_info);
1490 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1491 unsigned sym_addr = 0;
1492 char *sym_name = NULL;
1493
1494 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1495 si->name, idx);
1496 if(sym != 0) {
1497 sym_name = (char *)(strtab + symtab[sym].st_name);
1498 s = _do_lookup(si, sym_name, &base);
1499 if(s == 0) {
1500 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1501 return -1;
1502 }
1503#if 0
1504 if((base == 0) && (si->base != 0)){
1505 /* linking from libraries to main image is bad */
1506 DL_ERR("%5d cannot locate '%s'...",
1507 pid, strtab + symtab[sym].st_name);
1508 return -1;
1509 }
1510#endif
1511 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1512 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1513 "handle this yet", pid, si->name, s->st_shndx,
1514 s->st_value);
1515 return -1;
1516 }
1517 sym_addr = (unsigned)(s->st_value + base);
1518 COUNT_RELOC(RELOC_SYMBOL);
1519 } else {
1520 s = 0;
1521 }
1522
1523/* TODO: This is ugly. Split up the relocations by arch into
1524 * different files.
1525 */
1526 switch(type){
1527 case R_SH_JUMP_SLOT:
1528 COUNT_RELOC(RELOC_ABSOLUTE);
1529 MARK(rela->r_offset);
1530 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1531 reloc, sym_addr, sym_name);
1532 *((unsigned*)reloc) = sym_addr;
1533 break;
1534 case R_SH_GLOB_DAT:
1535 COUNT_RELOC(RELOC_ABSOLUTE);
1536 MARK(rela->r_offset);
1537 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1538 reloc, sym_addr, sym_name);
1539 *((unsigned*)reloc) = sym_addr;
1540 break;
1541 case R_SH_DIR32:
1542 COUNT_RELOC(RELOC_ABSOLUTE);
1543 MARK(rela->r_offset);
1544 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1545 reloc, sym_addr, sym_name);
1546 *((unsigned*)reloc) += sym_addr;
1547 break;
1548 case R_SH_RELATIVE:
1549 COUNT_RELOC(RELOC_RELATIVE);
1550 MARK(rela->r_offset);
1551 if(sym){
1552 DL_ERR("%5d odd RELATIVE form...", pid);
1553 return -1;
1554 }
1555 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1556 reloc, si->base);
1557 *((unsigned*)reloc) += si->base;
1558 break;
1559
1560 default:
1561 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1562 pid, type, rela, (int) (rela - start));
1563 return -1;
1564 }
1565 rela++;
1566 }
1567 return 0;
1568}
1569#endif /* ANDROID_SH_LINKER */
1570
David 'Digit' Turner82156792009-05-18 14:37:41 +02001571
1572/* Please read the "Initialization and Termination functions" functions.
1573 * of the linker design note in bionic/linker/README.TXT to understand
1574 * what the following code is doing.
1575 *
1576 * The important things to remember are:
1577 *
1578 * DT_PREINIT_ARRAY must be called first for executables, and should
1579 * not appear in shared libraries.
1580 *
1581 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1582 *
1583 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1584 *
1585 * DT_FINI_ARRAY must be parsed in reverse order.
1586 */
1587
1588static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001589{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001590 int n, inc = 1;
1591
1592 if (reverse) {
1593 ctor += (count-1);
1594 inc = -1;
1595 }
1596
1597 for(n = count; n > 0; n--) {
1598 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1599 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001600 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001601 void (*func)() = (void (*)()) *ctor;
1602 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001603 if(((int) func == 0) || ((int) func == -1)) continue;
1604 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1605 func();
1606 }
1607}
1608
1609static void call_constructors(soinfo *si)
1610{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001611 if (si->flags & FLAG_EXE) {
1612 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1613 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1614 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001615 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1617 } else {
1618 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001619 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001620 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001621 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001622 }
1623 }
1624
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001625 if (si->init_func) {
1626 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1627 (unsigned)si->init_func, si->name);
1628 si->init_func();
1629 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1630 }
1631
1632 if (si->init_array) {
1633 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1634 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001635 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001636 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1637 }
1638}
1639
David 'Digit' Turner82156792009-05-18 14:37:41 +02001640
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001641static void call_destructors(soinfo *si)
1642{
1643 if (si->fini_array) {
1644 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1645 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001646 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001647 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1648 }
1649
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001650 if (si->fini_func) {
1651 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1652 (unsigned)si->fini_func, si->name);
1653 si->fini_func();
1654 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1655 }
1656}
1657
1658/* Force any of the closed stdin, stdout and stderr to be associated with
1659 /dev/null. */
1660static int nullify_closed_stdio (void)
1661{
1662 int dev_null, i, status;
1663 int return_value = 0;
1664
1665 dev_null = open("/dev/null", O_RDWR);
1666 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001667 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001668 return -1;
1669 }
1670 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1671
1672 /* If any of the stdio file descriptors is valid and not associated
1673 with /dev/null, dup /dev/null to it. */
1674 for (i = 0; i < 3; i++) {
1675 /* If it is /dev/null already, we are done. */
1676 if (i == dev_null)
1677 continue;
1678
1679 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1680 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1681 can be interrupted but we do this just to be safe. */
1682 do {
1683 status = fcntl(i, F_GETFL);
1684 } while (status < 0 && errno == EINTR);
1685
1686 /* If file is openned, we are good. */
1687 if (status >= 0)
1688 continue;
1689
1690 /* The only error we allow is that the file descriptor does not
1691 exist, in which case we dup /dev/null to it. */
1692 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001693 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001694 return_value = -1;
1695 continue;
1696 }
1697
1698 /* Try dupping /dev/null to this stdio file descriptor and
1699 repeat if there is a signal. Note that any errors in closing
1700 the stdio descriptor are lost. */
1701 do {
1702 status = dup2(dev_null, i);
1703 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001704
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001705 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001706 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001707 return_value = -1;
1708 continue;
1709 }
1710 }
1711
1712 /* If /dev/null is not one of the stdio file descriptors, close it. */
1713 if (dev_null > 2) {
1714 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001715 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001716 status = close(dev_null);
1717 } while (status < 0 && errno == EINTR);
1718
1719 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001720 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001721 return_value = -1;
1722 }
1723 }
1724
1725 return return_value;
1726}
1727
1728static int link_image(soinfo *si, unsigned wr_offset)
1729{
1730 unsigned *d;
1731 Elf32_Phdr *phdr = si->phdr;
1732 int phnum = si->phnum;
1733
1734 INFO("[ %5d linking %s ]\n", pid, si->name);
1735 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1736 si->base, si->flags);
1737
1738 if (si->flags & FLAG_EXE) {
1739 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1740 * linkage info if this is the executable. If this was a
1741 * dynamic lib, that would have been done at load time.
1742 *
1743 * TODO: It's unfortunate that small pieces of this are
1744 * repeated from the load_library routine. Refactor this just
1745 * slightly to reuse these bits.
1746 */
1747 si->size = 0;
1748 for(; phnum > 0; --phnum, ++phdr) {
1749#ifdef ANDROID_ARM_LINKER
1750 if(phdr->p_type == PT_ARM_EXIDX) {
1751 /* exidx entries (used for stack unwinding) are 8 bytes each.
1752 */
1753 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1754 si->ARM_exidx_count = phdr->p_memsz / 8;
1755 }
1756#endif
1757 if (phdr->p_type == PT_LOAD) {
1758 /* For the executable, we use the si->size field only in
1759 dl_unwind_find_exidx(), so the meaning of si->size
1760 is not the size of the executable; it is the last
1761 virtual address of the loadable part of the executable;
1762 since si->base == 0 for an executable, we use the
1763 range [0, si->size) to determine whether a PC value
1764 falls within the executable section. Of course, if
1765 a value is below phdr->p_vaddr, it's not in the
1766 executable section, but a) we shouldn't be asking for
1767 such a value anyway, and b) if we have to provide
1768 an EXIDX for such a value, then the executable's
1769 EXIDX is probably the better choice.
1770 */
1771 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1772 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1773 si->size = phdr->p_vaddr + phdr->p_memsz;
1774 /* try to remember what range of addresses should be write
1775 * protected */
1776 if (!(phdr->p_flags & PF_W)) {
1777 unsigned _end;
1778
1779 if (phdr->p_vaddr < si->wrprotect_start)
1780 si->wrprotect_start = phdr->p_vaddr;
1781 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1782 (~PAGE_MASK)));
1783 if (_end > si->wrprotect_end)
1784 si->wrprotect_end = _end;
1785 }
1786 } else if (phdr->p_type == PT_DYNAMIC) {
1787 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001788 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001789 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001790 pid, si->name, si->base + phdr->p_vaddr,
1791 (unsigned)si->dynamic);
1792 goto fail;
1793 }
1794 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1795 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1796 }
1797 }
1798 }
1799
1800 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001801 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001802 goto fail;
1803 }
1804
1805 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1806
1807 /* extract useful information from dynamic section */
1808 for(d = si->dynamic; *d; d++){
1809 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1810 switch(*d++){
1811 case DT_HASH:
1812 si->nbucket = ((unsigned *) (si->base + *d))[0];
1813 si->nchain = ((unsigned *) (si->base + *d))[1];
1814 si->bucket = (unsigned *) (si->base + *d + 8);
1815 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1816 break;
1817 case DT_STRTAB:
1818 si->strtab = (const char *) (si->base + *d);
1819 break;
1820 case DT_SYMTAB:
1821 si->symtab = (Elf32_Sym *) (si->base + *d);
1822 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001823#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001824 case DT_PLTREL:
1825 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001826 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001827 goto fail;
1828 }
1829 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001830#endif
1831#ifdef ANDROID_SH_LINKER
1832 case DT_JMPREL:
1833 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1834 break;
1835 case DT_PLTRELSZ:
1836 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1837 break;
1838#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001839 case DT_JMPREL:
1840 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1841 break;
1842 case DT_PLTRELSZ:
1843 si->plt_rel_count = *d / 8;
1844 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001845#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001846 case DT_REL:
1847 si->rel = (Elf32_Rel*) (si->base + *d);
1848 break;
1849 case DT_RELSZ:
1850 si->rel_count = *d / 8;
1851 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001852#ifdef ANDROID_SH_LINKER
1853 case DT_RELASZ:
1854 si->rela_count = *d / sizeof(Elf32_Rela);
1855 break;
1856#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001857 case DT_PLTGOT:
1858 /* Save this in case we decide to do lazy binding. We don't yet. */
1859 si->plt_got = (unsigned *)(si->base + *d);
1860 break;
1861 case DT_DEBUG:
1862 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1863 *d = (int) &_r_debug;
1864 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001865#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001866 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001867 si->rela = (Elf32_Rela *) (si->base + *d);
1868 break;
1869#else
1870 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001871 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001872 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001873#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001874 case DT_INIT:
1875 si->init_func = (void (*)(void))(si->base + *d);
1876 DEBUG("%5d %s constructors (init func) found at %p\n",
1877 pid, si->name, si->init_func);
1878 break;
1879 case DT_FINI:
1880 si->fini_func = (void (*)(void))(si->base + *d);
1881 DEBUG("%5d %s destructors (fini func) found at %p\n",
1882 pid, si->name, si->fini_func);
1883 break;
1884 case DT_INIT_ARRAY:
1885 si->init_array = (unsigned *)(si->base + *d);
1886 DEBUG("%5d %s constructors (init_array) found at %p\n",
1887 pid, si->name, si->init_array);
1888 break;
1889 case DT_INIT_ARRAYSZ:
1890 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1891 break;
1892 case DT_FINI_ARRAY:
1893 si->fini_array = (unsigned *)(si->base + *d);
1894 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1895 pid, si->name, si->fini_array);
1896 break;
1897 case DT_FINI_ARRAYSZ:
1898 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1899 break;
1900 case DT_PREINIT_ARRAY:
1901 si->preinit_array = (unsigned *)(si->base + *d);
1902 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1903 pid, si->name, si->preinit_array);
1904 break;
1905 case DT_PREINIT_ARRAYSZ:
1906 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1907 break;
1908 case DT_TEXTREL:
1909 /* TODO: make use of this. */
1910 /* this means that we might have to write into where the text
1911 * segment was loaded during relocation... Do something with
1912 * it.
1913 */
1914 DEBUG("%5d Text segment should be writable during relocation.\n",
1915 pid);
1916 break;
1917 }
1918 }
1919
1920 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1921 pid, si->base, si->strtab, si->symtab);
1922
1923 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001924 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001925 goto fail;
1926 }
1927
Matt Fischer4fd42c12009-12-31 12:09:10 -06001928 /* if this is the main executable, then load all of the preloads now */
1929 if(si->flags & FLAG_EXE) {
1930 int i;
1931 memset(preloads, 0, sizeof(preloads));
1932 for(i = 0; ldpreload_names[i] != NULL; i++) {
1933 soinfo *lsi = find_library(ldpreload_names[i]);
1934 if(lsi == 0) {
1935 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1936 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1937 pid, ldpreload_names[i], si->name, tmp_err_buf);
1938 goto fail;
1939 }
1940 lsi->refcount++;
1941 preloads[i] = lsi;
1942 }
1943 }
1944
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001945 for(d = si->dynamic; *d; d += 2) {
1946 if(d[0] == DT_NEEDED){
1947 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001948 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001949 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001950 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001951 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001952 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001953 goto fail;
1954 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001955 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1956 of the DT_NEEDED entry itself, so that we can retrieve the
1957 soinfo directly later from the dynamic segment. This is a hack,
1958 but it allows us to map from DT_NEEDED to soinfo efficiently
1959 later on when we resolve relocations, trying to look up a symgol
1960 with dlsym().
1961 */
1962 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001963 lsi->refcount++;
1964 }
1965 }
1966
1967 if(si->plt_rel) {
1968 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1969 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1970 goto fail;
1971 }
1972 if(si->rel) {
1973 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1974 if(reloc_library(si, si->rel, si->rel_count))
1975 goto fail;
1976 }
1977
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001978#ifdef ANDROID_SH_LINKER
1979 if(si->plt_rela) {
1980 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1981 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1982 goto fail;
1983 }
1984 if(si->rela) {
1985 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1986 if(reloc_library_a(si, si->rela, si->rela_count))
1987 goto fail;
1988 }
1989#endif /* ANDROID_SH_LINKER */
1990
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001991 si->flags |= FLAG_LINKED;
1992 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1993
1994#if 0
1995 /* This is the way that the old dynamic linker did protection of
1996 * non-writable areas. It would scan section headers and find where
1997 * .text ended (rather where .data/.bss began) and assume that this is
1998 * the upper range of the non-writable area. This is too coarse,
1999 * and is kept here for reference until we fully move away from single
2000 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
2001 * that made this possible.
2002 */
2003 if(wr_offset < 0xffffffff){
2004 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
2005 }
2006#else
2007 /* TODO: Verify that this does the right thing in all cases, as it
2008 * presently probably does not. It is possible that an ELF image will
2009 * come with multiple read-only segments. What we ought to do is scan
2010 * the program headers again and mprotect all the read-only segments.
2011 * To prevent re-scanning the program header, we would have to build a
2012 * list of loadable segments in si, and then scan that instead. */
2013 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
2014 mprotect((void *)si->wrprotect_start,
2015 si->wrprotect_end - si->wrprotect_start,
2016 PROT_READ | PROT_EXEC);
2017 }
2018#endif
2019
2020 /* If this is a SET?ID program, dup /dev/null to opened stdin,
2021 stdout and stderr to close a security hole described in:
2022
2023 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
2024
2025 */
2026 if (getuid() != geteuid() || getgid() != getegid())
2027 nullify_closed_stdio ();
2028 call_constructors(si);
2029 notify_gdb_of_load(si);
2030 return 0;
2031
2032fail:
Doug Kwan94304352009-10-23 18:11:40 -07002033 DL_ERR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002034 si->flags |= FLAG_ERROR;
2035 return -1;
2036}
2037
David Bartleybc3a5c22009-06-02 18:27:28 -07002038static void parse_library_path(char *path, char *delim)
2039{
2040 size_t len;
2041 char *ldpaths_bufp = ldpaths_buf;
2042 int i = 0;
2043
2044 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2045
2046 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2047 if (*ldpaths[i] != '\0')
2048 ++i;
2049 }
2050
2051 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2052 * last char isn't '\0' (i.e. not originally a delim). */
2053 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2054 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2055 ldpaths[i - 1] = NULL;
2056 } else {
2057 ldpaths[i] = NULL;
2058 }
2059}
2060
Matt Fischer4fd42c12009-12-31 12:09:10 -06002061static void parse_preloads(char *path, char *delim)
2062{
2063 size_t len;
2064 char *ldpreloads_bufp = ldpreloads_buf;
2065 int i = 0;
2066
2067 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2068
2069 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2070 if (*ldpreload_names[i] != '\0') {
2071 ++i;
2072 }
2073 }
2074
2075 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2076 * last char isn't '\0' (i.e. not originally a delim). */
2077 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2078 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2079 ldpreload_names[i - 1] = NULL;
2080 } else {
2081 ldpreload_names[i] = NULL;
2082 }
2083}
2084
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002085int main(int argc, char **argv)
2086{
2087 return 0;
2088}
2089
2090#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
2091
2092static void * __tls_area[ANDROID_TLS_SLOTS];
2093
2094unsigned __linker_init(unsigned **elfdata)
2095{
2096 static soinfo linker_soinfo;
2097
2098 int argc = (int) *elfdata;
2099 char **argv = (char**) (elfdata + 1);
2100 unsigned *vecs = (unsigned*) (argv + argc + 1);
2101 soinfo *si;
2102 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07002103 char *ldpath_env = NULL;
Matt Fischer4fd42c12009-12-31 12:09:10 -06002104 char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002105
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002106 /* Setup a temporary TLS area that is used to get a working
2107 * errno for system calls.
2108 */
2109 __set_tls(__tls_area);
2110
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002111 pid = getpid();
2112
2113#if TIMING
2114 struct timeval t0, t1;
2115 gettimeofday(&t0, 0);
2116#endif
2117
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002118 /* NOTE: we store the elfdata pointer on a special location
2119 * of the temporary TLS area in order to pass it to
2120 * the C Library's runtime initializer.
2121 *
2122 * The initializer must clear the slot and reset the TLS
2123 * to point to a different location to ensure that no other
2124 * shared library constructor can access it.
2125 */
2126 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002127
2128 debugger_init();
2129
2130 /* skip past the environment */
2131 while(vecs[0] != 0) {
2132 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
2133 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07002134 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
2135 ldpath_env = (char*) vecs[0] + 16;
Matt Fischer4fd42c12009-12-31 12:09:10 -06002136 } else if(!strncmp((char*) vecs[0], "LD_PRELOAD=", 11)) {
2137 ldpreload_env = (char*) vecs[0] + 11;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002138 }
2139 vecs++;
2140 }
2141 vecs++;
2142
2143 INFO("[ android linker & debugger ]\n");
2144 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2145
2146 si = alloc_info(argv[0]);
2147 if(si == 0) {
2148 exit(-1);
2149 }
2150
2151 /* bootstrap the link map, the main exe always needs to be first */
2152 si->flags |= FLAG_EXE;
2153 map = &(si->linkmap);
2154
2155 map->l_addr = 0;
2156 map->l_name = argv[0];
2157 map->l_prev = NULL;
2158 map->l_next = NULL;
2159
2160 _r_debug.r_map = map;
2161 r_debug_tail = map;
2162
2163 /* gdb expects the linker to be in the debug shared object list,
2164 * and we need to make sure that the reported load address is zero.
2165 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2166 * is. Don't use alloc_info(), because the linker shouldn't
2167 * be on the soinfo list.
2168 */
2169 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
2170 linker_soinfo.flags = 0;
2171 linker_soinfo.base = 0; // This is the important part; must be zero.
2172 insert_soinfo_into_debug_map(&linker_soinfo);
2173
2174 /* extract information passed from the kernel */
2175 while(vecs[0] != 0){
2176 switch(vecs[0]){
2177 case AT_PHDR:
2178 si->phdr = (Elf32_Phdr*) vecs[1];
2179 break;
2180 case AT_PHNUM:
2181 si->phnum = (int) vecs[1];
2182 break;
2183 case AT_ENTRY:
2184 si->entry = vecs[1];
2185 break;
2186 }
2187 vecs += 2;
2188 }
2189
Iliyan Malcheve100f522010-02-10 15:19:37 -08002190 ba_init(&ba_nonprelink);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002191
2192 si->base = 0;
2193 si->dynamic = (unsigned *)-1;
2194 si->wrprotect_start = 0xffffffff;
2195 si->wrprotect_end = 0;
2196
David Bartleybc3a5c22009-06-02 18:27:28 -07002197 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
2198 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
2199 parse_library_path(ldpath_env, ":");
2200
Matt Fischer4fd42c12009-12-31 12:09:10 -06002201 if (ldpreload_env && getuid() == geteuid() && getgid() == getegid()) {
2202 parse_preloads(ldpreload_env, " :");
2203 }
2204
Dima Zavin2e855792009-05-20 18:28:09 -07002205 if(link_image(si, 0)) {
2206 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2207 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2208 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002209 exit(-1);
2210 }
2211
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002212#if ALLOW_SYMBOLS_FROM_MAIN
2213 /* Set somain after we've loaded all the libraries in order to prevent
2214 * linking of symbols back to the main image, which is not set up at that
2215 * point yet.
2216 */
2217 somain = si;
2218#endif
2219
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002220#if TIMING
2221 gettimeofday(&t1,NULL);
2222 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2223 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2224 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2225 ));
2226#endif
2227#if STATS
2228 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2229 linker_stats.reloc[RELOC_ABSOLUTE],
2230 linker_stats.reloc[RELOC_RELATIVE],
2231 linker_stats.reloc[RELOC_COPY],
2232 linker_stats.reloc[RELOC_SYMBOL]);
2233#endif
2234#if COUNT_PAGES
2235 {
2236 unsigned n;
2237 unsigned i;
2238 unsigned count = 0;
2239 for(n = 0; n < 4096; n++){
2240 if(bitmask[n]){
2241 unsigned x = bitmask[n];
2242 for(i = 0; i < 8; i++){
2243 if(x & 1) count++;
2244 x >>= 1;
2245 }
2246 }
2247 }
2248 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2249 }
2250#endif
2251
2252#if TIMING || STATS || COUNT_PAGES
2253 fflush(stdout);
2254#endif
2255
2256 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2257 si->entry);
2258 return si->entry;
2259}