blob: 9805b35e3f4183482809f606d6dce3280372b791 [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
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -0700111#if LINKER_DEBUG
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800112int debug_verbosity;
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -0700113#endif
114
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800115static int pid;
116
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100117/* This boolean is set if the program being loaded is setuid */
118static int program_is_setuid;
119
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800120#if STATS
121struct _link_stats linker_stats;
122#endif
123
124#if COUNT_PAGES
125unsigned bitmask[4096];
126#endif
127
128#ifndef PT_ARM_EXIDX
129#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
130#endif
131
Dima Zavin2e855792009-05-20 18:28:09 -0700132#define HOODLUM(name, ret, ...) \
133 ret name __VA_ARGS__ \
134 { \
135 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
136 write(2, errstr, sizeof(errstr)); \
137 abort(); \
138 }
139HOODLUM(malloc, void *, (size_t size));
140HOODLUM(free, void, (void *ptr));
141HOODLUM(realloc, void *, (void *ptr, size_t size));
142HOODLUM(calloc, void *, (size_t cnt, size_t size));
143
Dima Zavin03531952009-05-29 17:30:25 -0700144static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700145static char __linker_dl_err_buf[768];
146#define DL_ERR(fmt, x...) \
147 do { \
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800148 format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
Dima Zavin2e855792009-05-20 18:28:09 -0700149 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700150 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700151 } while(0)
152
153const char *linker_get_error(void)
154{
155 return (const char *)&__linker_dl_err_buf[0];
156}
157
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800158/*
159 * This function is an empty stub where GDB locates a breakpoint to get notified
160 * about linker activity.
161 */
162extern void __attribute__((noinline)) rtld_db_dlactivity(void);
163
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800164static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
165 RT_CONSISTENT, 0};
166static struct link_map *r_debug_tail = 0;
167
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700168static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800169
170static void insert_soinfo_into_debug_map(soinfo * info)
171{
172 struct link_map * map;
173
174 /* Copy the necessary fields into the debug structure.
175 */
176 map = &(info->linkmap);
177 map->l_addr = info->base;
178 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800179 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800180
181 /* Stick the new library at the end of the list.
182 * gdb tends to care more about libc than it does
183 * about leaf libraries, and ordering it this way
184 * reduces the back-and-forth over the wire.
185 */
186 if (r_debug_tail) {
187 r_debug_tail->l_next = map;
188 map->l_prev = r_debug_tail;
189 map->l_next = 0;
190 } else {
191 _r_debug.r_map = map;
192 map->l_prev = 0;
193 map->l_next = 0;
194 }
195 r_debug_tail = map;
196}
197
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700198static void remove_soinfo_from_debug_map(soinfo * info)
199{
200 struct link_map * map = &(info->linkmap);
201
202 if (r_debug_tail == map)
203 r_debug_tail = map->l_prev;
204
205 if (map->l_prev) map->l_prev->l_next = map->l_next;
206 if (map->l_next) map->l_next->l_prev = map->l_prev;
207}
208
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800209void notify_gdb_of_load(soinfo * info)
210{
211 if (info->flags & FLAG_EXE) {
212 // GDB already knows about the main executable
213 return;
214 }
215
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700216 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800217
218 _r_debug.r_state = RT_ADD;
219 rtld_db_dlactivity();
220
221 insert_soinfo_into_debug_map(info);
222
223 _r_debug.r_state = RT_CONSISTENT;
224 rtld_db_dlactivity();
225
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700226 pthread_mutex_unlock(&_r_debug_lock);
227}
228
229void notify_gdb_of_unload(soinfo * info)
230{
231 if (info->flags & FLAG_EXE) {
232 // GDB already knows about the main executable
233 return;
234 }
235
236 pthread_mutex_lock(&_r_debug_lock);
237
238 _r_debug.r_state = RT_DELETE;
239 rtld_db_dlactivity();
240
241 remove_soinfo_from_debug_map(info);
242
243 _r_debug.r_state = RT_CONSISTENT;
244 rtld_db_dlactivity();
245
246 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800247}
248
249void notify_gdb_of_libraries()
250{
251 _r_debug.r_state = RT_ADD;
252 rtld_db_dlactivity();
253 _r_debug.r_state = RT_CONSISTENT;
254 rtld_db_dlactivity();
255}
256
257static soinfo *alloc_info(const char *name)
258{
259 soinfo *si;
260
261 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700262 DL_ERR("%5d library name %s too long", pid, name);
Doug Kwan94304352009-10-23 18:11:40 -0700263 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800264 }
265
266 /* The freelist is populated when we call free_info(), which in turn is
267 done only by dlclose(), which is not likely to be used.
268 */
269 if (!freelist) {
270 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700271 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800272 return NULL;
273 }
274 freelist = sopool + socount++;
275 freelist->next = NULL;
276 }
277
278 si = freelist;
279 freelist = freelist->next;
280
281 /* Make sure we get a clean block of soinfo */
282 memset(si, 0, sizeof(soinfo));
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100283 strlcpy((char*) si->name, name, sizeof(si->name));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800284 sonext->next = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800285 si->next = NULL;
286 si->refcount = 0;
287 sonext = si;
288
289 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
290 return si;
291}
292
293static void free_info(soinfo *si)
294{
295 soinfo *prev = NULL, *trav;
296
297 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
298
299 for(trav = solist; trav != NULL; trav = trav->next){
300 if (trav == si)
301 break;
302 prev = trav;
303 }
304 if (trav == NULL) {
305 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700306 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800307 return;
308 }
309
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100310 /* prev will never be NULL, because the first entry in solist is
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800311 always the static libdl_info.
312 */
313 prev->next = si->next;
314 if (si == sonext) sonext = prev;
315 si->next = freelist;
316 freelist = si;
317}
318
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800319const char *addr_to_name(unsigned addr)
320{
321 soinfo *si;
322
323 for(si = solist; si != 0; si = si->next){
324 if((addr >= si->base) && (addr < (si->base + si->size))) {
325 return si->name;
326 }
327 }
328
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800329 return "";
330}
331
332/* For a given PC, find the .so that it belongs to.
333 * Returns the base address of the .ARM.exidx section
334 * for that .so, and the number of 8-byte entries
335 * in that section (via *pcount).
336 *
337 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
338 *
339 * This function is exposed via dlfcn.c and libdl.so.
340 */
341#ifdef ANDROID_ARM_LINKER
342_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
343{
344 soinfo *si;
345 unsigned addr = (unsigned)pc;
346
Nick Kralevich468319c2011-11-11 15:53:17 -0800347 for (si = solist; si != 0; si = si->next){
348 if ((addr >= si->base) && (addr < (si->base + si->size))) {
349 *pcount = si->ARM_exidx_count;
350 return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800351 }
352 }
353 *pcount = 0;
354 return NULL;
355}
David 'Digit' Turner70b16682012-01-30 17:17:58 +0100356#elif defined(ANDROID_X86_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800357/* Here, we only have to provide a callback to iterate across all the
358 * loaded libraries. gcc_eh does the rest. */
359int
360dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
361 void *data)
362{
363 soinfo *si;
364 struct dl_phdr_info dl_info;
365 int rv = 0;
366
367 for (si = solist; si != NULL; si = si->next) {
368 dl_info.dlpi_addr = si->linkmap.l_addr;
369 dl_info.dlpi_name = si->linkmap.l_name;
370 dl_info.dlpi_phdr = si->phdr;
371 dl_info.dlpi_phnum = si->phnum;
372 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
373 if (rv != 0)
374 break;
375 }
376 return rv;
377}
378#endif
379
380static Elf32_Sym *_elf_lookup(soinfo *si, unsigned hash, const char *name)
381{
382 Elf32_Sym *s;
383 Elf32_Sym *symtab = si->symtab;
384 const char *strtab = si->strtab;
385 unsigned n;
386
387 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
388 name, si->name, si->base, hash, hash % si->nbucket);
389 n = hash % si->nbucket;
390
391 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
392 s = symtab + n;
393 if(strcmp(strtab + s->st_name, name)) continue;
394
Doug Kwane8238072009-10-26 12:05:23 -0700395 /* only concern ourselves with global and weak symbol definitions */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800396 switch(ELF32_ST_BIND(s->st_info)){
397 case STB_GLOBAL:
Doug Kwane8238072009-10-26 12:05:23 -0700398 case STB_WEAK:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800399 /* no section == undefined */
400 if(s->st_shndx == 0) continue;
401
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800402 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
403 name, si->name, s->st_value, s->st_size);
404 return s;
405 }
406 }
407
Doug Kwan94304352009-10-23 18:11:40 -0700408 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800409}
410
Nick Kralevich7f03d232012-04-10 13:42:06 -0700411/*
412 * Essentially the same method as _elf_lookup() above, but only
413 * searches for LOCAL symbols
414 */
415static Elf32_Sym *_elf_lookup_local(soinfo *si, unsigned hash, const char *name)
416{
417 Elf32_Sym *symtab = si->symtab;
418 const char *strtab = si->strtab;
419 unsigned n = hash % si->nbucket;;
420
421 TRACE_TYPE(LOOKUP, "%5d LOCAL SEARCH %s in %s@0x%08x %08x %d\n", pid,
422 name, si->name, si->base, hash, hash % si->nbucket);
423 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
424 Elf32_Sym *s = symtab + n;
425 if (strcmp(strtab + s->st_name, name)) continue;
426 if (ELF32_ST_BIND(s->st_info) != STB_LOCAL) continue;
427 /* no section == undefined */
428 if(s->st_shndx == 0) continue;
429
430 TRACE_TYPE(LOOKUP, "%5d FOUND LOCAL %s in %s (%08x) %d\n", pid,
431 name, si->name, s->st_value, s->st_size);
432 return s;
433 }
434
435 return NULL;
436}
437
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800438static unsigned elfhash(const char *_name)
439{
440 const unsigned char *name = (const unsigned char *) _name;
441 unsigned h = 0, g;
442
443 while(*name) {
444 h = (h << 4) + *name++;
445 g = h & 0xf0000000;
446 h ^= g;
447 h ^= g >> 24;
448 }
449 return h;
450}
451
452static Elf32_Sym *
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700453_do_lookup(soinfo *si, const char *name, unsigned *base)
454{
Doug Kwan94304352009-10-23 18:11:40 -0700455 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700456 Elf32_Sym *s;
457 unsigned *d;
458 soinfo *lsi = si;
Matt Fischer4fd42c12009-12-31 12:09:10 -0600459 int i;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700460
Nick Kralevich7f03d232012-04-10 13:42:06 -0700461 /* If we are trying to find a symbol for the linker itself, look
462 * for LOCAL symbols first. Avoid using LOCAL symbols for other
463 * shared libraries until we have a better understanding of what
464 * might break by doing so. */
465 if (si->flags & FLAG_LINKER) {
466 s = _elf_lookup_local(si, elf_hash, name);
467 if(s != NULL)
468 goto done;
469 }
470
Nick Kralevich468319c2011-11-11 15:53:17 -0800471 /* Look for symbols in the local scope (the object who is
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700472 * searching). This happens with C++ templates on i386 for some
Doug Kwane8238072009-10-26 12:05:23 -0700473 * reason.
474 *
475 * Notes on weak symbols:
476 * The ELF specs are ambigious about treatment of weak definitions in
477 * dynamic linking. Some systems return the first definition found
478 * and some the first non-weak definition. This is system dependent.
479 * Here we return the first definition found for simplicity. */
Nick Kralevich468319c2011-11-11 15:53:17 -0800480
Doug Kwan94304352009-10-23 18:11:40 -0700481 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700482 if(s != NULL)
483 goto done;
484
Matt Fischer4fd42c12009-12-31 12:09:10 -0600485 /* Next, look for it in the preloads list */
486 for(i = 0; preloads[i] != NULL; i++) {
487 lsi = preloads[i];
Jean-Baptiste Queruf4394452010-05-12 10:05:59 -0700488 s = _elf_lookup(lsi, elf_hash, name);
Matt Fischer4fd42c12009-12-31 12:09:10 -0600489 if(s != NULL)
490 goto done;
491 }
492
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700493 for(d = si->dynamic; *d; d += 2) {
494 if(d[0] == DT_NEEDED){
495 lsi = (soinfo *)d[1];
496 if (!validate_soinfo(lsi)) {
497 DL_ERR("%5d bad DT_NEEDED pointer in %s",
498 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700499 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700500 }
501
502 DEBUG("%5d %s: looking up %s in %s\n",
503 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700504 s = _elf_lookup(lsi, elf_hash, name);
Min-su, Kim3cab22c2010-01-19 10:05:33 +0900505 if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700506 goto done;
507 }
508 }
509
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700510#if ALLOW_SYMBOLS_FROM_MAIN
511 /* If we are resolving relocations while dlopen()ing a library, it's OK for
512 * the library to resolve a symbol that's defined in the executable itself,
513 * although this is rare and is generally a bad idea.
514 */
515 if (somain) {
516 lsi = somain;
517 DEBUG("%5d %s: looking up %s in executable %s\n",
518 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700519 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700520 }
521#endif
522
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700523done:
524 if(s != NULL) {
525 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
526 "found in %s, base = 0x%08x\n",
527 pid, si->name, name, s->st_value, lsi->name, lsi->base);
528 *base = lsi->base;
529 return s;
530 }
531
Doug Kwan94304352009-10-23 18:11:40 -0700532 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700533}
534
535/* This is used by dl_sym(). It performs symbol lookup only within the
536 specified soinfo object and not in any of its dependencies.
537 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800538Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
539{
Doug Kwan94304352009-10-23 18:11:40 -0700540 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800541}
542
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700543/* This is used by dl_sym(). It performs a global symbol lookup.
544 */
Matt Fischer1698d9e2009-12-31 12:17:56 -0600545Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800546{
Doug Kwan94304352009-10-23 18:11:40 -0700547 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800548 Elf32_Sym *s = NULL;
549 soinfo *si;
550
Matt Fischer1698d9e2009-12-31 12:17:56 -0600551 if(start == NULL) {
552 start = solist;
553 }
554
555 for(si = start; (s == NULL) && (si != NULL); si = si->next)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800556 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700557 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800558 continue;
Doug Kwane8238072009-10-26 12:05:23 -0700559 s = _elf_lookup(si, elf_hash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800560 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700561 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800562 break;
563 }
564 }
565
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700566 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800567 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
568 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
569 return s;
570 }
571
Doug Kwan94304352009-10-23 18:11:40 -0700572 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800573}
574
Mathias Agopianbda5da02011-09-27 22:30:19 -0700575soinfo *find_containing_library(const void *addr)
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600576{
577 soinfo *si;
578
579 for(si = solist; si != NULL; si = si->next)
580 {
581 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
582 return si;
583 }
584 }
585
586 return NULL;
587}
588
Mathias Agopianbda5da02011-09-27 22:30:19 -0700589Elf32_Sym *find_containing_symbol(const void *addr, soinfo *si)
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600590{
591 unsigned int i;
592 unsigned soaddr = (unsigned)addr - si->base;
593
594 /* Search the library's symbol table for any defined symbol which
595 * contains this address */
596 for(i=0; i<si->nchain; i++) {
597 Elf32_Sym *sym = &si->symtab[i];
598
599 if(sym->st_shndx != SHN_UNDEF &&
600 soaddr >= sym->st_value &&
601 soaddr < sym->st_value + sym->st_size) {
602 return sym;
603 }
604 }
605
606 return NULL;
607}
608
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800609#if 0
610static void dump(soinfo *si)
611{
612 Elf32_Sym *s = si->symtab;
613 unsigned n;
614
615 for(n = 0; n < si->nchain; n++) {
616 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
617 s->st_info, s->st_shndx, s->st_value, s->st_size,
618 si->strtab + s->st_name);
619 s++;
620 }
621}
622#endif
623
624static const char *sopaths[] = {
Brian Swetlandfedbcde2010-09-19 03:39:13 -0700625 "/vendor/lib",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800626 "/system/lib",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800627 0
628};
629
630static int _open_lib(const char *name)
631{
632 int fd;
633 struct stat filestat;
634
635 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
636 if ((fd = open(name, O_RDONLY)) >= 0)
637 return fd;
638 }
639
640 return -1;
641}
642
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800643static int open_library(const char *name)
644{
645 int fd;
646 char buf[512];
647 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700648 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800649
650 TRACE("[ %5d opening %s ]\n", pid, name);
651
652 if(name == 0) return -1;
653 if(strlen(name) > 256) return -1;
654
655 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
656 return fd;
657
David Bartleybc3a5c22009-06-02 18:27:28 -0700658 for (path = ldpaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800659 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700660 if (n < 0 || n >= (int)sizeof(buf)) {
661 WARN("Ignoring very long library path: %s/%s\n", *path, name);
662 continue;
663 }
664 if ((fd = _open_lib(buf)) >= 0)
665 return fd;
666 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800667 for (path = sopaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800668 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700669 if (n < 0 || n >= (int)sizeof(buf)) {
670 WARN("Ignoring very long library path: %s/%s\n", *path, name);
671 continue;
672 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800673 if ((fd = _open_lib(buf)) >= 0)
674 return fd;
675 }
676
677 return -1;
678}
679
680/* temporary space for holding the first page of the shared lib
681 * which contains the elf header (with the pht). */
682static unsigned char __header[PAGE_SIZE];
683
684typedef struct {
685 long mmap_addr;
686 char tag[4]; /* 'P', 'R', 'E', ' ' */
687} prelink_info_t;
688
689/* Returns the requested base address if the library is prelinked,
690 * and 0 otherwise. */
691static unsigned long
692is_prelinked(int fd, const char *name)
693{
694 off_t sz;
695 prelink_info_t info;
696
697 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
698 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700699 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800700 return 0;
701 }
702
703 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
704 WARN("Could not read prelink_info_t structure for `%s`\n", name);
705 return 0;
706 }
707
708 if (strncmp(info.tag, "PRE ", 4)) {
709 WARN("`%s` is not a prelinked library\n", name);
710 return 0;
711 }
712
713 return (unsigned long)info.mmap_addr;
714}
715
716/* verify_elf_object
717 * Verifies if the object @ base is a valid ELF object
718 *
719 * Args:
720 *
721 * Returns:
722 * 0 on success
723 * -1 if no valid ELF object is found @ base.
724 */
725static int
726verify_elf_object(void *base, const char *name)
727{
728 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
729
730 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
731 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
732 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
733 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
734
735 /* TODO: Should we verify anything else in the header? */
Zhenghua Wang897815a2011-10-19 00:29:14 +0800736#ifdef ANDROID_ARM_LINKER
737 if (hdr->e_machine != EM_ARM) return -1;
738#elif defined(ANDROID_X86_LINKER)
739 if (hdr->e_machine != EM_386) return -1;
740#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800741 return 0;
742}
743
744
745/* get_lib_extents
746 * Retrieves the base (*base) address where the ELF object should be
747 * mapped and its overall memory size (*total_sz).
748 *
749 * Args:
750 * fd: Opened file descriptor for the library
751 * name: The name of the library
752 * _hdr: Pointer to the header page of the library
753 * total_sz: Total size of the memory that should be allocated for
754 * this library
755 *
756 * Returns:
757 * -1 if there was an error while trying to get the lib extents.
758 * The possible reasons are:
759 * - Could not determine if the library was prelinked.
760 * - The library provided is not a valid ELF object
761 * 0 if the library did not request a specific base offset (normal
762 * for non-prelinked libs)
763 * > 0 if the library requests a specific address to be mapped to.
764 * This indicates a pre-linked library.
765 */
766static unsigned
767get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
768{
769 unsigned req_base;
770 unsigned min_vaddr = 0xffffffff;
771 unsigned max_vaddr = 0;
772 unsigned char *_hdr = (unsigned char *)__hdr;
773 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
774 Elf32_Phdr *phdr;
775 int cnt;
776
777 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
778 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700779 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800780 return (unsigned)-1;
781 }
782
783 req_base = (unsigned) is_prelinked(fd, name);
784 if (req_base == (unsigned)-1)
785 return -1;
786 else if (req_base != 0) {
787 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
788 pid, name, req_base);
789 } else {
790 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
791 }
792
793 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
794
795 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
796 * get the range. */
797 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
798 if (phdr->p_type == PT_LOAD) {
799 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
800 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
801 if (phdr->p_vaddr < min_vaddr)
802 min_vaddr = phdr->p_vaddr;
803 }
804 }
805
806 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700807 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800808 return (unsigned)-1;
809 }
810
811 /* truncate min_vaddr down to page boundary */
812 min_vaddr &= ~PAGE_MASK;
813
814 /* round max_vaddr up to the next page */
815 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
816
817 *total_sz = (max_vaddr - min_vaddr);
818 return (unsigned)req_base;
819}
820
Nick Kralevich66259862012-03-16 13:06:12 -0700821/* reserve_mem_region
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800822 *
823 * This function reserves a chunk of memory to be used for mapping in
Nick Kralevich66259862012-03-16 13:06:12 -0700824 * a prelinked shared library. We reserve the entire memory region here, and
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800825 * then the rest of the linker will relocate the individual loadable
826 * segments into the correct locations within this memory range.
827 *
828 * Args:
Nick Kralevich66259862012-03-16 13:06:12 -0700829 * si->base: The requested base of the allocation.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800830 * si->size: The size of the allocation.
831 *
832 * Returns:
833 * -1 on failure, and 0 on success. On success, si->base will contain
834 * the virtual address at which the library will be mapped.
835 */
836
837static int reserve_mem_region(soinfo *si)
838{
Nick Kralevich66259862012-03-16 13:06:12 -0700839 void *base = mmap((void *)si->base, si->size, PROT_NONE,
Chris Dearmandb4bce02011-03-10 10:48:14 -0800840 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800841 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700842 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700843 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800844 pid, (si->base ? "" : "non-"), si->name, si->base,
845 errno, strerror(errno));
846 return -1;
847 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700848 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700849 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800850 si->name, (unsigned)base, si->base);
851 munmap(base, si->size);
852 return -1;
853 }
854 return 0;
855}
856
Nick Kralevich66259862012-03-16 13:06:12 -0700857static int alloc_mem_region(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800858{
859 if (si->base) {
860 /* Attempt to mmap a prelinked library. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800861 return reserve_mem_region(si);
862 }
863
Shih-wei Liao48527c32011-07-17 12:32:43 -0700864 /* This is not a prelinked library, so we use the kernel's default
865 allocator.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800866 */
Shih-wei Liao48527c32011-07-17 12:32:43 -0700867
Nick Kralevich66259862012-03-16 13:06:12 -0700868 void *base = mmap(NULL, si->size, PROT_NONE,
Shih-wei Liao48527c32011-07-17 12:32:43 -0700869 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
870 if (base == MAP_FAILED) {
871 DL_ERR("%5d mmap of library '%s' failed: %d (%s)\n",
872 pid, si->name,
873 errno, strerror(errno));
874 goto err;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800875 }
Shih-wei Liao48527c32011-07-17 12:32:43 -0700876 si->base = (unsigned) base;
877 PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
878 pid, si->name, si->base);
879 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800880
881err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700882 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800883 pid, si->name);
884 return -1;
885}
886
887#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
888#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
889 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
890 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
891/* load_segments
892 *
893 * This function loads all the loadable (PT_LOAD) segments into memory
894 * at their appropriate memory offsets off the base address.
895 *
896 * Args:
897 * fd: Open file descriptor to the library to load.
898 * header: Pointer to a header page that contains the ELF header.
899 * This is needed since we haven't mapped in the real file yet.
900 * si: ptr to soinfo struct describing the shared object.
901 *
902 * Returns:
903 * 0 on success, -1 on failure.
904 */
905static int
906load_segments(int fd, void *header, soinfo *si)
907{
908 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
909 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800910 Elf32_Addr base = (Elf32_Addr) si->base;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800911 int cnt;
912 unsigned len;
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800913 Elf32_Addr tmp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800914 unsigned char *pbase;
915 unsigned char *extra_base;
916 unsigned extra_len;
917 unsigned total_sz = 0;
918
919 si->wrprotect_start = 0xffffffff;
920 si->wrprotect_end = 0;
921
922 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
923 pid, si->name, (unsigned)si->base);
924 /* Now go through all the PT_LOAD segments and map them into memory
925 * at the appropriate locations. */
926 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
927 if (phdr->p_type == PT_LOAD) {
928 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
929 /* we want to map in the segment on a page boundary */
930 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
931 /* add the # of bytes we masked off above to the total length. */
932 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
933
934 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
935 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
936 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800937 pbase = mmap((void *)tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800938 MAP_PRIVATE | MAP_FIXED, fd,
939 phdr->p_offset & (~PAGE_MASK));
940 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700941 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700942 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800943 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
944 goto fail;
945 }
946
947 /* If 'len' didn't end on page boundary, and it's a writable
948 * segment, zero-fill the rest. */
949 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
950 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
951
952 /* Check to see if we need to extend the map for this segment to
953 * cover the diff between filesz and memsz (i.e. for bss).
954 *
955 * base _+---------------------+ page boundary
956 * . .
957 * | |
958 * . .
959 * pbase _+---------------------+ page boundary
960 * | |
961 * . .
962 * base + p_vaddr _| |
963 * . \ \ .
964 * . | filesz | .
965 * pbase + len _| / | |
966 * <0 pad> . . .
967 * extra_base _+------------|--------+ page boundary
968 * / . . .
969 * | . . .
970 * | +------------|--------+ page boundary
971 * extra_len-> | | | |
972 * | . | memsz .
973 * | . | .
974 * \ _| / |
975 * . .
976 * | |
977 * _+---------------------+ page boundary
978 */
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800979 tmp = (Elf32_Addr)(((unsigned)pbase + len + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800980 (~PAGE_MASK));
981 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
982 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
983 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
984 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
985 /* map in the extra page(s) as anonymous into the range.
986 * This is probably not necessary as we already mapped in
987 * the entire region previously, but we just want to be
988 * sure. This will also set the right flags on the region
989 * (though we can probably accomplish the same thing with
990 * mprotect).
991 */
992 extra_base = mmap((void *)tmp, extra_len,
993 PFLAGS_TO_PROT(phdr->p_flags),
994 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
995 -1, 0);
996 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700997 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700998 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800999 extra_len);
1000 goto fail;
1001 }
1002 /* TODO: Check if we need to memset-0 this region.
1003 * Anonymous mappings are zero-filled copy-on-writes, so we
1004 * shouldn't need to. */
1005 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
1006 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
1007 extra_len);
1008 }
1009 /* set the len here to show the full extent of the segment we
1010 * just loaded, mostly for debugging */
1011 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
1012 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
1013 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
1014 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
1015 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
1016 total_sz += len;
1017 /* Make the section writable just in case we'll have to write to
1018 * it during relocation (i.e. text segment). However, we will
1019 * remember what range of addresses should be write protected.
1020 *
1021 */
1022 if (!(phdr->p_flags & PF_W)) {
1023 if ((unsigned)pbase < si->wrprotect_start)
1024 si->wrprotect_start = (unsigned)pbase;
1025 if (((unsigned)pbase + len) > si->wrprotect_end)
1026 si->wrprotect_end = (unsigned)pbase + len;
1027 mprotect(pbase, len,
1028 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1029 }
1030 } else if (phdr->p_type == PT_DYNAMIC) {
1031 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1032 /* this segment contains the dynamic linking information */
1033 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001034 } else if (phdr->p_type == PT_GNU_RELRO) {
1035 if ((phdr->p_vaddr >= si->size)
Nick Kralevichd73b5ca2012-03-16 11:38:58 -07001036 || ((phdr->p_vaddr + phdr->p_memsz) > si->size)
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001037 || ((base + phdr->p_vaddr + phdr->p_memsz) < base)) {
1038 DL_ERR("%d invalid GNU_RELRO in '%s' "
1039 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1040 phdr->p_vaddr, phdr->p_memsz);
1041 goto fail;
1042 }
1043 si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
1044 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001045 } else {
1046#ifdef ANDROID_ARM_LINKER
1047 if (phdr->p_type == PT_ARM_EXIDX) {
1048 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1049 /* exidx entries (used for stack unwinding) are 8 bytes each.
1050 */
1051 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1052 si->ARM_exidx_count = phdr->p_memsz / 8;
1053 }
1054#endif
1055 }
1056
1057 }
1058
1059 /* Sanity check */
1060 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001061 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001062 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001063 pid, total_sz, si->name, si->size);
1064 goto fail;
1065 }
1066
1067 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1068 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1069 (unsigned)si->base, si->size);
1070 return 0;
1071
1072fail:
1073 /* We can just blindly unmap the entire region even though some things
1074 * were mapped in originally with anonymous and others could have been
1075 * been mapped in from the file before we failed. The kernel will unmap
1076 * all the pages in the range, irrespective of how they got there.
1077 */
1078 munmap((void *)si->base, si->size);
1079 si->flags |= FLAG_ERROR;
1080 return -1;
1081}
1082
1083/* TODO: Implement this to take care of the fact that Android ARM
1084 * ELF objects shove everything into a single loadable segment that has the
1085 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1086 * non-writable.
1087 */
1088#if 0
1089static unsigned
1090get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1091{
1092 Elf32_Shdr *shdr_start;
1093 Elf32_Shdr *shdr;
1094 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1095 int cnt;
1096 unsigned wr_offset = 0xffffffff;
1097
1098 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1099 ehdr->e_shoff & (~PAGE_MASK));
1100 if (shdr_start == MAP_FAILED) {
1101 WARN("%5d - Could not read section header info from '%s'. Will not "
1102 "not be able to determine write-protect offset.\n", pid, name);
1103 return (unsigned)-1;
1104 }
1105
1106 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1107 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1108 (shdr->sh_addr < wr_offset)) {
1109 wr_offset = shdr->sh_addr;
1110 }
1111 }
1112
1113 munmap(shdr_start, shdr_sz);
1114 return wr_offset;
1115}
1116#endif
1117
1118static soinfo *
1119load_library(const char *name)
1120{
1121 int fd = open_library(name);
1122 int cnt;
1123 unsigned ext_sz;
1124 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001125 const char *bname;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001126 soinfo *si = NULL;
1127 Elf32_Ehdr *hdr;
1128
Dima Zavin2e855792009-05-20 18:28:09 -07001129 if(fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001130 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001131 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001132 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001133
1134 /* We have to read the ELF header to figure out what to do with this image
1135 */
1136 if (lseek(fd, 0, SEEK_SET) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001137 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001138 goto fail;
1139 }
1140
1141 if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001142 DL_ERR("read() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001143 goto fail;
1144 }
1145
1146 /* Parse the ELF header and get the size of the memory footprint for
1147 * the library */
1148 req_base = get_lib_extents(fd, name, &__header[0], &ext_sz);
1149 if (req_base == (unsigned)-1)
1150 goto fail;
1151 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1152 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1153
1154 /* Now configure the soinfo struct where we'll store all of our data
1155 * for the ELF object. If the loading fails, we waste the entry, but
1156 * same thing would happen if we failed during linking. Configuring the
1157 * soinfo struct here is a lot more convenient.
1158 */
Erik Gillingfde86422009-07-28 20:28:19 -07001159 bname = strrchr(name, '/');
1160 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001161 if (si == NULL)
1162 goto fail;
1163
1164 /* Carve out a chunk of memory where we will map in the individual
1165 * segments */
1166 si->base = req_base;
1167 si->size = ext_sz;
1168 si->flags = 0;
1169 si->entry = 0;
1170 si->dynamic = (unsigned *)-1;
1171 if (alloc_mem_region(si) < 0)
1172 goto fail;
1173
1174 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1175 pid, name, (void *)si->base, (unsigned) ext_sz);
1176
1177 /* Now actually load the library's segments into right places in memory */
1178 if (load_segments(fd, &__header[0], si) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179 goto fail;
1180 }
1181
1182 /* this might not be right. Technically, we don't even need this info
1183 * once we go through 'load_segments'. */
1184 hdr = (Elf32_Ehdr *)si->base;
1185 si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
1186 si->phnum = hdr->e_phnum;
1187 /**/
1188
1189 close(fd);
1190 return si;
1191
1192fail:
1193 if (si) free_info(si);
1194 close(fd);
1195 return NULL;
1196}
1197
1198static soinfo *
1199init_library(soinfo *si)
1200{
1201 unsigned wr_offset = 0xffffffff;
1202
1203 /* At this point we know that whatever is loaded @ base is a valid ELF
1204 * shared library whose segments are properly mapped in. */
1205 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1206 pid, si->base, si->size, si->name);
1207
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001208 if(link_image(si, wr_offset)) {
1209 /* We failed to link. However, we can only restore libbase
1210 ** if no additional libraries have moved it since we updated it.
1211 */
1212 munmap((void *)si->base, si->size);
1213 return NULL;
1214 }
1215
1216 return si;
1217}
1218
1219soinfo *find_library(const char *name)
1220{
1221 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001222 const char *bname;
1223
1224#if ALLOW_SYMBOLS_FROM_MAIN
1225 if (name == NULL)
1226 return somain;
1227#else
1228 if (name == NULL)
1229 return NULL;
1230#endif
1231
1232 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001233 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001234
1235 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001236 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001237 if(si->flags & FLAG_ERROR) {
1238 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1239 return NULL;
1240 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001241 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001242 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001243 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244 }
1245 }
1246
1247 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1248 si = load_library(name);
1249 if(si == NULL)
1250 return NULL;
1251 return init_library(si);
1252}
1253
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001254/* TODO:
1255 * notify gdb of unload
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001256 * for non-prelinked libraries, find a way to decrement libbase
1257 */
1258static void call_destructors(soinfo *si);
1259unsigned unload_library(soinfo *si)
1260{
1261 unsigned *d;
1262 if (si->refcount == 1) {
1263 TRACE("%5d unloading '%s'\n", pid, si->name);
1264 call_destructors(si);
1265
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001266 /*
1267 * Make sure that we undo the PT_GNU_RELRO protections we added
1268 * in link_image. This is needed to undo the DT_NEEDED hack below.
1269 */
1270 if ((si->gnu_relro_start != 0) && (si->gnu_relro_len != 0)) {
1271 Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
1272 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1273 if (mprotect((void *) start, len, PROT_READ | PROT_WRITE) < 0)
1274 DL_ERR("%5d %s: could not undo GNU_RELRO protections. "
1275 "Expect a crash soon. errno=%d (%s)",
1276 pid, si->name, errno, strerror(errno));
1277
1278 }
1279
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001280 for(d = si->dynamic; *d; d += 2) {
1281 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001282 soinfo *lsi = (soinfo *)d[1];
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001283
1284 // The next line will segfault if the we don't undo the
1285 // PT_GNU_RELRO protections (see comments above and in
1286 // link_image().
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001287 d[1] = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001288
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001289 if (validate_soinfo(lsi)) {
1290 TRACE("%5d %s needs to unload %s\n", pid,
1291 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001292 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001293 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001294 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001295 DL_ERR("%5d %s: could not unload dependent library",
1296 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001297 }
1298 }
1299
1300 munmap((char *)si->base, si->size);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001301 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001302 free_info(si);
1303 si->refcount = 0;
1304 }
1305 else {
1306 si->refcount--;
1307 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1308 pid, si->name, si->refcount);
1309 }
1310 return si->refcount;
1311}
1312
1313/* TODO: don't use unsigned for addrs below. It works, but is not
1314 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1315 * long.
1316 */
1317static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1318{
1319 Elf32_Sym *symtab = si->symtab;
1320 const char *strtab = si->strtab;
1321 Elf32_Sym *s;
1322 unsigned base;
1323 Elf32_Rel *start = rel;
1324 unsigned idx;
1325
1326 for (idx = 0; idx < count; ++idx) {
1327 unsigned type = ELF32_R_TYPE(rel->r_info);
1328 unsigned sym = ELF32_R_SYM(rel->r_info);
1329 unsigned reloc = (unsigned)(rel->r_offset + si->base);
1330 unsigned sym_addr = 0;
1331 char *sym_name = NULL;
1332
1333 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1334 si->name, idx);
1335 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001336 sym_name = (char *)(strtab + symtab[sym].st_name);
1337 s = _do_lookup(si, sym_name, &base);
Doug Kwane8238072009-10-26 12:05:23 -07001338 if(s == NULL) {
1339 /* We only allow an undefined symbol if this is a weak
1340 reference.. */
1341 s = &symtab[sym];
1342 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1343 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1344 return -1;
1345 }
1346
1347 /* IHI0044C AAELF 4.5.1.1:
1348
1349 Libraries are not searched to resolve weak references.
1350 It is not an error for a weak reference to remain
1351 unsatisfied.
1352
1353 During linking, the value of an undefined weak reference is:
1354 - Zero if the relocation type is absolute
1355 - The address of the place if the relocation is pc-relative
1356 - The address of nominial base address if the relocation
1357 type is base-relative.
1358 */
1359
1360 switch (type) {
1361#if defined(ANDROID_ARM_LINKER)
1362 case R_ARM_JUMP_SLOT:
1363 case R_ARM_GLOB_DAT:
1364 case R_ARM_ABS32:
1365 case R_ARM_RELATIVE: /* Don't care. */
1366 case R_ARM_NONE: /* Don't care. */
1367#elif defined(ANDROID_X86_LINKER)
1368 case R_386_JUMP_SLOT:
1369 case R_386_GLOB_DAT:
1370 case R_386_32:
1371 case R_386_RELATIVE: /* Dont' care. */
1372#endif /* ANDROID_*_LINKER */
1373 /* sym_addr was initialized to be zero above or relocation
1374 code below does not care about value of sym_addr.
1375 No need to do anything. */
1376 break;
1377
1378#if defined(ANDROID_X86_LINKER)
1379 case R_386_PC32:
1380 sym_addr = reloc;
1381 break;
1382#endif /* ANDROID_X86_LINKER */
1383
1384#if defined(ANDROID_ARM_LINKER)
1385 case R_ARM_COPY:
1386 /* Fall through. Can't really copy if weak symbol is
1387 not found in run-time. */
1388#endif /* ANDROID_ARM_LINKER */
1389 default:
1390 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1391 pid, type, rel, (int) (rel - start));
1392 return -1;
1393 }
1394 } else {
1395 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001396#if 0
1397 if((base == 0) && (si->base != 0)){
1398 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001399 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001400 pid, strtab + symtab[sym].st_name);
1401 return -1;
1402 }
1403#endif
Doug Kwane8238072009-10-26 12:05:23 -07001404 sym_addr = (unsigned)(s->st_value + base);
1405 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 COUNT_RELOC(RELOC_SYMBOL);
1407 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001408 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001409 }
1410
1411/* TODO: This is ugly. Split up the relocations by arch into
1412 * different files.
1413 */
1414 switch(type){
1415#if defined(ANDROID_ARM_LINKER)
1416 case R_ARM_JUMP_SLOT:
1417 COUNT_RELOC(RELOC_ABSOLUTE);
1418 MARK(rel->r_offset);
1419 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1420 reloc, sym_addr, sym_name);
1421 *((unsigned*)reloc) = sym_addr;
1422 break;
1423 case R_ARM_GLOB_DAT:
1424 COUNT_RELOC(RELOC_ABSOLUTE);
1425 MARK(rel->r_offset);
1426 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1427 reloc, sym_addr, sym_name);
1428 *((unsigned*)reloc) = sym_addr;
1429 break;
1430 case R_ARM_ABS32:
1431 COUNT_RELOC(RELOC_ABSOLUTE);
1432 MARK(rel->r_offset);
1433 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1434 reloc, sym_addr, sym_name);
1435 *((unsigned*)reloc) += sym_addr;
1436 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001437 case R_ARM_REL32:
1438 COUNT_RELOC(RELOC_RELATIVE);
1439 MARK(rel->r_offset);
1440 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1441 reloc, sym_addr, rel->r_offset, sym_name);
1442 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1443 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001444#elif defined(ANDROID_X86_LINKER)
1445 case R_386_JUMP_SLOT:
1446 COUNT_RELOC(RELOC_ABSOLUTE);
1447 MARK(rel->r_offset);
1448 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1449 reloc, sym_addr, sym_name);
1450 *((unsigned*)reloc) = sym_addr;
1451 break;
1452 case R_386_GLOB_DAT:
1453 COUNT_RELOC(RELOC_ABSOLUTE);
1454 MARK(rel->r_offset);
1455 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1456 reloc, sym_addr, sym_name);
1457 *((unsigned*)reloc) = sym_addr;
1458 break;
1459#endif /* ANDROID_*_LINKER */
1460
1461#if defined(ANDROID_ARM_LINKER)
1462 case R_ARM_RELATIVE:
1463#elif defined(ANDROID_X86_LINKER)
1464 case R_386_RELATIVE:
1465#endif /* ANDROID_*_LINKER */
1466 COUNT_RELOC(RELOC_RELATIVE);
1467 MARK(rel->r_offset);
1468 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001469 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001470 return -1;
1471 }
1472 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1473 reloc, si->base);
1474 *((unsigned*)reloc) += si->base;
1475 break;
1476
1477#if defined(ANDROID_X86_LINKER)
1478 case R_386_32:
1479 COUNT_RELOC(RELOC_RELATIVE);
1480 MARK(rel->r_offset);
1481
1482 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1483 reloc, sym_addr, sym_name);
1484 *((unsigned *)reloc) += (unsigned)sym_addr;
1485 break;
1486
1487 case R_386_PC32:
1488 COUNT_RELOC(RELOC_RELATIVE);
1489 MARK(rel->r_offset);
1490 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1491 "+%08x (%08x - %08x) %s\n", pid, reloc,
1492 (sym_addr - reloc), sym_addr, reloc, sym_name);
1493 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1494 break;
1495#endif /* ANDROID_X86_LINKER */
1496
1497#ifdef ANDROID_ARM_LINKER
1498 case R_ARM_COPY:
1499 COUNT_RELOC(RELOC_COPY);
1500 MARK(rel->r_offset);
1501 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1502 reloc, s->st_size, sym_addr, sym_name);
1503 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1504 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001505 case R_ARM_NONE:
1506 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001507#endif /* ANDROID_ARM_LINKER */
1508
1509 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001510 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511 pid, type, rel, (int) (rel - start));
1512 return -1;
1513 }
1514 rel++;
1515 }
1516 return 0;
1517}
1518
David 'Digit' Turner82156792009-05-18 14:37:41 +02001519/* Please read the "Initialization and Termination functions" functions.
1520 * of the linker design note in bionic/linker/README.TXT to understand
1521 * what the following code is doing.
1522 *
1523 * The important things to remember are:
1524 *
1525 * DT_PREINIT_ARRAY must be called first for executables, and should
1526 * not appear in shared libraries.
1527 *
1528 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1529 *
1530 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1531 *
1532 * DT_FINI_ARRAY must be parsed in reverse order.
1533 */
1534
1535static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001536{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001537 int n, inc = 1;
1538
1539 if (reverse) {
1540 ctor += (count-1);
1541 inc = -1;
1542 }
1543
1544 for(n = count; n > 0; n--) {
1545 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1546 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001547 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001548 void (*func)() = (void (*)()) *ctor;
1549 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001550 if(((int) func == 0) || ((int) func == -1)) continue;
1551 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1552 func();
1553 }
1554}
1555
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001556void call_constructors_recursive(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001557{
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001558 if (si->constructors_called)
1559 return;
1560
Jesse Hallf5d16932012-01-30 15:39:57 -08001561 // Set this before actually calling the constructors, otherwise it doesn't
1562 // protect against recursive constructor calls. One simple example of
1563 // constructor recursion is the libc debug malloc, which is implemented in
1564 // libc_malloc_debug_leak.so:
1565 // 1. The program depends on libc, so libc's constructor is called here.
1566 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
1567 // 3. dlopen() calls call_constructors_recursive() with the newly created
1568 // soinfo for libc_malloc_debug_leak.so.
1569 // 4. The debug so depends on libc, so call_constructors_recursive() is
1570 // called again with the libc soinfo. If it doesn't trigger the early-
1571 // out above, the libc constructor will be called again (recursively!).
1572 si->constructors_called = 1;
1573
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001574 if (si->flags & FLAG_EXE) {
1575 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1576 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1577 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001578 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001579 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1580 } else {
1581 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001582 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001583 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001584 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001585 }
1586 }
1587
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001588 if (si->dynamic) {
1589 unsigned *d;
1590 for(d = si->dynamic; *d; d += 2) {
1591 if(d[0] == DT_NEEDED){
1592 soinfo* lsi = (soinfo *)d[1];
1593 if (!validate_soinfo(lsi)) {
1594 DL_ERR("%5d bad DT_NEEDED pointer in %s",
1595 pid, si->name);
1596 } else {
1597 call_constructors_recursive(lsi);
1598 }
1599 }
1600 }
1601 }
1602
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001603 if (si->init_func) {
1604 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1605 (unsigned)si->init_func, si->name);
1606 si->init_func();
1607 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1608 }
1609
1610 if (si->init_array) {
1611 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1612 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001613 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001614 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1615 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001617}
David 'Digit' Turner82156792009-05-18 14:37:41 +02001618
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001619static void call_destructors(soinfo *si)
1620{
1621 if (si->fini_array) {
1622 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1623 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001624 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001625 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1626 }
1627
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001628 if (si->fini_func) {
1629 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1630 (unsigned)si->fini_func, si->name);
1631 si->fini_func();
1632 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1633 }
1634}
1635
1636/* Force any of the closed stdin, stdout and stderr to be associated with
1637 /dev/null. */
1638static int nullify_closed_stdio (void)
1639{
1640 int dev_null, i, status;
1641 int return_value = 0;
1642
1643 dev_null = open("/dev/null", O_RDWR);
1644 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001645 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001646 return -1;
1647 }
1648 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1649
1650 /* If any of the stdio file descriptors is valid and not associated
1651 with /dev/null, dup /dev/null to it. */
1652 for (i = 0; i < 3; i++) {
1653 /* If it is /dev/null already, we are done. */
1654 if (i == dev_null)
1655 continue;
1656
1657 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1658 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1659 can be interrupted but we do this just to be safe. */
1660 do {
1661 status = fcntl(i, F_GETFL);
1662 } while (status < 0 && errno == EINTR);
1663
1664 /* If file is openned, we are good. */
1665 if (status >= 0)
1666 continue;
1667
1668 /* The only error we allow is that the file descriptor does not
1669 exist, in which case we dup /dev/null to it. */
1670 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001671 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001672 return_value = -1;
1673 continue;
1674 }
1675
1676 /* Try dupping /dev/null to this stdio file descriptor and
1677 repeat if there is a signal. Note that any errors in closing
1678 the stdio descriptor are lost. */
1679 do {
1680 status = dup2(dev_null, i);
1681 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001682
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001683 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001684 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001685 return_value = -1;
1686 continue;
1687 }
1688 }
1689
1690 /* If /dev/null is not one of the stdio file descriptors, close it. */
1691 if (dev_null > 2) {
1692 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001693 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001694 status = close(dev_null);
1695 } while (status < 0 && errno == EINTR);
1696
1697 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001698 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001699 return_value = -1;
1700 }
1701 }
1702
1703 return return_value;
1704}
1705
1706static int link_image(soinfo *si, unsigned wr_offset)
1707{
1708 unsigned *d;
1709 Elf32_Phdr *phdr = si->phdr;
1710 int phnum = si->phnum;
1711
1712 INFO("[ %5d linking %s ]\n", pid, si->name);
1713 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1714 si->base, si->flags);
1715
Nick Kralevich468319c2011-11-11 15:53:17 -08001716 if (si->flags & (FLAG_EXE | FLAG_LINKER)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
Nick Kralevich468319c2011-11-11 15:53:17 -08001718 * linkage info if this is the executable or the linker itself.
1719 * If this was a dynamic lib, that would have been done at load time.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001720 *
1721 * TODO: It's unfortunate that small pieces of this are
1722 * repeated from the load_library routine. Refactor this just
1723 * slightly to reuse these bits.
1724 */
1725 si->size = 0;
1726 for(; phnum > 0; --phnum, ++phdr) {
1727#ifdef ANDROID_ARM_LINKER
1728 if(phdr->p_type == PT_ARM_EXIDX) {
1729 /* exidx entries (used for stack unwinding) are 8 bytes each.
1730 */
1731 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1732 si->ARM_exidx_count = phdr->p_memsz / 8;
1733 }
1734#endif
1735 if (phdr->p_type == PT_LOAD) {
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001736 /* For the executable, we use the si->size field only in
1737 dl_unwind_find_exidx(), so the meaning of si->size
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001738 is not the size of the executable; it is the distance
1739 between the load location of the executable and the last
1740 address of the loadable part of the executable.
1741 We use the range [si->base, si->base + si->size) to
1742 determine whether a PC value falls within the executable
1743 section. Of course, if a value is between si->base and
1744 (si->base + phdr->p_vaddr), it's not in the executable
1745 section, but a) we shouldn't be asking for such a value
1746 anyway, and b) if we have to provide an EXIDX for such a
1747 value, then the executable's EXIDX is probably the better
1748 choice.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001749 */
1750 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1751 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1752 si->size = phdr->p_vaddr + phdr->p_memsz;
1753 /* try to remember what range of addresses should be write
1754 * protected */
1755 if (!(phdr->p_flags & PF_W)) {
1756 unsigned _end;
1757
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001758 if (si->base + phdr->p_vaddr < si->wrprotect_start)
1759 si->wrprotect_start = si->base + phdr->p_vaddr;
1760 _end = (((si->base + phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001761 (~PAGE_MASK)));
1762 if (_end > si->wrprotect_end)
1763 si->wrprotect_end = _end;
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001764 /* Make the section writable just in case we'll have to
1765 * write to it during relocation (i.e. text segment).
1766 * However, we will remember what range of addresses
1767 * should be write protected.
1768 */
1769 mprotect((void *) (si->base + phdr->p_vaddr),
1770 phdr->p_memsz,
1771 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001772 }
1773 } else if (phdr->p_type == PT_DYNAMIC) {
1774 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001775 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001776 "Segment at 0x%08x, previously one found at 0x%08x",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001777 pid, si->name, si->base + phdr->p_vaddr,
1778 (unsigned)si->dynamic);
1779 goto fail;
1780 }
1781 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1782 si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001783 } else if (phdr->p_type == PT_GNU_RELRO) {
1784 if ((phdr->p_vaddr >= si->size)
Nick Kralevichd73b5ca2012-03-16 11:38:58 -07001785 || ((phdr->p_vaddr + phdr->p_memsz) > si->size)
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001786 || ((si->base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
1787 DL_ERR("%d invalid GNU_RELRO in '%s' "
1788 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1789 phdr->p_vaddr, phdr->p_memsz);
1790 goto fail;
1791 }
1792 si->gnu_relro_start = (Elf32_Addr) (si->base + phdr->p_vaddr);
1793 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001794 }
1795 }
1796 }
1797
1798 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001799 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001800 goto fail;
1801 }
1802
1803 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1804
1805 /* extract useful information from dynamic section */
1806 for(d = si->dynamic; *d; d++){
1807 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1808 switch(*d++){
1809 case DT_HASH:
1810 si->nbucket = ((unsigned *) (si->base + *d))[0];
1811 si->nchain = ((unsigned *) (si->base + *d))[1];
1812 si->bucket = (unsigned *) (si->base + *d + 8);
1813 si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
1814 break;
1815 case DT_STRTAB:
1816 si->strtab = (const char *) (si->base + *d);
1817 break;
1818 case DT_SYMTAB:
1819 si->symtab = (Elf32_Sym *) (si->base + *d);
1820 break;
1821 case DT_PLTREL:
1822 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001823 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001824 goto fail;
1825 }
1826 break;
1827 case DT_JMPREL:
1828 si->plt_rel = (Elf32_Rel*) (si->base + *d);
1829 break;
1830 case DT_PLTRELSZ:
1831 si->plt_rel_count = *d / 8;
1832 break;
1833 case DT_REL:
1834 si->rel = (Elf32_Rel*) (si->base + *d);
1835 break;
1836 case DT_RELSZ:
1837 si->rel_count = *d / 8;
1838 break;
1839 case DT_PLTGOT:
1840 /* Save this in case we decide to do lazy binding. We don't yet. */
1841 si->plt_got = (unsigned *)(si->base + *d);
1842 break;
1843 case DT_DEBUG:
1844 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1845 *d = (int) &_r_debug;
1846 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001847 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001848 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001849 goto fail;
1850 case DT_INIT:
1851 si->init_func = (void (*)(void))(si->base + *d);
1852 DEBUG("%5d %s constructors (init func) found at %p\n",
1853 pid, si->name, si->init_func);
1854 break;
1855 case DT_FINI:
1856 si->fini_func = (void (*)(void))(si->base + *d);
1857 DEBUG("%5d %s destructors (fini func) found at %p\n",
1858 pid, si->name, si->fini_func);
1859 break;
1860 case DT_INIT_ARRAY:
1861 si->init_array = (unsigned *)(si->base + *d);
1862 DEBUG("%5d %s constructors (init_array) found at %p\n",
1863 pid, si->name, si->init_array);
1864 break;
1865 case DT_INIT_ARRAYSZ:
1866 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1867 break;
1868 case DT_FINI_ARRAY:
1869 si->fini_array = (unsigned *)(si->base + *d);
1870 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1871 pid, si->name, si->fini_array);
1872 break;
1873 case DT_FINI_ARRAYSZ:
1874 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1875 break;
1876 case DT_PREINIT_ARRAY:
1877 si->preinit_array = (unsigned *)(si->base + *d);
1878 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1879 pid, si->name, si->preinit_array);
1880 break;
1881 case DT_PREINIT_ARRAYSZ:
1882 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1883 break;
1884 case DT_TEXTREL:
1885 /* TODO: make use of this. */
1886 /* this means that we might have to write into where the text
1887 * segment was loaded during relocation... Do something with
1888 * it.
1889 */
1890 DEBUG("%5d Text segment should be writable during relocation.\n",
1891 pid);
1892 break;
1893 }
1894 }
1895
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001896 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001897 pid, si->base, si->strtab, si->symtab);
1898
1899 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001900 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001901 goto fail;
1902 }
1903
Matt Fischer4fd42c12009-12-31 12:09:10 -06001904 /* if this is the main executable, then load all of the preloads now */
1905 if(si->flags & FLAG_EXE) {
1906 int i;
1907 memset(preloads, 0, sizeof(preloads));
1908 for(i = 0; ldpreload_names[i] != NULL; i++) {
1909 soinfo *lsi = find_library(ldpreload_names[i]);
1910 if(lsi == 0) {
1911 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1912 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1913 pid, ldpreload_names[i], si->name, tmp_err_buf);
1914 goto fail;
1915 }
1916 lsi->refcount++;
1917 preloads[i] = lsi;
1918 }
1919 }
1920
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001921 for(d = si->dynamic; *d; d += 2) {
1922 if(d[0] == DT_NEEDED){
1923 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001924 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001925 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001926 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001927 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001928 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001929 goto fail;
1930 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001931 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1932 of the DT_NEEDED entry itself, so that we can retrieve the
1933 soinfo directly later from the dynamic segment. This is a hack,
1934 but it allows us to map from DT_NEEDED to soinfo efficiently
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001935 later on when we resolve relocations, trying to look up a symbol
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001936 with dlsym().
1937 */
1938 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001939 lsi->refcount++;
1940 }
1941 }
1942
1943 if(si->plt_rel) {
1944 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1945 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1946 goto fail;
1947 }
1948 if(si->rel) {
1949 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1950 if(reloc_library(si, si->rel, si->rel_count))
1951 goto fail;
1952 }
1953
1954 si->flags |= FLAG_LINKED;
1955 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1956
1957#if 0
1958 /* This is the way that the old dynamic linker did protection of
1959 * non-writable areas. It would scan section headers and find where
1960 * .text ended (rather where .data/.bss began) and assume that this is
1961 * the upper range of the non-writable area. This is too coarse,
1962 * and is kept here for reference until we fully move away from single
1963 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1964 * that made this possible.
1965 */
1966 if(wr_offset < 0xffffffff){
1967 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1968 }
1969#else
1970 /* TODO: Verify that this does the right thing in all cases, as it
1971 * presently probably does not. It is possible that an ELF image will
1972 * come with multiple read-only segments. What we ought to do is scan
1973 * the program headers again and mprotect all the read-only segments.
1974 * To prevent re-scanning the program header, we would have to build a
1975 * list of loadable segments in si, and then scan that instead. */
1976 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1977 mprotect((void *)si->wrprotect_start,
1978 si->wrprotect_end - si->wrprotect_start,
1979 PROT_READ | PROT_EXEC);
1980 }
1981#endif
1982
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001983 if (si->gnu_relro_start != 0 && si->gnu_relro_len != 0) {
1984 Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
1985 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1986 if (mprotect((void *) start, len, PROT_READ) < 0) {
1987 DL_ERR("%5d GNU_RELRO mprotect of library '%s' failed: %d (%s)\n",
1988 pid, si->name, errno, strerror(errno));
1989 goto fail;
1990 }
1991 }
1992
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001993 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1994 stdout and stderr to close a security hole described in:
1995
1996 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1997
1998 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001999 if (program_is_setuid)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002000 nullify_closed_stdio ();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002001 notify_gdb_of_load(si);
2002 return 0;
2003
2004fail:
Dima Zavina7161902010-08-17 15:56:40 -07002005 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002006 si->flags |= FLAG_ERROR;
2007 return -1;
2008}
2009
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002010static void parse_library_path(const char *path, char *delim)
David Bartleybc3a5c22009-06-02 18:27:28 -07002011{
2012 size_t len;
2013 char *ldpaths_bufp = ldpaths_buf;
2014 int i = 0;
2015
2016 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2017
2018 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2019 if (*ldpaths[i] != '\0')
2020 ++i;
2021 }
2022
2023 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2024 * last char isn't '\0' (i.e. not originally a delim). */
2025 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2026 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2027 ldpaths[i - 1] = NULL;
2028 } else {
2029 ldpaths[i] = NULL;
2030 }
2031}
2032
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002033static void parse_preloads(const char *path, char *delim)
Matt Fischer4fd42c12009-12-31 12:09:10 -06002034{
2035 size_t len;
2036 char *ldpreloads_bufp = ldpreloads_buf;
2037 int i = 0;
2038
2039 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2040
2041 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2042 if (*ldpreload_names[i] != '\0') {
2043 ++i;
2044 }
2045 }
2046
2047 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2048 * last char isn't '\0' (i.e. not originally a delim). */
2049 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2050 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2051 ldpreload_names[i - 1] = NULL;
2052 } else {
2053 ldpreload_names[i] = NULL;
2054 }
2055}
2056
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002057#define ANDROID_TLS_SLOTS BIONIC_TLS_SLOTS
2058
2059static void * __tls_area[ANDROID_TLS_SLOTS];
2060
Nick Kralevich468319c2011-11-11 15:53:17 -08002061/*
2062 * This code is called after the linker has linked itself and
2063 * fixed it's own GOT. It is safe to make references to externs
2064 * and other non-local data at this point.
2065 */
2066static unsigned __linker_init_post_relocation(unsigned **elfdata)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002067{
2068 static soinfo linker_soinfo;
2069
2070 int argc = (int) *elfdata;
2071 char **argv = (char**) (elfdata + 1);
Stephen Smalleybb440552012-01-20 10:59:15 -08002072 unsigned *vecs = (unsigned*) (argv + argc + 1);
2073 unsigned *v;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002074 soinfo *si;
2075 struct link_map * map;
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002076 const char *ldpath_env = NULL;
2077 const char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002078
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002079 /* Setup a temporary TLS area that is used to get a working
2080 * errno for system calls.
2081 */
2082 __set_tls(__tls_area);
2083
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002084 pid = getpid();
2085
2086#if TIMING
2087 struct timeval t0, t1;
2088 gettimeofday(&t0, 0);
2089#endif
2090
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002091 /* NOTE: we store the elfdata pointer on a special location
2092 * of the temporary TLS area in order to pass it to
2093 * the C Library's runtime initializer.
2094 *
2095 * The initializer must clear the slot and reset the TLS
2096 * to point to a different location to ensure that no other
2097 * shared library constructor can access it.
2098 */
2099 __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002100
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002101 /* Initialize environment functions, and get to the ELF aux vectors table */
2102 vecs = linker_env_init(vecs);
2103
Stephen Smalley861b42a2012-01-13 07:48:11 -05002104 /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
2105 has file caps, or caused a SELinux/AppArmor domain transition. */
2106 for (v = vecs; v[0]; v += 2) {
2107 if (v[0] == AT_SECURE) {
2108 /* kernel told us whether to enable secure mode */
2109 program_is_setuid = v[1];
2110 goto sanitize;
2111 }
2112 }
2113
2114 /* Kernel did not provide AT_SECURE - fall back on legacy test. */
2115 program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
2116
2117sanitize:
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002118 /* Sanitize environment if we're loading a setuid program */
2119 if (program_is_setuid)
2120 linker_env_secure();
2121
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002122 debugger_init();
2123
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002124 /* Get a few environment variables */
2125 {
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -07002126#if LINKER_DEBUG
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002127 const char* env;
2128 env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
2129 if (env)
2130 debug_verbosity = atoi(env);
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -07002131#endif
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002132
2133 /* Normally, these are cleaned by linker_env_secure, but the test
2134 * against program_is_setuid doesn't cost us anything */
2135 if (!program_is_setuid) {
2136 ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2137 ldpreload_env = linker_env_get("LD_PRELOAD");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002138 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002139 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002140
2141 INFO("[ android linker & debugger ]\n");
2142 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2143
2144 si = alloc_info(argv[0]);
2145 if(si == 0) {
2146 exit(-1);
2147 }
2148
2149 /* bootstrap the link map, the main exe always needs to be first */
2150 si->flags |= FLAG_EXE;
2151 map = &(si->linkmap);
2152
2153 map->l_addr = 0;
2154 map->l_name = argv[0];
2155 map->l_prev = NULL;
2156 map->l_next = NULL;
2157
2158 _r_debug.r_map = map;
2159 r_debug_tail = map;
2160
2161 /* gdb expects the linker to be in the debug shared object list,
2162 * and we need to make sure that the reported load address is zero.
2163 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2164 * is. Don't use alloc_info(), because the linker shouldn't
2165 * be on the soinfo list.
2166 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002167 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002168 linker_soinfo.flags = 0;
2169 linker_soinfo.base = 0; // This is the important part; must be zero.
2170 insert_soinfo_into_debug_map(&linker_soinfo);
2171
2172 /* extract information passed from the kernel */
2173 while(vecs[0] != 0){
2174 switch(vecs[0]){
2175 case AT_PHDR:
2176 si->phdr = (Elf32_Phdr*) vecs[1];
2177 break;
2178 case AT_PHNUM:
2179 si->phnum = (int) vecs[1];
2180 break;
2181 case AT_ENTRY:
2182 si->entry = vecs[1];
2183 break;
2184 }
2185 vecs += 2;
2186 }
2187
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002188 /* Compute the value of si->base. We can't rely on the fact that
2189 * the first entry is the PHDR because this will not be true
2190 * for certain executables (e.g. some in the NDK unit test suite)
2191 */
2192 int nn;
2193 si->base = 0;
2194 for ( nn = 0; nn < si->phnum; nn++ ) {
2195 if (si->phdr[nn].p_type == PT_PHDR) {
2196 si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_vaddr;
2197 break;
2198 }
2199 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002200 si->dynamic = (unsigned *)-1;
2201 si->wrprotect_start = 0xffffffff;
2202 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002203 si->refcount = 1;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002204 si->gnu_relro_start = 0;
2205 si->gnu_relro_len = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002206
David Bartleybc3a5c22009-06-02 18:27:28 -07002207 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002208 if (ldpath_env)
David Bartleybc3a5c22009-06-02 18:27:28 -07002209 parse_library_path(ldpath_env, ":");
2210
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002211 if (ldpreload_env) {
Matt Fischer4fd42c12009-12-31 12:09:10 -06002212 parse_preloads(ldpreload_env, " :");
2213 }
2214
Dima Zavin2e855792009-05-20 18:28:09 -07002215 if(link_image(si, 0)) {
2216 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2217 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2218 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002219 exit(-1);
2220 }
2221
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04002222 call_constructors_recursive(si);
2223
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002224#if ALLOW_SYMBOLS_FROM_MAIN
2225 /* Set somain after we've loaded all the libraries in order to prevent
2226 * linking of symbols back to the main image, which is not set up at that
2227 * point yet.
2228 */
2229 somain = si;
2230#endif
2231
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002232#if TIMING
2233 gettimeofday(&t1,NULL);
2234 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2235 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2236 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2237 ));
2238#endif
2239#if STATS
2240 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2241 linker_stats.reloc[RELOC_ABSOLUTE],
2242 linker_stats.reloc[RELOC_RELATIVE],
2243 linker_stats.reloc[RELOC_COPY],
2244 linker_stats.reloc[RELOC_SYMBOL]);
2245#endif
2246#if COUNT_PAGES
2247 {
2248 unsigned n;
2249 unsigned i;
2250 unsigned count = 0;
2251 for(n = 0; n < 4096; n++){
2252 if(bitmask[n]){
2253 unsigned x = bitmask[n];
2254 for(i = 0; i < 8; i++){
2255 if(x & 1) count++;
2256 x >>= 1;
2257 }
2258 }
2259 }
2260 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2261 }
2262#endif
2263
2264#if TIMING || STATS || COUNT_PAGES
2265 fflush(stdout);
2266#endif
2267
2268 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2269 si->entry);
2270 return si->entry;
2271}
Nick Kralevich468319c2011-11-11 15:53:17 -08002272
2273/*
2274 * Find the value of AT_BASE passed to us by the kernel. This is the load
2275 * location of the linker.
2276 */
2277static unsigned find_linker_base(unsigned **elfdata) {
2278 int argc = (int) *elfdata;
2279 char **argv = (char**) (elfdata + 1);
2280 unsigned *vecs = (unsigned*) (argv + argc + 1);
2281 while (vecs[0] != 0) {
2282 vecs++;
2283 }
2284
2285 /* The end of the environment block is marked by two NULL pointers */
2286 vecs++;
2287
2288 while(vecs[0]) {
2289 if (vecs[0] == AT_BASE) {
2290 return vecs[1];
2291 }
2292 vecs += 2;
2293 }
2294
2295 return 0; // should never happen
2296}
2297
2298/*
2299 * This is the entry point for the linker, called from begin.S. This
2300 * method is responsible for fixing the linker's own relocations, and
2301 * then calling __linker_init_post_relocation().
2302 *
2303 * Because this method is called before the linker has fixed it's own
2304 * relocations, any attempt to reference an extern variable, extern
2305 * function, or other GOT reference will generate a segfault.
2306 */
2307unsigned __linker_init(unsigned **elfdata) {
2308 unsigned linker_addr = find_linker_base(elfdata);
2309 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
2310 Elf32_Phdr *phdr =
2311 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);
2312
2313 soinfo linker_so;
2314 memset(&linker_so, 0, sizeof(soinfo));
2315
2316 linker_so.base = linker_addr;
2317 linker_so.dynamic = (unsigned *) -1;
2318 linker_so.phdr = phdr;
2319 linker_so.phnum = elf_hdr->e_phnum;
2320 linker_so.flags |= FLAG_LINKER;
2321 linker_so.wrprotect_start = 0xffffffff;
2322 linker_so.wrprotect_end = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002323 linker_so.gnu_relro_start = 0;
2324 linker_so.gnu_relro_len = 0;
Nick Kralevich468319c2011-11-11 15:53:17 -08002325
2326 if (link_image(&linker_so, 0)) {
2327 // It would be nice to print an error message, but if the linker
2328 // can't link itself, there's no guarantee that we'll be able to
2329 // call write() (because it involves a GOT reference).
2330 //
2331 // This situation should never occur unless the linker itself
2332 // is corrupt.
2333 exit(-1);
2334 }
2335
2336 // We have successfully fixed our own relocations. It's safe to run
2337 // the main part of the linker now.
2338 return __linker_init_post_relocation(elfdata);
2339}