blob: 599fe695e20a8f216079d44d153b1eb82e3e8770 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
Doug Kwan94304352009-10-23 18:11:40 -07002 * Copyright (C) 2008, 2009 The Android Open Source Project
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08003 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <linux/auxvec.h>
30
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35#include <fcntl.h>
36#include <errno.h>
37#include <dlfcn.h>
38#include <sys/stat.h>
39
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -070040#include <pthread.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080041
42#include <sys/mman.h>
43
44#include <sys/atomics.h>
45
46/* special private C library header - see Android.mk */
47#include <bionic_tls.h>
48
49#include "linker.h"
50#include "linker_debug.h"
51
52#include "ba.h"
53
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070054#define ALLOW_SYMBOLS_FROM_MAIN 1
James Dongba52b302009-04-30 20:37:36 -070055#define SO_MAX 96
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056
David Bartleybc3a5c22009-06-02 18:27:28 -070057/* Assume average path length of 64 and max 8 paths */
58#define LDPATH_BUFSIZE 512
59#define LDPATH_MAX 8
60
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080061/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
62 *
63 * Do NOT use malloc() and friends or pthread_*() code here.
64 * Don't use printf() either; it's caused mysterious memory
65 * corruption in the past.
66 * The linker runs before we bring up libc and it's easiest
67 * to make sure it does not depend on any complex libc features
68 *
69 * open issues / todo:
70 *
71 * - should we do anything special for STB_WEAK symbols?
72 * - are we doing everything we should for ARM_COPY relocations?
73 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080074 * - after linking, set as much stuff as possible to READONLY
75 * and NOEXEC
76 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
77 * headers provide versions that are negative...
78 * - allocate space for soinfo structs dynamically instead of
79 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080080*/
81
82
83static int link_image(soinfo *si, unsigned wr_offset);
84
85static int socount = 0;
86static soinfo sopool[SO_MAX];
87static soinfo *freelist = NULL;
88static soinfo *solist = &libdl_info;
89static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070090#if ALLOW_SYMBOLS_FROM_MAIN
91static soinfo *somain; /* main process, always the one after libdl_info */
92#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080093
Iliyan Malchev6ed80c82009-09-28 19:38:04 -070094static inline int validate_soinfo(soinfo *si)
95{
96 return (si >= sopool && si < sopool + SO_MAX) ||
97 si == &libdl_info;
98}
99
David Bartleybc3a5c22009-06-02 18:27:28 -0700100static char ldpaths_buf[LDPATH_BUFSIZE];
101static const char *ldpaths[LDPATH_MAX + 1];
102
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103int debug_verbosity;
104static int pid;
105
106#if STATS
107struct _link_stats linker_stats;
108#endif
109
110#if COUNT_PAGES
111unsigned bitmask[4096];
112#endif
113
114#ifndef PT_ARM_EXIDX
115#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
116#endif
117
Dima Zavin2e855792009-05-20 18:28:09 -0700118#define HOODLUM(name, ret, ...) \
119 ret name __VA_ARGS__ \
120 { \
121 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
122 write(2, errstr, sizeof(errstr)); \
123 abort(); \
124 }
125HOODLUM(malloc, void *, (size_t size));
126HOODLUM(free, void, (void *ptr));
127HOODLUM(realloc, void *, (void *ptr, size_t size));
128HOODLUM(calloc, void *, (size_t cnt, size_t size));
129
Dima Zavin03531952009-05-29 17:30:25 -0700130static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700131static char __linker_dl_err_buf[768];
132#define DL_ERR(fmt, x...) \
133 do { \
134 snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
135 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700136 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700137 } while(0)
138
139const char *linker_get_error(void)
140{
141 return (const char *)&__linker_dl_err_buf[0];
142}
143
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800144/*
145 * This function is an empty stub where GDB locates a breakpoint to get notified
146 * about linker activity.
147 */
148extern void __attribute__((noinline)) rtld_db_dlactivity(void);
149
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800150static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
151 RT_CONSISTENT, 0};
152static struct link_map *r_debug_tail = 0;
153
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700154static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800155
156static void insert_soinfo_into_debug_map(soinfo * info)
157{
158 struct link_map * map;
159
160 /* Copy the necessary fields into the debug structure.
161 */
162 map = &(info->linkmap);
163 map->l_addr = info->base;
164 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800165 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166
167 /* Stick the new library at the end of the list.
168 * gdb tends to care more about libc than it does
169 * about leaf libraries, and ordering it this way
170 * reduces the back-and-forth over the wire.
171 */
172 if (r_debug_tail) {
173 r_debug_tail->l_next = map;
174 map->l_prev = r_debug_tail;
175 map->l_next = 0;
176 } else {
177 _r_debug.r_map = map;
178 map->l_prev = 0;
179 map->l_next = 0;
180 }
181 r_debug_tail = map;
182}
183
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700184static void remove_soinfo_from_debug_map(soinfo * info)
185{
186 struct link_map * map = &(info->linkmap);
187
188 if (r_debug_tail == map)
189 r_debug_tail = map->l_prev;
190
191 if (map->l_prev) map->l_prev->l_next = map->l_next;
192 if (map->l_next) map->l_next->l_prev = map->l_prev;
193}
194
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800195void notify_gdb_of_load(soinfo * info)
196{
197 if (info->flags & FLAG_EXE) {
198 // GDB already knows about the main executable
199 return;
200 }
201
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700202 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800203
204 _r_debug.r_state = RT_ADD;
205 rtld_db_dlactivity();
206
207 insert_soinfo_into_debug_map(info);
208
209 _r_debug.r_state = RT_CONSISTENT;
210 rtld_db_dlactivity();
211
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700212 pthread_mutex_unlock(&_r_debug_lock);
213}
214
215void notify_gdb_of_unload(soinfo * info)
216{
217 if (info->flags & FLAG_EXE) {
218 // GDB already knows about the main executable
219 return;
220 }
221
222 pthread_mutex_lock(&_r_debug_lock);
223
224 _r_debug.r_state = RT_DELETE;
225 rtld_db_dlactivity();
226
227 remove_soinfo_from_debug_map(info);
228
229 _r_debug.r_state = RT_CONSISTENT;
230 rtld_db_dlactivity();
231
232 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233}
234
235void notify_gdb_of_libraries()
236{
237 _r_debug.r_state = RT_ADD;
238 rtld_db_dlactivity();
239 _r_debug.r_state = RT_CONSISTENT;
240 rtld_db_dlactivity();
241}
242
243static soinfo *alloc_info(const char *name)
244{
245 soinfo *si;
246
247 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700248 DL_ERR("%5d library name %s too long", pid, name);
Doug Kwan94304352009-10-23 18:11:40 -0700249 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800250 }
251
252 /* The freelist is populated when we call free_info(), which in turn is
253 done only by dlclose(), which is not likely to be used.
254 */
255 if (!freelist) {
256 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700257 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800258 return NULL;
259 }
260 freelist = sopool + socount++;
261 freelist->next = NULL;
262 }
263
264 si = freelist;
265 freelist = freelist->next;
266
267 /* Make sure we get a clean block of soinfo */
268 memset(si, 0, sizeof(soinfo));
269 strcpy((char*) si->name, name);
270 sonext->next = si;
271 si->ba_index = -1; /* by default, prelinked */
272 si->next = NULL;
273 si->refcount = 0;
274 sonext = si;
275
276 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
277 return si;
278}
279
280static void free_info(soinfo *si)
281{
282 soinfo *prev = NULL, *trav;
283
284 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
285
286 for(trav = solist; trav != NULL; trav = trav->next){
287 if (trav == si)
288 break;
289 prev = trav;
290 }
291 if (trav == NULL) {
292 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700293 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800294 return;
295 }
296
297 /* prev will never be NULL, because the first entry in solist is
298 always the static libdl_info.
299 */
300 prev->next = si->next;
301 if (si == sonext) sonext = prev;
302 si->next = freelist;
303 freelist = si;
304}
305
306#ifndef LINKER_TEXT_BASE
307#error "linker's makefile must define LINKER_TEXT_BASE"
308#endif
309#ifndef LINKER_AREA_SIZE
310#error "linker's makefile must define LINKER_AREA_SIZE"
311#endif
312#define LINKER_BASE ((LINKER_TEXT_BASE) & 0xfff00000)
313#define LINKER_TOP (LINKER_BASE + (LINKER_AREA_SIZE))
314
315const char *addr_to_name(unsigned addr)
316{
317 soinfo *si;
318
319 for(si = solist; si != 0; si = si->next){
320 if((addr >= si->base) && (addr < (si->base + si->size))) {
321 return si->name;
322 }
323 }
324
325 if((addr >= LINKER_BASE) && (addr < LINKER_TOP)){
326 return "linker";
327 }
328
329 return "";
330}
331
332/* For a given PC, find the .so that it belongs to.
333 * Returns the base address of the .ARM.exidx section
334 * for that .so, and the number of 8-byte entries
335 * in that section (via *pcount).
336 *
337 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
338 *
339 * This function is exposed via dlfcn.c and libdl.so.
340 */
341#ifdef ANDROID_ARM_LINKER
342_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
343{
344 soinfo *si;
345 unsigned addr = (unsigned)pc;
346
347 if ((addr < LINKER_BASE) || (addr >= LINKER_TOP)) {
348 for (si = solist; si != 0; si = si->next){
349 if ((addr >= si->base) && (addr < (si->base + si->size))) {
350 *pcount = si->ARM_exidx_count;
351 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
352 }
353 }
354 }
355 *pcount = 0;
356 return NULL;
357}
358#elif defined(ANDROID_X86_LINKER)
359/* Here, we only have to provide a callback to iterate across all the
360 * loaded libraries. gcc_eh does the rest. */
361int
362dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
363 void *data)
364{
365 soinfo *si;
366 struct dl_phdr_info dl_info;
367 int rv = 0;
368
369 for (si = solist; si != NULL; si = si->next) {
370 dl_info.dlpi_addr = si->linkmap.l_addr;
371 dl_info.dlpi_name = si->linkmap.l_name;
372 dl_info.dlpi_phdr = si->phdr;
373 dl_info.dlpi_phnum = si->phnum;
374 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
375 if (rv != 0)
376 break;
377 }
378 return rv;
379}
380#endif
381
382static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
383{
384 Elf32_Sym *s;
385 Elf32_Sym *symtab = si->symtab;
386 const char *strtab = si->strtab;
387 unsigned n;
388
389 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
390 name, si->name, si->base, hash, hash % si->nbucket);
391 n = hash % si->nbucket;
392
393 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
394 s = symtab + n;
395 if(strcmp(strtab + s->st_name, name)) continue;
396
397 /* only concern ourselves with global symbols */
398 switch(ELF32_ST_BIND(s->st_info)){
399 case STB_GLOBAL:
400 /* no section == undefined */
401 if(s->st_shndx == 0) continue;
402
403 case STB_WEAK:
404 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
405 name, si->name, s->st_value, s->st_size);
406 return s;
407 }
408 }
409
Doug Kwan94304352009-10-23 18:11:40 -0700410 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800411}
412
413static unsigned elfhash(const char *_name)
414{
415 const unsigned char *name = (const unsigned char *) _name;
416 unsigned h = 0, g;
417
418 while(*name) {
419 h = (h << 4) + *name++;
420 g = h & 0xf0000000;
421 h ^= g;
422 h ^= g >> 24;
423 }
424 return h;
425}
426
427static Elf32_Sym *
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700428_do_lookup(soinfo *si, const char *name, unsigned *base)
429{
Doug Kwan94304352009-10-23 18:11:40 -0700430 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700431 Elf32_Sym *s;
432 unsigned *d;
433 soinfo *lsi = si;
434
435 /* Look for symbols in the local scope first (the object who is
436 * searching). This happens with C++ templates on i386 for some
437 * reason. */
Doug Kwan94304352009-10-23 18:11:40 -0700438 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700439 if(s != NULL)
440 goto done;
441
442 for(d = si->dynamic; *d; d += 2) {
443 if(d[0] == DT_NEEDED){
444 lsi = (soinfo *)d[1];
445 if (!validate_soinfo(lsi)) {
446 DL_ERR("%5d bad DT_NEEDED pointer in %s",
447 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700448 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700449 }
450
451 DEBUG("%5d %s: looking up %s in %s\n",
452 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700453 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700454 if(s != NULL)
455 goto done;
456 }
457 }
458
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700459#if ALLOW_SYMBOLS_FROM_MAIN
460 /* If we are resolving relocations while dlopen()ing a library, it's OK for
461 * the library to resolve a symbol that's defined in the executable itself,
462 * although this is rare and is generally a bad idea.
463 */
464 if (somain) {
465 lsi = somain;
466 DEBUG("%5d %s: looking up %s in executable %s\n",
467 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700468 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700469 }
470#endif
471
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700472done:
473 if(s != NULL) {
474 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
475 "found in %s, base = 0x%08x\n",
476 pid, si->name, name, s->st_value, lsi->name, lsi->base);
477 *base = lsi->base;
478 return s;
479 }
480
Doug Kwan94304352009-10-23 18:11:40 -0700481 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700482}
483
484/* This is used by dl_sym(). It performs symbol lookup only within the
485 specified soinfo object and not in any of its dependencies.
486 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800487Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
488{
Doug Kwan94304352009-10-23 18:11:40 -0700489 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800490}
491
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700492/* This is used by dl_sym(). It performs a global symbol lookup.
493 */
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700494Elf32_Sym *lookup(const char *name, soinfo **found)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800495{
Doug Kwan94304352009-10-23 18:11:40 -0700496 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800497 Elf32_Sym *s = NULL;
498 soinfo *si;
499
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800500 for(si = solist; (s == NULL) && (si != NULL); si = si->next)
501 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700502 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800503 continue;
Doug Kwan94304352009-10-23 18:11:40 -0700504 s = _elf_lookup(si, elfhash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800505 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700506 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800507 break;
508 }
509 }
510
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700511 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800512 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
513 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
514 return s;
515 }
516
Doug Kwan94304352009-10-23 18:11:40 -0700517 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800518}
519
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800520#if 0
521static void dump(soinfo *si)
522{
523 Elf32_Sym *s = si->symtab;
524 unsigned n;
525
526 for(n = 0; n < si->nchain; n++) {
527 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
528 s->st_info, s->st_shndx, s->st_value, s->st_size,
529 si->strtab + s->st_name);
530 s++;
531 }
532}
533#endif
534
535static const char *sopaths[] = {
536 "/system/lib",
537 "/lib",
538 0
539};
540
541static int _open_lib(const char *name)
542{
543 int fd;
544 struct stat filestat;
545
546 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
547 if ((fd = open(name, O_RDONLY)) >= 0)
548 return fd;
549 }
550
551 return -1;
552}
553
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800554static int open_library(const char *name)
555{
556 int fd;
557 char buf[512];
558 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700559 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800560
561 TRACE("[ %5d opening %s ]\n", pid, name);
562
563 if(name == 0) return -1;
564 if(strlen(name) > 256) return -1;
565
566 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
567 return fd;
568
David Bartleybc3a5c22009-06-02 18:27:28 -0700569 for (path = ldpaths; *path; path++) {
570 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
571 if (n < 0 || n >= (int)sizeof(buf)) {
572 WARN("Ignoring very long library path: %s/%s\n", *path, name);
573 continue;
574 }
575 if ((fd = _open_lib(buf)) >= 0)
576 return fd;
577 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800578 for (path = sopaths; *path; path++) {
David Bartleybc3a5c22009-06-02 18:27:28 -0700579 n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
580 if (n < 0 || n >= (int)sizeof(buf)) {
581 WARN("Ignoring very long library path: %s/%s\n", *path, name);
582 continue;
583 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800584 if ((fd = _open_lib(buf)) >= 0)
585 return fd;
586 }
587
588 return -1;
589}
590
591/* temporary space for holding the first page of the shared lib
592 * which contains the elf header (with the pht). */
593static unsigned char __header[PAGE_SIZE];
594
595typedef struct {
596 long mmap_addr;
597 char tag[4]; /* 'P', 'R', 'E', ' ' */
598} prelink_info_t;
599
600/* Returns the requested base address if the library is prelinked,
601 * and 0 otherwise. */
602static unsigned long
603is_prelinked(int fd, const char *name)
604{
605 off_t sz;
606 prelink_info_t info;
607
608 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
609 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700610 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800611 return 0;
612 }
613
614 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
615 WARN("Could not read prelink_info_t structure for `%s`\n", name);
616 return 0;
617 }
618
619 if (strncmp(info.tag, "PRE ", 4)) {
620 WARN("`%s` is not a prelinked library\n", name);
621 return 0;
622 }
623
624 return (unsigned long)info.mmap_addr;
625}
626
627/* verify_elf_object
628 * Verifies if the object @ base is a valid ELF object
629 *
630 * Args:
631 *
632 * Returns:
633 * 0 on success
634 * -1 if no valid ELF object is found @ base.
635 */
636static int
637verify_elf_object(void *base, const char *name)
638{
639 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
640
641 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
642 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
643 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
644 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
645
646 /* TODO: Should we verify anything else in the header? */
647
648 return 0;
649}
650
651
652/* get_lib_extents
653 * Retrieves the base (*base) address where the ELF object should be
654 * mapped and its overall memory size (*total_sz).
655 *
656 * Args:
657 * fd: Opened file descriptor for the library
658 * name: The name of the library
659 * _hdr: Pointer to the header page of the library
660 * total_sz: Total size of the memory that should be allocated for
661 * this library
662 *
663 * Returns:
664 * -1 if there was an error while trying to get the lib extents.
665 * The possible reasons are:
666 * - Could not determine if the library was prelinked.
667 * - The library provided is not a valid ELF object
668 * 0 if the library did not request a specific base offset (normal
669 * for non-prelinked libs)
670 * > 0 if the library requests a specific address to be mapped to.
671 * This indicates a pre-linked library.
672 */
673static unsigned
674get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
675{
676 unsigned req_base;
677 unsigned min_vaddr = 0xffffffff;
678 unsigned max_vaddr = 0;
679 unsigned char *_hdr = (unsigned char *)__hdr;
680 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
681 Elf32_Phdr *phdr;
682 int cnt;
683
684 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
685 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700686 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800687 return (unsigned)-1;
688 }
689
690 req_base = (unsigned) is_prelinked(fd, name);
691 if (req_base == (unsigned)-1)
692 return -1;
693 else if (req_base != 0) {
694 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
695 pid, name, req_base);
696 } else {
697 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
698 }
699
700 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
701
702 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
703 * get the range. */
704 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
705 if (phdr->p_type == PT_LOAD) {
706 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
707 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
708 if (phdr->p_vaddr < min_vaddr)
709 min_vaddr = phdr->p_vaddr;
710 }
711 }
712
713 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700714 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800715 return (unsigned)-1;
716 }
717
718 /* truncate min_vaddr down to page boundary */
719 min_vaddr &= ~PAGE_MASK;
720
721 /* round max_vaddr up to the next page */
722 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
723
724 *total_sz = (max_vaddr - min_vaddr);
725 return (unsigned)req_base;
726}
727
728/* alloc_mem_region
729 *
730 * This function reserves a chunk of memory to be used for mapping in
731 * the shared library. We reserve the entire memory region here, and
732 * then the rest of the linker will relocate the individual loadable
733 * segments into the correct locations within this memory range.
734 *
735 * Args:
736 * si->base: The requested base of the allocation. If 0, a sane one will be
737 * chosen in the range LIBBASE <= base < LIBLAST.
738 * si->size: The size of the allocation.
739 *
740 * Returns:
741 * -1 on failure, and 0 on success. On success, si->base will contain
742 * the virtual address at which the library will be mapped.
743 */
744
745static int reserve_mem_region(soinfo *si)
746{
747 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
748 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
749 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700750 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700751 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800752 pid, (si->base ? "" : "non-"), si->name, si->base,
753 errno, strerror(errno));
754 return -1;
755 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700756 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700757 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800758 si->name, (unsigned)base, si->base);
759 munmap(base, si->size);
760 return -1;
761 }
762 return 0;
763}
764
765static int
766alloc_mem_region(soinfo *si)
767{
768 if (si->base) {
769 /* Attempt to mmap a prelinked library. */
770 si->ba_index = -1;
771 return reserve_mem_region(si);
772 }
773
774 /* This is not a prelinked library, so we attempt to allocate space
775 for it from the buddy allocator, which manages the area between
776 LIBBASE and LIBLAST.
777 */
778 si->ba_index = ba_allocate(si->size);
779 if(si->ba_index >= 0) {
780 si->base = ba_start_addr(si->ba_index);
781 PRINT("%5d mapping library '%s' at %08x (index %d) " \
782 "through buddy allocator.\n",
783 pid, si->name, si->base, si->ba_index);
784 if (reserve_mem_region(si) < 0) {
785 ba_free(si->ba_index);
786 si->ba_index = -1;
787 si->base = 0;
788 goto err;
789 }
790 return 0;
791 }
792
793err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700794 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800795 pid, si->name);
796 return -1;
797}
798
799#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
800#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
801 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
802 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
803/* load_segments
804 *
805 * This function loads all the loadable (PT_LOAD) segments into memory
806 * at their appropriate memory offsets off the base address.
807 *
808 * Args:
809 * fd: Open file descriptor to the library to load.
810 * header: Pointer to a header page that contains the ELF header.
811 * This is needed since we haven't mapped in the real file yet.
812 * si: ptr to soinfo struct describing the shared object.
813 *
814 * Returns:
815 * 0 on success, -1 on failure.
816 */
817static int
818load_segments(int fd, void *header, soinfo *si)
819{
820 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
821 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
822 unsigned char *base = (unsigned char *)si->base;
823 int cnt;
824 unsigned len;
825 unsigned char *tmp;
826 unsigned char *pbase;
827 unsigned char *extra_base;
828 unsigned extra_len;
829 unsigned total_sz = 0;
830
831 si->wrprotect_start = 0xffffffff;
832 si->wrprotect_end = 0;
833
834 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
835 pid, si->name, (unsigned)si->base);
836 /* Now go through all the PT_LOAD segments and map them into memory
837 * at the appropriate locations. */
838 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
839 if (phdr->p_type == PT_LOAD) {
840 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
841 /* we want to map in the segment on a page boundary */
842 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
843 /* add the # of bytes we masked off above to the total length. */
844 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
845
846 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
847 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
848 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
849 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
850 MAP_PRIVATE | MAP_FIXED, fd,
851 phdr->p_offset & (~PAGE_MASK));
852 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700853 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700854 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800855 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
856 goto fail;
857 }
858
859 /* If 'len' didn't end on page boundary, and it's a writable
860 * segment, zero-fill the rest. */
861 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
862 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
863
864 /* Check to see if we need to extend the map for this segment to
865 * cover the diff between filesz and memsz (i.e. for bss).
866 *
867 * base _+---------------------+ page boundary
868 * . .
869 * | |
870 * . .
871 * pbase _+---------------------+ page boundary
872 * | |
873 * . .
874 * base + p_vaddr _| |
875 * . \ \ .
876 * . | filesz | .
877 * pbase + len _| / | |
878 * <0 pad> . . .
879 * extra_base _+------------|--------+ page boundary
880 * / . . .
881 * | . . .
882 * | +------------|--------+ page boundary
883 * extra_len-> | | | |
884 * | . | memsz .
885 * | . | .
886 * \ _| / |
887 * . .
888 * | |
889 * _+---------------------+ page boundary
890 */
891 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
892 (~PAGE_MASK));
893 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
894 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
895 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
896 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
897 /* map in the extra page(s) as anonymous into the range.
898 * This is probably not necessary as we already mapped in
899 * the entire region previously, but we just want to be
900 * sure. This will also set the right flags on the region
901 * (though we can probably accomplish the same thing with
902 * mprotect).
903 */
904 extra_base = mmap((void *)tmp, extra_len,
905 PFLAGS_TO_PROT(phdr->p_flags),
906 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
907 -1, 0);
908 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700909 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700910 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800911 extra_len);
912 goto fail;
913 }
914 /* TODO: Check if we need to memset-0 this region.
915 * Anonymous mappings are zero-filled copy-on-writes, so we
916 * shouldn't need to. */
917 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
918 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
919 extra_len);
920 }
921 /* set the len here to show the full extent of the segment we
922 * just loaded, mostly for debugging */
923 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
924 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
925 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
926 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
927 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
928 total_sz += len;
929 /* Make the section writable just in case we'll have to write to
930 * it during relocation (i.e. text segment). However, we will
931 * remember what range of addresses should be write protected.
932 *
933 */
934 if (!(phdr->p_flags & PF_W)) {
935 if ((unsigned)pbase < si->wrprotect_start)
936 si->wrprotect_start = (unsigned)pbase;
937 if (((unsigned)pbase + len) > si->wrprotect_end)
938 si->wrprotect_end = (unsigned)pbase + len;
939 mprotect(pbase, len,
940 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
941 }
942 } else if (phdr->p_type == PT_DYNAMIC) {
943 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
944 /* this segment contains the dynamic linking information */
945 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
946 } else {
947#ifdef ANDROID_ARM_LINKER
948 if (phdr->p_type == PT_ARM_EXIDX) {
949 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
950 /* exidx entries (used for stack unwinding) are 8 bytes each.
951 */
952 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
953 si->ARM_exidx_count = phdr->p_memsz / 8;
954 }
955#endif
956 }
957
958 }
959
960 /* Sanity check */
961 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700962 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700963 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800964 pid, total_sz, si->name, si->size);
965 goto fail;
966 }
967
968 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
969 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
970 (unsigned)si->base, si->size);
971 return 0;
972
973fail:
974 /* We can just blindly unmap the entire region even though some things
975 * were mapped in originally with anonymous and others could have been
976 * been mapped in from the file before we failed. The kernel will unmap
977 * all the pages in the range, irrespective of how they got there.
978 */
979 munmap((void *)si->base, si->size);
980 si->flags |= FLAG_ERROR;
981 return -1;
982}
983
984/* TODO: Implement this to take care of the fact that Android ARM
985 * ELF objects shove everything into a single loadable segment that has the
986 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
987 * non-writable.
988 */
989#if 0
990static unsigned
991get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
992{
993 Elf32_Shdr *shdr_start;
994 Elf32_Shdr *shdr;
995 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
996 int cnt;
997 unsigned wr_offset = 0xffffffff;
998
999 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1000 ehdr->e_shoff & (~PAGE_MASK));
1001 if (shdr_start == MAP_FAILED) {
1002 WARN("%5d - Could not read section header info from '%s'. Will not "
1003 "not be able to determine write-protect offset.\n", pid, name);
1004 return (unsigned)-1;
1005 }
1006
1007 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1008 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1009 (shdr->sh_addr < wr_offset)) {
1010 wr_offset = shdr->sh_addr;
1011 }
1012 }
1013
1014 munmap(shdr_start, shdr_sz);
1015 return wr_offset;
1016}
1017#endif
1018
1019static soinfo *
1020load_library(const char *name)
1021{
1022 int fd = open_library(name);
1023 int cnt;
1024 unsigned ext_sz;
1025 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001026 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001027 soinfo *si = NULL;
1028 Elf32_Ehdr *hdr;
1029
Dima Zavin2e855792009-05-20 18:28:09 -07001030 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001031 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001032 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001033 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001034
1035 /* We have to read the ELF header to figure out what to do with this image
1036 */
1037 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001038 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001039 goto fail;
1040 }
1041
1042 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001043 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001044 goto fail;
1045 }
1046
1047 /* Parse the ELF header and get the size of the memory footprint for
1048 * the library */
1049 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1050 if (req_base == (unsigned)-1)
1051 goto fail;
1052 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1053 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1054
1055 /* Now configure the soinfo struct where we'll store all of our data
1056 * for the ELF object. If the loading fails, we waste the entry, but
1057 * same thing would happen if we failed during linking. Configuring the
1058 * soinfo struct here is a lot more convenient.
1059 */
Erik Gillingfde86422009-07-28 20:28:19 -07001060 bname = strrchr(name, '/');
1061 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001062 if (si == NULL)
1063 goto fail;
1064
1065 /* Carve out a chunk of memory where we will map in the individual
1066 * segments */
1067 si->base = req_base;
1068 si->size = ext_sz;
1069 si->flags = 0;
1070 si->entry = 0;
1071 si->dynamic = (unsigned *)-1;
1072 if (alloc_mem_region(si) < 0)
1073 goto fail;
1074
1075 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1076 pid, name, (void *)si->base, (unsigned) ext_sz);
1077
1078 /* Now actually load the library's segments into right places in memory */
1079 if (load_segments(fd, &__header[0], si) < 0) {
1080 if (si->ba_index >= 0) {
1081 ba_free(si->ba_index);
1082 si->ba_index = -1;
1083 }
1084 goto fail;
1085 }
1086
1087 /* this might not be right. Technically, we don't even need this info
1088 * once we go through 'load_segments'. */
1089 hdr = (Elf32_Ehdr *)si->base;
1090 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1091 si->phnum = hdr->e_phnum;
1092 /**/
1093
1094 close(fd);
1095 return si;
1096
1097fail:
1098 if (si) free_info(si);
1099 close(fd);
1100 return NULL;
1101}
1102
1103static soinfo *
1104init_library(soinfo *si)
1105{
1106 unsigned wr_offset = 0xffffffff;
1107
1108 /* At this point we know that whatever is loaded @ base is a valid ELF
1109 * shared library whose segments are properly mapped in. */
1110 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1111 pid, si->base, si->size, si->name);
1112
1113 if (si->base < LIBBASE || si->base >= LIBLAST)
1114 si->flags |= FLAG_PRELINKED;
1115
1116 if(link_image(si, wr_offset)) {
1117 /* We failed to link. However, we can only restore libbase
1118 ** if no additional libraries have moved it since we updated it.
1119 */
1120 munmap((void *)si->base, si->size);
1121 return NULL;
1122 }
1123
1124 return si;
1125}
1126
1127soinfo *find_library(const char *name)
1128{
1129 soinfo *si;
Erik Gillingfde86422009-07-28 20:28:19 -07001130 const char *bname = strrchr(name, '/');
1131 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001132
1133 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001134 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001135 if(si->flags & FLAG_ERROR) {
1136 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1137 return NULL;
1138 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001139 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001140 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001141 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001142 }
1143 }
1144
1145 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1146 si = load_library(name);
1147 if(si == NULL)
1148 return NULL;
1149 return init_library(si);
1150}
1151
1152/* TODO:
1153 * notify gdb of unload
1154 * for non-prelinked libraries, find a way to decrement libbase
1155 */
1156static void call_destructors(soinfo *si);
1157unsigned unload_library(soinfo *si)
1158{
1159 unsigned *d;
1160 if (si->refcount == 1) {
1161 TRACE("%5d unloading '%s'\n", pid, si->name);
1162 call_destructors(si);
1163
1164 for(d = si->dynamic; *d; d += 2) {
1165 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001166 soinfo *lsi = (soinfo *)d[1];
1167 d[1] = 0;
1168 if (validate_soinfo(lsi)) {
1169 TRACE("%5d %s needs to unload %s\n", pid,
1170 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001171 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001172 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001173 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001174 DL_ERR("%5d %s: could not unload dependent library",
1175 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176 }
1177 }
1178
1179 munmap((char *)si->base, si->size);
1180 if (si->ba_index >= 0) {
1181 PRINT("%5d releasing library '%s' address space at %08x "\
1182 "through buddy allocator.\n",
1183 pid, si->name, si->base);
1184 ba_free(si->ba_index);
1185 }
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001186 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001187 free_info(si);
1188 si->refcount = 0;
1189 }
1190 else {
1191 si->refcount--;
1192 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1193 pid, si->name, si->refcount);
1194 }
1195 return si->refcount;
1196}
1197
1198/* TODO: don't use unsigned for addrs below. It works, but is not
1199 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1200 * long.
1201 */
1202static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1203{
1204 Elf32_Sym *symtab = si->symtab;
1205 const char *strtab = si->strtab;
1206 Elf32_Sym *s;
1207 unsigned base;
1208 Elf32_Rel *start = rel;
1209 unsigned idx;
1210
1211 for (idx = 0; idx < count; ++idx) {
1212 unsigned type = ELF32_R_TYPE(rel->r_info);
1213 unsigned sym = ELF32_R_SYM(rel->r_info);
1214 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1215 unsigned sym_addr = 0;
1216 char *sym_name = NULL;
1217
1218 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1219 si->name, idx);
1220 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001221 sym_name = (char *)(strtab + symtab[sym].st_name);
1222 s = _do_lookup(si, sym_name, &base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001223 if(s == 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001224 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001225 return -1;
1226 }
1227#if 0
1228 if((base == 0) && (si->base != 0)){
1229 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001230 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001231 pid, strtab + symtab[sym].st_name);
1232 return -1;
1233 }
1234#endif
David 'Digit' Turner3c998762009-10-13 16:55:18 -07001235 // st_shndx==SHN_UNDEF means an undefined symbol.
1236 // st_value should be 0 then, except that the low bit of st_value is
1237 // used to indicate whether the symbol points to an ARM or thumb function,
1238 // and should be ignored in the following check.
1239 if ((s->st_shndx == SHN_UNDEF) && ((s->st_value & ~1) != 0)) {
1240 DL_ERR("%5d In '%s', symbol=%s shndx=%d && value=0x%08x. We do not "
1241 "handle this yet", pid, si->name, sym_name, s->st_shndx,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001242 s->st_value);
1243 return -1;
1244 }
1245 sym_addr = (unsigned)(s->st_value + base);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246 COUNT_RELOC(RELOC_SYMBOL);
1247 } else {
1248 s = 0;
1249 }
1250
1251/* TODO: This is ugly. Split up the relocations by arch into
1252 * different files.
1253 */
1254 switch(type){
1255#if defined(ANDROID_ARM_LINKER)
1256 case R_ARM_JUMP_SLOT:
1257 COUNT_RELOC(RELOC_ABSOLUTE);
1258 MARK(rel->r_offset);
1259 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1260 reloc, sym_addr, sym_name);
1261 *((unsigned*)reloc) = sym_addr;
1262 break;
1263 case R_ARM_GLOB_DAT:
1264 COUNT_RELOC(RELOC_ABSOLUTE);
1265 MARK(rel->r_offset);
1266 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1267 reloc, sym_addr, sym_name);
1268 *((unsigned*)reloc) = sym_addr;
1269 break;
1270 case R_ARM_ABS32:
1271 COUNT_RELOC(RELOC_ABSOLUTE);
1272 MARK(rel->r_offset);
1273 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1274 reloc, sym_addr, sym_name);
1275 *((unsigned*)reloc) += sym_addr;
1276 break;
1277#elif defined(ANDROID_X86_LINKER)
1278 case R_386_JUMP_SLOT:
1279 COUNT_RELOC(RELOC_ABSOLUTE);
1280 MARK(rel->r_offset);
1281 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1282 reloc, sym_addr, sym_name);
1283 *((unsigned*)reloc) = sym_addr;
1284 break;
1285 case R_386_GLOB_DAT:
1286 COUNT_RELOC(RELOC_ABSOLUTE);
1287 MARK(rel->r_offset);
1288 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1289 reloc, sym_addr, sym_name);
1290 *((unsigned*)reloc) = sym_addr;
1291 break;
1292#endif /* ANDROID_*_LINKER */
1293
1294#if defined(ANDROID_ARM_LINKER)
1295 case R_ARM_RELATIVE:
1296#elif defined(ANDROID_X86_LINKER)
1297 case R_386_RELATIVE:
1298#endif /* ANDROID_*_LINKER */
1299 COUNT_RELOC(RELOC_RELATIVE);
1300 MARK(rel->r_offset);
1301 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001302 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001303 return -1;
1304 }
1305 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1306 reloc, si->base);
1307 *((unsigned*)reloc) += si->base;
1308 break;
1309
1310#if defined(ANDROID_X86_LINKER)
1311 case R_386_32:
1312 COUNT_RELOC(RELOC_RELATIVE);
1313 MARK(rel->r_offset);
1314
1315 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1316 reloc, sym_addr, sym_name);
1317 *((unsigned *)reloc) += (unsigned)sym_addr;
1318 break;
1319
1320 case R_386_PC32:
1321 COUNT_RELOC(RELOC_RELATIVE);
1322 MARK(rel->r_offset);
1323 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1324 "+%08x (%08x - %08x) %s\n", pid, reloc,
1325 (sym_addr - reloc), sym_addr, reloc, sym_name);
1326 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1327 break;
1328#endif /* ANDROID_X86_LINKER */
1329
1330#ifdef ANDROID_ARM_LINKER
1331 case R_ARM_COPY:
1332 COUNT_RELOC(RELOC_COPY);
1333 MARK(rel->r_offset);
1334 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1335 reloc, s->st_size, sym_addr, sym_name);
1336 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1337 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001338 case R_ARM_NONE:
1339 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001340#endif /* ANDROID_ARM_LINKER */
1341
1342 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001343 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001344 pid, type, rel, (int) (rel - start));
1345 return -1;
1346 }
1347 rel++;
1348 }
1349 return 0;
1350}
1351
David 'Digit' Turner82156792009-05-18 14:37:41 +02001352
1353/* Please read the "Initialization and Termination functions" functions.
1354 * of the linker design note in bionic/linker/README.TXT to understand
1355 * what the following code is doing.
1356 *
1357 * The important things to remember are:
1358 *
1359 * DT_PREINIT_ARRAY must be called first for executables, and should
1360 * not appear in shared libraries.
1361 *
1362 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1363 *
1364 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1365 *
1366 * DT_FINI_ARRAY must be parsed in reverse order.
1367 */
1368
1369static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001370{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001371 int n, inc = 1;
1372
1373 if (reverse) {
1374 ctor += (count-1);
1375 inc = -1;
1376 }
1377
1378 for(n = count; n > 0; n--) {
1379 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1380 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001381 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001382 void (*func)() = (void (*)()) *ctor;
1383 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001384 if(((int) func == 0) || ((int) func == -1)) continue;
1385 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1386 func();
1387 }
1388}
1389
1390static void call_constructors(soinfo *si)
1391{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001392 if (si->flags & FLAG_EXE) {
1393 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1394 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1395 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001396 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1398 } else {
1399 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001400 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001401 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001402 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001403 }
1404 }
1405
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 if (si->init_func) {
1407 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1408 (unsigned)si->init_func, si->name);
1409 si->init_func();
1410 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1411 }
1412
1413 if (si->init_array) {
1414 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1415 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001416 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001417 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1418 }
1419}
1420
David 'Digit' Turner82156792009-05-18 14:37:41 +02001421
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001422static void call_destructors(soinfo *si)
1423{
1424 if (si->fini_array) {
1425 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1426 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001427 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001428 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1429 }
1430
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001431 if (si->fini_func) {
1432 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1433 (unsigned)si->fini_func, si->name);
1434 si->fini_func();
1435 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1436 }
1437}
1438
1439/* Force any of the closed stdin, stdout and stderr to be associated with
1440 /dev/null. */
1441static int nullify_closed_stdio (void)
1442{
1443 int dev_null, i, status;
1444 int return_value = 0;
1445
1446 dev_null = open("/dev/null", O_RDWR);
1447 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001448 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001449 return -1;
1450 }
1451 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1452
1453 /* If any of the stdio file descriptors is valid and not associated
1454 with /dev/null, dup /dev/null to it. */
1455 for (i = 0; i < 3; i++) {
1456 /* If it is /dev/null already, we are done. */
1457 if (i == dev_null)
1458 continue;
1459
1460 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1461 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1462 can be interrupted but we do this just to be safe. */
1463 do {
1464 status = fcntl(i, F_GETFL);
1465 } while (status < 0 && errno == EINTR);
1466
1467 /* If file is openned, we are good. */
1468 if (status >= 0)
1469 continue;
1470
1471 /* The only error we allow is that the file descriptor does not
1472 exist, in which case we dup /dev/null to it. */
1473 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001474 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001475 return_value = -1;
1476 continue;
1477 }
1478
1479 /* Try dupping /dev/null to this stdio file descriptor and
1480 repeat if there is a signal. Note that any errors in closing
1481 the stdio descriptor are lost. */
1482 do {
1483 status = dup2(dev_null, i);
1484 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001485
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001486 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001487 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001488 return_value = -1;
1489 continue;
1490 }
1491 }
1492
1493 /* If /dev/null is not one of the stdio file descriptors, close it. */
1494 if (dev_null > 2) {
1495 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001496 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001497 status = close(dev_null);
1498 } while (status < 0 && errno == EINTR);
1499
1500 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001501 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001502 return_value = -1;
1503 }
1504 }
1505
1506 return return_value;
1507}
1508
1509static int link_image(soinfo *si, unsigned wr_offset)
1510{
1511 unsigned *d;
1512 Elf32_Phdr *phdr = si->phdr;
1513 int phnum = si->phnum;
1514
1515 INFO("[ %5d linking %s ]\n", pid, si->name);
1516 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1517 si->base, si->flags);
1518
1519 if (si->flags & FLAG_EXE) {
1520 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1521 * linkage info if this is the executable. If this was a
1522 * dynamic lib, that would have been done at load time.
1523 *
1524 * TODO: It's unfortunate that small pieces of this are
1525 * repeated from the load_library routine. Refactor this just
1526 * slightly to reuse these bits.
1527 */
1528 si->size = 0;
1529 for(; phnum > 0; --phnum, ++phdr) {
1530#ifdef ANDROID_ARM_LINKER
1531 if(phdr->p_type == PT_ARM_EXIDX) {
1532 /* exidx entries (used for stack unwinding) are 8 bytes each.
1533 */
1534 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1535 si->ARM_exidx_count = phdr->p_memsz / 8;
1536 }
1537#endif
1538 if (phdr->p_type == PT_LOAD) {
1539 /* For the executable, we use the si->size field only in
1540 dl_unwind_find_exidx(), so the meaning of si->size
1541 is not the size of the executable; it is the last
1542 virtual address of the loadable part of the executable;
1543 since si->base == 0 for an executable, we use the
1544 range [0, si->size) to determine whether a PC value
1545 falls within the executable section. Of course, if
1546 a value is below phdr->p_vaddr, it's not in the
1547 executable section, but a) we shouldn't be asking for
1548 such a value anyway, and b) if we have to provide
1549 an EXIDX for such a value, then the executable's
1550 EXIDX is probably the better choice.
1551 */
1552 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1553 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1554 si->size = phdr->p_vaddr + phdr->p_memsz;
1555 /* try to remember what range of addresses should be write
1556 * protected */
1557 if (!(phdr->p_flags & PF_W)) {
1558 unsigned _end;
1559
1560 if (phdr->p_vaddr < si->wrprotect_start)
1561 si->wrprotect_start = phdr->p_vaddr;
1562 _end = (((phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
1563 (~PAGE_MASK)));
1564 if (_end > si->wrprotect_end)
1565 si->wrprotect_end = _end;
1566 }
1567 } else if (phdr->p_type == PT_DYNAMIC) {
1568 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001569 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001570 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001571 pid, si->name, si->base + phdr->p_vaddr,
1572 (unsigned)si->dynamic);
1573 goto fail;
1574 }
1575 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1576 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1577 }
1578 }
1579 }
1580
1581 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001582 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001583 goto fail;
1584 }
1585
1586 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1587
1588 /* extract useful information from dynamic section */
1589 for(d = si->dynamic; *d; d++){
1590 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1591 switch(*d++){
1592 case DT_HASH:
1593 si->nbucket = ((unsigned *) (si->base + *d))[0];
1594 si->nchain = ((unsigned *) (si->base + *d))[1];
1595 si->bucket = (unsigned *) (si->base + *d + 8);
1596 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1597 break;
1598 case DT_STRTAB:
1599 si->strtab = (const char *) (si->base + *d);
1600 break;
1601 case DT_SYMTAB:
1602 si->symtab = (Elf32_Sym *) (si->base + *d);
1603 break;
1604 case DT_PLTREL:
1605 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001606 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001607 goto fail;
1608 }
1609 break;
1610 case DT_JMPREL:
1611 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1612 break;
1613 case DT_PLTRELSZ:
1614 si->plt_rel_count = *d / 8;
1615 break;
1616 case DT_REL:
1617 si->rel = (Elf32_Rel*) (si->base + *d);
1618 break;
1619 case DT_RELSZ:
1620 si->rel_count = *d / 8;
1621 break;
1622 case DT_PLTGOT:
1623 /* Save this in case we decide to do lazy binding. We don't yet. */
1624 si->plt_got = (unsigned *)(si->base + *d);
1625 break;
1626 case DT_DEBUG:
1627 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1628 *d = (int) &_r_debug;
1629 break;
1630 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001631 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001632 goto fail;
1633 case DT_INIT:
1634 si->init_func = (void (*)(void))(si->base + *d);
1635 DEBUG("%5d %s constructors (init func) found at %p\n",
1636 pid, si->name, si->init_func);
1637 break;
1638 case DT_FINI:
1639 si->fini_func = (void (*)(void))(si->base + *d);
1640 DEBUG("%5d %s destructors (fini func) found at %p\n",
1641 pid, si->name, si->fini_func);
1642 break;
1643 case DT_INIT_ARRAY:
1644 si->init_array = (unsigned *)(si->base + *d);
1645 DEBUG("%5d %s constructors (init_array) found at %p\n",
1646 pid, si->name, si->init_array);
1647 break;
1648 case DT_INIT_ARRAYSZ:
1649 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1650 break;
1651 case DT_FINI_ARRAY:
1652 si->fini_array = (unsigned *)(si->base + *d);
1653 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1654 pid, si->name, si->fini_array);
1655 break;
1656 case DT_FINI_ARRAYSZ:
1657 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1658 break;
1659 case DT_PREINIT_ARRAY:
1660 si->preinit_array = (unsigned *)(si->base + *d);
1661 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1662 pid, si->name, si->preinit_array);
1663 break;
1664 case DT_PREINIT_ARRAYSZ:
1665 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1666 break;
1667 case DT_TEXTREL:
1668 /* TODO: make use of this. */
1669 /* this means that we might have to write into where the text
1670 * segment was loaded during relocation... Do something with
1671 * it.
1672 */
1673 DEBUG("%5d Text segment should be writable during relocation.\n",
1674 pid);
1675 break;
1676 }
1677 }
1678
1679 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
1680 pid, si->base, si->strtab, si->symtab);
1681
1682 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001683 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001684 goto fail;
1685 }
1686
1687 for(d = si->dynamic; *d; d += 2) {
1688 if(d[0] == DT_NEEDED){
1689 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001690 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001691 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001692 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001693 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001694 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001695 goto fail;
1696 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001697 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1698 of the DT_NEEDED entry itself, so that we can retrieve the
1699 soinfo directly later from the dynamic segment. This is a hack,
1700 but it allows us to map from DT_NEEDED to soinfo efficiently
1701 later on when we resolve relocations, trying to look up a symgol
1702 with dlsym().
1703 */
1704 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001705 lsi->refcount++;
1706 }
1707 }
1708
1709 if(si->plt_rel) {
1710 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1711 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1712 goto fail;
1713 }
1714 if(si->rel) {
1715 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1716 if(reloc_library(si, si->rel, si->rel_count))
1717 goto fail;
1718 }
1719
1720 si->flags |= FLAG_LINKED;
1721 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1722
1723#if 0
1724 /* This is the way that the old dynamic linker did protection of
1725 * non-writable areas. It would scan section headers and find where
1726 * .text ended (rather where .data/.bss began) and assume that this is
1727 * the upper range of the non-writable area. This is too coarse,
1728 * and is kept here for reference until we fully move away from single
1729 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1730 * that made this possible.
1731 */
1732 if(wr_offset < 0xffffffff){
1733 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1734 }
1735#else
1736 /* TODO: Verify that this does the right thing in all cases, as it
1737 * presently probably does not. It is possible that an ELF image will
1738 * come with multiple read-only segments. What we ought to do is scan
1739 * the program headers again and mprotect all the read-only segments.
1740 * To prevent re-scanning the program header, we would have to build a
1741 * list of loadable segments in si, and then scan that instead. */
1742 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1743 mprotect((void *)si->wrprotect_start,
1744 si->wrprotect_end - si->wrprotect_start,
1745 PROT_READ | PROT_EXEC);
1746 }
1747#endif
1748
1749 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1750 stdout and stderr to close a security hole described in:
1751
1752 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1753
1754 */
1755 if (getuid() != geteuid() || getgid() != getegid())
1756 nullify_closed_stdio ();
1757 call_constructors(si);
1758 notify_gdb_of_load(si);
1759 return 0;
1760
1761fail:
Doug Kwan94304352009-10-23 18:11:40 -07001762 DL_ERR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001763 si->flags |= FLAG_ERROR;
1764 return -1;
1765}
1766
David Bartleybc3a5c22009-06-02 18:27:28 -07001767static void parse_library_path(char *path, char *delim)
1768{
1769 size_t len;
1770 char *ldpaths_bufp = ldpaths_buf;
1771 int i = 0;
1772
1773 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1774
1775 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1776 if (*ldpaths[i] != '\0')
1777 ++i;
1778 }
1779
1780 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1781 * last char isn't '\0' (i.e. not originally a delim). */
1782 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1783 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1784 ldpaths[i - 1] = NULL;
1785 } else {
1786 ldpaths[i] = NULL;
1787 }
1788}
1789
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001790int main(int argc, char **argv)
1791{
1792 return 0;
1793}
1794
1795#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
1796
1797static void * __tls_area[ANDROID_TLS_SLOTS];
1798
1799unsigned __linker_init(unsigned **elfdata)
1800{
1801 static soinfo linker_soinfo;
1802
1803 int argc = (int) *elfdata;
1804 char **argv = (char**) (elfdata + 1);
1805 unsigned *vecs = (unsigned*) (argv + argc + 1);
1806 soinfo *si;
1807 struct link_map * map;
David Bartleybc3a5c22009-06-02 18:27:28 -07001808 char *ldpath_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001809
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001810 /* Setup a temporary TLS area that is used to get a working
1811 * errno for system calls.
1812 */
1813 __set_tls(__tls_area);
1814
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001815 pid = getpid();
1816
1817#if TIMING
1818 struct timeval t0, t1;
1819 gettimeofday(&t0, 0);
1820#endif
1821
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02001822 /* NOTE: we store the elfdata pointer on a special location
1823 * of the temporary TLS area in order to pass it to
1824 * the C Library's runtime initializer.
1825 *
1826 * The initializer must clear the slot and reset the TLS
1827 * to point to a different location to ensure that no other
1828 * shared library constructor can access it.
1829 */
1830 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001831
1832 debugger_init();
1833
1834 /* skip past the environment */
1835 while(vecs[0] != 0) {
1836 if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
1837 debug_verbosity = atoi(((char*) vecs[0]) + 6);
David Bartleybc3a5c22009-06-02 18:27:28 -07001838 } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
1839 ldpath_env = (char*) vecs[0] + 16;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001840 }
1841 vecs++;
1842 }
1843 vecs++;
1844
1845 INFO("[ android linker & debugger ]\n");
1846 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
1847
1848 si = alloc_info(argv[0]);
1849 if(si == 0) {
1850 exit(-1);
1851 }
1852
1853 /* bootstrap the link map, the main exe always needs to be first */
1854 si->flags |= FLAG_EXE;
1855 map = &(si->linkmap);
1856
1857 map->l_addr = 0;
1858 map->l_name = argv[0];
1859 map->l_prev = NULL;
1860 map->l_next = NULL;
1861
1862 _r_debug.r_map = map;
1863 r_debug_tail = map;
1864
1865 /* gdb expects the linker to be in the debug shared object list,
1866 * and we need to make sure that the reported load address is zero.
1867 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
1868 * is. Don't use alloc_info(), because the linker shouldn't
1869 * be on the soinfo list.
1870 */
1871 strcpy((char*) linker_soinfo.name, "/system/bin/linker");
1872 linker_soinfo.flags = 0;
1873 linker_soinfo.base = 0; // This is the important part; must be zero.
1874 insert_soinfo_into_debug_map(&linker_soinfo);
1875
1876 /* extract information passed from the kernel */
1877 while(vecs[0] != 0){
1878 switch(vecs[0]){
1879 case AT_PHDR:
1880 si->phdr = (Elf32_Phdr*) vecs[1];
1881 break;
1882 case AT_PHNUM:
1883 si->phnum = (int) vecs[1];
1884 break;
1885 case AT_ENTRY:
1886 si->entry = vecs[1];
1887 break;
1888 }
1889 vecs += 2;
1890 }
1891
1892 ba_init();
1893
1894 si->base = 0;
1895 si->dynamic = (unsigned *)-1;
1896 si->wrprotect_start = 0xffffffff;
1897 si->wrprotect_end = 0;
1898
David Bartleybc3a5c22009-06-02 18:27:28 -07001899 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
1900 if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
1901 parse_library_path(ldpath_env, ":");
1902
Dima Zavin2e855792009-05-20 18:28:09 -07001903 if(link_image(si, 0)) {
1904 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
1905 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
1906 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001907 exit(-1);
1908 }
1909
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07001910#if ALLOW_SYMBOLS_FROM_MAIN
1911 /* Set somain after we've loaded all the libraries in order to prevent
1912 * linking of symbols back to the main image, which is not set up at that
1913 * point yet.
1914 */
1915 somain = si;
1916#endif
1917
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001918#if TIMING
1919 gettimeofday(&t1,NULL);
1920 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
1921 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
1922 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
1923 ));
1924#endif
1925#if STATS
1926 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
1927 linker_stats.reloc[RELOC_ABSOLUTE],
1928 linker_stats.reloc[RELOC_RELATIVE],
1929 linker_stats.reloc[RELOC_COPY],
1930 linker_stats.reloc[RELOC_SYMBOL]);
1931#endif
1932#if COUNT_PAGES
1933 {
1934 unsigned n;
1935 unsigned i;
1936 unsigned count = 0;
1937 for(n = 0; n < 4096; n++){
1938 if(bitmask[n]){
1939 unsigned x = bitmask[n];
1940 for(i = 0; i < 8; i++){
1941 if(x & 1) count++;
1942 x >>= 1;
1943 }
1944 }
1945 }
1946 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
1947 }
1948#endif
1949
1950#if TIMING || STATS || COUNT_PAGES
1951 fflush(stdout);
1952#endif
1953
1954 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
1955 si->entry);
1956 return si->entry;
1957}