blob: e9f4dc958d2d5a1a6e2fffe69be4361a8afbd401 [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 Kralevich468319c2011-11-11 15:53:17 -0800344 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 Kralevich468319c2011-11-11 15:53:17 -0800408/*
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 Kralevich468319c2011-11-11 15:53:17 -0800458 /* 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 Kralevich468319c2011-11-11 15:53:17 -0800477
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? */
Zhenghua Wang897815a2011-10-19 00:29:14 +0800733#ifdef ANDROID_ARM_LINKER
734 if (hdr->e_machine != EM_ARM) return -1;
735#elif defined(ANDROID_X86_LINKER)
736 if (hdr->e_machine != EM_386) return -1;
737#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800738 return 0;
739}
740
741
742/* get_lib_extents
743 * Retrieves the base (*base) address where the ELF object should be
744 * mapped and its overall memory size (*total_sz).
745 *
746 * Args:
747 * fd: Opened file descriptor for the library
748 * name: The name of the library
749 * _hdr: Pointer to the header page of the library
750 * total_sz: Total size of the memory that should be allocated for
751 * this library
752 *
753 * Returns:
754 * -1 if there was an error while trying to get the lib extents.
755 * The possible reasons are:
756 * - Could not determine if the library was prelinked.
757 * - The library provided is not a valid ELF object
758 * 0 if the library did not request a specific base offset (normal
759 * for non-prelinked libs)
760 * > 0 if the library requests a specific address to be mapped to.
761 * This indicates a pre-linked library.
762 */
763static unsigned
764get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
765{
766 unsigned req_base;
767 unsigned min_vaddr = 0xffffffff;
768 unsigned max_vaddr = 0;
769 unsigned char *_hdr = (unsigned char *)__hdr;
770 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
771 Elf32_Phdr *phdr;
772 int cnt;
773
774 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
775 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700776 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800777 return (unsigned)-1;
778 }
779
780 req_base = (unsigned) is_prelinked(fd, name);
781 if (req_base == (unsigned)-1)
782 return -1;
783 else if (req_base != 0) {
784 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
785 pid, name, req_base);
786 } else {
787 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
788 }
789
790 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
791
792 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
793 * get the range. */
794 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
795 if (phdr->p_type == PT_LOAD) {
796 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
797 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
798 if (phdr->p_vaddr < min_vaddr)
799 min_vaddr = phdr->p_vaddr;
800 }
801 }
802
803 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700804 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800805 return (unsigned)-1;
806 }
807
808 /* truncate min_vaddr down to page boundary */
809 min_vaddr &= ~PAGE_MASK;
810
811 /* round max_vaddr up to the next page */
812 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
813
814 *total_sz = (max_vaddr - min_vaddr);
815 return (unsigned)req_base;
816}
817
818/* alloc_mem_region
819 *
820 * This function reserves a chunk of memory to be used for mapping in
821 * the shared library. We reserve the entire memory region here, and
822 * then the rest of the linker will relocate the individual loadable
823 * segments into the correct locations within this memory range.
824 *
825 * Args:
826 * si->base: The requested base of the allocation. If 0, a sane one will be
827 * chosen in the range LIBBASE <= base < LIBLAST.
828 * si->size: The size of the allocation.
829 *
830 * Returns:
831 * -1 on failure, and 0 on success. On success, si->base will contain
832 * the virtual address at which the library will be mapped.
833 */
834
835static int reserve_mem_region(soinfo *si)
836{
837 void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
Chris Dearmandb4bce02011-03-10 10:48:14 -0800838 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800839 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700840 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700841 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800842 pid, (si->base ? "" : "non-"), si->name, si->base,
843 errno, strerror(errno));
844 return -1;
845 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700846 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700847 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800848 si->name, (unsigned)base, si->base);
849 munmap(base, si->size);
850 return -1;
851 }
852 return 0;
853}
854
855static int
856alloc_mem_region(soinfo *si)
857{
858 if (si->base) {
859 /* Attempt to mmap a prelinked library. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800860 return reserve_mem_region(si);
861 }
862
Shih-wei Liao48527c32011-07-17 12:32:43 -0700863 /* This is not a prelinked library, so we use the kernel's default
864 allocator.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800865 */
Shih-wei Liao48527c32011-07-17 12:32:43 -0700866
867 void *base = mmap(NULL, si->size, PROT_READ | PROT_EXEC,
868 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
869 if (base == MAP_FAILED) {
870 DL_ERR("%5d mmap of library '%s' failed: %d (%s)\n",
871 pid, si->name,
872 errno, strerror(errno));
873 goto err;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800874 }
Shih-wei Liao48527c32011-07-17 12:32:43 -0700875 si->base = (unsigned) base;
876 PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
877 pid, si->name, si->base);
878 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800879
880err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700881 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800882 pid, si->name);
883 return -1;
884}
885
886#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
887#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
888 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
889 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
890/* load_segments
891 *
892 * This function loads all the loadable (PT_LOAD) segments into memory
893 * at their appropriate memory offsets off the base address.
894 *
895 * Args:
896 * fd: Open file descriptor to the library to load.
897 * header: Pointer to a header page that contains the ELF header.
898 * This is needed since we haven't mapped in the real file yet.
899 * si: ptr to soinfo struct describing the shared object.
900 *
901 * Returns:
902 * 0 on success, -1 on failure.
903 */
904static int
905load_segments(int fd, void *header, soinfo *si)
906{
907 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
908 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
909 unsigned char *base = (unsigned char *)si->base;
910 int cnt;
911 unsigned len;
912 unsigned char *tmp;
913 unsigned char *pbase;
914 unsigned char *extra_base;
915 unsigned extra_len;
916 unsigned total_sz = 0;
917
918 si->wrprotect_start = 0xffffffff;
919 si->wrprotect_end = 0;
920
921 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
922 pid, si->name, (unsigned)si->base);
923 /* Now go through all the PT_LOAD segments and map them into memory
924 * at the appropriate locations. */
925 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
926 if (phdr->p_type == PT_LOAD) {
927 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
928 /* we want to map in the segment on a page boundary */
929 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
930 /* add the # of bytes we masked off above to the total length. */
931 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
932
933 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
934 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
935 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
936 pbase = mmap(tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
937 MAP_PRIVATE | MAP_FIXED, fd,
938 phdr->p_offset & (~PAGE_MASK));
939 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700940 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700941 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800942 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
943 goto fail;
944 }
945
946 /* If 'len' didn't end on page boundary, and it's a writable
947 * segment, zero-fill the rest. */
948 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
949 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
950
951 /* Check to see if we need to extend the map for this segment to
952 * cover the diff between filesz and memsz (i.e. for bss).
953 *
954 * base _+---------------------+ page boundary
955 * . .
956 * | |
957 * . .
958 * pbase _+---------------------+ page boundary
959 * | |
960 * . .
961 * base + p_vaddr _| |
962 * . \ \ .
963 * . | filesz | .
964 * pbase + len _| / | |
965 * <0 pad> . . .
966 * extra_base _+------------|--------+ page boundary
967 * / . . .
968 * | . . .
969 * | +------------|--------+ page boundary
970 * extra_len-> | | | |
971 * | . | memsz .
972 * | . | .
973 * \ _| / |
974 * . .
975 * | |
976 * _+---------------------+ page boundary
977 */
978 tmp = (unsigned char *)(((unsigned)pbase + len + PAGE_SIZE - 1) &
979 (~PAGE_MASK));
980 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
981 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
982 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
983 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
984 /* map in the extra page(s) as anonymous into the range.
985 * This is probably not necessary as we already mapped in
986 * the entire region previously, but we just want to be
987 * sure. This will also set the right flags on the region
988 * (though we can probably accomplish the same thing with
989 * mprotect).
990 */
991 extra_base = mmap((void *)tmp, extra_len,
992 PFLAGS_TO_PROT(phdr->p_flags),
993 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
994 -1, 0);
995 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700996 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700997 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800998 extra_len);
999 goto fail;
1000 }
1001 /* TODO: Check if we need to memset-0 this region.
1002 * Anonymous mappings are zero-filled copy-on-writes, so we
1003 * shouldn't need to. */
1004 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
1005 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
1006 extra_len);
1007 }
1008 /* set the len here to show the full extent of the segment we
1009 * just loaded, mostly for debugging */
1010 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
1011 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
1012 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
1013 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
1014 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
1015 total_sz += len;
1016 /* Make the section writable just in case we'll have to write to
1017 * it during relocation (i.e. text segment). However, we will
1018 * remember what range of addresses should be write protected.
1019 *
1020 */
1021 if (!(phdr->p_flags & PF_W)) {
1022 if ((unsigned)pbase < si->wrprotect_start)
1023 si->wrprotect_start = (unsigned)pbase;
1024 if (((unsigned)pbase + len) > si->wrprotect_end)
1025 si->wrprotect_end = (unsigned)pbase + len;
1026 mprotect(pbase, len,
1027 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1028 }
1029 } else if (phdr->p_type == PT_DYNAMIC) {
1030 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1031 /* this segment contains the dynamic linking information */
1032 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
1033 } else {
1034#ifdef ANDROID_ARM_LINKER
1035 if (phdr->p_type == PT_ARM_EXIDX) {
1036 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1037 /* exidx entries (used for stack unwinding) are 8 bytes each.
1038 */
1039 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1040 si->ARM_exidx_count = phdr->p_memsz / 8;
1041 }
1042#endif
1043 }
1044
1045 }
1046
1047 /* Sanity check */
1048 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001049 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001050 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001051 pid, total_sz, si->name, si->size);
1052 goto fail;
1053 }
1054
1055 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1056 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1057 (unsigned)si->base, si->size);
1058 return 0;
1059
1060fail:
1061 /* We can just blindly unmap the entire region even though some things
1062 * were mapped in originally with anonymous and others could have been
1063 * been mapped in from the file before we failed. The kernel will unmap
1064 * all the pages in the range, irrespective of how they got there.
1065 */
1066 munmap((void *)si->base, si->size);
1067 si->flags |= FLAG_ERROR;
1068 return -1;
1069}
1070
1071/* TODO: Implement this to take care of the fact that Android ARM
1072 * ELF objects shove everything into a single loadable segment that has the
1073 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1074 * non-writable.
1075 */
1076#if 0
1077static unsigned
1078get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1079{
1080 Elf32_Shdr *shdr_start;
1081 Elf32_Shdr *shdr;
1082 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1083 int cnt;
1084 unsigned wr_offset = 0xffffffff;
1085
1086 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1087 ehdr->e_shoff & (~PAGE_MASK));
1088 if (shdr_start == MAP_FAILED) {
1089 WARN("%5d - Could not read section header info from '%s'. Will not "
1090 "not be able to determine write-protect offset.\n", pid, name);
1091 return (unsigned)-1;
1092 }
1093
1094 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1095 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1096 (shdr->sh_addr < wr_offset)) {
1097 wr_offset = shdr->sh_addr;
1098 }
1099 }
1100
1101 munmap(shdr_start, shdr_sz);
1102 return wr_offset;
1103}
1104#endif
1105
1106static soinfo *
1107load_library(const char *name)
1108{
1109 int fd = open_library(name);
1110 int cnt;
1111 unsigned ext_sz;
1112 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001113 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001114 soinfo *si = NULL;
1115 Elf32_Ehdr *hdr;
1116
Dima Zavin2e855792009-05-20 18:28:09 -07001117 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001118 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001119 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001120 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001121
1122 /* We have to read the ELF header to figure out what to do with this image
1123 */
1124 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001125 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001126 goto fail;
1127 }
1128
1129 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001130 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001131 goto fail;
1132 }
1133
1134 /* Parse the ELF header and get the size of the memory footprint for
1135 * the library */
1136 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1137 if (req_base == (unsigned)-1)
1138 goto fail;
1139 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1140 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1141
1142 /* Now configure the soinfo struct where we'll store all of our data
1143 * for the ELF object. If the loading fails, we waste the entry, but
1144 * same thing would happen if we failed during linking. Configuring the
1145 * soinfo struct here is a lot more convenient.
1146 */
Erik Gillingfde86422009-07-28 20:28:19 -07001147 bname = strrchr(name, '/');
1148 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001149 if (si == NULL)
1150 goto fail;
1151
1152 /* Carve out a chunk of memory where we will map in the individual
1153 * segments */
1154 si->base = req_base;
1155 si->size = ext_sz;
1156 si->flags = 0;
1157 si->entry = 0;
1158 si->dynamic = (unsigned *)-1;
1159 if (alloc_mem_region(si) < 0)
1160 goto fail;
1161
1162 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1163 pid, name, (void *)si->base, (unsigned) ext_sz);
1164
1165 /* Now actually load the library's segments into right places in memory */
1166 if (load_segments(fd, &__header[0], si) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001167 goto fail;
1168 }
1169
1170 /* this might not be right. Technically, we don't even need this info
1171 * once we go through 'load_segments'. */
1172 hdr = (Elf32_Ehdr *)si->base;
1173 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1174 si->phnum = hdr->e_phnum;
1175 /**/
1176
1177 close(fd);
1178 return si;
1179
1180fail:
1181 if (si) free_info(si);
1182 close(fd);
1183 return NULL;
1184}
1185
1186static soinfo *
1187init_library(soinfo *si)
1188{
1189 unsigned wr_offset = 0xffffffff;
1190
1191 /* At this point we know that whatever is loaded @ base is a valid ELF
1192 * shared library whose segments are properly mapped in. */
1193 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1194 pid, si->base, si->size, si->name);
1195
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001196 if(link_image(si, wr_offset)) {
1197 /* We failed to link. However, we can only restore libbase
1198 ** if no additional libraries have moved it since we updated it.
1199 */
1200 munmap((void *)si->base, si->size);
1201 return NULL;
1202 }
1203
1204 return si;
1205}
1206
1207soinfo *find_library(const char *name)
1208{
1209 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001210 const char *bname;
1211
1212#if ALLOW_SYMBOLS_FROM_MAIN
1213 if (name == NULL)
1214 return somain;
1215#else
1216 if (name == NULL)
1217 return NULL;
1218#endif
1219
1220 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001221 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001222
1223 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001224 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001225 if(si->flags & FLAG_ERROR) {
1226 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1227 return NULL;
1228 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001229 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001230 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001231 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001232 }
1233 }
1234
1235 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1236 si = load_library(name);
1237 if(si == NULL)
1238 return NULL;
1239 return init_library(si);
1240}
1241
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001242/* TODO:
1243 * notify gdb of unload
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244 * for non-prelinked libraries, find a way to decrement libbase
1245 */
1246static void call_destructors(soinfo *si);
1247unsigned unload_library(soinfo *si)
1248{
1249 unsigned *d;
1250 if (si->refcount == 1) {
1251 TRACE("%5d unloading '%s'\n", pid, si->name);
1252 call_destructors(si);
1253
1254 for(d = si->dynamic; *d; d += 2) {
1255 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001256 soinfo *lsi = (soinfo *)d[1];
1257 d[1] = 0;
1258 if (validate_soinfo(lsi)) {
1259 TRACE("%5d %s needs to unload %s\n", pid,
1260 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001261 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001262 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001263 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001264 DL_ERR("%5d %s: could not unload dependent library",
1265 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001266 }
1267 }
1268
1269 munmap((char *)si->base, si->size);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001270 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001271 free_info(si);
1272 si->refcount = 0;
1273 }
1274 else {
1275 si->refcount--;
1276 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1277 pid, si->name, si->refcount);
1278 }
1279 return si->refcount;
1280}
1281
1282/* TODO: don't use unsigned for addrs below. It works, but is not
1283 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1284 * long.
1285 */
1286static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1287{
1288 Elf32_Sym *symtab = si->symtab;
1289 const char *strtab = si->strtab;
1290 Elf32_Sym *s;
1291 unsigned base;
1292 Elf32_Rel *start = rel;
1293 unsigned idx;
1294
1295 for (idx = 0; idx < count; ++idx) {
1296 unsigned type = ELF32_R_TYPE(rel->r_info);
1297 unsigned sym = ELF32_R_SYM(rel->r_info);
1298 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1299 unsigned sym_addr = 0;
1300 char *sym_name = NULL;
1301
1302 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1303 si->name, idx);
1304 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001305 sym_name = (char *)(strtab + symtab[sym].st_name);
1306 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001307 if(s == NULL) {
1308 /* We only allow an undefined symbol if this is a weak
1309 reference.. */
1310 s = &symtab[sym];
1311 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1312 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1313 return -1;
1314 }
1315
1316 /* IHI0044C AAELF 4.5.1.1:
1317
1318 Libraries are not searched to resolve weak references.
1319 It is not an error for a weak reference to remain
1320 unsatisfied.
1321
1322 During linking, the value of an undefined weak reference is:
1323 - Zero if the relocation type is absolute
1324 - The address of the place if the relocation is pc-relative
1325 - The address of nominial base address if the relocation
1326 type is base-relative.
1327 */
1328
1329 switch (type) {
1330#if defined(ANDROID_ARM_LINKER)
1331 case R_ARM_JUMP_SLOT:
1332 case R_ARM_GLOB_DAT:
1333 case R_ARM_ABS32:
1334 case R_ARM_RELATIVE: /* Don't care. */
1335 case R_ARM_NONE: /* Don't care. */
1336#elif defined(ANDROID_X86_LINKER)
1337 case R_386_JUMP_SLOT:
1338 case R_386_GLOB_DAT:
1339 case R_386_32:
1340 case R_386_RELATIVE: /* Dont' care. */
1341#endif /* ANDROID_*_LINKER */
1342 /* sym_addr was initialized to be zero above or relocation
1343 code below does not care about value of sym_addr.
1344 No need to do anything. */
1345 break;
1346
1347#if defined(ANDROID_X86_LINKER)
1348 case R_386_PC32:
1349 sym_addr = reloc;
1350 break;
1351#endif /* ANDROID_X86_LINKER */
1352
1353#if defined(ANDROID_ARM_LINKER)
1354 case R_ARM_COPY:
1355 /* Fall through. Can't really copy if weak symbol is
1356 not found in run-time. */
1357#endif /* ANDROID_ARM_LINKER */
1358 default:
1359 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1360 pid, type, rel, (int) (rel - start));
1361 return -1;
1362 }
1363 } else {
1364 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001365#if 0
1366 if((base == 0) && (si->base != 0)){
1367 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001368 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001369 pid, strtab + symtab[sym].st_name);
1370 return -1;
1371 }
1372#endif
Doug Kwane8238072009-10-26 12:05:23 -07001373 sym_addr = (unsigned)(s->st_value + base);
1374 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001375 COUNT_RELOC(RELOC_SYMBOL);
1376 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001377 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001378 }
1379
1380/* TODO: This is ugly. Split up the relocations by arch into
1381 * different files.
1382 */
1383 switch(type){
1384#if defined(ANDROID_ARM_LINKER)
1385 case R_ARM_JUMP_SLOT:
1386 COUNT_RELOC(RELOC_ABSOLUTE);
1387 MARK(rel->r_offset);
1388 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1389 reloc, sym_addr, sym_name);
1390 *((unsigned*)reloc) = sym_addr;
1391 break;
1392 case R_ARM_GLOB_DAT:
1393 COUNT_RELOC(RELOC_ABSOLUTE);
1394 MARK(rel->r_offset);
1395 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1396 reloc, sym_addr, sym_name);
1397 *((unsigned*)reloc) = sym_addr;
1398 break;
1399 case R_ARM_ABS32:
1400 COUNT_RELOC(RELOC_ABSOLUTE);
1401 MARK(rel->r_offset);
1402 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1403 reloc, sym_addr, sym_name);
1404 *((unsigned*)reloc) += sym_addr;
1405 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001406 case R_ARM_REL32:
1407 COUNT_RELOC(RELOC_RELATIVE);
1408 MARK(rel->r_offset);
1409 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1410 reloc, sym_addr, rel->r_offset, sym_name);
1411 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1412 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001413#elif defined(ANDROID_X86_LINKER)
1414 case R_386_JUMP_SLOT:
1415 COUNT_RELOC(RELOC_ABSOLUTE);
1416 MARK(rel->r_offset);
1417 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1418 reloc, sym_addr, sym_name);
1419 *((unsigned*)reloc) = sym_addr;
1420 break;
1421 case R_386_GLOB_DAT:
1422 COUNT_RELOC(RELOC_ABSOLUTE);
1423 MARK(rel->r_offset);
1424 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1425 reloc, sym_addr, sym_name);
1426 *((unsigned*)reloc) = sym_addr;
1427 break;
1428#endif /* ANDROID_*_LINKER */
1429
1430#if defined(ANDROID_ARM_LINKER)
1431 case R_ARM_RELATIVE:
1432#elif defined(ANDROID_X86_LINKER)
1433 case R_386_RELATIVE:
1434#endif /* ANDROID_*_LINKER */
1435 COUNT_RELOC(RELOC_RELATIVE);
1436 MARK(rel->r_offset);
1437 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001438 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001439 return -1;
1440 }
1441 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1442 reloc, si->base);
1443 *((unsigned*)reloc) += si->base;
1444 break;
1445
1446#if defined(ANDROID_X86_LINKER)
1447 case R_386_32:
1448 COUNT_RELOC(RELOC_RELATIVE);
1449 MARK(rel->r_offset);
1450
1451 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1452 reloc, sym_addr, sym_name);
1453 *((unsigned *)reloc) += (unsigned)sym_addr;
1454 break;
1455
1456 case R_386_PC32:
1457 COUNT_RELOC(RELOC_RELATIVE);
1458 MARK(rel->r_offset);
1459 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1460 "+%08x (%08x - %08x) %s\n", pid, reloc,
1461 (sym_addr - reloc), sym_addr, reloc, sym_name);
1462 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1463 break;
1464#endif /* ANDROID_X86_LINKER */
1465
1466#ifdef ANDROID_ARM_LINKER
1467 case R_ARM_COPY:
1468 COUNT_RELOC(RELOC_COPY);
1469 MARK(rel->r_offset);
1470 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1471 reloc, s->st_size, sym_addr, sym_name);
1472 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1473 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001474 case R_ARM_NONE:
1475 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001476#endif /* ANDROID_ARM_LINKER */
1477
1478 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001479 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001480 pid, type, rel, (int) (rel - start));
1481 return -1;
1482 }
1483 rel++;
1484 }
1485 return 0;
1486}
1487
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001488#if defined(ANDROID_SH_LINKER)
1489static int reloc_library_a(soinfo *si, Elf32_Rela *rela, unsigned count)
1490{
1491 Elf32_Sym *symtab = si->symtab;
1492 const char *strtab = si->strtab;
1493 Elf32_Sym *s;
1494 unsigned base;
1495 Elf32_Rela *start = rela;
1496 unsigned idx;
1497
1498 for (idx = 0; idx < count; ++idx) {
1499 unsigned type = ELF32_R_TYPE(rela->r_info);
1500 unsigned sym = ELF32_R_SYM(rela->r_info);
1501 unsigned reloc = (unsigned)(rela->r_offset + si->base);
1502 unsigned sym_addr = 0;
1503 char *sym_name = NULL;
1504
1505 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1506 si->name, idx);
1507 if(sym != 0) {
1508 sym_name = (char *)(strtab + symtab[sym].st_name);
1509 s = _do_lookup(si, sym_name, &base);
1510 if(s == 0) {
1511 DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
1512 return -1;
1513 }
1514#if 0
1515 if((base == 0) && (si->base != 0)){
1516 /* linking from libraries to main image is bad */
1517 DL_ERR("%5d cannot locate '%s'...",
1518 pid, strtab + symtab[sym].st_name);
1519 return -1;
1520 }
1521#endif
1522 if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
1523 DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
1524 "handle this yet", pid, si->name, s->st_shndx,
1525 s->st_value);
1526 return -1;
1527 }
1528 sym_addr = (unsigned)(s->st_value + base);
1529 COUNT_RELOC(RELOC_SYMBOL);
1530 } else {
1531 s = 0;
1532 }
1533
1534/* TODO: This is ugly. Split up the relocations by arch into
1535 * different files.
1536 */
1537 switch(type){
1538 case R_SH_JUMP_SLOT:
1539 COUNT_RELOC(RELOC_ABSOLUTE);
1540 MARK(rela->r_offset);
1541 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1542 reloc, sym_addr, sym_name);
1543 *((unsigned*)reloc) = sym_addr;
1544 break;
1545 case R_SH_GLOB_DAT:
1546 COUNT_RELOC(RELOC_ABSOLUTE);
1547 MARK(rela->r_offset);
1548 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1549 reloc, sym_addr, sym_name);
1550 *((unsigned*)reloc) = sym_addr;
1551 break;
1552 case R_SH_DIR32:
1553 COUNT_RELOC(RELOC_ABSOLUTE);
1554 MARK(rela->r_offset);
1555 TRACE_TYPE(RELO, "%5d RELO DIR32 %08x <- %08x %s\n", pid,
1556 reloc, sym_addr, sym_name);
1557 *((unsigned*)reloc) += sym_addr;
1558 break;
1559 case R_SH_RELATIVE:
1560 COUNT_RELOC(RELOC_RELATIVE);
1561 MARK(rela->r_offset);
1562 if(sym){
1563 DL_ERR("%5d odd RELATIVE form...", pid);
1564 return -1;
1565 }
1566 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1567 reloc, si->base);
1568 *((unsigned*)reloc) += si->base;
1569 break;
1570
1571 default:
1572 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
1573 pid, type, rela, (int) (rela - start));
1574 return -1;
1575 }
1576 rela++;
1577 }
1578 return 0;
1579}
1580#endif /* ANDROID_SH_LINKER */
1581
David 'Digit' Turner82156792009-05-18 14:37:41 +02001582
1583/* Please read the "Initialization and Termination functions" functions.
1584 * of the linker design note in bionic/linker/README.TXT to understand
1585 * what the following code is doing.
1586 *
1587 * The important things to remember are:
1588 *
1589 * DT_PREINIT_ARRAY must be called first for executables, and should
1590 * not appear in shared libraries.
1591 *
1592 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1593 *
1594 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1595 *
1596 * DT_FINI_ARRAY must be parsed in reverse order.
1597 */
1598
1599static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001600{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001601 int n, inc = 1;
1602
1603 if (reverse) {
1604 ctor += (count-1);
1605 inc = -1;
1606 }
1607
1608 for(n = count; n > 0; n--) {
1609 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1610 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001611 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001612 void (*func)() = (void (*)()) *ctor;
1613 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001614 if(((int) func == 0) || ((int) func == -1)) continue;
1615 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1616 func();
1617 }
1618}
1619
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001620void call_constructors_recursive(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001621{
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001622 if (si->constructors_called)
1623 return;
1624
Jesse Hallf5d16932012-01-30 15:39:57 -08001625 // Set this before actually calling the constructors, otherwise it doesn't
1626 // protect against recursive constructor calls. One simple example of
1627 // constructor recursion is the libc debug malloc, which is implemented in
1628 // libc_malloc_debug_leak.so:
1629 // 1. The program depends on libc, so libc's constructor is called here.
1630 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
1631 // 3. dlopen() calls call_constructors_recursive() with the newly created
1632 // soinfo for libc_malloc_debug_leak.so.
1633 // 4. The debug so depends on libc, so call_constructors_recursive() is
1634 // called again with the libc soinfo. If it doesn't trigger the early-
1635 // out above, the libc constructor will be called again (recursively!).
1636 si->constructors_called = 1;
1637
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001638 if (si->flags & FLAG_EXE) {
1639 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1640 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1641 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001642 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001643 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1644 } else {
1645 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001646 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001647 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001648 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001649 }
1650 }
1651
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001652 if (si->dynamic) {
1653 unsigned *d;
1654 for(d = si->dynamic; *d; d += 2) {
1655 if(d[0] == DT_NEEDED){
1656 soinfo* lsi = (soinfo *)d[1];
1657 if (!validate_soinfo(lsi)) {
1658 DL_ERR("%5d bad DT_NEEDED pointer in %s",
1659 pid, si->name);
1660 } else {
1661 call_constructors_recursive(lsi);
1662 }
1663 }
1664 }
1665 }
1666
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001667 if (si->init_func) {
1668 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1669 (unsigned)si->init_func, si->name);
1670 si->init_func();
1671 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1672 }
1673
1674 if (si->init_array) {
1675 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1676 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001677 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001678 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1679 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001680
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001681}
David 'Digit' Turner82156792009-05-18 14:37:41 +02001682
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001683static void call_destructors(soinfo *si)
1684{
1685 if (si->fini_array) {
1686 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1687 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001688 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001689 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1690 }
1691
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001692 if (si->fini_func) {
1693 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1694 (unsigned)si->fini_func, si->name);
1695 si->fini_func();
1696 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1697 }
1698}
1699
1700/* Force any of the closed stdin, stdout and stderr to be associated with
1701 /dev/null. */
1702static int nullify_closed_stdio (void)
1703{
1704 int dev_null, i, status;
1705 int return_value = 0;
1706
1707 dev_null = open("/dev/null", O_RDWR);
1708 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001709 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001710 return -1;
1711 }
1712 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1713
1714 /* If any of the stdio file descriptors is valid and not associated
1715 with /dev/null, dup /dev/null to it. */
1716 for (i = 0; i < 3; i++) {
1717 /* If it is /dev/null already, we are done. */
1718 if (i == dev_null)
1719 continue;
1720
1721 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1722 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1723 can be interrupted but we do this just to be safe. */
1724 do {
1725 status = fcntl(i, F_GETFL);
1726 } while (status < 0 && errno == EINTR);
1727
1728 /* If file is openned, we are good. */
1729 if (status >= 0)
1730 continue;
1731
1732 /* The only error we allow is that the file descriptor does not
1733 exist, in which case we dup /dev/null to it. */
1734 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001735 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001736 return_value = -1;
1737 continue;
1738 }
1739
1740 /* Try dupping /dev/null to this stdio file descriptor and
1741 repeat if there is a signal. Note that any errors in closing
1742 the stdio descriptor are lost. */
1743 do {
1744 status = dup2(dev_null, i);
1745 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001746
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001747 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001748 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001749 return_value = -1;
1750 continue;
1751 }
1752 }
1753
1754 /* If /dev/null is not one of the stdio file descriptors, close it. */
1755 if (dev_null > 2) {
1756 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001757 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001758 status = close(dev_null);
1759 } while (status < 0 && errno == EINTR);
1760
1761 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001762 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001763 return_value = -1;
1764 }
1765 }
1766
1767 return return_value;
1768}
1769
1770static int link_image(soinfo *si, unsigned wr_offset)
1771{
1772 unsigned *d;
1773 Elf32_Phdr *phdr = si->phdr;
1774 int phnum = si->phnum;
1775
1776 INFO("[ %5d linking %s ]\n", pid, si->name);
1777 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1778 si->base, si->flags);
1779
Nick Kralevich468319c2011-11-11 15:53:17 -08001780 if (si->flags & (FLAG_EXE | FLAG_LINKER)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001781 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
Nick Kralevich468319c2011-11-11 15:53:17 -08001782 * linkage info if this is the executable or the linker itself.
1783 * If this was a dynamic lib, that would have been done at load time.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001784 *
1785 * TODO: It's unfortunate that small pieces of this are
1786 * repeated from the load_library routine. Refactor this just
1787 * slightly to reuse these bits.
1788 */
1789 si->size = 0;
1790 for(; phnum > 0; --phnum, ++phdr) {
1791#ifdef ANDROID_ARM_LINKER
1792 if(phdr->p_type == PT_ARM_EXIDX) {
1793 /* exidx entries (used for stack unwinding) are 8 bytes each.
1794 */
1795 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1796 si->ARM_exidx_count = phdr->p_memsz / 8;
1797 }
1798#endif
1799 if (phdr->p_type == PT_LOAD) {
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001800 /* For the executable, we use the si->size field only in
1801 dl_unwind_find_exidx(), so the meaning of si->size
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001802 is not the size of the executable; it is the distance
1803 between the load location of the executable and the last
1804 address of the loadable part of the executable.
1805 We use the range [si->base, si->base + si->size) to
1806 determine whether a PC value falls within the executable
1807 section. Of course, if a value is between si->base and
1808 (si->base + phdr->p_vaddr), it's not in the executable
1809 section, but a) we shouldn't be asking for such a value
1810 anyway, and b) if we have to provide an EXIDX for such a
1811 value, then the executable's EXIDX is probably the better
1812 choice.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001813 */
1814 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1815 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1816 si->size = phdr->p_vaddr + phdr->p_memsz;
1817 /* try to remember what range of addresses should be write
1818 * protected */
1819 if (!(phdr->p_flags & PF_W)) {
1820 unsigned _end;
1821
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001822 if (si->base + phdr->p_vaddr < si->wrprotect_start)
1823 si->wrprotect_start = si->base + phdr->p_vaddr;
1824 _end = (((si->base + phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001825 (~PAGE_MASK)));
1826 if (_end > si->wrprotect_end)
1827 si->wrprotect_end = _end;
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001828 /* Make the section writable just in case we'll have to
1829 * write to it during relocation (i.e. text segment).
1830 * However, we will remember what range of addresses
1831 * should be write protected.
1832 */
1833 mprotect((void *) (si->base + phdr->p_vaddr),
1834 phdr->p_memsz,
1835 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001836 }
1837 } else if (phdr->p_type == PT_DYNAMIC) {
1838 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001839 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001840 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001841 pid, si->name, si->base + phdr->p_vaddr,
1842 (unsigned)si->dynamic);
1843 goto fail;
1844 }
1845 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1846 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
1847 }
1848 }
1849 }
1850
1851 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001852 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001853 goto fail;
1854 }
1855
1856 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1857
1858 /* extract useful information from dynamic section */
1859 for(d = si->dynamic; *d; d++){
1860 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1861 switch(*d++){
1862 case DT_HASH:
1863 si->nbucket = ((unsigned *) (si->base + *d))[0];
1864 si->nchain = ((unsigned *) (si->base + *d))[1];
1865 si->bucket = (unsigned *) (si->base + *d + 8);
1866 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1867 break;
1868 case DT_STRTAB:
1869 si->strtab = (const char *) (si->base + *d);
1870 break;
1871 case DT_SYMTAB:
1872 si->symtab = (Elf32_Sym *) (si->base + *d);
1873 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001874#if !defined(ANDROID_SH_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001875 case DT_PLTREL:
1876 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001877 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001878 goto fail;
1879 }
1880 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001881#endif
1882#ifdef ANDROID_SH_LINKER
1883 case DT_JMPREL:
1884 si->plt_rela = (Elf32_Rela*) (si->base + *d);
1885 break;
1886 case DT_PLTRELSZ:
1887 si->plt_rela_count = *d / sizeof(Elf32_Rela);
1888 break;
1889#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001890 case DT_JMPREL:
1891 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1892 break;
1893 case DT_PLTRELSZ:
1894 si->plt_rel_count = *d / 8;
1895 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001896#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001897 case DT_REL:
1898 si->rel = (Elf32_Rel*) (si->base + *d);
1899 break;
1900 case DT_RELSZ:
1901 si->rel_count = *d / 8;
1902 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001903#ifdef ANDROID_SH_LINKER
1904 case DT_RELASZ:
1905 si->rela_count = *d / sizeof(Elf32_Rela);
1906 break;
1907#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001908 case DT_PLTGOT:
1909 /* Save this in case we decide to do lazy binding. We don't yet. */
1910 si->plt_got = (unsigned *)(si->base + *d);
1911 break;
1912 case DT_DEBUG:
1913 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1914 *d = (int) &_r_debug;
1915 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001916#ifdef ANDROID_SH_LINKER
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001917 case DT_RELA:
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001918 si->rela = (Elf32_Rela *) (si->base + *d);
1919 break;
1920#else
1921 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001922 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001923 goto fail;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001924#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001925 case DT_INIT:
1926 si->init_func = (void (*)(void))(si->base + *d);
1927 DEBUG("%5d %s constructors (init func) found at %p\n",
1928 pid, si->name, si->init_func);
1929 break;
1930 case DT_FINI:
1931 si->fini_func = (void (*)(void))(si->base + *d);
1932 DEBUG("%5d %s destructors (fini func) found at %p\n",
1933 pid, si->name, si->fini_func);
1934 break;
1935 case DT_INIT_ARRAY:
1936 si->init_array = (unsigned *)(si->base + *d);
1937 DEBUG("%5d %s constructors (init_array) found at %p\n",
1938 pid, si->name, si->init_array);
1939 break;
1940 case DT_INIT_ARRAYSZ:
1941 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1942 break;
1943 case DT_FINI_ARRAY:
1944 si->fini_array = (unsigned *)(si->base + *d);
1945 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1946 pid, si->name, si->fini_array);
1947 break;
1948 case DT_FINI_ARRAYSZ:
1949 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1950 break;
1951 case DT_PREINIT_ARRAY:
1952 si->preinit_array = (unsigned *)(si->base + *d);
1953 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1954 pid, si->name, si->preinit_array);
1955 break;
1956 case DT_PREINIT_ARRAYSZ:
1957 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1958 break;
1959 case DT_TEXTREL:
1960 /* TODO: make use of this. */
1961 /* this means that we might have to write into where the text
1962 * segment was loaded during relocation... Do something with
1963 * it.
1964 */
1965 DEBUG("%5d Text segment should be writable during relocation.\n",
1966 pid);
1967 break;
1968 }
1969 }
1970
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001971 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001972 pid, si->base, si->strtab, si->symtab);
1973
1974 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001975 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001976 goto fail;
1977 }
1978
Matt Fischer4fd42c12009-12-31 12:09:10 -06001979 /* if this is the main executable, then load all of the preloads now */
1980 if(si->flags & FLAG_EXE) {
1981 int i;
1982 memset(preloads, 0, sizeof(preloads));
1983 for(i = 0; ldpreload_names[i] != NULL; i++) {
1984 soinfo *lsi = find_library(ldpreload_names[i]);
1985 if(lsi == 0) {
1986 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1987 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1988 pid, ldpreload_names[i], si->name, tmp_err_buf);
1989 goto fail;
1990 }
1991 lsi->refcount++;
1992 preloads[i] = lsi;
1993 }
1994 }
1995
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001996 for(d = si->dynamic; *d; d += 2) {
1997 if(d[0] == DT_NEEDED){
1998 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001999 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002000 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07002001 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07002002 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07002003 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002004 goto fail;
2005 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07002006 /* Save the soinfo of the loaded DT_NEEDED library in the payload
2007 of the DT_NEEDED entry itself, so that we can retrieve the
2008 soinfo directly later from the dynamic segment. This is a hack,
2009 but it allows us to map from DT_NEEDED to soinfo efficiently
2010 later on when we resolve relocations, trying to look up a symgol
2011 with dlsym().
2012 */
2013 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002014 lsi->refcount++;
2015 }
2016 }
2017
2018 if(si->plt_rel) {
2019 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
2020 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
2021 goto fail;
2022 }
2023 if(si->rel) {
2024 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
2025 if(reloc_library(si, si->rel, si->rel_count))
2026 goto fail;
2027 }
2028
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09002029#ifdef ANDROID_SH_LINKER
2030 if(si->plt_rela) {
2031 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
2032 if(reloc_library_a(si, si->plt_rela, si->plt_rela_count))
2033 goto fail;
2034 }
2035 if(si->rela) {
2036 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
2037 if(reloc_library_a(si, si->rela, si->rela_count))
2038 goto fail;
2039 }
2040#endif /* ANDROID_SH_LINKER */
2041
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002042 si->flags |= FLAG_LINKED;
2043 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
2044
2045#if 0
2046 /* This is the way that the old dynamic linker did protection of
2047 * non-writable areas. It would scan section headers and find where
2048 * .text ended (rather where .data/.bss began) and assume that this is
2049 * the upper range of the non-writable area. This is too coarse,
2050 * and is kept here for reference until we fully move away from single
2051 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
2052 * that made this possible.
2053 */
2054 if(wr_offset < 0xffffffff){
2055 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
2056 }
2057#else
2058 /* TODO: Verify that this does the right thing in all cases, as it
2059 * presently probably does not. It is possible that an ELF image will
2060 * come with multiple read-only segments. What we ought to do is scan
2061 * the program headers again and mprotect all the read-only segments.
2062 * To prevent re-scanning the program header, we would have to build a
2063 * list of loadable segments in si, and then scan that instead. */
2064 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
2065 mprotect((void *)si->wrprotect_start,
2066 si->wrprotect_end - si->wrprotect_start,
2067 PROT_READ | PROT_EXEC);
2068 }
2069#endif
2070
2071 /* If this is a SET?ID program, dup /dev/null to opened stdin,
2072 stdout and stderr to close a security hole described in:
2073
2074 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
2075
2076 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002077 if (program_is_setuid)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002078 nullify_closed_stdio ();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002079 notify_gdb_of_load(si);
2080 return 0;
2081
2082fail:
Dima Zavina7161902010-08-17 15:56:40 -07002083 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002084 si->flags |= FLAG_ERROR;
2085 return -1;
2086}
2087
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002088static void parse_library_path(const char *path, char *delim)
David Bartleybc3a5c22009-06-02 18:27:28 -07002089{
2090 size_t len;
2091 char *ldpaths_bufp = ldpaths_buf;
2092 int i = 0;
2093
2094 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2095
2096 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2097 if (*ldpaths[i] != '\0')
2098 ++i;
2099 }
2100
2101 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2102 * last char isn't '\0' (i.e. not originally a delim). */
2103 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2104 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2105 ldpaths[i - 1] = NULL;
2106 } else {
2107 ldpaths[i] = NULL;
2108 }
2109}
2110
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002111static void parse_preloads(const char *path, char *delim)
Matt Fischer4fd42c12009-12-31 12:09:10 -06002112{
2113 size_t len;
2114 char *ldpreloads_bufp = ldpreloads_buf;
2115 int i = 0;
2116
2117 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2118
2119 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2120 if (*ldpreload_names[i] != '\0') {
2121 ++i;
2122 }
2123 }
2124
2125 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2126 * last char isn't '\0' (i.e. not originally a delim). */
2127 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2128 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2129 ldpreload_names[i - 1] = NULL;
2130 } else {
2131 ldpreload_names[i] = NULL;
2132 }
2133}
2134
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002135#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
2136
2137static void * __tls_area[ANDROID_TLS_SLOTS];
2138
Nick Kralevich468319c2011-11-11 15:53:17 -08002139/*
2140 * This code is called after the linker has linked itself and
2141 * fixed it's own GOT. It is safe to make references to externs
2142 * and other non-local data at this point.
2143 */
2144static unsigned __linker_init_post_relocation(unsigned **elfdata)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002145{
2146 static soinfo linker_soinfo;
2147
2148 int argc = (int) *elfdata;
2149 char **argv = (char**) (elfdata + 1);
Stephen Smalleybb440552012-01-20 10:59:15 -08002150 unsigned *vecs = (unsigned*) (argv + argc + 1);
2151 unsigned *v;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002152 soinfo *si;
2153 struct link_map * map;
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002154 const char *ldpath_env = NULL;
2155 const char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002156
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002157 /* Setup a temporary TLS area that is used to get a working
2158 * errno for system calls.
2159 */
2160 __set_tls(__tls_area);
2161
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002162 pid = getpid();
2163
2164#if TIMING
2165 struct timeval t0, t1;
2166 gettimeofday(&t0, 0);
2167#endif
2168
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002169 /* NOTE: we store the elfdata pointer on a special location
2170 * of the temporary TLS area in order to pass it to
2171 * the C Library's runtime initializer.
2172 *
2173 * The initializer must clear the slot and reset the TLS
2174 * to point to a different location to ensure that no other
2175 * shared library constructor can access it.
2176 */
2177 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002178
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002179 /* Initialize environment functions, and get to the ELF aux vectors table */
2180 vecs = linker_env_init(vecs);
2181
Stephen Smalley861b42a2012-01-13 07:48:11 -05002182 /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
2183 has file caps, or caused a SELinux/AppArmor domain transition. */
2184 for (v = vecs; v[0]; v += 2) {
2185 if (v[0] == AT_SECURE) {
2186 /* kernel told us whether to enable secure mode */
2187 program_is_setuid = v[1];
2188 goto sanitize;
2189 }
2190 }
2191
2192 /* Kernel did not provide AT_SECURE - fall back on legacy test. */
2193 program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
2194
2195sanitize:
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002196 /* Sanitize environment if we're loading a setuid program */
2197 if (program_is_setuid)
2198 linker_env_secure();
2199
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002200 debugger_init();
2201
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002202 /* Get a few environment variables */
2203 {
2204 const char* env;
2205 env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
2206 if (env)
2207 debug_verbosity = atoi(env);
2208
2209 /* Normally, these are cleaned by linker_env_secure, but the test
2210 * against program_is_setuid doesn't cost us anything */
2211 if (!program_is_setuid) {
2212 ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2213 ldpreload_env = linker_env_get("LD_PRELOAD");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002214 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002215 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002216
2217 INFO("[ android linker & debugger ]\n");
2218 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2219
2220 si = alloc_info(argv[0]);
2221 if(si == 0) {
2222 exit(-1);
2223 }
2224
2225 /* bootstrap the link map, the main exe always needs to be first */
2226 si->flags |= FLAG_EXE;
2227 map = &(si->linkmap);
2228
2229 map->l_addr = 0;
2230 map->l_name = argv[0];
2231 map->l_prev = NULL;
2232 map->l_next = NULL;
2233
2234 _r_debug.r_map = map;
2235 r_debug_tail = map;
2236
2237 /* gdb expects the linker to be in the debug shared object list,
2238 * and we need to make sure that the reported load address is zero.
2239 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2240 * is. Don't use alloc_info(), because the linker shouldn't
2241 * be on the soinfo list.
2242 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002243 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002244 linker_soinfo.flags = 0;
2245 linker_soinfo.base = 0; // This is the important part; must be zero.
2246 insert_soinfo_into_debug_map(&linker_soinfo);
2247
2248 /* extract information passed from the kernel */
2249 while(vecs[0] != 0){
2250 switch(vecs[0]){
2251 case AT_PHDR:
2252 si->phdr = (Elf32_Phdr*) vecs[1];
2253 break;
2254 case AT_PHNUM:
2255 si->phnum = (int) vecs[1];
2256 break;
2257 case AT_ENTRY:
2258 si->entry = vecs[1];
2259 break;
2260 }
2261 vecs += 2;
2262 }
2263
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002264 /* Compute the value of si->base. We can't rely on the fact that
2265 * the first entry is the PHDR because this will not be true
2266 * for certain executables (e.g. some in the NDK unit test suite)
2267 */
2268 int nn;
2269 si->base = 0;
2270 for ( nn = 0; nn < si->phnum; nn++ ) {
2271 if (si->phdr[nn].p_type == PT_PHDR) {
2272 si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_vaddr;
2273 break;
2274 }
2275 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002276 si->dynamic = (unsigned *)-1;
2277 si->wrprotect_start = 0xffffffff;
2278 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002279 si->refcount = 1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002280
David Bartleybc3a5c22009-06-02 18:27:28 -07002281 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002282 if (ldpath_env)
David Bartleybc3a5c22009-06-02 18:27:28 -07002283 parse_library_path(ldpath_env, ":");
2284
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002285 if (ldpreload_env) {
Matt Fischer4fd42c12009-12-31 12:09:10 -06002286 parse_preloads(ldpreload_env, " :");
2287 }
2288
Dima Zavin2e855792009-05-20 18:28:09 -07002289 if(link_image(si, 0)) {
2290 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2291 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2292 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002293 exit(-1);
2294 }
2295
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04002296 call_constructors_recursive(si);
2297
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002298#if ALLOW_SYMBOLS_FROM_MAIN
2299 /* Set somain after we've loaded all the libraries in order to prevent
2300 * linking of symbols back to the main image, which is not set up at that
2301 * point yet.
2302 */
2303 somain = si;
2304#endif
2305
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002306#if TIMING
2307 gettimeofday(&t1,NULL);
2308 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2309 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2310 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2311 ));
2312#endif
2313#if STATS
2314 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2315 linker_stats.reloc[RELOC_ABSOLUTE],
2316 linker_stats.reloc[RELOC_RELATIVE],
2317 linker_stats.reloc[RELOC_COPY],
2318 linker_stats.reloc[RELOC_SYMBOL]);
2319#endif
2320#if COUNT_PAGES
2321 {
2322 unsigned n;
2323 unsigned i;
2324 unsigned count = 0;
2325 for(n = 0; n < 4096; n++){
2326 if(bitmask[n]){
2327 unsigned x = bitmask[n];
2328 for(i = 0; i < 8; i++){
2329 if(x & 1) count++;
2330 x >>= 1;
2331 }
2332 }
2333 }
2334 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2335 }
2336#endif
2337
2338#if TIMING || STATS || COUNT_PAGES
2339 fflush(stdout);
2340#endif
2341
2342 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2343 si->entry);
2344 return si->entry;
2345}
Nick Kralevich468319c2011-11-11 15:53:17 -08002346
2347/*
2348 * Find the value of AT_BASE passed to us by the kernel. This is the load
2349 * location of the linker.
2350 */
2351static unsigned find_linker_base(unsigned **elfdata) {
2352 int argc = (int) *elfdata;
2353 char **argv = (char**) (elfdata + 1);
2354 unsigned *vecs = (unsigned*) (argv + argc + 1);
2355 while (vecs[0] != 0) {
2356 vecs++;
2357 }
2358
2359 /* The end of the environment block is marked by two NULL pointers */
2360 vecs++;
2361
2362 while(vecs[0]) {
2363 if (vecs[0] == AT_BASE) {
2364 return vecs[1];
2365 }
2366 vecs += 2;
2367 }
2368
2369 return 0; // should never happen
2370}
2371
2372/*
2373 * This is the entry point for the linker, called from begin.S. This
2374 * method is responsible for fixing the linker's own relocations, and
2375 * then calling __linker_init_post_relocation().
2376 *
2377 * Because this method is called before the linker has fixed it's own
2378 * relocations, any attempt to reference an extern variable, extern
2379 * function, or other GOT reference will generate a segfault.
2380 */
2381unsigned __linker_init(unsigned **elfdata) {
2382 unsigned linker_addr = find_linker_base(elfdata);
2383 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
2384 Elf32_Phdr *phdr =
2385 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);
2386
2387 soinfo linker_so;
2388 memset(&linker_so, 0, sizeof(soinfo));
2389
2390 linker_so.base = linker_addr;
2391 linker_so.dynamic = (unsigned *) -1;
2392 linker_so.phdr = phdr;
2393 linker_so.phnum = elf_hdr->e_phnum;
2394 linker_so.flags |= FLAG_LINKER;
2395 linker_so.wrprotect_start = 0xffffffff;
2396 linker_so.wrprotect_end = 0;
2397
2398 if (link_image(&linker_so, 0)) {
2399 // It would be nice to print an error message, but if the linker
2400 // can't link itself, there's no guarantee that we'll be able to
2401 // call write() (because it involves a GOT reference).
2402 //
2403 // This situation should never occur unless the linker itself
2404 // is corrupt.
2405 exit(-1);
2406 }
2407
2408 // We have successfully fixed our own relocations. It's safe to run
2409 // the main part of the linker now.
2410 return __linker_init_post_relocation(elfdata);
2411}