blob: cf66211dbb4bb9dcc0af1692940b1f3a8f2cd73a [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' Turnerbe575592010-12-16 19:52:02 +010051#include "linker_environ.h"
David 'Digit' Turner5c734642010-01-20 12:36:51 -080052#include "linker_format.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070054#define ALLOW_SYMBOLS_FROM_MAIN 1
Kenny Root72f9a5c2011-02-10 17:02:21 -080055#define SO_MAX 128
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
Matt Fischer4fd42c12009-12-31 12:09:10 -060061#define LDPRELOAD_BUFSIZE 512
62#define LDPRELOAD_MAX 8
63
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080064/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
65 *
66 * Do NOT use malloc() and friends or pthread_*() code here.
67 * Don't use printf() either; it's caused mysterious memory
68 * corruption in the past.
69 * The linker runs before we bring up libc and it's easiest
70 * to make sure it does not depend on any complex libc features
71 *
72 * open issues / todo:
73 *
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080074 * - are we doing everything we should for ARM_COPY relocations?
75 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080076 * - after linking, set as much stuff as possible to READONLY
77 * and NOEXEC
78 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
79 * headers provide versions that are negative...
80 * - allocate space for soinfo structs dynamically instead of
81 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080082*/
83
84
85static int link_image(soinfo *si, unsigned wr_offset);
86
87static int socount = 0;
88static soinfo sopool[SO_MAX];
89static soinfo *freelist = NULL;
90static soinfo *solist = &libdl_info;
91static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070092#if ALLOW_SYMBOLS_FROM_MAIN
93static soinfo *somain; /* main process, always the one after libdl_info */
94#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080095
Iliyan Malchevaf7315a2009-10-16 17:50:42 -070096
Iliyan Malchev6ed80c82009-09-28 19:38:04 -070097static inline int validate_soinfo(soinfo *si)
98{
99 return (si >= sopool && si < sopool + SO_MAX) ||
100 si == &libdl_info;
101}
102
David Bartleybc3a5c22009-06-02 18:27:28 -0700103static char ldpaths_buf[LDPATH_BUFSIZE];
104static const char *ldpaths[LDPATH_MAX + 1];
105
Matt Fischer4fd42c12009-12-31 12:09:10 -0600106static char ldpreloads_buf[LDPRELOAD_BUFSIZE];
107static const char *ldpreload_names[LDPRELOAD_MAX + 1];
108
109static soinfo *preloads[LDPRELOAD_MAX + 1];
110
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800111int debug_verbosity;
112static int pid;
113
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100114/* This boolean is set if the program being loaded is setuid */
115static int program_is_setuid;
116
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800117#if STATS
118struct _link_stats linker_stats;
119#endif
120
121#if COUNT_PAGES
122unsigned bitmask[4096];
123#endif
124
125#ifndef PT_ARM_EXIDX
126#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
127#endif
128
Dima Zavin2e855792009-05-20 18:28:09 -0700129#define HOODLUM(name, ret, ...) \
130 ret name __VA_ARGS__ \
131 { \
132 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
133 write(2, errstr, sizeof(errstr)); \
134 abort(); \
135 }
136HOODLUM(malloc, void *, (size_t size));
137HOODLUM(free, void, (void *ptr));
138HOODLUM(realloc, void *, (void *ptr, size_t size));
139HOODLUM(calloc, void *, (size_t cnt, size_t size));
140
Dima Zavin03531952009-05-29 17:30:25 -0700141static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700142static char __linker_dl_err_buf[768];
143#define DL_ERR(fmt, x...) \
144 do { \
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800145 format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
Dima Zavin2e855792009-05-20 18:28:09 -0700146 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700147 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700148 } while(0)
149
150const char *linker_get_error(void)
151{
152 return (const char *)&__linker_dl_err_buf[0];
153}
154
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800155/*
156 * This function is an empty stub where GDB locates a breakpoint to get notified
157 * about linker activity.
158 */
159extern void __attribute__((noinline)) rtld_db_dlactivity(void);
160
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800161static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
162 RT_CONSISTENT, 0};
163static struct link_map *r_debug_tail = 0;
164
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700165static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800166
167static void insert_soinfo_into_debug_map(soinfo * info)
168{
169 struct link_map * map;
170
171 /* Copy the necessary fields into the debug structure.
172 */
173 map = &(info->linkmap);
174 map->l_addr = info->base;
175 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800176 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800177
178 /* Stick the new library at the end of the list.
179 * gdb tends to care more about libc than it does
180 * about leaf libraries, and ordering it this way
181 * reduces the back-and-forth over the wire.
182 */
183 if (r_debug_tail) {
184 r_debug_tail->l_next = map;
185 map->l_prev = r_debug_tail;
186 map->l_next = 0;
187 } else {
188 _r_debug.r_map = map;
189 map->l_prev = 0;
190 map->l_next = 0;
191 }
192 r_debug_tail = map;
193}
194
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700195static void remove_soinfo_from_debug_map(soinfo * info)
196{
197 struct link_map * map = &(info->linkmap);
198
199 if (r_debug_tail == map)
200 r_debug_tail = map->l_prev;
201
202 if (map->l_prev) map->l_prev->l_next = map->l_next;
203 if (map->l_next) map->l_next->l_prev = map->l_prev;
204}
205
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800206void notify_gdb_of_load(soinfo * info)
207{
208 if (info->flags & FLAG_EXE) {
209 // GDB already knows about the main executable
210 return;
211 }
212
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700213 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800214
215 _r_debug.r_state = RT_ADD;
216 rtld_db_dlactivity();
217
218 insert_soinfo_into_debug_map(info);
219
220 _r_debug.r_state = RT_CONSISTENT;
221 rtld_db_dlactivity();
222
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700223 pthread_mutex_unlock(&_r_debug_lock);
224}
225
226void notify_gdb_of_unload(soinfo * info)
227{
228 if (info->flags & FLAG_EXE) {
229 // GDB already knows about the main executable
230 return;
231 }
232
233 pthread_mutex_lock(&_r_debug_lock);
234
235 _r_debug.r_state = RT_DELETE;
236 rtld_db_dlactivity();
237
238 remove_soinfo_from_debug_map(info);
239
240 _r_debug.r_state = RT_CONSISTENT;
241 rtld_db_dlactivity();
242
243 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800244}
245
246void notify_gdb_of_libraries()
247{
248 _r_debug.r_state = RT_ADD;
249 rtld_db_dlactivity();
250 _r_debug.r_state = RT_CONSISTENT;
251 rtld_db_dlactivity();
252}
253
254static soinfo *alloc_info(const char *name)
255{
256 soinfo *si;
257
258 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700259 DL_ERR("%5d library name %s too long", pid, name);
Doug Kwan94304352009-10-23 18:11:40 -0700260 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261 }
262
263 /* The freelist is populated when we call free_info(), which in turn is
264 done only by dlclose(), which is not likely to be used.
265 */
266 if (!freelist) {
267 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700268 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800269 return NULL;
270 }
271 freelist = sopool + socount++;
272 freelist->next = NULL;
273 }
274
275 si = freelist;
276 freelist = freelist->next;
277
278 /* Make sure we get a clean block of soinfo */
279 memset(si, 0, sizeof(soinfo));
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100280 strlcpy((char*) si->name, name, sizeof(si->name));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800281 sonext->next = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800282 si->next = NULL;
283 si->refcount = 0;
284 sonext = si;
285
286 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
287 return si;
288}
289
290static void free_info(soinfo *si)
291{
292 soinfo *prev = NULL, *trav;
293
294 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
295
296 for(trav = solist; trav != NULL; trav = trav->next){
297 if (trav == si)
298 break;
299 prev = trav;
300 }
301 if (trav == NULL) {
302 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700303 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800304 return;
305 }
306
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100307 /* prev will never be NULL, because the first entry in solist is
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800308 always the static libdl_info.
309 */
310 prev->next = si->next;
311 if (si == sonext) sonext = prev;
312 si->next = freelist;
313 freelist = si;
314}
315
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800316const char *addr_to_name(unsigned addr)
317{
318 soinfo *si;
319
320 for(si = solist; si != 0; si = si->next){
321 if((addr >= si->base) && (addr < (si->base + si->size))) {
322 return si->name;
323 }
324 }
325
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800326 return "";
327}
328
329/* For a given PC, find the .so that it belongs to.
330 * Returns the base address of the .ARM.exidx section
331 * for that .so, and the number of 8-byte entries
332 * in that section (via *pcount).
333 *
334 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
335 *
336 * This function is exposed via dlfcn.c and libdl.so.
337 */
338#ifdef ANDROID_ARM_LINKER
339_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
340{
341 soinfo *si;
342 unsigned addr = (unsigned)pc;
343
Nick Kralevich994e9a52011-11-01 10:51:22 -0700344 for (si = solist; si != 0; si = si->next){
345 if ((addr >= si->base) && (addr < (si->base + si->size))) {
346 *pcount = si->ARM_exidx_count;
347 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800348 }
349 }
350 *pcount = 0;
351 return NULL;
352}
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +0900353#elif defined(ANDROID_X86_LINKER) || defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800354/* Here, we only have to provide a callback to iterate across all the
355 * loaded libraries. gcc_eh does the rest. */
356int
357dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
358 void *data)
359{
360 soinfo *si;
361 struct dl_phdr_info dl_info;
362 int rv = 0;
363
364 for (si = solist; si != NULL; si = si->next) {
365 dl_info.dlpi_addr = si->linkmap.l_addr;
366 dl_info.dlpi_name = si->linkmap.l_name;
367 dl_info.dlpi_phdr = si->phdr;
368 dl_info.dlpi_phnum = si->phnum;
369 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
370 if (rv != 0)
371 break;
372 }
373 return rv;
374}
375#endif
376
377static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
378{
379 Elf32_Sym *s;
380 Elf32_Sym *symtab = si->symtab;
381 const char *strtab = si->strtab;
382 unsigned n;
383
384 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
385 name, si->name, si->base, hash, hash % si->nbucket);
386 n = hash % si->nbucket;
387
388 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
389 s = symtab + n;
390 if(strcmp(strtab + s->st_name, name)) continue;
391
Doug Kwane8238072009-10-26 12:05:23 -0700392 /* only concern ourselves with global and weak symbol definitions */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800393 switch(ELF32_ST_BIND(s->st_info)){
394 case STB_GLOBAL:
Doug Kwane8238072009-10-26 12:05:23 -0700395 case STB_WEAK:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800396 /* no section == undefined */
397 if(s->st_shndx == 0) continue;
398
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800399 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
400 name, si->name, s->st_value, s->st_size);
401 return s;
402 }
403 }
404
Doug Kwan94304352009-10-23 18:11:40 -0700405 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800406}
407
Nick Kralevich994e9a52011-11-01 10:51:22 -0700408/*
409 * Essentially the same method as _elf_lookup() above, but only
410 * searches for LOCAL symbols
411 */
412static Elf32_Sym *_elf_lookup_local(soinfo *si, unsigned hash, const char *name)
413{
414 Elf32_Sym *symtab = si->symtab;
415 const char *strtab = si->strtab;
416 unsigned n = hash % si->nbucket;;
417
418 TRACE_TYPE(LOOKUP, "%5d LOCAL SEARCH %s in %s@0x%08x %08x %d\n", pid,
419 name, si->name, si->base, hash, hash % si->nbucket);
420 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
421 Elf32_Sym *s = symtab + n;
422 if (strcmp(strtab + s->st_name, name)) continue;
423 if (ELF32_ST_BIND(s->st_info) != STB_LOCAL) continue;
424 /* no section == undefined */
425 if(s->st_shndx == 0) continue;
426
427 TRACE_TYPE(LOOKUP, "%5d FOUND LOCAL %s in %s (%08x) %d\n", pid,
428 name, si->name, s->st_value, s->st_size);
429 return s;
430 }
431
432 return NULL;
433}
434
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800435static unsigned elfhash(const char *_name)
436{
437 const unsigned char *name = (const unsigned char *) _name;
438 unsigned h = 0, g;
439
440 while(*name) {
441 h = (h << 4) + *name++;
442 g = h & 0xf0000000;
443 h ^= g;
444 h ^= g >> 24;
445 }
446 return h;
447}
448
449static Elf32_Sym *
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700450_do_lookup(soinfo *si, const char *name, unsigned *base)
451{
Doug Kwan94304352009-10-23 18:11:40 -0700452 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700453 Elf32_Sym *s;
454 unsigned *d;
455 soinfo *lsi = si;
Matt Fischer4fd42c12009-12-31 12:09:10 -0600456 int i;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700457
Nick Kralevich994e9a52011-11-01 10:51:22 -0700458 /* If we are trying to find a symbol for the linker itself, look
459 * for LOCAL symbols first. Avoid using LOCAL symbols for other
460 * shared libraries until we have a better understanding of what
461 * might break by doing so. */
462 if (si->flags & FLAG_LINKER) {
463 s = _elf_lookup_local(si, elf_hash, name);
464 if(s != NULL)
465 goto done;
466 }
467
468 /* Look for symbols in the local scope (the object who is
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700469 * searching). This happens with C++ templates on i386 for some
Doug Kwane8238072009-10-26 12:05:23 -0700470 * reason.
471 *
472 * Notes on weak symbols:
473 * The ELF specs are ambigious about treatment of weak definitions in
474 * dynamic linking. Some systems return the first definition found
475 * and some the first non-weak definition. This is system dependent.
476 * Here we return the first definition found for simplicity. */
Nick Kralevich994e9a52011-11-01 10:51:22 -0700477
Doug Kwan94304352009-10-23 18:11:40 -0700478 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700479 if(s != NULL)
480 goto done;
481
Matt Fischer4fd42c12009-12-31 12:09:10 -0600482 /* Next, look for it in the preloads list */
483 for(i = 0; preloads[i] != NULL; i++) {
484 lsi = preloads[i];
Jean-Baptiste Queruf4394452010-05-12 10:05:59 -0700485 s = _elf_lookup(lsi, elf_hash, name);
Matt Fischer4fd42c12009-12-31 12:09:10 -0600486 if(s != NULL)
487 goto done;
488 }
489
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700490 for(d = si->dynamic; *d; d += 2) {
491 if(d[0] == DT_NEEDED){
492 lsi = (soinfo *)d[1];
493 if (!validate_soinfo(lsi)) {
494 DL_ERR("%5d bad DT_NEEDED pointer in %s",
495 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700496 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700497 }
498
499 DEBUG("%5d %s: looking up %s in %s\n",
500 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700501 s = _elf_lookup(lsi, elf_hash, name);
Min-su, Kim3cab22c2010-01-19 10:05:33 +0900502 if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700503 goto done;
504 }
505 }
506
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700507#if ALLOW_SYMBOLS_FROM_MAIN
508 /* If we are resolving relocations while dlopen()ing a library, it's OK for
509 * the library to resolve a symbol that's defined in the executable itself,
510 * although this is rare and is generally a bad idea.
511 */
512 if (somain) {
513 lsi = somain;
514 DEBUG("%5d %s: looking up %s in executable %s\n",
515 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700516 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700517 }
518#endif
519
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700520done:
521 if(s != NULL) {
522 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
523 "found in %s, base = 0x%08x\n",
524 pid, si->name, name, s->st_value, lsi->name, lsi->base);
525 *base = lsi->base;
526 return s;
527 }
528
Doug Kwan94304352009-10-23 18:11:40 -0700529 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700530}
531
532/* This is used by dl_sym(). It performs symbol lookup only within the
533 specified soinfo object and not in any of its dependencies.
534 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800535Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
536{
Doug Kwan94304352009-10-23 18:11:40 -0700537 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800538}
539
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700540/* This is used by dl_sym(). It performs a global symbol lookup.
541 */
Matt Fischer1698d9e2009-12-31 12:17:56 -0600542Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800543{
Doug Kwan94304352009-10-23 18:11:40 -0700544 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800545 Elf32_Sym *s = NULL;
546 soinfo *si;
547
Matt Fischer1698d9e2009-12-31 12:17:56 -0600548 if(start == NULL) {
549 start = solist;
550 }
551
552 for(si = start; (s == NULL) && (si != NULL); si = si->next)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800553 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700554 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800555 continue;
Doug Kwane8238072009-10-26 12:05:23 -0700556 s = _elf_lookup(si, elf_hash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800557 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700558 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800559 break;
560 }
561 }
562
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700563 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800564 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
565 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
566 return s;
567 }
568
Doug Kwan94304352009-10-23 18:11:40 -0700569 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800570}
571
Mathias Agopianbda5da02011-09-27 22:30:19 -0700572soinfo *find_containing_library(const void *addr)
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600573{
574 soinfo *si;
575
576 for(si = solist; si != NULL; si = si->next)
577 {
578 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
579 return si;
580 }
581 }
582
583 return NULL;
584}
585
Mathias Agopianbda5da02011-09-27 22:30:19 -0700586Elf32_Sym *find_containing_symbol(const void *addr, soinfo *si)
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600587{
588 unsigned int i;
589 unsigned soaddr = (unsigned)addr - si->base;
590
591 /* Search the library's symbol table for any defined symbol which
592 * contains this address */
593 for(i=0; i<si->nchain; i++) {
594 Elf32_Sym *sym = &si->symtab[i];
595
596 if(sym->st_shndx != SHN_UNDEF &&
597 soaddr >= sym->st_value &&
598 soaddr < sym->st_value + sym->st_size) {
599 return sym;
600 }
601 }
602
603 return NULL;
604}
605
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800606#if 0
607static void dump(soinfo *si)
608{
609 Elf32_Sym *s = si->symtab;
610 unsigned n;
611
612 for(n = 0; n < si->nchain; n++) {
613 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
614 s->st_info, s->st_shndx, s->st_value, s->st_size,
615 si->strtab + s->st_name);
616 s++;
617 }
618}
619#endif
620
621static const char *sopaths[] = {
Brian Swetlandfedbcde2010-09-19 03:39:13 -0700622 "/vendor/lib",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800623 "/system/lib",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800624 0
625};
626
627static int _open_lib(const char *name)
628{
629 int fd;
630 struct stat filestat;
631
632 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
633 if ((fd = open(name, O_RDONLY)) >= 0)
634 return fd;
635 }
636
637 return -1;
638}
639
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800640static int open_library(const char *name)
641{
642 int fd;
643 char buf[512];
644 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700645 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800646
647 TRACE("[ %5d opening %s ]\n", pid, name);
648
649 if(name == 0) return -1;
650 if(strlen(name) > 256) return -1;
651
652 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
653 return fd;
654
David Bartleybc3a5c22009-06-02 18:27:28 -0700655 for (path = ldpaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800656 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700657 if (n < 0 || n >= (int)sizeof(buf)) {
658 WARN("Ignoring very long library path: %s/%s\n", *path, name);
659 continue;
660 }
661 if ((fd = _open_lib(buf)) >= 0)
662 return fd;
663 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800664 for (path = sopaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800665 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700666 if (n < 0 || n >= (int)sizeof(buf)) {
667 WARN("Ignoring very long library path: %s/%s\n", *path, name);
668 continue;
669 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800670 if ((fd = _open_lib(buf)) >= 0)
671 return fd;
672 }
673
674 return -1;
675}
676
677/* temporary space for holding the first page of the shared lib
678 * which contains the elf header (with the pht). */
679static unsigned char __header[PAGE_SIZE];
680
681typedef struct {
682 long mmap_addr;
683 char tag[4]; /* 'P', 'R', 'E', ' ' */
684} prelink_info_t;
685
686/* Returns the requested base address if the library is prelinked,
687 * and 0 otherwise. */
688static unsigned long
689is_prelinked(int fd, const char *name)
690{
691 off_t sz;
692 prelink_info_t info;
693
694 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
695 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700696 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800697 return 0;
698 }
699
700 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
701 WARN("Could not read prelink_info_t structure for `%s`\n", name);
702 return 0;
703 }
704
705 if (strncmp(info.tag, "PRE ", 4)) {
706 WARN("`%s` is not a prelinked library\n", name);
707 return 0;
708 }
709
710 return (unsigned long)info.mmap_addr;
711}
712
713/* verify_elf_object
714 * Verifies if the object @ base is a valid ELF object
715 *
716 * Args:
717 *
718 * Returns:
719 * 0 on success
720 * -1 if no valid ELF object is found @ base.
721 */
722static int
723verify_elf_object(void *base, const char *name)
724{
725 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
726
727 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
728 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
729 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
730 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
731
732 /* TODO: Should we verify anything else in the header? */
733
734 return 0;
735}
736
737
738/* get_lib_extents
739 * Retrieves the base (*base) address where the ELF object should be
740 * mapped and its overall memory size (*total_sz).
741 *
742 * Args:
743 * fd: Opened file descriptor for the library
744 * name: The name of the library
745 * _hdr: Pointer to the header page of the library
746 * total_sz: Total size of the memory that should be allocated for
747 * this library
748 *
749 * Returns:
750 * -1 if there was an error while trying to get the lib extents.
751 * The possible reasons are:
752 * - Could not determine if the library was prelinked.
753 * - The library provided is not a valid ELF object
754 * 0 if the library did not request a specific base offset (normal
755 * for non-prelinked libs)
756 * > 0 if the library requests a specific address to be mapped to.
757 * This indicates a pre-linked library.
758 */
759static unsigned
760get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
761{
762 unsigned req_base;
763 unsigned min_vaddr = 0xffffffff;
764 unsigned max_vaddr = 0;
765 unsigned char *_hdr = (unsigned char *)__hdr;
766 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
767 Elf32_Phdr *phdr;
768 int cnt;
769
770 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
771 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700772 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800773 return (unsigned)-1;
774 }
775
776 req_base = (unsigned) is_prelinked(fd, name);
777 if (req_base == (unsigned)-1)
778 return -1;
779 else if (req_base != 0) {
780 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
781 pid, name, req_base);
782 } else {
783 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
784 }
785
786 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
787
788 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
789 * get the range. */
790 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
791 if (phdr->p_type == PT_LOAD) {
792 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
793 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
794 if (phdr->p_vaddr < min_vaddr)
795 min_vaddr = phdr->p_vaddr;
796 }
797 }
798
799 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700800 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800801 return (unsigned)-1;
802 }
803
804 /* truncate min_vaddr down to page boundary */
805 min_vaddr &= ~PAGE_MASK;
806
807 /* round max_vaddr up to the next page */
808 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
809
810 *total_sz = (max_vaddr - min_vaddr);
811 return (unsigned)req_base;
812}
813
814/* alloc_mem_region
815 *
816 * This function reserves a chunk of memory to be used for mapping in
817 * the shared library. We reserve the entire memory region here, and
818 * then the rest of the linker will relocate the individual loadable
819 * segments into the correct locations within this memory range.
820 *
821 * Args:
822 * si->base: The requested base of the allocation. If 0, a sane one will be
823 * chosen in the range LIBBASE <= base < LIBLAST.
824 * si->size: The size of the allocation.
825 *
826 * Returns:
827 * -1 on failure, and 0 on success. On success, si->base will contain
828 * the virtual address at which the library will be mapped.
829 */
830
831static int reserve_mem_region(soinfo *si)
832{
833 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
Chris Dearmandb4bce02011-03-10 10:48:14 -0800834 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800835 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700836 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700837 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800838 pid, (si->base ? "" : "non-"), si->name, si->base,
839 errno, strerror(errno));
840 return -1;
841 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700842 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700843 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800844 si->name, (unsigned)base, si->base);
845 munmap(base, si->size);
846 return -1;
847 }
848 return 0;
849}
850
851static int
852alloc_mem_region(soinfo *si)
853{
854 if (si->base) {
855 /* Attempt to mmap a prelinked library. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800856 return reserve_mem_region(si);
857 }
858
Shih-wei Liao48527c32011-07-17 12:32:43 -0700859 /* This is not a prelinked library, so we use the kernel's default
860 allocator.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861 */
Shih-wei Liao48527c32011-07-17 12:32:43 -0700862
863 void *base = mmap(NULL, si->size, PROT_READ | PROT_EXEC,
864 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
865 if (base == MAP_FAILED) {
866 DL_ERR("%5d mmap of library '%s' failed: %d (%s)\n",
867 pid, si->name,
868 errno, strerror(errno));
869 goto err;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800870 }
Shih-wei Liao48527c32011-07-17 12:32:43 -0700871 si->base = (unsigned) base;
872 PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
873 pid, si->name, si->base);
874 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800875
876err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700877 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800878 pid, si->name);
879 return -1;
880}
881
882#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
883#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
884 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
885 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
886/* load_segments
887 *
888 * This function loads all the loadable (PT_LOAD) segments into memory
889 * at their appropriate memory offsets off the base address.
890 *
891 * Args:
892 * fd: Open file descriptor to the library to load.
893 * header: Pointer to a header page that contains the ELF header.
894 * This is needed since we haven't mapped in the real file yet.
895 * si: ptr to soinfo struct describing the shared object.
896 *
897 * Returns:
898 * 0 on success, -1 on failure.
899 */
900static int
901load_segments(int fd, void *header, soinfo *si)
902{
903 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
904 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
905 unsigned char *base = (unsigned char *)si->base;
906 int cnt;
907 unsigned len;
908 unsigned char *tmp;
909 unsigned char *pbase;
910 unsigned char *extra_base;
911 unsigned extra_len;
912 unsigned total_sz = 0;
913
914 si->wrprotect_start = 0xffffffff;
915 si->wrprotect_end = 0;
916
917 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
918 pid, si->name, (unsigned)si->base);
919 /* Now go through all the PT_LOAD segments and map them into memory
920 * at the appropriate locations. */
921 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
922 if (phdr->p_type == PT_LOAD) {
923 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
924 /* we want to map in the segment on a page boundary */
925 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
926 /* add the # of bytes we masked off above to the total length. */
927 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
928
929 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
930 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
931 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
932 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
933 MAP_PRIVATE | MAP_FIXED, fd,
934 phdr->p_offset & (~PAGE_MASK));
935 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700936 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700937 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800938 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
939 goto fail;
940 }
941
942 /* If 'len' didn't end on page boundary, and it's a writable
943 * segment, zero-fill the rest. */
944 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
945 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
946
947 /* Check to see if we need to extend the map for this segment to
948 * cover the diff between filesz and memsz (i.e. for bss).
949 *
950 * base _+---------------------+ page boundary
951 * . .
952 * | |
953 * . .
954 * pbase _+---------------------+ page boundary
955 * | |
956 * . .
957 * base + p_vaddr _| |
958 * . \ \ .
959 * . | filesz | .
960 * pbase + len _| / | |
961 * <0 pad> . . .
962 * extra_base _+------------|--------+ page boundary
963 * / . . .
964 * | . . .
965 * | +------------|--------+ page boundary
966 * extra_len-> | | | |
967 * | . | memsz .
968 * | . | .
969 * \ _| / |
970 * . .
971 * | |
972 * _+---------------------+ page boundary
973 */
974 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
975 (~PAGE_MASK));
976 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
977 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
978 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
979 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
980 /* map in the extra page(s) as anonymous into the range.
981 * This is probably not necessary as we already mapped in
982 * the entire region previously, but we just want to be
983 * sure. This will also set the right flags on the region
984 * (though we can probably accomplish the same thing with
985 * mprotect).
986 */
987 extra_base = mmap((void *)tmp, extra_len,
988 PFLAGS_TO_PROT(phdr->p_flags),
989 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
990 -1, 0);
991 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700992 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700993 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800994 extra_len);
995 goto fail;
996 }
997 /* TODO: Check if we need to memset-0 this region.
998 * Anonymous mappings are zero-filled copy-on-writes, so we
999 * shouldn't need to. */
1000 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
1001 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
1002 extra_len);
1003 }
1004 /* set the len here to show the full extent of the segment we
1005 * just loaded, mostly for debugging */
1006 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
1007 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
1008 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
1009 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
1010 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
1011 total_sz += len;
1012 /* Make the section writable just in case we'll have to write to
1013 * it during relocation (i.e. text segment). However, we will
1014 * remember what range of addresses should be write protected.
1015 *
1016 */
1017 if (!(phdr->p_flags & PF_W)) {
1018 if ((unsigned)pbase < si->wrprotect_start)
1019 si->wrprotect_start = (unsigned)pbase;
1020 if (((unsigned)pbase + len) > si->wrprotect_end)
1021 si->wrprotect_end = (unsigned)pbase + len;
1022 mprotect(pbase, len,
1023 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1024 }
1025 } else if (phdr->p_type == PT_DYNAMIC) {
1026 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1027 /* this segment contains the dynamic linking information */
1028 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
1029 } else {
1030#ifdef ANDROID_ARM_LINKER
1031 if (phdr->p_type == PT_ARM_EXIDX) {
1032 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1033 /* exidx entries (used for stack unwinding) are 8 bytes each.
1034 */
1035 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1036 si->ARM_exidx_count = phdr->p_memsz / 8;
1037 }
1038#endif
1039 }
1040
1041 }
1042
1043 /* Sanity check */
1044 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001045 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001046 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001047 pid, total_sz, si->name, si->size);
1048 goto fail;
1049 }
1050
1051 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1052 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1053 (unsigned)si->base, si->size);
1054 return 0;
1055
1056fail:
1057 /* We can just blindly unmap the entire region even though some things
1058 * were mapped in originally with anonymous and others could have been
1059 * been mapped in from the file before we failed. The kernel will unmap
1060 * all the pages in the range, irrespective of how they got there.
1061 */
1062 munmap((void *)si->base, si->size);
1063 si->flags |= FLAG_ERROR;
1064 return -1;
1065}
1066
1067/* TODO: Implement this to take care of the fact that Android ARM
1068 * ELF objects shove everything into a single loadable segment that has the
1069 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1070 * non-writable.
1071 */
1072#if 0
1073static unsigned
1074get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1075{
1076 Elf32_Shdr *shdr_start;
1077 Elf32_Shdr *shdr;
1078 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1079 int cnt;
1080 unsigned wr_offset = 0xffffffff;
1081
1082 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1083 ehdr->e_shoff & (~PAGE_MASK));
1084 if (shdr_start == MAP_FAILED) {
1085 WARN("%5d - Could not read section header info from '%s'. Will not "
1086 "not be able to determine write-protect offset.\n", pid, name);
1087 return (unsigned)-1;
1088 }
1089
1090 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1091 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1092 (shdr->sh_addr < wr_offset)) {
1093 wr_offset = shdr->sh_addr;
1094 }
1095 }
1096
1097 munmap(shdr_start, shdr_sz);
1098 return wr_offset;
1099}
1100#endif
1101
1102static soinfo *
1103load_library(const char *name)
1104{
1105 int fd = open_library(name);
1106 int cnt;
1107 unsigned ext_sz;
1108 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001109 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001110 soinfo *si = NULL;
1111 Elf32_Ehdr *hdr;
1112
Dima Zavin2e855792009-05-20 18:28:09 -07001113 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001114 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001115 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001116 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001117
1118 /* We have to read the ELF header to figure out what to do with this image
1119 */
1120 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001121 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001122 goto fail;
1123 }
1124
1125 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001126 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001127 goto fail;
1128 }
1129
1130 /* Parse the ELF header and get the size of the memory footprint for
1131 * the library */
1132 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1133 if (req_base == (unsigned)-1)
1134 goto fail;
1135 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1136 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1137
1138 /* Now configure the soinfo struct where we'll store all of our data
1139 * for the ELF object. If the loading fails, we waste the entry, but
1140 * same thing would happen if we failed during linking. Configuring the
1141 * soinfo struct here is a lot more convenient.
1142 */
Erik Gillingfde86422009-07-28 20:28:19 -07001143 bname = strrchr(name, '/');
1144 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001145 if (si == NULL)
1146 goto fail;
1147
1148 /* Carve out a chunk of memory where we will map in the individual
1149 * segments */
1150 si->base = req_base;
1151 si->size = ext_sz;
1152 si->flags = 0;
1153 si->entry = 0;
1154 si->dynamic = (unsigned *)-1;
1155 if (alloc_mem_region(si) < 0)
1156 goto fail;
1157
1158 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1159 pid, name, (void *)si->base, (unsigned) ext_sz);
1160
1161 /* Now actually load the library's segments into right places in memory */
1162 if (load_segments(fd, &__header[0], si) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001163 goto fail;
1164 }
1165
1166 /* this might not be right. Technically, we don't even need this info
1167 * once we go through 'load_segments'. */
1168 hdr = (Elf32_Ehdr *)si->base;
1169 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1170 si->phnum = hdr->e_phnum;
1171 /**/
1172
1173 close(fd);
1174 return si;
1175
1176fail:
1177 if (si) free_info(si);
1178 close(fd);
1179 return NULL;
1180}
1181
1182static soinfo *
1183init_library(soinfo *si)
1184{
1185 unsigned wr_offset = 0xffffffff;
1186
1187 /* At this point we know that whatever is loaded @ base is a valid ELF
1188 * shared library whose segments are properly mapped in. */
1189 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1190 pid, si->base, si->size, si->name);
1191
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001192 if(link_image(si, wr_offset)) {
1193 /* We failed to link. However, we can only restore libbase
1194 ** if no additional libraries have moved it since we updated it.
1195 */
1196 munmap((void *)si->base, si->size);
1197 return NULL;
1198 }
1199
1200 return si;
1201}
1202
1203soinfo *find_library(const char *name)
1204{
1205 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001206 const char *bname;
1207
1208#if ALLOW_SYMBOLS_FROM_MAIN
1209 if (name == NULL)
1210 return somain;
1211#else
1212 if (name == NULL)
1213 return NULL;
1214#endif
1215
1216 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001217 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001218
1219 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001220 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001221 if(si->flags & FLAG_ERROR) {
1222 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1223 return NULL;
1224 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001225 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001226 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001227 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001228 }
1229 }
1230
1231 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1232 si = load_library(name);
1233 if(si == NULL)
1234 return NULL;
1235 return init_library(si);
1236}
1237
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001238/* TODO:
1239 * notify gdb of unload
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 * for non-prelinked libraries, find a way to decrement libbase
1241 */
1242static void call_destructors(soinfo *si);
1243unsigned unload_library(soinfo *si)
1244{
1245 unsigned *d;
1246 if (si->refcount == 1) {
1247 TRACE("%5d unloading '%s'\n", pid, si->name);
1248 call_destructors(si);
1249
1250 for(d = si->dynamic; *d; d += 2) {
1251 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001252 soinfo *lsi = (soinfo *)d[1];
1253 d[1] = 0;
1254 if (validate_soinfo(lsi)) {
1255 TRACE("%5d %s needs to unload %s\n", pid,
1256 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001257 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001258 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001259 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001260 DL_ERR("%5d %s: could not unload dependent library",
1261 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001262 }
1263 }
1264
1265 munmap((char *)si->base, si->size);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001266 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001267 free_info(si);
1268 si->refcount = 0;
1269 }
1270 else {
1271 si->refcount--;
1272 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1273 pid, si->name, si->refcount);
1274 }
1275 return si->refcount;
1276}
1277
1278/* TODO: don't use unsigned for addrs below. It works, but is not
1279 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1280 * long.
1281 */
1282static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1283{
1284 Elf32_Sym *symtab = si->symtab;
1285 const char *strtab = si->strtab;
1286 Elf32_Sym *s;
1287 unsigned base;
1288 Elf32_Rel *start = rel;
1289 unsigned idx;
1290
1291 for (idx = 0; idx < count; ++idx) {
1292 unsigned type = ELF32_R_TYPE(rel->r_info);
1293 unsigned sym = ELF32_R_SYM(rel->r_info);
1294 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1295 unsigned sym_addr = 0;
1296 char *sym_name = NULL;
1297
1298 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1299 si->name, idx);
1300 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001301 sym_name = (char *)(strtab + symtab[sym].st_name);
1302 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001303 if(s == NULL) {
1304 /* We only allow an undefined symbol if this is a weak
1305 reference.. */
1306 s = &symtab[sym];
1307 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1308 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1309 return -1;
1310 }
1311
1312 /* IHI0044C AAELF 4.5.1.1:
1313
1314 Libraries are not searched to resolve weak references.
1315 It is not an error for a weak reference to remain
1316 unsatisfied.
1317
1318 During linking, the value of an undefined weak reference is:
1319 - Zero if the relocation type is absolute
1320 - The address of the place if the relocation is pc-relative
1321 - The address of nominial base address if the relocation
1322 type is base-relative.
1323 */
1324
1325 switch (type) {
1326#if defined(ANDROID_ARM_LINKER)
1327 case R_ARM_JUMP_SLOT:
1328 case R_ARM_GLOB_DAT:
1329 case R_ARM_ABS32:
1330 case R_ARM_RELATIVE: /* Don't care. */
1331 case R_ARM_NONE: /* Don't care. */
1332#elif defined(ANDROID_X86_LINKER)
1333 case R_386_JUMP_SLOT:
1334 case R_386_GLOB_DAT:
1335 case R_386_32:
1336 case R_386_RELATIVE: /* Dont' care. */
1337#endif /* ANDROID_*_LINKER */
1338 /* sym_addr was initialized to be zero above or relocation
1339 code below does not care about value of sym_addr.
1340 No need to do anything. */
1341 break;
1342
1343#if defined(ANDROID_X86_LINKER)
1344 case R_386_PC32:
1345 sym_addr = reloc;
1346 break;
1347#endif /* ANDROID_X86_LINKER */
1348
1349#if defined(ANDROID_ARM_LINKER)
1350 case R_ARM_COPY:
1351 /* Fall through. Can't really copy if weak symbol is
1352 not found in run-time. */
1353#endif /* ANDROID_ARM_LINKER */
1354 default:
1355 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1356 pid, type, rel, (int) (rel - start));
1357 return -1;
1358 }
1359 } else {
1360 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001361#if 0
1362 if((base == 0) && (si->base != 0)){
1363 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001364 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365 pid, strtab + symtab[sym].st_name);
1366 return -1;
1367 }
1368#endif
Doug Kwane8238072009-10-26 12:05:23 -07001369 sym_addr = (unsigned)(s->st_value + base);
1370 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001371 COUNT_RELOC(RELOC_SYMBOL);
1372 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001373 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001374 }
1375
1376/* TODO: This is ugly. Split up the relocations by arch into
1377 * different files.
1378 */
1379 switch(type){
1380#if defined(ANDROID_ARM_LINKER)
1381 case R_ARM_JUMP_SLOT:
1382 COUNT_RELOC(RELOC_ABSOLUTE);
1383 MARK(rel->r_offset);
1384 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1385 reloc, sym_addr, sym_name);
1386 *((unsigned*)reloc) = sym_addr;
1387 break;
1388 case R_ARM_GLOB_DAT:
1389 COUNT_RELOC(RELOC_ABSOLUTE);
1390 MARK(rel->r_offset);
1391 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1392 reloc, sym_addr, sym_name);
1393 *((unsigned*)reloc) = sym_addr;
1394 break;
1395 case R_ARM_ABS32:
1396 COUNT_RELOC(RELOC_ABSOLUTE);
1397 MARK(rel->r_offset);
1398 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1399 reloc, sym_addr, sym_name);
1400 *((unsigned*)reloc) += sym_addr;
1401 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001402 case R_ARM_REL32:
1403 COUNT_RELOC(RELOC_RELATIVE);
1404 MARK(rel->r_offset);
1405 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1406 reloc, sym_addr, rel->r_offset, sym_name);
1407 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1408 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001409#elif defined(ANDROID_X86_LINKER)
1410 case R_386_JUMP_SLOT:
1411 COUNT_RELOC(RELOC_ABSOLUTE);
1412 MARK(rel->r_offset);
1413 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1414 reloc, sym_addr, sym_name);
1415 *((unsigned*)reloc) = sym_addr;
1416 break;
1417 case R_386_GLOB_DAT:
1418 COUNT_RELOC(RELOC_ABSOLUTE);
1419 MARK(rel->r_offset);
1420 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1421 reloc, sym_addr, sym_name);
1422 *((unsigned*)reloc) = sym_addr;
1423 break;
1424#endif /* ANDROID_*_LINKER */
1425
1426#if defined(ANDROID_ARM_LINKER)
1427 case R_ARM_RELATIVE:
1428#elif defined(ANDROID_X86_LINKER)
1429 case R_386_RELATIVE:
1430#endif /* ANDROID_*_LINKER */
1431 COUNT_RELOC(RELOC_RELATIVE);
1432 MARK(rel->r_offset);
1433 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001434 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001435 return -1;
1436 }
1437 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1438 reloc, si->base);
1439 *((unsigned*)reloc) += si->base;
1440 break;
1441
1442#if defined(ANDROID_X86_LINKER)
1443 case R_386_32:
1444 COUNT_RELOC(RELOC_RELATIVE);
1445 MARK(rel->r_offset);
1446
1447 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1448 reloc, sym_addr, sym_name);
1449 *((unsigned *)reloc) += (unsigned)sym_addr;
1450 break;
1451
1452 case R_386_PC32:
1453 COUNT_RELOC(RELOC_RELATIVE);
1454 MARK(rel->r_offset);
1455 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1456 "+%08x (%08x - %08x) %s\n", pid, reloc,
1457 (sym_addr - reloc), sym_addr, reloc, sym_name);
1458 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1459 break;
1460#endif /* ANDROID_X86_LINKER */
1461
1462#ifdef ANDROID_ARM_LINKER
1463 case R_ARM_COPY:
1464 COUNT_RELOC(RELOC_COPY);
1465 MARK(rel->r_offset);
1466 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1467 reloc, s->st_size, sym_addr, sym_name);
1468 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1469 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001470 case R_ARM_NONE:
1471 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001472#endif /* ANDROID_ARM_LINKER */
1473
1474 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001475 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001476 pid, type, rel, (int) (rel - start));
1477 return -1;
1478 }
1479 rel++;
1480 }
1481 return 0;
1482}
1483
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001484#if defined(ANDROID_SH_LINKER)
1485static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1486{
1487 Elf32_Sym *symtab = si->symtab;
1488 const char *strtab = si->strtab;
1489 Elf32_Sym *s;
1490 unsigned base;
1491 Elf32_Rela *start = rela;
1492 unsigned idx;
1493
1494 for (idx = 0; idx < count; ++idx) {
1495 unsigned type = ELF32_R_TYPE(rela->r_info);
1496 unsigned sym = ELF32_R_SYM(rela->r_info);
1497 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1498 unsigned sym_addr = 0;
1499 char *sym_name = NULL;
1500
1501 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1502 si->name, idx);
1503 if(sym != 0) {
1504 sym_name = (char *)(strtab + symtab[sym].st_name);
1505 s = _do_lookup(si, sym_name, &base);
1506 if(s == 0) {
1507 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1508 return -1;
1509 }
1510#if 0
1511 if((base == 0) && (si->base != 0)){
1512 /* linking from libraries to main image is bad */
1513 DL_ERR("%5d cannot locate '%s'...",
1514 pid, strtab + symtab[sym].st_name);
1515 return -1;
1516 }
1517#endif
1518 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1519 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1520 "handle this yet", pid, si->name, s->st_shndx,
1521 s->st_value);
1522 return -1;
1523 }
1524 sym_addr = (unsigned)(s->st_value + base);
1525 COUNT_RELOC(RELOC_SYMBOL);
1526 } else {
1527 s = 0;
1528 }
1529
1530/* TODO: This is ugly. Split up the relocations by arch into
1531 * different files.
1532 */
1533 switch(type){
1534 case R_SH_JUMP_SLOT:
1535 COUNT_RELOC(RELOC_ABSOLUTE);
1536 MARK(rela->r_offset);
1537 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1538 reloc, sym_addr, sym_name);
1539 *((unsigned*)reloc) = sym_addr;
1540 break;
1541 case R_SH_GLOB_DAT:
1542 COUNT_RELOC(RELOC_ABSOLUTE);
1543 MARK(rela->r_offset);
1544 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1545 reloc, sym_addr, sym_name);
1546 *((unsigned*)reloc) = sym_addr;
1547 break;
1548 case R_SH_DIR32:
1549 COUNT_RELOC(RELOC_ABSOLUTE);
1550 MARK(rela->r_offset);
1551 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1552 reloc, sym_addr, sym_name);
1553 *((unsigned*)reloc) += sym_addr;
1554 break;
1555 case R_SH_RELATIVE:
1556 COUNT_RELOC(RELOC_RELATIVE);
1557 MARK(rela->r_offset);
1558 if(sym){
1559 DL_ERR("%5d odd RELATIVE form...", pid);
1560 return -1;
1561 }
1562 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1563 reloc, si->base);
1564 *((unsigned*)reloc) += si->base;
1565 break;
1566
1567 default:
1568 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1569 pid, type, rela, (int) (rela - start));
1570 return -1;
1571 }
1572 rela++;
1573 }
1574 return 0;
1575}
1576#endif /* ANDROID_SH_LINKER */
1577
David 'Digit' Turner82156792009-05-18 14:37:41 +02001578
1579/* Please read the "Initialization and Termination functions" functions.
1580 * of the linker design note in bionic/linker/README.TXT to understand
1581 * what the following code is doing.
1582 *
1583 * The important things to remember are:
1584 *
1585 * DT_PREINIT_ARRAY must be called first for executables, and should
1586 * not appear in shared libraries.
1587 *
1588 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1589 *
1590 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1591 *
1592 * DT_FINI_ARRAY must be parsed in reverse order.
1593 */
1594
1595static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001596{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001597 int n, inc = 1;
1598
1599 if (reverse) {
1600 ctor += (count-1);
1601 inc = -1;
1602 }
1603
1604 for(n = count; n > 0; n--) {
1605 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1606 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001607 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001608 void (*func)() = (void (*)()) *ctor;
1609 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001610 if(((int) func == 0) || ((int) func == -1)) continue;
1611 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1612 func();
1613 }
1614}
1615
1616static void call_constructors(soinfo *si)
1617{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001618 if (si->flags & FLAG_EXE) {
1619 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1620 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1621 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001622 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001623 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1624 } else {
1625 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001626 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001627 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001628 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001629 }
1630 }
1631
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001632 if (si->init_func) {
1633 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1634 (unsigned)si->init_func, si->name);
1635 si->init_func();
1636 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1637 }
1638
1639 if (si->init_array) {
1640 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1641 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001642 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001643 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1644 }
1645}
1646
David 'Digit' Turner82156792009-05-18 14:37:41 +02001647
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001648static void call_destructors(soinfo *si)
1649{
1650 if (si->fini_array) {
1651 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1652 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001653 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001654 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1655 }
1656
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001657 if (si->fini_func) {
1658 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1659 (unsigned)si->fini_func, si->name);
1660 si->fini_func();
1661 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1662 }
1663}
1664
1665/* Force any of the closed stdin, stdout and stderr to be associated with
1666 /dev/null. */
1667static int nullify_closed_stdio (void)
1668{
1669 int dev_null, i, status;
1670 int return_value = 0;
1671
1672 dev_null = open("/dev/null", O_RDWR);
1673 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001674 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001675 return -1;
1676 }
1677 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1678
1679 /* If any of the stdio file descriptors is valid and not associated
1680 with /dev/null, dup /dev/null to it. */
1681 for (i = 0; i < 3; i++) {
1682 /* If it is /dev/null already, we are done. */
1683 if (i == dev_null)
1684 continue;
1685
1686 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1687 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1688 can be interrupted but we do this just to be safe. */
1689 do {
1690 status = fcntl(i, F_GETFL);
1691 } while (status < 0 && errno == EINTR);
1692
1693 /* If file is openned, we are good. */
1694 if (status >= 0)
1695 continue;
1696
1697 /* The only error we allow is that the file descriptor does not
1698 exist, in which case we dup /dev/null to it. */
1699 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001700 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001701 return_value = -1;
1702 continue;
1703 }
1704
1705 /* Try dupping /dev/null to this stdio file descriptor and
1706 repeat if there is a signal. Note that any errors in closing
1707 the stdio descriptor are lost. */
1708 do {
1709 status = dup2(dev_null, i);
1710 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001711
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001712 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001713 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001714 return_value = -1;
1715 continue;
1716 }
1717 }
1718
1719 /* If /dev/null is not one of the stdio file descriptors, close it. */
1720 if (dev_null > 2) {
1721 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001722 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001723 status = close(dev_null);
1724 } while (status < 0 && errno == EINTR);
1725
1726 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001727 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001728 return_value = -1;
1729 }
1730 }
1731
1732 return return_value;
1733}
1734
1735static int link_image(soinfo *si, unsigned wr_offset)
1736{
1737 unsigned *d;
1738 Elf32_Phdr *phdr = si->phdr;
1739 int phnum = si->phnum;
1740
1741 INFO("[ %5d linking %s ]\n", pid, si->name);
1742 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1743 si->base, si->flags);
1744
1745 if (si->flags & FLAG_EXE) {
1746 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
1747 * linkage info if this is the executable. If this was a
1748 * dynamic lib, that would have been done at load time.
1749 *
1750 * TODO: It's unfortunate that small pieces of this are
1751 * repeated from the load_library routine. Refactor this just
1752 * slightly to reuse these bits.
1753 */
1754 si->size = 0;
1755 for(; phnum > 0; --phnum, ++phdr) {
1756#ifdef ANDROID_ARM_LINKER
1757 if(phdr->p_type == PT_ARM_EXIDX) {
1758 /* exidx entries (used for stack unwinding) are 8 bytes each.
1759 */
1760 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1761 si->ARM_exidx_count = phdr->p_memsz / 8;
1762 }
1763#endif
1764 if (phdr->p_type == PT_LOAD) {
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001765 /* For the executable, we use the si->size field only in
1766 dl_unwind_find_exidx(), so the meaning of si->size
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001767 is not the size of the executable; it is the distance
1768 between the load location of the executable and the last
1769 address of the loadable part of the executable.
1770 We use the range [si->base, si->base + si->size) to
1771 determine whether a PC value falls within the executable
1772 section. Of course, if a value is between si->base and
1773 (si->base + phdr->p_vaddr), it's not in the executable
1774 section, but a) we shouldn't be asking for such a value
1775 anyway, and b) if we have to provide an EXIDX for such a
1776 value, then the executable's EXIDX is probably the better
1777 choice.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001778 */
1779 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1780 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1781 si->size = phdr->p_vaddr + phdr->p_memsz;
1782 /* try to remember what range of addresses should be write
1783 * protected */
1784 if (!(phdr->p_flags & PF_W)) {
1785 unsigned _end;
1786
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001787 if (si->base + phdr->p_vaddr < si->wrprotect_start)
1788 si->wrprotect_start = si->base + phdr->p_vaddr;
1789 _end = (((si->base + phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001790 (~PAGE_MASK)));
1791 if (_end > si->wrprotect_end)
1792 si->wrprotect_end = _end;
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001793 /* Make the section writable just in case we'll have to
1794 * write to it during relocation (i.e. text segment).
1795 * However, we will remember what range of addresses
1796 * should be write protected.
1797 */
1798 mprotect((void *) (si->base + phdr->p_vaddr),
1799 phdr->p_memsz,
1800 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001801 }
1802 } else if (phdr->p_type == PT_DYNAMIC) {
1803 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001804 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001805 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001806 pid, si->name, si->base + phdr->p_vaddr,
1807 (unsigned)si->dynamic);
1808 goto fail;
1809 }
1810 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1811 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1812 }
1813 }
1814 }
1815
1816 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001817 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001818 goto fail;
1819 }
1820
1821 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1822
1823 /* extract useful information from dynamic section */
1824 for(d = si->dynamic; *d; d++){
1825 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1826 switch(*d++){
1827 case DT_HASH:
1828 si->nbucket = ((unsigned *) (si->base + *d))[0];
1829 si->nchain = ((unsigned *) (si->base + *d))[1];
1830 si->bucket = (unsigned *) (si->base + *d + 8);
1831 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1832 break;
1833 case DT_STRTAB:
1834 si->strtab = (const char *) (si->base + *d);
1835 break;
1836 case DT_SYMTAB:
1837 si->symtab = (Elf32_Sym *) (si->base + *d);
1838 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001839#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001840 case DT_PLTREL:
1841 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001842 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001843 goto fail;
1844 }
1845 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001846#endif
1847#ifdef ANDROID_SH_LINKER
1848 case DT_JMPREL:
1849 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1850 break;
1851 case DT_PLTRELSZ:
1852 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1853 break;
1854#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001855 case DT_JMPREL:
1856 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1857 break;
1858 case DT_PLTRELSZ:
1859 si->plt_rel_count = *d / 8;
1860 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001861#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001862 case DT_REL:
1863 si->rel = (Elf32_Rel*) (si->base + *d);
1864 break;
1865 case DT_RELSZ:
1866 si->rel_count = *d / 8;
1867 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001868#ifdef ANDROID_SH_LINKER
1869 case DT_RELASZ:
1870 si->rela_count = *d / sizeof(Elf32_Rela);
1871 break;
1872#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001873 case DT_PLTGOT:
1874 /* Save this in case we decide to do lazy binding. We don't yet. */
1875 si->plt_got = (unsigned *)(si->base + *d);
1876 break;
1877 case DT_DEBUG:
1878 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1879 *d = (int) &_r_debug;
1880 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001881#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001882 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001883 si->rela = (Elf32_Rela *) (si->base + *d);
1884 break;
1885#else
1886 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001887 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001888 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001889#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001890 case DT_INIT:
1891 si->init_func = (void (*)(void))(si->base + *d);
1892 DEBUG("%5d %s constructors (init func) found at %p\n",
1893 pid, si->name, si->init_func);
1894 break;
1895 case DT_FINI:
1896 si->fini_func = (void (*)(void))(si->base + *d);
1897 DEBUG("%5d %s destructors (fini func) found at %p\n",
1898 pid, si->name, si->fini_func);
1899 break;
1900 case DT_INIT_ARRAY:
1901 si->init_array = (unsigned *)(si->base + *d);
1902 DEBUG("%5d %s constructors (init_array) found at %p\n",
1903 pid, si->name, si->init_array);
1904 break;
1905 case DT_INIT_ARRAYSZ:
1906 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1907 break;
1908 case DT_FINI_ARRAY:
1909 si->fini_array = (unsigned *)(si->base + *d);
1910 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1911 pid, si->name, si->fini_array);
1912 break;
1913 case DT_FINI_ARRAYSZ:
1914 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1915 break;
1916 case DT_PREINIT_ARRAY:
1917 si->preinit_array = (unsigned *)(si->base + *d);
1918 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1919 pid, si->name, si->preinit_array);
1920 break;
1921 case DT_PREINIT_ARRAYSZ:
1922 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1923 break;
1924 case DT_TEXTREL:
1925 /* TODO: make use of this. */
1926 /* this means that we might have to write into where the text
1927 * segment was loaded during relocation... Do something with
1928 * it.
1929 */
1930 DEBUG("%5d Text segment should be writable during relocation.\n",
1931 pid);
1932 break;
1933 }
1934 }
1935
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001936 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001937 pid, si->base, si->strtab, si->symtab);
1938
1939 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001940 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001941 goto fail;
1942 }
1943
Matt Fischer4fd42c12009-12-31 12:09:10 -06001944 /* if this is the main executable, then load all of the preloads now */
1945 if(si->flags & FLAG_EXE) {
1946 int i;
1947 memset(preloads, 0, sizeof(preloads));
1948 for(i = 0; ldpreload_names[i] != NULL; i++) {
1949 soinfo *lsi = find_library(ldpreload_names[i]);
1950 if(lsi == 0) {
1951 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1952 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1953 pid, ldpreload_names[i], si->name, tmp_err_buf);
1954 goto fail;
1955 }
1956 lsi->refcount++;
1957 preloads[i] = lsi;
1958 }
1959 }
1960
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001961 for(d = si->dynamic; *d; d += 2) {
1962 if(d[0] == DT_NEEDED){
1963 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001964 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001965 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001966 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001967 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001968 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001969 goto fail;
1970 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001971 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1972 of the DT_NEEDED entry itself, so that we can retrieve the
1973 soinfo directly later from the dynamic segment. This is a hack,
1974 but it allows us to map from DT_NEEDED to soinfo efficiently
1975 later on when we resolve relocations, trying to look up a symgol
1976 with dlsym().
1977 */
1978 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001979 lsi->refcount++;
1980 }
1981 }
1982
1983 if(si->plt_rel) {
1984 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1985 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1986 goto fail;
1987 }
1988 if(si->rel) {
1989 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1990 if(reloc_library(si, si->rel, si->rel_count))
1991 goto fail;
1992 }
1993
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001994#ifdef ANDROID_SH_LINKER
1995 if(si->plt_rela) {
1996 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1997 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
1998 goto fail;
1999 }
2000 if(si->rela) {
2001 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
2002 if(reloc_library_a(si, si->rela, si->rela_count))
2003 goto fail;
2004 }
2005#endif /* ANDROID_SH_LINKER */
2006
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002007 si->flags |= FLAG_LINKED;
2008 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
2009
2010#if 0
2011 /* This is the way that the old dynamic linker did protection of
2012 * non-writable areas. It would scan section headers and find where
2013 * .text ended (rather where .data/.bss began) and assume that this is
2014 * the upper range of the non-writable area. This is too coarse,
2015 * and is kept here for reference until we fully move away from single
2016 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
2017 * that made this possible.
2018 */
2019 if(wr_offset < 0xffffffff){
2020 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
2021 }
2022#else
2023 /* TODO: Verify that this does the right thing in all cases, as it
2024 * presently probably does not. It is possible that an ELF image will
2025 * come with multiple read-only segments. What we ought to do is scan
2026 * the program headers again and mprotect all the read-only segments.
2027 * To prevent re-scanning the program header, we would have to build a
2028 * list of loadable segments in si, and then scan that instead. */
2029 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
2030 mprotect((void *)si->wrprotect_start,
2031 si->wrprotect_end - si->wrprotect_start,
2032 PROT_READ | PROT_EXEC);
2033 }
2034#endif
2035
2036 /* If this is a SET?ID program, dup /dev/null to opened stdin,
2037 stdout and stderr to close a security hole described in:
2038
2039 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
2040
2041 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002042 if (program_is_setuid)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002043 nullify_closed_stdio ();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002044 notify_gdb_of_load(si);
David 'Digit' Turnere5ea4552011-08-27 10:21:01 +02002045 call_constructors(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002046 return 0;
2047
2048fail:
Dima Zavina7161902010-08-17 15:56:40 -07002049 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002050 si->flags |= FLAG_ERROR;
2051 return -1;
2052}
2053
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002054static void parse_library_path(const char *path, char *delim)
David Bartleybc3a5c22009-06-02 18:27:28 -07002055{
2056 size_t len;
2057 char *ldpaths_bufp = ldpaths_buf;
2058 int i = 0;
2059
2060 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2061
2062 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2063 if (*ldpaths[i] != '\0')
2064 ++i;
2065 }
2066
2067 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2068 * last char isn't '\0' (i.e. not originally a delim). */
2069 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2070 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2071 ldpaths[i - 1] = NULL;
2072 } else {
2073 ldpaths[i] = NULL;
2074 }
2075}
2076
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002077static void parse_preloads(const char *path, char *delim)
Matt Fischer4fd42c12009-12-31 12:09:10 -06002078{
2079 size_t len;
2080 char *ldpreloads_bufp = ldpreloads_buf;
2081 int i = 0;
2082
2083 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2084
2085 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2086 if (*ldpreload_names[i] != '\0') {
2087 ++i;
2088 }
2089 }
2090
2091 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2092 * last char isn't '\0' (i.e. not originally a delim). */
2093 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2094 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2095 ldpreload_names[i - 1] = NULL;
2096 } else {
2097 ldpreload_names[i] = NULL;
2098 }
2099}
2100
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002101int main(int argc, char **argv)
2102{
2103 return 0;
2104}
2105
2106#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
2107
2108static void * __tls_area[ANDROID_TLS_SLOTS];
2109
Nick Kralevich994e9a52011-11-01 10:51:22 -07002110/*
2111 * This code is called after the linker has linked itself and
2112 * fixed it's own GOT. It is safe to make references to externs
2113 * and other non-local data at this point.
2114 */
2115static unsigned __linker_init_post_relocation(unsigned **elfdata)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002116{
2117 static soinfo linker_soinfo;
2118
2119 int argc = (int) *elfdata;
2120 char **argv = (char**) (elfdata + 1);
2121 unsigned *vecs = (unsigned*) (argv + argc + 1);
2122 soinfo *si;
2123 struct link_map * map;
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002124 const char *ldpath_env = NULL;
2125 const char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002126
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002127 /* Setup a temporary TLS area that is used to get a working
2128 * errno for system calls.
2129 */
2130 __set_tls(__tls_area);
2131
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002132 pid = getpid();
2133
2134#if TIMING
2135 struct timeval t0, t1;
2136 gettimeofday(&t0, 0);
2137#endif
2138
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002139 /* NOTE: we store the elfdata pointer on a special location
2140 * of the temporary TLS area in order to pass it to
2141 * the C Library's runtime initializer.
2142 *
2143 * The initializer must clear the slot and reset the TLS
2144 * to point to a different location to ensure that no other
2145 * shared library constructor can access it.
2146 */
2147 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002148
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002149 /* Are we setuid? */
2150 program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
2151
2152 /* Initialize environment functions, and get to the ELF aux vectors table */
2153 vecs = linker_env_init(vecs);
2154
2155 /* Sanitize environment if we're loading a setuid program */
2156 if (program_is_setuid)
2157 linker_env_secure();
2158
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002159 debugger_init();
2160
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002161 /* Get a few environment variables */
2162 {
2163 const char* env;
2164 env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
2165 if (env)
2166 debug_verbosity = atoi(env);
2167
2168 /* Normally, these are cleaned by linker_env_secure, but the test
2169 * against program_is_setuid doesn't cost us anything */
2170 if (!program_is_setuid) {
2171 ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2172 ldpreload_env = linker_env_get("LD_PRELOAD");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002173 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002174 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002175
2176 INFO("[ android linker & debugger ]\n");
2177 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2178
2179 si = alloc_info(argv[0]);
2180 if(si == 0) {
2181 exit(-1);
2182 }
2183
2184 /* bootstrap the link map, the main exe always needs to be first */
2185 si->flags |= FLAG_EXE;
2186 map = &(si->linkmap);
2187
2188 map->l_addr = 0;
2189 map->l_name = argv[0];
2190 map->l_prev = NULL;
2191 map->l_next = NULL;
2192
2193 _r_debug.r_map = map;
2194 r_debug_tail = map;
2195
2196 /* gdb expects the linker to be in the debug shared object list,
2197 * and we need to make sure that the reported load address is zero.
2198 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2199 * is. Don't use alloc_info(), because the linker shouldn't
2200 * be on the soinfo list.
2201 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002202 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002203 linker_soinfo.flags = 0;
2204 linker_soinfo.base = 0; // This is the important part; must be zero.
2205 insert_soinfo_into_debug_map(&linker_soinfo);
2206
2207 /* extract information passed from the kernel */
2208 while(vecs[0] != 0){
2209 switch(vecs[0]){
2210 case AT_PHDR:
2211 si->phdr = (Elf32_Phdr*) vecs[1];
2212 break;
2213 case AT_PHNUM:
2214 si->phnum = (int) vecs[1];
2215 break;
2216 case AT_ENTRY:
2217 si->entry = vecs[1];
2218 break;
2219 }
2220 vecs += 2;
2221 }
2222
Nick Kralevichd9ad6232011-10-20 14:57:56 -07002223 si->base = (Elf32_Addr) si->phdr - si->phdr->p_vaddr;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002224 si->dynamic = (unsigned *)-1;
2225 si->wrprotect_start = 0xffffffff;
2226 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002227 si->refcount = 1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002228
David Bartleybc3a5c22009-06-02 18:27:28 -07002229 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002230 if (ldpath_env)
David Bartleybc3a5c22009-06-02 18:27:28 -07002231 parse_library_path(ldpath_env, ":");
2232
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002233 if (ldpreload_env) {
Matt Fischer4fd42c12009-12-31 12:09:10 -06002234 parse_preloads(ldpreload_env, " :");
2235 }
2236
Dima Zavin2e855792009-05-20 18:28:09 -07002237 if(link_image(si, 0)) {
2238 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2239 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2240 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002241 exit(-1);
2242 }
2243
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002244#if ALLOW_SYMBOLS_FROM_MAIN
2245 /* Set somain after we've loaded all the libraries in order to prevent
2246 * linking of symbols back to the main image, which is not set up at that
2247 * point yet.
2248 */
2249 somain = si;
2250#endif
2251
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002252#if TIMING
2253 gettimeofday(&t1,NULL);
2254 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2255 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2256 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2257 ));
2258#endif
2259#if STATS
2260 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2261 linker_stats.reloc[RELOC_ABSOLUTE],
2262 linker_stats.reloc[RELOC_RELATIVE],
2263 linker_stats.reloc[RELOC_COPY],
2264 linker_stats.reloc[RELOC_SYMBOL]);
2265#endif
2266#if COUNT_PAGES
2267 {
2268 unsigned n;
2269 unsigned i;
2270 unsigned count = 0;
2271 for(n = 0; n < 4096; n++){
2272 if(bitmask[n]){
2273 unsigned x = bitmask[n];
2274 for(i = 0; i < 8; i++){
2275 if(x & 1) count++;
2276 x >>= 1;
2277 }
2278 }
2279 }
2280 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2281 }
2282#endif
2283
2284#if TIMING || STATS || COUNT_PAGES
2285 fflush(stdout);
2286#endif
2287
2288 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2289 si->entry);
2290 return si->entry;
2291}
Nick Kralevich994e9a52011-11-01 10:51:22 -07002292
2293/*
2294 * Find the value of AT_BASE passed to us by the kernel. This is the load
2295 * location of the linker.
2296 */
2297static unsigned find_linker_base(unsigned **elfdata) {
2298 int argc = (int) *elfdata;
2299 char **argv = (char**) (elfdata + 1);
2300 unsigned *vecs = (unsigned*) (argv + argc + 1);
2301 while (vecs[0] != 0) {
2302 vecs++;
2303 }
2304
2305 /* The end of the environment block is marked by two NULL pointers */
2306 vecs++;
2307
2308 while(vecs[0]) {
2309 if (vecs[0] == AT_BASE) {
2310 return vecs[1];
2311 }
2312 vecs += 2;
2313 }
2314
2315 return 0; // should never happen
2316}
2317
2318/*
2319 * This is the entry point for the linker, called from begin.S. This
2320 * method is responsible for fixing the linker's own relocations, and
2321 * then calling __linker_init_post_relocation().
2322 *
2323 * Because this method is called before the linker has fixed it's own
2324 * relocations, any attempt to reference an extern variable, extern
2325 * function, or other GOT reference will generate a segfault.
2326 */
2327unsigned __linker_init(unsigned **elfdata) {
2328 unsigned linker_addr = find_linker_base(elfdata);
2329 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
2330 Elf32_Phdr *phdr =
2331 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);
2332
2333 soinfo linker_so;
2334 memset(&linker_so, 0, sizeof(soinfo));
2335
2336 linker_so.base = linker_addr;
2337 linker_so.dynamic = (unsigned *) -1;
2338 linker_so.phdr = phdr;
2339 linker_so.phnum = elf_hdr->e_phnum;
2340 linker_so.flags |= FLAG_LINKER;
2341
2342 /*
2343 * Find the DYNAMIC section of the linker itself, so we can
2344 * fix our own relocations.
2345 */
2346 int i;
2347 for (i = 0; i < linker_so.phnum; i++) {
2348 if (phdr[i].p_type == PT_DYNAMIC) {
2349 linker_so.dynamic = (unsigned *)(linker_so.base + phdr[i].p_vaddr);
2350 break;
2351 }
2352 }
2353
2354 if ((linker_so.dynamic != (unsigned char*) -1)
2355 && link_image(&linker_so, 0)) {
2356 // It would be nice to print an error message, but if the linker
2357 // can't link itself, there's no guarantee that we'll be able to
2358 // call write() (because it involves a GOT reference).
2359 //
2360 // This situation should never occur unless the linker itself
2361 // is corrupt.
2362 exit(-1);
2363 }
2364
2365 // We have successfully fixed our own relocations. It's safe to run
2366 // the main part of the linker now.
2367 return __linker_init_post_relocation(elfdata);
2368}