blob: f365fb614d924fdfdacfff41706e47dbdfbcbd65 [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}
David 'Digit' Turner70b16682012-01-30 17:17:58 +0100353#elif defined(ANDROID_X86_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
Nick Kralevich66259862012-03-16 13:06:12 -0700818/* reserve_mem_region
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800819 *
820 * This function reserves a chunk of memory to be used for mapping in
Nick Kralevich66259862012-03-16 13:06:12 -0700821 * a prelinked shared library. We reserve the entire memory region here, and
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800822 * then the rest of the linker will relocate the individual loadable
823 * segments into the correct locations within this memory range.
824 *
825 * Args:
Nick Kralevich66259862012-03-16 13:06:12 -0700826 * si->base: The requested base of the allocation.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800827 * si->size: The size of the allocation.
828 *
829 * Returns:
830 * -1 on failure, and 0 on success. On success, si->base will contain
831 * the virtual address at which the library will be mapped.
832 */
833
834static int reserve_mem_region(soinfo *si)
835{
Nick Kralevich66259862012-03-16 13:06:12 -0700836 void *base = mmap((void *)si->base, si->size, PROT_NONE,
Chris Dearmandb4bce02011-03-10 10:48:14 -0800837 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800838 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700839 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700840 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800841 pid, (si->base ? "" : "non-"), si->name, si->base,
842 errno, strerror(errno));
843 return -1;
844 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700845 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700846 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800847 si->name, (unsigned)base, si->base);
848 munmap(base, si->size);
849 return -1;
850 }
851 return 0;
852}
853
Nick Kralevich66259862012-03-16 13:06:12 -0700854static int alloc_mem_region(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800855{
856 if (si->base) {
857 /* Attempt to mmap a prelinked library. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800858 return reserve_mem_region(si);
859 }
860
Shih-wei Liao48527c32011-07-17 12:32:43 -0700861 /* This is not a prelinked library, so we use the kernel's default
862 allocator.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800863 */
Shih-wei Liao48527c32011-07-17 12:32:43 -0700864
Nick Kralevich66259862012-03-16 13:06:12 -0700865 void *base = mmap(NULL, si->size, PROT_NONE,
Shih-wei Liao48527c32011-07-17 12:32:43 -0700866 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
867 if (base == MAP_FAILED) {
868 DL_ERR("%5d mmap of library '%s' failed: %d (%s)\n",
869 pid, si->name,
870 errno, strerror(errno));
871 goto err;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800872 }
Shih-wei Liao48527c32011-07-17 12:32:43 -0700873 si->base = (unsigned) base;
874 PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
875 pid, si->name, si->base);
876 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800877
878err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700879 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800880 pid, si->name);
881 return -1;
882}
883
884#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
885#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
886 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
887 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
888/* load_segments
889 *
890 * This function loads all the loadable (PT_LOAD) segments into memory
891 * at their appropriate memory offsets off the base address.
892 *
893 * Args:
894 * fd: Open file descriptor to the library to load.
895 * header: Pointer to a header page that contains the ELF header.
896 * This is needed since we haven't mapped in the real file yet.
897 * si: ptr to soinfo struct describing the shared object.
898 *
899 * Returns:
900 * 0 on success, -1 on failure.
901 */
902static int
903load_segments(int fd, void *header, soinfo *si)
904{
905 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
906 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800907 Elf32_Addr base = (Elf32_Addr) si->base;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800908 int cnt;
909 unsigned len;
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800910 Elf32_Addr tmp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800911 unsigned char *pbase;
912 unsigned char *extra_base;
913 unsigned extra_len;
914 unsigned total_sz = 0;
915
916 si->wrprotect_start = 0xffffffff;
917 si->wrprotect_end = 0;
918
919 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
920 pid, si->name, (unsigned)si->base);
921 /* Now go through all the PT_LOAD segments and map them into memory
922 * at the appropriate locations. */
923 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
924 if (phdr->p_type == PT_LOAD) {
925 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
926 /* we want to map in the segment on a page boundary */
927 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
928 /* add the # of bytes we masked off above to the total length. */
929 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
930
931 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
932 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
933 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800934 pbase = mmap((void *)tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800935 MAP_PRIVATE | MAP_FIXED, fd,
936 phdr->p_offset & (~PAGE_MASK));
937 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700938 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700939 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800940 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
941 goto fail;
942 }
943
944 /* If 'len' didn't end on page boundary, and it's a writable
945 * segment, zero-fill the rest. */
946 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
947 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
948
949 /* Check to see if we need to extend the map for this segment to
950 * cover the diff between filesz and memsz (i.e. for bss).
951 *
952 * base _+---------------------+ page boundary
953 * . .
954 * | |
955 * . .
956 * pbase _+---------------------+ page boundary
957 * | |
958 * . .
959 * base + p_vaddr _| |
960 * . \ \ .
961 * . | filesz | .
962 * pbase + len _| / | |
963 * <0 pad> . . .
964 * extra_base _+------------|--------+ page boundary
965 * / . . .
966 * | . . .
967 * | +------------|--------+ page boundary
968 * extra_len-> | | | |
969 * | . | memsz .
970 * | . | .
971 * \ _| / |
972 * . .
973 * | |
974 * _+---------------------+ page boundary
975 */
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800976 tmp = (Elf32_Addr)(((unsigned)pbase + len + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800977 (~PAGE_MASK));
978 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
979 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
980 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
981 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
982 /* map in the extra page(s) as anonymous into the range.
983 * This is probably not necessary as we already mapped in
984 * the entire region previously, but we just want to be
985 * sure. This will also set the right flags on the region
986 * (though we can probably accomplish the same thing with
987 * mprotect).
988 */
989 extra_base = mmap((void *)tmp, extra_len,
990 PFLAGS_TO_PROT(phdr->p_flags),
991 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
992 -1, 0);
993 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700994 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700995 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800996 extra_len);
997 goto fail;
998 }
999 /* TODO: Check if we need to memset-0 this region.
1000 * Anonymous mappings are zero-filled copy-on-writes, so we
1001 * shouldn't need to. */
1002 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
1003 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
1004 extra_len);
1005 }
1006 /* set the len here to show the full extent of the segment we
1007 * just loaded, mostly for debugging */
1008 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
1009 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
1010 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
1011 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
1012 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
1013 total_sz += len;
1014 /* Make the section writable just in case we'll have to write to
1015 * it during relocation (i.e. text segment). However, we will
1016 * remember what range of addresses should be write protected.
1017 *
1018 */
1019 if (!(phdr->p_flags & PF_W)) {
1020 if ((unsigned)pbase < si->wrprotect_start)
1021 si->wrprotect_start = (unsigned)pbase;
1022 if (((unsigned)pbase + len) > si->wrprotect_end)
1023 si->wrprotect_end = (unsigned)pbase + len;
1024 mprotect(pbase, len,
1025 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1026 }
1027 } else if (phdr->p_type == PT_DYNAMIC) {
1028 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1029 /* this segment contains the dynamic linking information */
1030 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001031 } else if (phdr->p_type == PT_GNU_RELRO) {
1032 if ((phdr->p_vaddr >= si->size)
1033 || ((phdr->p_vaddr + phdr->p_memsz) >= si->size)
1034 || ((base + phdr->p_vaddr + phdr->p_memsz) < base)) {
1035 DL_ERR("%d invalid GNU_RELRO in '%s' "
1036 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1037 phdr->p_vaddr, phdr->p_memsz);
1038 goto fail;
1039 }
1040 si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
1041 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001042 } else {
1043#ifdef ANDROID_ARM_LINKER
1044 if (phdr->p_type == PT_ARM_EXIDX) {
1045 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1046 /* exidx entries (used for stack unwinding) are 8 bytes each.
1047 */
1048 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1049 si->ARM_exidx_count = phdr->p_memsz / 8;
1050 }
1051#endif
1052 }
1053
1054 }
1055
1056 /* Sanity check */
1057 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001058 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001059 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001060 pid, total_sz, si->name, si->size);
1061 goto fail;
1062 }
1063
1064 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1065 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1066 (unsigned)si->base, si->size);
1067 return 0;
1068
1069fail:
1070 /* We can just blindly unmap the entire region even though some things
1071 * were mapped in originally with anonymous and others could have been
1072 * been mapped in from the file before we failed. The kernel will unmap
1073 * all the pages in the range, irrespective of how they got there.
1074 */
1075 munmap((void *)si->base, si->size);
1076 si->flags |= FLAG_ERROR;
1077 return -1;
1078}
1079
1080/* TODO: Implement this to take care of the fact that Android ARM
1081 * ELF objects shove everything into a single loadable segment that has the
1082 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1083 * non-writable.
1084 */
1085#if 0
1086static unsigned
1087get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1088{
1089 Elf32_Shdr *shdr_start;
1090 Elf32_Shdr *shdr;
1091 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1092 int cnt;
1093 unsigned wr_offset = 0xffffffff;
1094
1095 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1096 ehdr->e_shoff & (~PAGE_MASK));
1097 if (shdr_start == MAP_FAILED) {
1098 WARN("%5d - Could not read section header info from '%s'. Will not "
1099 "not be able to determine write-protect offset.\n", pid, name);
1100 return (unsigned)-1;
1101 }
1102
1103 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1104 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1105 (shdr->sh_addr < wr_offset)) {
1106 wr_offset = shdr->sh_addr;
1107 }
1108 }
1109
1110 munmap(shdr_start, shdr_sz);
1111 return wr_offset;
1112}
1113#endif
1114
1115static soinfo *
1116load_library(const char *name)
1117{
1118 int fd = open_library(name);
1119 int cnt;
1120 unsigned ext_sz;
1121 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001122 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001123 soinfo *si = NULL;
1124 Elf32_Ehdr *hdr;
1125
Dima Zavin2e855792009-05-20 18:28:09 -07001126 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001127 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001128 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001129 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001130
1131 /* We have to read the ELF header to figure out what to do with this image
1132 */
1133 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001134 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001135 goto fail;
1136 }
1137
1138 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001139 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001140 goto fail;
1141 }
1142
1143 /* Parse the ELF header and get the size of the memory footprint for
1144 * the library */
1145 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1146 if (req_base == (unsigned)-1)
1147 goto fail;
1148 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1149 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1150
1151 /* Now configure the soinfo struct where we'll store all of our data
1152 * for the ELF object. If the loading fails, we waste the entry, but
1153 * same thing would happen if we failed during linking. Configuring the
1154 * soinfo struct here is a lot more convenient.
1155 */
Erik Gillingfde86422009-07-28 20:28:19 -07001156 bname = strrchr(name, '/');
1157 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001158 if (si == NULL)
1159 goto fail;
1160
1161 /* Carve out a chunk of memory where we will map in the individual
1162 * segments */
1163 si->base = req_base;
1164 si->size = ext_sz;
1165 si->flags = 0;
1166 si->entry = 0;
1167 si->dynamic = (unsigned *)-1;
1168 if (alloc_mem_region(si) < 0)
1169 goto fail;
1170
1171 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1172 pid, name, (void *)si->base, (unsigned) ext_sz);
1173
1174 /* Now actually load the library's segments into right places in memory */
1175 if (load_segments(fd, &__header[0], si) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176 goto fail;
1177 }
1178
1179 /* this might not be right. Technically, we don't even need this info
1180 * once we go through 'load_segments'. */
1181 hdr = (Elf32_Ehdr *)si->base;
1182 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1183 si->phnum = hdr->e_phnum;
1184 /**/
1185
1186 close(fd);
1187 return si;
1188
1189fail:
1190 if (si) free_info(si);
1191 close(fd);
1192 return NULL;
1193}
1194
1195static soinfo *
1196init_library(soinfo *si)
1197{
1198 unsigned wr_offset = 0xffffffff;
1199
1200 /* At this point we know that whatever is loaded @ base is a valid ELF
1201 * shared library whose segments are properly mapped in. */
1202 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1203 pid, si->base, si->size, si->name);
1204
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001205 if(link_image(si, wr_offset)) {
1206 /* We failed to link. However, we can only restore libbase
1207 ** if no additional libraries have moved it since we updated it.
1208 */
1209 munmap((void *)si->base, si->size);
1210 return NULL;
1211 }
1212
1213 return si;
1214}
1215
1216soinfo *find_library(const char *name)
1217{
1218 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001219 const char *bname;
1220
1221#if ALLOW_SYMBOLS_FROM_MAIN
1222 if (name == NULL)
1223 return somain;
1224#else
1225 if (name == NULL)
1226 return NULL;
1227#endif
1228
1229 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001230 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001231
1232 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001233 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001234 if(si->flags & FLAG_ERROR) {
1235 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1236 return NULL;
1237 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001238 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001239 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001240 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001241 }
1242 }
1243
1244 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1245 si = load_library(name);
1246 if(si == NULL)
1247 return NULL;
1248 return init_library(si);
1249}
1250
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001251/* TODO:
1252 * notify gdb of unload
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001253 * for non-prelinked libraries, find a way to decrement libbase
1254 */
1255static void call_destructors(soinfo *si);
1256unsigned unload_library(soinfo *si)
1257{
1258 unsigned *d;
1259 if (si->refcount == 1) {
1260 TRACE("%5d unloading '%s'\n", pid, si->name);
1261 call_destructors(si);
1262
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001263 /*
1264 * Make sure that we undo the PT_GNU_RELRO protections we added
1265 * in link_image. This is needed to undo the DT_NEEDED hack below.
1266 */
1267 if ((si->gnu_relro_start != 0) && (si->gnu_relro_len != 0)) {
1268 Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
1269 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1270 if (mprotect((void *) start, len, PROT_READ | PROT_WRITE) < 0)
1271 DL_ERR("%5d %s: could not undo GNU_RELRO protections. "
1272 "Expect a crash soon. errno=%d (%s)",
1273 pid, si->name, errno, strerror(errno));
1274
1275 }
1276
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001277 for(d = si->dynamic; *d; d += 2) {
1278 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001279 soinfo *lsi = (soinfo *)d[1];
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001280
1281 // The next line will segfault if the we don't undo the
1282 // PT_GNU_RELRO protections (see comments above and in
1283 // link_image().
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001284 d[1] = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001285
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001286 if (validate_soinfo(lsi)) {
1287 TRACE("%5d %s needs to unload %s\n", pid,
1288 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001289 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001290 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001291 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001292 DL_ERR("%5d %s: could not unload dependent library",
1293 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001294 }
1295 }
1296
1297 munmap((char *)si->base, si->size);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001298 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001299 free_info(si);
1300 si->refcount = 0;
1301 }
1302 else {
1303 si->refcount--;
1304 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1305 pid, si->name, si->refcount);
1306 }
1307 return si->refcount;
1308}
1309
1310/* TODO: don't use unsigned for addrs below. It works, but is not
1311 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1312 * long.
1313 */
1314static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1315{
1316 Elf32_Sym *symtab = si->symtab;
1317 const char *strtab = si->strtab;
1318 Elf32_Sym *s;
1319 unsigned base;
1320 Elf32_Rel *start = rel;
1321 unsigned idx;
1322
1323 for (idx = 0; idx < count; ++idx) {
1324 unsigned type = ELF32_R_TYPE(rel->r_info);
1325 unsigned sym = ELF32_R_SYM(rel->r_info);
1326 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1327 unsigned sym_addr = 0;
1328 char *sym_name = NULL;
1329
1330 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1331 si->name, idx);
1332 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001333 sym_name = (char *)(strtab + symtab[sym].st_name);
1334 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001335 if(s == NULL) {
1336 /* We only allow an undefined symbol if this is a weak
1337 reference.. */
1338 s = &symtab[sym];
1339 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1340 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1341 return -1;
1342 }
1343
1344 /* IHI0044C AAELF 4.5.1.1:
1345
1346 Libraries are not searched to resolve weak references.
1347 It is not an error for a weak reference to remain
1348 unsatisfied.
1349
1350 During linking, the value of an undefined weak reference is:
1351 - Zero if the relocation type is absolute
1352 - The address of the place if the relocation is pc-relative
1353 - The address of nominial base address if the relocation
1354 type is base-relative.
1355 */
1356
1357 switch (type) {
1358#if defined(ANDROID_ARM_LINKER)
1359 case R_ARM_JUMP_SLOT:
1360 case R_ARM_GLOB_DAT:
1361 case R_ARM_ABS32:
1362 case R_ARM_RELATIVE: /* Don't care. */
1363 case R_ARM_NONE: /* Don't care. */
1364#elif defined(ANDROID_X86_LINKER)
1365 case R_386_JUMP_SLOT:
1366 case R_386_GLOB_DAT:
1367 case R_386_32:
1368 case R_386_RELATIVE: /* Dont' care. */
1369#endif /* ANDROID_*_LINKER */
1370 /* sym_addr was initialized to be zero above or relocation
1371 code below does not care about value of sym_addr.
1372 No need to do anything. */
1373 break;
1374
1375#if defined(ANDROID_X86_LINKER)
1376 case R_386_PC32:
1377 sym_addr = reloc;
1378 break;
1379#endif /* ANDROID_X86_LINKER */
1380
1381#if defined(ANDROID_ARM_LINKER)
1382 case R_ARM_COPY:
1383 /* Fall through. Can't really copy if weak symbol is
1384 not found in run-time. */
1385#endif /* ANDROID_ARM_LINKER */
1386 default:
1387 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1388 pid, type, rel, (int) (rel - start));
1389 return -1;
1390 }
1391 } else {
1392 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001393#if 0
1394 if((base == 0) && (si->base != 0)){
1395 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001396 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 pid, strtab + symtab[sym].st_name);
1398 return -1;
1399 }
1400#endif
Doug Kwane8238072009-10-26 12:05:23 -07001401 sym_addr = (unsigned)(s->st_value + base);
1402 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001403 COUNT_RELOC(RELOC_SYMBOL);
1404 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001405 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 }
1407
1408/* TODO: This is ugly. Split up the relocations by arch into
1409 * different files.
1410 */
1411 switch(type){
1412#if defined(ANDROID_ARM_LINKER)
1413 case R_ARM_JUMP_SLOT:
1414 COUNT_RELOC(RELOC_ABSOLUTE);
1415 MARK(rel->r_offset);
1416 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1417 reloc, sym_addr, sym_name);
1418 *((unsigned*)reloc) = sym_addr;
1419 break;
1420 case R_ARM_GLOB_DAT:
1421 COUNT_RELOC(RELOC_ABSOLUTE);
1422 MARK(rel->r_offset);
1423 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1424 reloc, sym_addr, sym_name);
1425 *((unsigned*)reloc) = sym_addr;
1426 break;
1427 case R_ARM_ABS32:
1428 COUNT_RELOC(RELOC_ABSOLUTE);
1429 MARK(rel->r_offset);
1430 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1431 reloc, sym_addr, sym_name);
1432 *((unsigned*)reloc) += sym_addr;
1433 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001434 case R_ARM_REL32:
1435 COUNT_RELOC(RELOC_RELATIVE);
1436 MARK(rel->r_offset);
1437 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1438 reloc, sym_addr, rel->r_offset, sym_name);
1439 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1440 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001441#elif defined(ANDROID_X86_LINKER)
1442 case R_386_JUMP_SLOT:
1443 COUNT_RELOC(RELOC_ABSOLUTE);
1444 MARK(rel->r_offset);
1445 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1446 reloc, sym_addr, sym_name);
1447 *((unsigned*)reloc) = sym_addr;
1448 break;
1449 case R_386_GLOB_DAT:
1450 COUNT_RELOC(RELOC_ABSOLUTE);
1451 MARK(rel->r_offset);
1452 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1453 reloc, sym_addr, sym_name);
1454 *((unsigned*)reloc) = sym_addr;
1455 break;
1456#endif /* ANDROID_*_LINKER */
1457
1458#if defined(ANDROID_ARM_LINKER)
1459 case R_ARM_RELATIVE:
1460#elif defined(ANDROID_X86_LINKER)
1461 case R_386_RELATIVE:
1462#endif /* ANDROID_*_LINKER */
1463 COUNT_RELOC(RELOC_RELATIVE);
1464 MARK(rel->r_offset);
1465 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001466 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467 return -1;
1468 }
1469 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1470 reloc, si->base);
1471 *((unsigned*)reloc) += si->base;
1472 break;
1473
1474#if defined(ANDROID_X86_LINKER)
1475 case R_386_32:
1476 COUNT_RELOC(RELOC_RELATIVE);
1477 MARK(rel->r_offset);
1478
1479 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1480 reloc, sym_addr, sym_name);
1481 *((unsigned *)reloc) += (unsigned)sym_addr;
1482 break;
1483
1484 case R_386_PC32:
1485 COUNT_RELOC(RELOC_RELATIVE);
1486 MARK(rel->r_offset);
1487 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1488 "+%08x (%08x - %08x) %s\n", pid, reloc,
1489 (sym_addr - reloc), sym_addr, reloc, sym_name);
1490 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1491 break;
1492#endif /* ANDROID_X86_LINKER */
1493
1494#ifdef ANDROID_ARM_LINKER
1495 case R_ARM_COPY:
1496 COUNT_RELOC(RELOC_COPY);
1497 MARK(rel->r_offset);
1498 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1499 reloc, s->st_size, sym_addr, sym_name);
1500 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1501 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001502 case R_ARM_NONE:
1503 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001504#endif /* ANDROID_ARM_LINKER */
1505
1506 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001507 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001508 pid, type, rel, (int) (rel - start));
1509 return -1;
1510 }
1511 rel++;
1512 }
1513 return 0;
1514}
1515
David 'Digit' Turner82156792009-05-18 14:37:41 +02001516/* Please read the "Initialization and Termination functions" functions.
1517 * of the linker design note in bionic/linker/README.TXT to understand
1518 * what the following code is doing.
1519 *
1520 * The important things to remember are:
1521 *
1522 * DT_PREINIT_ARRAY must be called first for executables, and should
1523 * not appear in shared libraries.
1524 *
1525 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1526 *
1527 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1528 *
1529 * DT_FINI_ARRAY must be parsed in reverse order.
1530 */
1531
1532static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001533{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001534 int n, inc = 1;
1535
1536 if (reverse) {
1537 ctor += (count-1);
1538 inc = -1;
1539 }
1540
1541 for(n = count; n > 0; n--) {
1542 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1543 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001544 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001545 void (*func)() = (void (*)()) *ctor;
1546 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001547 if(((int) func == 0) || ((int) func == -1)) continue;
1548 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1549 func();
1550 }
1551}
1552
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001553void call_constructors_recursive(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001554{
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001555 if (si->constructors_called)
1556 return;
1557
Jesse Hallf5d16932012-01-30 15:39:57 -08001558 // Set this before actually calling the constructors, otherwise it doesn't
1559 // protect against recursive constructor calls. One simple example of
1560 // constructor recursion is the libc debug malloc, which is implemented in
1561 // libc_malloc_debug_leak.so:
1562 // 1. The program depends on libc, so libc's constructor is called here.
1563 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
1564 // 3. dlopen() calls call_constructors_recursive() with the newly created
1565 // soinfo for libc_malloc_debug_leak.so.
1566 // 4. The debug so depends on libc, so call_constructors_recursive() is
1567 // called again with the libc soinfo. If it doesn't trigger the early-
1568 // out above, the libc constructor will be called again (recursively!).
1569 si->constructors_called = 1;
1570
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001571 if (si->flags & FLAG_EXE) {
1572 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1573 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1574 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001575 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001576 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1577 } else {
1578 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001579 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001580 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001581 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001582 }
1583 }
1584
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001585 if (si->dynamic) {
1586 unsigned *d;
1587 for(d = si->dynamic; *d; d += 2) {
1588 if(d[0] == DT_NEEDED){
1589 soinfo* lsi = (soinfo *)d[1];
1590 if (!validate_soinfo(lsi)) {
1591 DL_ERR("%5d bad DT_NEEDED pointer in %s",
1592 pid, si->name);
1593 } else {
1594 call_constructors_recursive(lsi);
1595 }
1596 }
1597 }
1598 }
1599
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001600 if (si->init_func) {
1601 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1602 (unsigned)si->init_func, si->name);
1603 si->init_func();
1604 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1605 }
1606
1607 if (si->init_array) {
1608 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1609 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001610 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001611 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1612 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001613
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001614}
David 'Digit' Turner82156792009-05-18 14:37:41 +02001615
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616static void call_destructors(soinfo *si)
1617{
1618 if (si->fini_array) {
1619 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1620 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001621 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001622 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1623 }
1624
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001625 if (si->fini_func) {
1626 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1627 (unsigned)si->fini_func, si->name);
1628 si->fini_func();
1629 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1630 }
1631}
1632
1633/* Force any of the closed stdin, stdout and stderr to be associated with
1634 /dev/null. */
1635static int nullify_closed_stdio (void)
1636{
1637 int dev_null, i, status;
1638 int return_value = 0;
1639
1640 dev_null = open("/dev/null", O_RDWR);
1641 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001642 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001643 return -1;
1644 }
1645 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1646
1647 /* If any of the stdio file descriptors is valid and not associated
1648 with /dev/null, dup /dev/null to it. */
1649 for (i = 0; i < 3; i++) {
1650 /* If it is /dev/null already, we are done. */
1651 if (i == dev_null)
1652 continue;
1653
1654 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1655 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1656 can be interrupted but we do this just to be safe. */
1657 do {
1658 status = fcntl(i, F_GETFL);
1659 } while (status < 0 && errno == EINTR);
1660
1661 /* If file is openned, we are good. */
1662 if (status >= 0)
1663 continue;
1664
1665 /* The only error we allow is that the file descriptor does not
1666 exist, in which case we dup /dev/null to it. */
1667 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001668 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001669 return_value = -1;
1670 continue;
1671 }
1672
1673 /* Try dupping /dev/null to this stdio file descriptor and
1674 repeat if there is a signal. Note that any errors in closing
1675 the stdio descriptor are lost. */
1676 do {
1677 status = dup2(dev_null, i);
1678 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001679
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001680 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001681 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001682 return_value = -1;
1683 continue;
1684 }
1685 }
1686
1687 /* If /dev/null is not one of the stdio file descriptors, close it. */
1688 if (dev_null > 2) {
1689 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001690 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001691 status = close(dev_null);
1692 } while (status < 0 && errno == EINTR);
1693
1694 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001695 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001696 return_value = -1;
1697 }
1698 }
1699
1700 return return_value;
1701}
1702
1703static int link_image(soinfo *si, unsigned wr_offset)
1704{
1705 unsigned *d;
1706 Elf32_Phdr *phdr = si->phdr;
1707 int phnum = si->phnum;
1708
1709 INFO("[ %5d linking %s ]\n", pid, si->name);
1710 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1711 si->base, si->flags);
1712
Nick Kralevich468319c2011-11-11 15:53:17 -08001713 if (si->flags & (FLAG_EXE | FLAG_LINKER)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001714 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
Nick Kralevich468319c2011-11-11 15:53:17 -08001715 * linkage info if this is the executable or the linker itself.
1716 * If this was a dynamic lib, that would have been done at load time.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717 *
1718 * TODO: It's unfortunate that small pieces of this are
1719 * repeated from the load_library routine. Refactor this just
1720 * slightly to reuse these bits.
1721 */
1722 si->size = 0;
1723 for(; phnum > 0; --phnum, ++phdr) {
1724#ifdef ANDROID_ARM_LINKER
1725 if(phdr->p_type == PT_ARM_EXIDX) {
1726 /* exidx entries (used for stack unwinding) are 8 bytes each.
1727 */
1728 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1729 si->ARM_exidx_count = phdr->p_memsz / 8;
1730 }
1731#endif
1732 if (phdr->p_type == PT_LOAD) {
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001733 /* For the executable, we use the si->size field only in
1734 dl_unwind_find_exidx(), so the meaning of si->size
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001735 is not the size of the executable; it is the distance
1736 between the load location of the executable and the last
1737 address of the loadable part of the executable.
1738 We use the range [si->base, si->base + si->size) to
1739 determine whether a PC value falls within the executable
1740 section. Of course, if a value is between si->base and
1741 (si->base + phdr->p_vaddr), it's not in the executable
1742 section, but a) we shouldn't be asking for such a value
1743 anyway, and b) if we have to provide an EXIDX for such a
1744 value, then the executable's EXIDX is probably the better
1745 choice.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001746 */
1747 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1748 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1749 si->size = phdr->p_vaddr + phdr->p_memsz;
1750 /* try to remember what range of addresses should be write
1751 * protected */
1752 if (!(phdr->p_flags & PF_W)) {
1753 unsigned _end;
1754
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001755 if (si->base + phdr->p_vaddr < si->wrprotect_start)
1756 si->wrprotect_start = si->base + phdr->p_vaddr;
1757 _end = (((si->base + phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001758 (~PAGE_MASK)));
1759 if (_end > si->wrprotect_end)
1760 si->wrprotect_end = _end;
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001761 /* Make the section writable just in case we'll have to
1762 * write to it during relocation (i.e. text segment).
1763 * However, we will remember what range of addresses
1764 * should be write protected.
1765 */
1766 mprotect((void *) (si->base + phdr->p_vaddr),
1767 phdr->p_memsz,
1768 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001769 }
1770 } else if (phdr->p_type == PT_DYNAMIC) {
1771 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001772 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001773 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001774 pid, si->name, si->base + phdr->p_vaddr,
1775 (unsigned)si->dynamic);
1776 goto fail;
1777 }
1778 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1779 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001780 } else if (phdr->p_type == PT_GNU_RELRO) {
1781 if ((phdr->p_vaddr >= si->size)
1782 || ((phdr->p_vaddr + phdr->p_memsz) >= si->size)
1783 || ((si->base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
1784 DL_ERR("%d invalid GNU_RELRO in '%s' "
1785 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1786 phdr->p_vaddr, phdr->p_memsz);
1787 goto fail;
1788 }
1789 si->gnu_relro_start = (Elf32_Addr) (si->base + phdr->p_vaddr);
1790 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001791 }
1792 }
1793 }
1794
1795 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001796 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001797 goto fail;
1798 }
1799
1800 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1801
1802 /* extract useful information from dynamic section */
1803 for(d = si->dynamic; *d; d++){
1804 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1805 switch(*d++){
1806 case DT_HASH:
1807 si->nbucket = ((unsigned *) (si->base + *d))[0];
1808 si->nchain = ((unsigned *) (si->base + *d))[1];
1809 si->bucket = (unsigned *) (si->base + *d + 8);
1810 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1811 break;
1812 case DT_STRTAB:
1813 si->strtab = (const char *) (si->base + *d);
1814 break;
1815 case DT_SYMTAB:
1816 si->symtab = (Elf32_Sym *) (si->base + *d);
1817 break;
1818 case DT_PLTREL:
1819 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001820 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001821 goto fail;
1822 }
1823 break;
1824 case DT_JMPREL:
1825 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1826 break;
1827 case DT_PLTRELSZ:
1828 si->plt_rel_count = *d / 8;
1829 break;
1830 case DT_REL:
1831 si->rel = (Elf32_Rel*) (si->base + *d);
1832 break;
1833 case DT_RELSZ:
1834 si->rel_count = *d / 8;
1835 break;
1836 case DT_PLTGOT:
1837 /* Save this in case we decide to do lazy binding. We don't yet. */
1838 si->plt_got = (unsigned *)(si->base + *d);
1839 break;
1840 case DT_DEBUG:
1841 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1842 *d = (int) &_r_debug;
1843 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001844 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001845 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001846 goto fail;
1847 case DT_INIT:
1848 si->init_func = (void (*)(void))(si->base + *d);
1849 DEBUG("%5d %s constructors (init func) found at %p\n",
1850 pid, si->name, si->init_func);
1851 break;
1852 case DT_FINI:
1853 si->fini_func = (void (*)(void))(si->base + *d);
1854 DEBUG("%5d %s destructors (fini func) found at %p\n",
1855 pid, si->name, si->fini_func);
1856 break;
1857 case DT_INIT_ARRAY:
1858 si->init_array = (unsigned *)(si->base + *d);
1859 DEBUG("%5d %s constructors (init_array) found at %p\n",
1860 pid, si->name, si->init_array);
1861 break;
1862 case DT_INIT_ARRAYSZ:
1863 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1864 break;
1865 case DT_FINI_ARRAY:
1866 si->fini_array = (unsigned *)(si->base + *d);
1867 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1868 pid, si->name, si->fini_array);
1869 break;
1870 case DT_FINI_ARRAYSZ:
1871 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1872 break;
1873 case DT_PREINIT_ARRAY:
1874 si->preinit_array = (unsigned *)(si->base + *d);
1875 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1876 pid, si->name, si->preinit_array);
1877 break;
1878 case DT_PREINIT_ARRAYSZ:
1879 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1880 break;
1881 case DT_TEXTREL:
1882 /* TODO: make use of this. */
1883 /* this means that we might have to write into where the text
1884 * segment was loaded during relocation... Do something with
1885 * it.
1886 */
1887 DEBUG("%5d Text segment should be writable during relocation.\n",
1888 pid);
1889 break;
1890 }
1891 }
1892
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001893 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001894 pid, si->base, si->strtab, si->symtab);
1895
1896 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001897 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001898 goto fail;
1899 }
1900
Matt Fischer4fd42c12009-12-31 12:09:10 -06001901 /* if this is the main executable, then load all of the preloads now */
1902 if(si->flags & FLAG_EXE) {
1903 int i;
1904 memset(preloads, 0, sizeof(preloads));
1905 for(i = 0; ldpreload_names[i] != NULL; i++) {
1906 soinfo *lsi = find_library(ldpreload_names[i]);
1907 if(lsi == 0) {
1908 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1909 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1910 pid, ldpreload_names[i], si->name, tmp_err_buf);
1911 goto fail;
1912 }
1913 lsi->refcount++;
1914 preloads[i] = lsi;
1915 }
1916 }
1917
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001918 for(d = si->dynamic; *d; d += 2) {
1919 if(d[0] == DT_NEEDED){
1920 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001921 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001922 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001923 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001924 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001925 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001926 goto fail;
1927 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001928 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1929 of the DT_NEEDED entry itself, so that we can retrieve the
1930 soinfo directly later from the dynamic segment. This is a hack,
1931 but it allows us to map from DT_NEEDED to soinfo efficiently
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001932 later on when we resolve relocations, trying to look up a symbol
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001933 with dlsym().
1934 */
1935 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001936 lsi->refcount++;
1937 }
1938 }
1939
1940 if(si->plt_rel) {
1941 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1942 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1943 goto fail;
1944 }
1945 if(si->rel) {
1946 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1947 if(reloc_library(si, si->rel, si->rel_count))
1948 goto fail;
1949 }
1950
1951 si->flags |= FLAG_LINKED;
1952 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1953
1954#if 0
1955 /* This is the way that the old dynamic linker did protection of
1956 * non-writable areas. It would scan section headers and find where
1957 * .text ended (rather where .data/.bss began) and assume that this is
1958 * the upper range of the non-writable area. This is too coarse,
1959 * and is kept here for reference until we fully move away from single
1960 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1961 * that made this possible.
1962 */
1963 if(wr_offset < 0xffffffff){
1964 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1965 }
1966#else
1967 /* TODO: Verify that this does the right thing in all cases, as it
1968 * presently probably does not. It is possible that an ELF image will
1969 * come with multiple read-only segments. What we ought to do is scan
1970 * the program headers again and mprotect all the read-only segments.
1971 * To prevent re-scanning the program header, we would have to build a
1972 * list of loadable segments in si, and then scan that instead. */
1973 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1974 mprotect((void *)si->wrprotect_start,
1975 si->wrprotect_end - si->wrprotect_start,
1976 PROT_READ | PROT_EXEC);
1977 }
1978#endif
1979
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001980 if (si->gnu_relro_start != 0 && si->gnu_relro_len != 0) {
1981 Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
1982 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1983 if (mprotect((void *) start, len, PROT_READ) < 0) {
1984 DL_ERR("%5d GNU_RELRO mprotect of library '%s' failed: %d (%s)\n",
1985 pid, si->name, errno, strerror(errno));
1986 goto fail;
1987 }
1988 }
1989
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001990 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1991 stdout and stderr to close a security hole described in:
1992
1993 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1994
1995 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001996 if (program_is_setuid)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001997 nullify_closed_stdio ();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001998 notify_gdb_of_load(si);
1999 return 0;
2000
2001fail:
Dima Zavina7161902010-08-17 15:56:40 -07002002 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002003 si->flags |= FLAG_ERROR;
2004 return -1;
2005}
2006
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002007static void parse_library_path(const char *path, char *delim)
David Bartleybc3a5c22009-06-02 18:27:28 -07002008{
2009 size_t len;
2010 char *ldpaths_bufp = ldpaths_buf;
2011 int i = 0;
2012
2013 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2014
2015 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2016 if (*ldpaths[i] != '\0')
2017 ++i;
2018 }
2019
2020 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2021 * last char isn't '\0' (i.e. not originally a delim). */
2022 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2023 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2024 ldpaths[i - 1] = NULL;
2025 } else {
2026 ldpaths[i] = NULL;
2027 }
2028}
2029
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002030static void parse_preloads(const char *path, char *delim)
Matt Fischer4fd42c12009-12-31 12:09:10 -06002031{
2032 size_t len;
2033 char *ldpreloads_bufp = ldpreloads_buf;
2034 int i = 0;
2035
2036 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2037
2038 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2039 if (*ldpreload_names[i] != '\0') {
2040 ++i;
2041 }
2042 }
2043
2044 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2045 * last char isn't '\0' (i.e. not originally a delim). */
2046 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2047 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2048 ldpreload_names[i - 1] = NULL;
2049 } else {
2050 ldpreload_names[i] = NULL;
2051 }
2052}
2053
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002054#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
2055
2056static void * __tls_area[ANDROID_TLS_SLOTS];
2057
Nick Kralevich468319c2011-11-11 15:53:17 -08002058/*
2059 * This code is called after the linker has linked itself and
2060 * fixed it's own GOT. It is safe to make references to externs
2061 * and other non-local data at this point.
2062 */
2063static unsigned __linker_init_post_relocation(unsigned **elfdata)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002064{
2065 static soinfo linker_soinfo;
2066
2067 int argc = (int) *elfdata;
2068 char **argv = (char**) (elfdata + 1);
Stephen Smalleybb440552012-01-20 10:59:15 -08002069 unsigned *vecs = (unsigned*) (argv + argc + 1);
2070 unsigned *v;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002071 soinfo *si;
2072 struct link_map * map;
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002073 const char *ldpath_env = NULL;
2074 const char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002075
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002076 /* Setup a temporary TLS area that is used to get a working
2077 * errno for system calls.
2078 */
2079 __set_tls(__tls_area);
2080
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002081 pid = getpid();
2082
2083#if TIMING
2084 struct timeval t0, t1;
2085 gettimeofday(&t0, 0);
2086#endif
2087
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002088 /* NOTE: we store the elfdata pointer on a special location
2089 * of the temporary TLS area in order to pass it to
2090 * the C Library's runtime initializer.
2091 *
2092 * The initializer must clear the slot and reset the TLS
2093 * to point to a different location to ensure that no other
2094 * shared library constructor can access it.
2095 */
2096 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002097
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002098 /* Initialize environment functions, and get to the ELF aux vectors table */
2099 vecs = linker_env_init(vecs);
2100
Stephen Smalley861b42a2012-01-13 07:48:11 -05002101 /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
2102 has file caps, or caused a SELinux/AppArmor domain transition. */
2103 for (v = vecs; v[0]; v += 2) {
2104 if (v[0] == AT_SECURE) {
2105 /* kernel told us whether to enable secure mode */
2106 program_is_setuid = v[1];
2107 goto sanitize;
2108 }
2109 }
2110
2111 /* Kernel did not provide AT_SECURE - fall back on legacy test. */
2112 program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
2113
2114sanitize:
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002115 /* Sanitize environment if we're loading a setuid program */
2116 if (program_is_setuid)
2117 linker_env_secure();
2118
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002119 debugger_init();
2120
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002121 /* Get a few environment variables */
2122 {
2123 const char* env;
2124 env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
2125 if (env)
2126 debug_verbosity = atoi(env);
2127
2128 /* Normally, these are cleaned by linker_env_secure, but the test
2129 * against program_is_setuid doesn't cost us anything */
2130 if (!program_is_setuid) {
2131 ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2132 ldpreload_env = linker_env_get("LD_PRELOAD");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002133 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002134 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002135
2136 INFO("[ android linker & debugger ]\n");
2137 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2138
2139 si = alloc_info(argv[0]);
2140 if(si == 0) {
2141 exit(-1);
2142 }
2143
2144 /* bootstrap the link map, the main exe always needs to be first */
2145 si->flags |= FLAG_EXE;
2146 map = &(si->linkmap);
2147
2148 map->l_addr = 0;
2149 map->l_name = argv[0];
2150 map->l_prev = NULL;
2151 map->l_next = NULL;
2152
2153 _r_debug.r_map = map;
2154 r_debug_tail = map;
2155
2156 /* gdb expects the linker to be in the debug shared object list,
2157 * and we need to make sure that the reported load address is zero.
2158 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2159 * is. Don't use alloc_info(), because the linker shouldn't
2160 * be on the soinfo list.
2161 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002162 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002163 linker_soinfo.flags = 0;
2164 linker_soinfo.base = 0; // This is the important part; must be zero.
2165 insert_soinfo_into_debug_map(&linker_soinfo);
2166
2167 /* extract information passed from the kernel */
2168 while(vecs[0] != 0){
2169 switch(vecs[0]){
2170 case AT_PHDR:
2171 si->phdr = (Elf32_Phdr*) vecs[1];
2172 break;
2173 case AT_PHNUM:
2174 si->phnum = (int) vecs[1];
2175 break;
2176 case AT_ENTRY:
2177 si->entry = vecs[1];
2178 break;
2179 }
2180 vecs += 2;
2181 }
2182
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002183 /* Compute the value of si->base. We can't rely on the fact that
2184 * the first entry is the PHDR because this will not be true
2185 * for certain executables (e.g. some in the NDK unit test suite)
2186 */
2187 int nn;
2188 si->base = 0;
2189 for ( nn = 0; nn < si->phnum; nn++ ) {
2190 if (si->phdr[nn].p_type == PT_PHDR) {
2191 si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_vaddr;
2192 break;
2193 }
2194 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002195 si->dynamic = (unsigned *)-1;
2196 si->wrprotect_start = 0xffffffff;
2197 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002198 si->refcount = 1;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002199 si->gnu_relro_start = 0;
2200 si->gnu_relro_len = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002201
David Bartleybc3a5c22009-06-02 18:27:28 -07002202 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002203 if (ldpath_env)
David Bartleybc3a5c22009-06-02 18:27:28 -07002204 parse_library_path(ldpath_env, ":");
2205
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002206 if (ldpreload_env) {
Matt Fischer4fd42c12009-12-31 12:09:10 -06002207 parse_preloads(ldpreload_env, " :");
2208 }
2209
Dima Zavin2e855792009-05-20 18:28:09 -07002210 if(link_image(si, 0)) {
2211 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2212 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2213 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002214 exit(-1);
2215 }
2216
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04002217 call_constructors_recursive(si);
2218
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002219#if ALLOW_SYMBOLS_FROM_MAIN
2220 /* Set somain after we've loaded all the libraries in order to prevent
2221 * linking of symbols back to the main image, which is not set up at that
2222 * point yet.
2223 */
2224 somain = si;
2225#endif
2226
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002227#if TIMING
2228 gettimeofday(&t1,NULL);
2229 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2230 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2231 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2232 ));
2233#endif
2234#if STATS
2235 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2236 linker_stats.reloc[RELOC_ABSOLUTE],
2237 linker_stats.reloc[RELOC_RELATIVE],
2238 linker_stats.reloc[RELOC_COPY],
2239 linker_stats.reloc[RELOC_SYMBOL]);
2240#endif
2241#if COUNT_PAGES
2242 {
2243 unsigned n;
2244 unsigned i;
2245 unsigned count = 0;
2246 for(n = 0; n < 4096; n++){
2247 if(bitmask[n]){
2248 unsigned x = bitmask[n];
2249 for(i = 0; i < 8; i++){
2250 if(x & 1) count++;
2251 x >>= 1;
2252 }
2253 }
2254 }
2255 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2256 }
2257#endif
2258
2259#if TIMING || STATS || COUNT_PAGES
2260 fflush(stdout);
2261#endif
2262
2263 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2264 si->entry);
2265 return si->entry;
2266}
Nick Kralevich468319c2011-11-11 15:53:17 -08002267
2268/*
2269 * Find the value of AT_BASE passed to us by the kernel. This is the load
2270 * location of the linker.
2271 */
2272static unsigned find_linker_base(unsigned **elfdata) {
2273 int argc = (int) *elfdata;
2274 char **argv = (char**) (elfdata + 1);
2275 unsigned *vecs = (unsigned*) (argv + argc + 1);
2276 while (vecs[0] != 0) {
2277 vecs++;
2278 }
2279
2280 /* The end of the environment block is marked by two NULL pointers */
2281 vecs++;
2282
2283 while(vecs[0]) {
2284 if (vecs[0] == AT_BASE) {
2285 return vecs[1];
2286 }
2287 vecs += 2;
2288 }
2289
2290 return 0; // should never happen
2291}
2292
2293/*
2294 * This is the entry point for the linker, called from begin.S. This
2295 * method is responsible for fixing the linker's own relocations, and
2296 * then calling __linker_init_post_relocation().
2297 *
2298 * Because this method is called before the linker has fixed it's own
2299 * relocations, any attempt to reference an extern variable, extern
2300 * function, or other GOT reference will generate a segfault.
2301 */
2302unsigned __linker_init(unsigned **elfdata) {
2303 unsigned linker_addr = find_linker_base(elfdata);
2304 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
2305 Elf32_Phdr *phdr =
2306 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);
2307
2308 soinfo linker_so;
2309 memset(&linker_so, 0, sizeof(soinfo));
2310
2311 linker_so.base = linker_addr;
2312 linker_so.dynamic = (unsigned *) -1;
2313 linker_so.phdr = phdr;
2314 linker_so.phnum = elf_hdr->e_phnum;
2315 linker_so.flags |= FLAG_LINKER;
2316 linker_so.wrprotect_start = 0xffffffff;
2317 linker_so.wrprotect_end = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002318 linker_so.gnu_relro_start = 0;
2319 linker_so.gnu_relro_len = 0;
Nick Kralevich468319c2011-11-11 15:53:17 -08002320
2321 if (link_image(&linker_so, 0)) {
2322 // It would be nice to print an error message, but if the linker
2323 // can't link itself, there's no guarantee that we'll be able to
2324 // call write() (because it involves a GOT reference).
2325 //
2326 // This situation should never occur unless the linker itself
2327 // is corrupt.
2328 exit(-1);
2329 }
2330
2331 // We have successfully fixed our own relocations. It's safe to run
2332 // the main part of the linker now.
2333 return __linker_init_post_relocation(elfdata);
2334}