blob: be90fd730c5fab5383e214ea7600f9aefc3f0b26 [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;
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900350 return (_Unwind_Ptr)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
411static unsigned elfhash(const char *_name)
412{
413 const unsigned char *name = (const unsigned char *) _name;
414 unsigned h = 0, g;
415
416 while(*name) {
417 h = (h << 4) + *name++;
418 g = h & 0xf0000000;
419 h ^= g;
420 h ^= g >> 24;
421 }
422 return h;
423}
424
425static Elf32_Sym *
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900426_do_lookup(soinfo *si, const char *name, unsigned *base, Elf32_Addr *offset)
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700427{
Doug Kwan94304352009-10-23 18:11:40 -0700428 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700429 Elf32_Sym *s;
430 unsigned *d;
431 soinfo *lsi = si;
Matt Fischer4fd42c12009-12-31 12:09:10 -0600432 int i;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700433
Nick Kralevich468319c2011-11-11 15:53:17 -0800434 /* Look for symbols in the local scope (the object who is
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700435 * searching). This happens with C++ templates on i386 for some
Doug Kwane8238072009-10-26 12:05:23 -0700436 * reason.
437 *
438 * Notes on weak symbols:
439 * The ELF specs are ambigious about treatment of weak definitions in
440 * dynamic linking. Some systems return the first definition found
441 * and some the first non-weak definition. This is system dependent.
442 * Here we return the first definition found for simplicity. */
Nick Kralevich468319c2011-11-11 15:53:17 -0800443
Doug Kwan94304352009-10-23 18:11:40 -0700444 s = _elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700445 if(s != NULL)
446 goto done;
447
Matt Fischer4fd42c12009-12-31 12:09:10 -0600448 /* Next, look for it in the preloads list */
449 for(i = 0; preloads[i] != NULL; i++) {
450 lsi = preloads[i];
Jean-Baptiste Queruf4394452010-05-12 10:05:59 -0700451 s = _elf_lookup(lsi, elf_hash, name);
Matt Fischer4fd42c12009-12-31 12:09:10 -0600452 if(s != NULL)
453 goto done;
454 }
455
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700456 for(d = si->dynamic; *d; d += 2) {
457 if(d[0] == DT_NEEDED){
458 lsi = (soinfo *)d[1];
459 if (!validate_soinfo(lsi)) {
460 DL_ERR("%5d bad DT_NEEDED pointer in %s",
461 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700462 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700463 }
464
465 DEBUG("%5d %s: looking up %s in %s\n",
466 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700467 s = _elf_lookup(lsi, elf_hash, name);
Min-su, Kim3cab22c2010-01-19 10:05:33 +0900468 if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700469 goto done;
470 }
471 }
472
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700473#if ALLOW_SYMBOLS_FROM_MAIN
474 /* If we are resolving relocations while dlopen()ing a library, it's OK for
475 * the library to resolve a symbol that's defined in the executable itself,
476 * although this is rare and is generally a bad idea.
477 */
478 if (somain) {
479 lsi = somain;
480 DEBUG("%5d %s: looking up %s in executable %s\n",
481 pid, si->name, name, lsi->name);
Doug Kwan94304352009-10-23 18:11:40 -0700482 s = _elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700483 }
484#endif
485
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700486done:
487 if(s != NULL) {
488 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900489 "found in %s, base = 0x%08x, load offset = 0x%08x\n",
490 pid, si->name, name, s->st_value,
491 lsi->name, lsi->base, lsi->load_offset);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700492 *base = lsi->base;
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900493 *offset = lsi->load_offset;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700494 return s;
495 }
496
Doug Kwan94304352009-10-23 18:11:40 -0700497 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700498}
499
500/* This is used by dl_sym(). It performs symbol lookup only within the
501 specified soinfo object and not in any of its dependencies.
502 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800503Elf32_Sym *lookup_in_library(soinfo *si, const char *name)
504{
Doug Kwan94304352009-10-23 18:11:40 -0700505 return _elf_lookup(si, elfhash(name), name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800506}
507
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700508/* This is used by dl_sym(). It performs a global symbol lookup.
509 */
Matt Fischer1698d9e2009-12-31 12:17:56 -0600510Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800511{
Doug Kwan94304352009-10-23 18:11:40 -0700512 unsigned elf_hash = elfhash(name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800513 Elf32_Sym *s = NULL;
514 soinfo *si;
515
Matt Fischer1698d9e2009-12-31 12:17:56 -0600516 if(start == NULL) {
517 start = solist;
518 }
519
520 for(si = start; (s == NULL) && (si != NULL); si = si->next)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800521 {
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700522 if(si->flags & FLAG_ERROR)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800523 continue;
Doug Kwane8238072009-10-26 12:05:23 -0700524 s = _elf_lookup(si, elf_hash, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800525 if (s != NULL) {
Iliyan Malchev9ea64da2009-09-28 18:21:30 -0700526 *found = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800527 break;
528 }
529 }
530
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700531 if(s != NULL) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800532 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
533 "si->base = 0x%08x\n", pid, name, s->st_value, si->base);
534 return s;
535 }
536
Doug Kwan94304352009-10-23 18:11:40 -0700537 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800538}
539
Mathias Agopianbda5da02011-09-27 22:30:19 -0700540soinfo *find_containing_library(const void *addr)
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600541{
542 soinfo *si;
543
544 for(si = solist; si != NULL; si = si->next)
545 {
546 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
547 return si;
548 }
549 }
550
551 return NULL;
552}
553
Mathias Agopianbda5da02011-09-27 22:30:19 -0700554Elf32_Sym *find_containing_symbol(const void *addr, soinfo *si)
Matt Fischere2a8b1f2009-12-31 12:17:40 -0600555{
556 unsigned int i;
557 unsigned soaddr = (unsigned)addr - si->base;
558
559 /* Search the library's symbol table for any defined symbol which
560 * contains this address */
561 for(i=0; i<si->nchain; i++) {
562 Elf32_Sym *sym = &si->symtab[i];
563
564 if(sym->st_shndx != SHN_UNDEF &&
565 soaddr >= sym->st_value &&
566 soaddr < sym->st_value + sym->st_size) {
567 return sym;
568 }
569 }
570
571 return NULL;
572}
573
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800574#if 0
575static void dump(soinfo *si)
576{
577 Elf32_Sym *s = si->symtab;
578 unsigned n;
579
580 for(n = 0; n < si->nchain; n++) {
581 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s,
582 s->st_info, s->st_shndx, s->st_value, s->st_size,
583 si->strtab + s->st_name);
584 s++;
585 }
586}
587#endif
588
589static const char *sopaths[] = {
Brian Swetlandfedbcde2010-09-19 03:39:13 -0700590 "/vendor/lib",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800591 "/system/lib",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800592 0
593};
594
595static int _open_lib(const char *name)
596{
597 int fd;
598 struct stat filestat;
599
600 if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
601 if ((fd = open(name, O_RDONLY)) >= 0)
602 return fd;
603 }
604
605 return -1;
606}
607
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800608static int open_library(const char *name)
609{
610 int fd;
611 char buf[512];
612 const char **path;
David Bartleybc3a5c22009-06-02 18:27:28 -0700613 int n;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614
615 TRACE("[ %5d opening %s ]\n", pid, name);
616
617 if(name == 0) return -1;
618 if(strlen(name) > 256) return -1;
619
620 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
621 return fd;
622
David Bartleybc3a5c22009-06-02 18:27:28 -0700623 for (path = ldpaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800624 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700625 if (n < 0 || n >= (int)sizeof(buf)) {
626 WARN("Ignoring very long library path: %s/%s\n", *path, name);
627 continue;
628 }
629 if ((fd = _open_lib(buf)) >= 0)
630 return fd;
631 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800632 for (path = sopaths; *path; path++) {
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800633 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
David Bartleybc3a5c22009-06-02 18:27:28 -0700634 if (n < 0 || n >= (int)sizeof(buf)) {
635 WARN("Ignoring very long library path: %s/%s\n", *path, name);
636 continue;
637 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800638 if ((fd = _open_lib(buf)) >= 0)
639 return fd;
640 }
641
642 return -1;
643}
644
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800645typedef struct {
646 long mmap_addr;
647 char tag[4]; /* 'P', 'R', 'E', ' ' */
648} prelink_info_t;
649
650/* Returns the requested base address if the library is prelinked,
651 * and 0 otherwise. */
652static unsigned long
653is_prelinked(int fd, const char *name)
654{
655 off_t sz;
656 prelink_info_t info;
657
658 sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
659 if (sz < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700660 DL_ERR("lseek() failed!");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800661 return 0;
662 }
663
664 if (read(fd, &info, sizeof(info)) != sizeof(info)) {
665 WARN("Could not read prelink_info_t structure for `%s`\n", name);
666 return 0;
667 }
668
669 if (strncmp(info.tag, "PRE ", 4)) {
670 WARN("`%s` is not a prelinked library\n", name);
671 return 0;
672 }
673
674 return (unsigned long)info.mmap_addr;
675}
676
677/* verify_elf_object
678 * Verifies if the object @ base is a valid ELF object
679 *
680 * Args:
681 *
682 * Returns:
683 * 0 on success
684 * -1 if no valid ELF object is found @ base.
685 */
686static int
687verify_elf_object(void *base, const char *name)
688{
689 Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
690
691 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
692 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
693 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
694 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
695
696 /* TODO: Should we verify anything else in the header? */
Zhenghua Wang897815a2011-10-19 00:29:14 +0800697#ifdef ANDROID_ARM_LINKER
698 if (hdr->e_machine != EM_ARM) return -1;
699#elif defined(ANDROID_X86_LINKER)
700 if (hdr->e_machine != EM_386) return -1;
701#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800702 return 0;
703}
704
705
706/* get_lib_extents
707 * Retrieves the base (*base) address where the ELF object should be
708 * mapped and its overall memory size (*total_sz).
709 *
710 * Args:
711 * fd: Opened file descriptor for the library
712 * name: The name of the library
713 * _hdr: Pointer to the header page of the library
714 * total_sz: Total size of the memory that should be allocated for
715 * this library
716 *
717 * Returns:
718 * -1 if there was an error while trying to get the lib extents.
719 * The possible reasons are:
720 * - Could not determine if the library was prelinked.
721 * - The library provided is not a valid ELF object
722 * 0 if the library did not request a specific base offset (normal
723 * for non-prelinked libs)
724 * > 0 if the library requests a specific address to be mapped to.
725 * This indicates a pre-linked library.
726 */
727static unsigned
728get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
729{
730 unsigned req_base;
731 unsigned min_vaddr = 0xffffffff;
732 unsigned max_vaddr = 0;
733 unsigned char *_hdr = (unsigned char *)__hdr;
734 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
735 Elf32_Phdr *phdr;
736 int cnt;
737
738 TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
739 if (verify_elf_object(_hdr, name) < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700740 DL_ERR("%5d - %s is not a valid ELF object", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800741 return (unsigned)-1;
742 }
743
744 req_base = (unsigned) is_prelinked(fd, name);
745 if (req_base == (unsigned)-1)
746 return -1;
747 else if (req_base != 0) {
748 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
749 pid, name, req_base);
750 } else {
751 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
752 }
753
754 phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
755
756 /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
757 * get the range. */
758 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
759 if (phdr->p_type == PT_LOAD) {
760 if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
761 max_vaddr = phdr->p_vaddr + phdr->p_memsz;
762 if (phdr->p_vaddr < min_vaddr)
763 min_vaddr = phdr->p_vaddr;
764 }
765 }
766
767 if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700768 DL_ERR("%5d - No loadable segments found in %s.", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800769 return (unsigned)-1;
770 }
771
772 /* truncate min_vaddr down to page boundary */
773 min_vaddr &= ~PAGE_MASK;
774
775 /* round max_vaddr up to the next page */
776 max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
777
778 *total_sz = (max_vaddr - min_vaddr);
779 return (unsigned)req_base;
780}
781
Nick Kralevich66259862012-03-16 13:06:12 -0700782/* reserve_mem_region
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800783 *
784 * This function reserves a chunk of memory to be used for mapping in
Nick Kralevich66259862012-03-16 13:06:12 -0700785 * a prelinked shared library. We reserve the entire memory region here, and
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800786 * then the rest of the linker will relocate the individual loadable
787 * segments into the correct locations within this memory range.
788 *
789 * Args:
Nick Kralevich66259862012-03-16 13:06:12 -0700790 * si->base: The requested base of the allocation.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800791 * si->size: The size of the allocation.
792 *
793 * Returns:
794 * -1 on failure, and 0 on success. On success, si->base will contain
795 * the virtual address at which the library will be mapped.
796 */
797
798static int reserve_mem_region(soinfo *si)
799{
Nick Kralevich66259862012-03-16 13:06:12 -0700800 void *base = mmap((void *)si->base, si->size, PROT_NONE,
Chris Dearmandb4bce02011-03-10 10:48:14 -0800801 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800802 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700803 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700804 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800805 pid, (si->base ? "" : "non-"), si->name, si->base,
806 errno, strerror(errno));
807 return -1;
808 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700809 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700810 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800811 si->name, (unsigned)base, si->base);
812 munmap(base, si->size);
813 return -1;
814 }
815 return 0;
816}
817
Nick Kralevich66259862012-03-16 13:06:12 -0700818static int alloc_mem_region(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800819{
820 if (si->base) {
821 /* Attempt to mmap a prelinked library. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800822 return reserve_mem_region(si);
823 }
824
Shih-wei Liao48527c32011-07-17 12:32:43 -0700825 /* This is not a prelinked library, so we use the kernel's default
826 allocator.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800827 */
Shih-wei Liao48527c32011-07-17 12:32:43 -0700828
Nick Kralevich66259862012-03-16 13:06:12 -0700829 void *base = mmap(NULL, si->size, PROT_NONE,
Shih-wei Liao48527c32011-07-17 12:32:43 -0700830 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
831 if (base == MAP_FAILED) {
832 DL_ERR("%5d mmap of library '%s' failed: %d (%s)\n",
833 pid, si->name,
834 errno, strerror(errno));
835 goto err;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800836 }
Shih-wei Liao48527c32011-07-17 12:32:43 -0700837 si->base = (unsigned) base;
838 PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
839 pid, si->name, si->base);
840 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800841
842err:
Erik Gillingd00d23a2009-07-22 17:06:11 -0700843 DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800844 pid, si->name);
845 return -1;
846}
847
848#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
849#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
850 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
851 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
852/* load_segments
853 *
854 * This function loads all the loadable (PT_LOAD) segments into memory
855 * at their appropriate memory offsets off the base address.
856 *
857 * Args:
858 * fd: Open file descriptor to the library to load.
859 * header: Pointer to a header page that contains the ELF header.
860 * This is needed since we haven't mapped in the real file yet.
861 * si: ptr to soinfo struct describing the shared object.
862 *
863 * Returns:
864 * 0 on success, -1 on failure.
865 */
866static int
867load_segments(int fd, void *header, soinfo *si)
868{
869 Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
870 Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900871 Elf32_Phdr *phdr0 = 0; /* program header for the first LOAD segment */
872 Elf32_Addr base;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800873 int cnt;
874 unsigned len;
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800875 Elf32_Addr tmp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800876 unsigned char *pbase;
877 unsigned char *extra_base;
878 unsigned extra_len;
879 unsigned total_sz = 0;
880
881 si->wrprotect_start = 0xffffffff;
882 si->wrprotect_end = 0;
883
884 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
885 pid, si->name, (unsigned)si->base);
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900886
887 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
888 if (phdr->p_type == PT_LOAD) {
889 phdr0 = phdr;
890 /*
891 * ELF specification section 2-2.
892 *
893 * PT_LOAD: "Loadable segment entries in the program
894 * header table appear in ascending order, sorted on the
895 * p_vaddr member."
896 */
897 si->load_offset = phdr->p_vaddr & (~PAGE_MASK);
898 break;
899 }
900 }
901 /* "base" might wrap around UINT32_MAX. */
902 base = (Elf32_Addr)(si->base - si->load_offset);
903
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800904 /* Now go through all the PT_LOAD segments and map them into memory
905 * at the appropriate locations. */
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900906 phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800907 for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
908 if (phdr->p_type == PT_LOAD) {
909 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
910 /* we want to map in the segment on a page boundary */
911 tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
912 /* add the # of bytes we masked off above to the total length. */
913 len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
914
915 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
916 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
917 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800918 pbase = mmap((void *)tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800919 MAP_PRIVATE | MAP_FIXED, fd,
920 phdr->p_offset & (~PAGE_MASK));
921 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700922 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700923 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800924 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
925 goto fail;
926 }
927
928 /* If 'len' didn't end on page boundary, and it's a writable
929 * segment, zero-fill the rest. */
930 if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
931 memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
932
933 /* Check to see if we need to extend the map for this segment to
934 * cover the diff between filesz and memsz (i.e. for bss).
935 *
936 * base _+---------------------+ page boundary
937 * . .
938 * | |
939 * . .
940 * pbase _+---------------------+ page boundary
941 * | |
942 * . .
943 * base + p_vaddr _| |
944 * . \ \ .
945 * . | filesz | .
946 * pbase + len _| / | |
947 * <0 pad> . . .
948 * extra_base _+------------|--------+ page boundary
949 * / . . .
950 * | . . .
951 * | +------------|--------+ page boundary
952 * extra_len-> | | | |
953 * | . | memsz .
954 * | . | .
955 * \ _| / |
956 * . .
957 * | |
958 * _+---------------------+ page boundary
959 */
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800960 tmp = (Elf32_Addr)(((unsigned)pbase + len + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800961 (~PAGE_MASK));
962 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
963 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
964 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
965 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
966 /* map in the extra page(s) as anonymous into the range.
967 * This is probably not necessary as we already mapped in
968 * the entire region previously, but we just want to be
969 * sure. This will also set the right flags on the region
970 * (though we can probably accomplish the same thing with
971 * mprotect).
972 */
973 extra_base = mmap((void *)tmp, extra_len,
974 PFLAGS_TO_PROT(phdr->p_flags),
975 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
976 -1, 0);
977 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700978 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700979 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800980 extra_len);
981 goto fail;
982 }
983 /* TODO: Check if we need to memset-0 this region.
984 * Anonymous mappings are zero-filled copy-on-writes, so we
985 * shouldn't need to. */
986 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
987 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
988 extra_len);
989 }
990 /* set the len here to show the full extent of the segment we
991 * just loaded, mostly for debugging */
992 len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
993 PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
994 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
995 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
996 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
997 total_sz += len;
998 /* Make the section writable just in case we'll have to write to
999 * it during relocation (i.e. text segment). However, we will
1000 * remember what range of addresses should be write protected.
1001 *
1002 */
1003 if (!(phdr->p_flags & PF_W)) {
1004 if ((unsigned)pbase < si->wrprotect_start)
1005 si->wrprotect_start = (unsigned)pbase;
1006 if (((unsigned)pbase + len) > si->wrprotect_end)
1007 si->wrprotect_end = (unsigned)pbase + len;
1008 mprotect(pbase, len,
1009 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
1010 }
1011 } else if (phdr->p_type == PT_DYNAMIC) {
1012 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
1013 /* this segment contains the dynamic linking information */
1014 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001015 } else if (phdr->p_type == PT_GNU_RELRO) {
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001016 if (((base + phdr->p_vaddr) >= si->base + si->size)
1017 || ((base + phdr->p_vaddr + phdr->p_memsz) > si->base + si->size)
1018 || ((base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001019 DL_ERR("%d invalid GNU_RELRO in '%s' "
1020 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1021 phdr->p_vaddr, phdr->p_memsz);
1022 goto fail;
1023 }
1024 si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
1025 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001026 } else {
1027#ifdef ANDROID_ARM_LINKER
1028 if (phdr->p_type == PT_ARM_EXIDX) {
1029 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
1030 /* exidx entries (used for stack unwinding) are 8 bytes each.
1031 */
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001032 si->ARM_exidx = (unsigned *)(base + phdr->p_vaddr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001033 si->ARM_exidx_count = phdr->p_memsz / 8;
1034 }
1035#endif
1036 }
1037
1038 }
1039
1040 /* Sanity check */
1041 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -07001042 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001043 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001044 pid, total_sz, si->name, si->size);
1045 goto fail;
1046 }
1047
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001048 /* vaddr : Real virtual address in process' address space.
1049 * p_vaddr : Relative virtual address in ELF object
1050 * p_offset : File offset in ELF object
1051 *
1052 * vaddr p_vaddr p_offset
1053 * ----- ------------ --------
1054 * base 0
1055 * si->base phdr0->p_vaddr & ~PAGE_MASK
1056 * phdr0->p_vaddr phdr0->p_offset
1057 * phdr ehdr->e_phoff
1058 */
1059 si->phdr = (Elf32_Phdr *)(base + phdr0->p_vaddr +
1060 ehdr->e_phoff - phdr0->p_offset);
1061 si->phnum = ehdr->e_phnum;
1062
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001063 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
1064 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
1065 (unsigned)si->base, si->size);
1066 return 0;
1067
1068fail:
1069 /* We can just blindly unmap the entire region even though some things
1070 * were mapped in originally with anonymous and others could have been
1071 * been mapped in from the file before we failed. The kernel will unmap
1072 * all the pages in the range, irrespective of how they got there.
1073 */
1074 munmap((void *)si->base, si->size);
1075 si->flags |= FLAG_ERROR;
1076 return -1;
1077}
1078
1079/* TODO: Implement this to take care of the fact that Android ARM
1080 * ELF objects shove everything into a single loadable segment that has the
1081 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
1082 * non-writable.
1083 */
1084#if 0
1085static unsigned
1086get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1087{
1088 Elf32_Shdr *shdr_start;
1089 Elf32_Shdr *shdr;
1090 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1091 int cnt;
1092 unsigned wr_offset = 0xffffffff;
1093
1094 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
1095 ehdr->e_shoff & (~PAGE_MASK));
1096 if (shdr_start == MAP_FAILED) {
1097 WARN("%5d - Could not read section header info from '%s'. Will not "
1098 "not be able to determine write-protect offset.\n", pid, name);
1099 return (unsigned)-1;
1100 }
1101
1102 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1103 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1104 (shdr->sh_addr < wr_offset)) {
1105 wr_offset = shdr->sh_addr;
1106 }
1107 }
1108
1109 munmap(shdr_start, shdr_sz);
1110 return wr_offset;
1111}
1112#endif
1113
1114static soinfo *
1115load_library(const char *name)
1116{
1117 int fd = open_library(name);
1118 int cnt;
1119 unsigned ext_sz;
1120 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001121 const char *bname;
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001122 struct stat sb;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001123 soinfo *si = NULL;
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001124 Elf32_Ehdr *hdr = MAP_FAILED;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001125
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001126 if (fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001127 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001128 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001129 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001130
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001131 /* We have to read the ELF header to figure out what to do with this image.
1132 * Map entire file for this. There won't be much difference in physical
1133 * memory usage or performance.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001134 */
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001135 if (fstat(fd, &sb) < 0) {
1136 DL_ERR("%5d fstat() failed! (%s)", pid, strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001137 goto fail;
1138 }
1139
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001140 hdr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1141 if (hdr == MAP_FAILED) {
1142 DL_ERR("%5d failed to mmap() header of '%s' (%s)",
1143 pid, name, strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001144 goto fail;
1145 }
1146
1147 /* Parse the ELF header and get the size of the memory footprint for
1148 * the library */
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001149 req_base = get_lib_extents(fd, name, hdr, &ext_sz);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001150 if (req_base == (unsigned)-1)
1151 goto fail;
1152 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1153 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1154
1155 /* Now configure the soinfo struct where we'll store all of our data
1156 * for the ELF object. If the loading fails, we waste the entry, but
1157 * same thing would happen if we failed during linking. Configuring the
1158 * soinfo struct here is a lot more convenient.
1159 */
Erik Gillingfde86422009-07-28 20:28:19 -07001160 bname = strrchr(name, '/');
1161 si = alloc_info(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001162 if (si == NULL)
1163 goto fail;
1164
1165 /* Carve out a chunk of memory where we will map in the individual
1166 * segments */
1167 si->base = req_base;
1168 si->size = ext_sz;
1169 si->flags = 0;
1170 si->entry = 0;
1171 si->dynamic = (unsigned *)-1;
1172 if (alloc_mem_region(si) < 0)
1173 goto fail;
1174
1175 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1176 pid, name, (void *)si->base, (unsigned) ext_sz);
1177
1178 /* Now actually load the library's segments into right places in memory */
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001179 if (load_segments(fd, hdr, si) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001180 goto fail;
1181 }
1182
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001183 munmap(hdr, sb.st_size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001184 close(fd);
1185 return si;
1186
1187fail:
1188 if (si) free_info(si);
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001189 if (hdr != MAP_FAILED) munmap(hdr, sb.st_size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001190 close(fd);
1191 return NULL;
1192}
1193
1194static soinfo *
1195init_library(soinfo *si)
1196{
1197 unsigned wr_offset = 0xffffffff;
1198
1199 /* At this point we know that whatever is loaded @ base is a valid ELF
1200 * shared library whose segments are properly mapped in. */
1201 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1202 pid, si->base, si->size, si->name);
1203
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001204 if(link_image(si, wr_offset)) {
1205 /* We failed to link. However, we can only restore libbase
1206 ** if no additional libraries have moved it since we updated it.
1207 */
1208 munmap((void *)si->base, si->size);
1209 return NULL;
1210 }
1211
1212 return si;
1213}
1214
1215soinfo *find_library(const char *name)
1216{
1217 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001218 const char *bname;
1219
1220#if ALLOW_SYMBOLS_FROM_MAIN
1221 if (name == NULL)
1222 return somain;
1223#else
1224 if (name == NULL)
1225 return NULL;
1226#endif
1227
1228 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001229 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001230
1231 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001232 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001233 if(si->flags & FLAG_ERROR) {
1234 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1235 return NULL;
1236 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001237 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001238 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001239 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 }
1241 }
1242
1243 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1244 si = load_library(name);
1245 if(si == NULL)
1246 return NULL;
1247 return init_library(si);
1248}
1249
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001250/* TODO:
1251 * notify gdb of unload
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001252 * for non-prelinked libraries, find a way to decrement libbase
1253 */
1254static void call_destructors(soinfo *si);
1255unsigned unload_library(soinfo *si)
1256{
1257 unsigned *d;
1258 if (si->refcount == 1) {
1259 TRACE("%5d unloading '%s'\n", pid, si->name);
1260 call_destructors(si);
1261
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001262 /*
1263 * Make sure that we undo the PT_GNU_RELRO protections we added
1264 * in link_image. This is needed to undo the DT_NEEDED hack below.
1265 */
1266 if ((si->gnu_relro_start != 0) && (si->gnu_relro_len != 0)) {
1267 Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
1268 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1269 if (mprotect((void *) start, len, PROT_READ | PROT_WRITE) < 0)
1270 DL_ERR("%5d %s: could not undo GNU_RELRO protections. "
1271 "Expect a crash soon. errno=%d (%s)",
1272 pid, si->name, errno, strerror(errno));
1273
1274 }
1275
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001276 for(d = si->dynamic; *d; d += 2) {
1277 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001278 soinfo *lsi = (soinfo *)d[1];
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001279
1280 // The next line will segfault if the we don't undo the
1281 // PT_GNU_RELRO protections (see comments above and in
1282 // link_image().
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001283 d[1] = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001284
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001285 if (validate_soinfo(lsi)) {
1286 TRACE("%5d %s needs to unload %s\n", pid,
1287 si->name, lsi->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001288 unload_library(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001289 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001290 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001291 DL_ERR("%5d %s: could not unload dependent library",
1292 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001293 }
1294 }
1295
1296 munmap((char *)si->base, si->size);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001297 notify_gdb_of_unload(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001298 free_info(si);
1299 si->refcount = 0;
1300 }
1301 else {
1302 si->refcount--;
1303 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1304 pid, si->name, si->refcount);
1305 }
1306 return si->refcount;
1307}
1308
1309/* TODO: don't use unsigned for addrs below. It works, but is not
1310 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1311 * long.
1312 */
1313static int reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
1314{
1315 Elf32_Sym *symtab = si->symtab;
1316 const char *strtab = si->strtab;
1317 Elf32_Sym *s;
1318 unsigned base;
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001319 Elf32_Addr offset;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001320 Elf32_Rel *start = rel;
1321 unsigned idx;
1322
1323 for (idx = 0; idx < count; ++idx) {
1324 unsigned type = ELF32_R_TYPE(rel->r_info);
1325 unsigned sym = ELF32_R_SYM(rel->r_info);
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001326 unsigned reloc = (unsigned)(rel->r_offset + si->base - si->load_offset);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001327 unsigned sym_addr = 0;
1328 char *sym_name = NULL;
1329
1330 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1331 si->name, idx);
1332 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001333 sym_name = (char *)(strtab + symtab[sym].st_name);
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001334 s = _do_lookup(si, sym_name, &base, &offset);
Doug Kwane8238072009-10-26 12:05:23 -07001335 if(s == NULL) {
1336 /* We only allow an undefined symbol if this is a weak
1337 reference.. */
1338 s = &symtab[sym];
1339 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1340 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1341 return -1;
1342 }
1343
1344 /* IHI0044C AAELF 4.5.1.1:
1345
1346 Libraries are not searched to resolve weak references.
1347 It is not an error for a weak reference to remain
1348 unsatisfied.
1349
1350 During linking, the value of an undefined weak reference is:
1351 - Zero if the relocation type is absolute
1352 - The address of the place if the relocation is pc-relative
1353 - The address of nominial base address if the relocation
1354 type is base-relative.
1355 */
1356
1357 switch (type) {
1358#if defined(ANDROID_ARM_LINKER)
1359 case R_ARM_JUMP_SLOT:
1360 case R_ARM_GLOB_DAT:
1361 case R_ARM_ABS32:
1362 case R_ARM_RELATIVE: /* Don't care. */
1363 case R_ARM_NONE: /* Don't care. */
1364#elif defined(ANDROID_X86_LINKER)
1365 case R_386_JUMP_SLOT:
1366 case R_386_GLOB_DAT:
1367 case R_386_32:
1368 case R_386_RELATIVE: /* Dont' care. */
1369#endif /* ANDROID_*_LINKER */
1370 /* sym_addr was initialized to be zero above or relocation
1371 code below does not care about value of sym_addr.
1372 No need to do anything. */
1373 break;
1374
1375#if defined(ANDROID_X86_LINKER)
1376 case R_386_PC32:
1377 sym_addr = reloc;
1378 break;
1379#endif /* ANDROID_X86_LINKER */
1380
1381#if defined(ANDROID_ARM_LINKER)
1382 case R_ARM_COPY:
1383 /* Fall through. Can't really copy if weak symbol is
1384 not found in run-time. */
1385#endif /* ANDROID_ARM_LINKER */
1386 default:
1387 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1388 pid, type, rel, (int) (rel - start));
1389 return -1;
1390 }
1391 } else {
1392 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001393#if 0
1394 if((base == 0) && (si->base != 0)){
1395 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001396 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 pid, strtab + symtab[sym].st_name);
1398 return -1;
1399 }
1400#endif
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001401 sym_addr = (unsigned)(s->st_value + base - offset);
Doug Kwane8238072009-10-26 12:05:23 -07001402 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001403 COUNT_RELOC(RELOC_SYMBOL);
1404 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001405 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001406 }
1407
1408/* TODO: This is ugly. Split up the relocations by arch into
1409 * different files.
1410 */
1411 switch(type){
1412#if defined(ANDROID_ARM_LINKER)
1413 case R_ARM_JUMP_SLOT:
1414 COUNT_RELOC(RELOC_ABSOLUTE);
1415 MARK(rel->r_offset);
1416 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1417 reloc, sym_addr, sym_name);
1418 *((unsigned*)reloc) = sym_addr;
1419 break;
1420 case R_ARM_GLOB_DAT:
1421 COUNT_RELOC(RELOC_ABSOLUTE);
1422 MARK(rel->r_offset);
1423 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1424 reloc, sym_addr, sym_name);
1425 *((unsigned*)reloc) = sym_addr;
1426 break;
1427 case R_ARM_ABS32:
1428 COUNT_RELOC(RELOC_ABSOLUTE);
1429 MARK(rel->r_offset);
1430 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1431 reloc, sym_addr, sym_name);
1432 *((unsigned*)reloc) += sym_addr;
1433 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001434 case R_ARM_REL32:
1435 COUNT_RELOC(RELOC_RELATIVE);
1436 MARK(rel->r_offset);
1437 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1438 reloc, sym_addr, rel->r_offset, sym_name);
1439 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1440 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001441#elif defined(ANDROID_X86_LINKER)
1442 case R_386_JUMP_SLOT:
1443 COUNT_RELOC(RELOC_ABSOLUTE);
1444 MARK(rel->r_offset);
1445 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1446 reloc, sym_addr, sym_name);
1447 *((unsigned*)reloc) = sym_addr;
1448 break;
1449 case R_386_GLOB_DAT:
1450 COUNT_RELOC(RELOC_ABSOLUTE);
1451 MARK(rel->r_offset);
1452 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1453 reloc, sym_addr, sym_name);
1454 *((unsigned*)reloc) = sym_addr;
1455 break;
1456#endif /* ANDROID_*_LINKER */
1457
1458#if defined(ANDROID_ARM_LINKER)
1459 case R_ARM_RELATIVE:
1460#elif defined(ANDROID_X86_LINKER)
1461 case R_386_RELATIVE:
1462#endif /* ANDROID_*_LINKER */
1463 COUNT_RELOC(RELOC_RELATIVE);
1464 MARK(rel->r_offset);
1465 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001466 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001467 return -1;
1468 }
1469 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1470 reloc, si->base);
1471 *((unsigned*)reloc) += si->base;
1472 break;
1473
1474#if defined(ANDROID_X86_LINKER)
1475 case R_386_32:
1476 COUNT_RELOC(RELOC_RELATIVE);
1477 MARK(rel->r_offset);
1478
1479 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1480 reloc, sym_addr, sym_name);
1481 *((unsigned *)reloc) += (unsigned)sym_addr;
1482 break;
1483
1484 case R_386_PC32:
1485 COUNT_RELOC(RELOC_RELATIVE);
1486 MARK(rel->r_offset);
1487 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1488 "+%08x (%08x - %08x) %s\n", pid, reloc,
1489 (sym_addr - reloc), sym_addr, reloc, sym_name);
1490 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1491 break;
1492#endif /* ANDROID_X86_LINKER */
1493
1494#ifdef ANDROID_ARM_LINKER
1495 case R_ARM_COPY:
1496 COUNT_RELOC(RELOC_COPY);
1497 MARK(rel->r_offset);
1498 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1499 reloc, s->st_size, sym_addr, sym_name);
1500 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1501 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001502 case R_ARM_NONE:
1503 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001504#endif /* ANDROID_ARM_LINKER */
1505
1506 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001507 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001508 pid, type, rel, (int) (rel - start));
1509 return -1;
1510 }
1511 rel++;
1512 }
1513 return 0;
1514}
1515
David 'Digit' Turner82156792009-05-18 14:37:41 +02001516/* Please read the "Initialization and Termination functions" functions.
1517 * of the linker design note in bionic/linker/README.TXT to understand
1518 * what the following code is doing.
1519 *
1520 * The important things to remember are:
1521 *
1522 * DT_PREINIT_ARRAY must be called first for executables, and should
1523 * not appear in shared libraries.
1524 *
1525 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1526 *
1527 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1528 *
1529 * DT_FINI_ARRAY must be parsed in reverse order.
1530 */
1531
1532static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001533{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001534 int n, inc = 1;
1535
1536 if (reverse) {
1537 ctor += (count-1);
1538 inc = -1;
1539 }
1540
1541 for(n = count; n > 0; n--) {
1542 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1543 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001544 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001545 void (*func)() = (void (*)()) *ctor;
1546 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001547 if(((int) func == 0) || ((int) func == -1)) continue;
1548 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1549 func();
1550 }
1551}
1552
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001553void call_constructors_recursive(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001554{
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001555 if (si->constructors_called)
1556 return;
1557
Jesse Hallf5d16932012-01-30 15:39:57 -08001558 // Set this before actually calling the constructors, otherwise it doesn't
1559 // protect against recursive constructor calls. One simple example of
1560 // constructor recursion is the libc debug malloc, which is implemented in
1561 // libc_malloc_debug_leak.so:
1562 // 1. The program depends on libc, so libc's constructor is called here.
1563 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
1564 // 3. dlopen() calls call_constructors_recursive() with the newly created
1565 // soinfo for libc_malloc_debug_leak.so.
1566 // 4. The debug so depends on libc, so call_constructors_recursive() is
1567 // called again with the libc soinfo. If it doesn't trigger the early-
1568 // out above, the libc constructor will be called again (recursively!).
1569 si->constructors_called = 1;
1570
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001571 if (si->flags & FLAG_EXE) {
1572 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1573 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1574 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001575 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001576 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1577 } else {
1578 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001579 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001580 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001581 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001582 }
1583 }
1584
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001585 if (si->dynamic) {
1586 unsigned *d;
1587 for(d = si->dynamic; *d; d += 2) {
1588 if(d[0] == DT_NEEDED){
1589 soinfo* lsi = (soinfo *)d[1];
1590 if (!validate_soinfo(lsi)) {
1591 DL_ERR("%5d bad DT_NEEDED pointer in %s",
1592 pid, si->name);
1593 } else {
1594 call_constructors_recursive(lsi);
1595 }
1596 }
1597 }
1598 }
1599
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001600 if (si->init_func) {
1601 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1602 (unsigned)si->init_func, si->name);
1603 si->init_func();
1604 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1605 }
1606
1607 if (si->init_array) {
1608 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1609 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001610 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001611 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1612 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001613
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001614}
David 'Digit' Turner82156792009-05-18 14:37:41 +02001615
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616static void call_destructors(soinfo *si)
1617{
1618 if (si->fini_array) {
1619 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1620 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001621 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001622 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1623 }
1624
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001625 if (si->fini_func) {
1626 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1627 (unsigned)si->fini_func, si->name);
1628 si->fini_func();
1629 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1630 }
1631}
1632
1633/* Force any of the closed stdin, stdout and stderr to be associated with
1634 /dev/null. */
1635static int nullify_closed_stdio (void)
1636{
1637 int dev_null, i, status;
1638 int return_value = 0;
1639
1640 dev_null = open("/dev/null", O_RDWR);
1641 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001642 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001643 return -1;
1644 }
1645 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1646
1647 /* If any of the stdio file descriptors is valid and not associated
1648 with /dev/null, dup /dev/null to it. */
1649 for (i = 0; i < 3; i++) {
1650 /* If it is /dev/null already, we are done. */
1651 if (i == dev_null)
1652 continue;
1653
1654 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1655 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1656 can be interrupted but we do this just to be safe. */
1657 do {
1658 status = fcntl(i, F_GETFL);
1659 } while (status < 0 && errno == EINTR);
1660
1661 /* If file is openned, we are good. */
1662 if (status >= 0)
1663 continue;
1664
1665 /* The only error we allow is that the file descriptor does not
1666 exist, in which case we dup /dev/null to it. */
1667 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001668 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001669 return_value = -1;
1670 continue;
1671 }
1672
1673 /* Try dupping /dev/null to this stdio file descriptor and
1674 repeat if there is a signal. Note that any errors in closing
1675 the stdio descriptor are lost. */
1676 do {
1677 status = dup2(dev_null, i);
1678 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001679
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001680 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001681 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001682 return_value = -1;
1683 continue;
1684 }
1685 }
1686
1687 /* If /dev/null is not one of the stdio file descriptors, close it. */
1688 if (dev_null > 2) {
1689 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001690 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001691 status = close(dev_null);
1692 } while (status < 0 && errno == EINTR);
1693
1694 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001695 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001696 return_value = -1;
1697 }
1698 }
1699
1700 return return_value;
1701}
1702
1703static int link_image(soinfo *si, unsigned wr_offset)
1704{
1705 unsigned *d;
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001706 /* "base" might wrap around UINT32_MAX. */
1707 Elf32_Addr base = si->base - si->load_offset;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001708 Elf32_Phdr *phdr = si->phdr;
1709 int phnum = si->phnum;
1710
1711 INFO("[ %5d linking %s ]\n", pid, si->name);
1712 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1713 si->base, si->flags);
1714
Nick Kralevich468319c2011-11-11 15:53:17 -08001715 if (si->flags & (FLAG_EXE | FLAG_LINKER)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001716 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001717 * linkage info if this is the executable or the linker itself.
Nick Kralevich468319c2011-11-11 15:53:17 -08001718 * If this was a dynamic lib, that would have been done at load time.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001719 *
1720 * TODO: It's unfortunate that small pieces of this are
1721 * repeated from the load_library routine. Refactor this just
1722 * slightly to reuse these bits.
1723 */
1724 si->size = 0;
1725 for(; phnum > 0; --phnum, ++phdr) {
1726#ifdef ANDROID_ARM_LINKER
1727 if(phdr->p_type == PT_ARM_EXIDX) {
1728 /* exidx entries (used for stack unwinding) are 8 bytes each.
1729 */
1730 si->ARM_exidx = (unsigned *)phdr->p_vaddr;
1731 si->ARM_exidx_count = phdr->p_memsz / 8;
1732 }
1733#endif
1734 if (phdr->p_type == PT_LOAD) {
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001735 /* For the executable, we use the si->size field only in
1736 dl_unwind_find_exidx(), so the meaning of si->size
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001737 is not the size of the executable; it is the distance
1738 between the load location of the executable and the last
1739 address of the loadable part of the executable.
1740 We use the range [si->base, si->base + si->size) to
1741 determine whether a PC value falls within the executable
1742 section. Of course, if a value is between si->base and
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001743 (base + phdr->p_vaddr), it's not in the executable
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001744 section, but a) we shouldn't be asking for such a value
1745 anyway, and b) if we have to provide an EXIDX for such a
1746 value, then the executable's EXIDX is probably the better
1747 choice.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001748 */
1749 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1750 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1751 si->size = phdr->p_vaddr + phdr->p_memsz;
1752 /* try to remember what range of addresses should be write
1753 * protected */
1754 if (!(phdr->p_flags & PF_W)) {
1755 unsigned _end;
1756
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001757 if (base + phdr->p_vaddr < si->wrprotect_start)
1758 si->wrprotect_start = base + phdr->p_vaddr;
1759 _end = (((base + phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001760 (~PAGE_MASK)));
1761 if (_end > si->wrprotect_end)
1762 si->wrprotect_end = _end;
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001763 /* Make the section writable just in case we'll have to
1764 * write to it during relocation (i.e. text segment).
1765 * However, we will remember what range of addresses
1766 * should be write protected.
1767 */
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001768 mprotect((void *) (base + phdr->p_vaddr),
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001769 phdr->p_memsz,
1770 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001771 }
1772 } else if (phdr->p_type == PT_DYNAMIC) {
1773 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001774 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001775 "Segment at 0x%08x, previously one found at 0x%08x",
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001776 pid, si->name, base + phdr->p_vaddr,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001777 (unsigned)si->dynamic);
1778 goto fail;
1779 }
1780 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001781 si->dynamic = (unsigned *) (base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001782 } else if (phdr->p_type == PT_GNU_RELRO) {
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001783 if ((base + phdr->p_vaddr >= si->base + si->size)
1784 || ((base + phdr->p_vaddr + phdr->p_memsz) > si->base + si->size)
1785 || ((base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001786 DL_ERR("%d invalid GNU_RELRO in '%s' "
1787 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1788 phdr->p_vaddr, phdr->p_memsz);
1789 goto fail;
1790 }
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001791 si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001792 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001793 }
1794 }
1795 }
1796
1797 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001798 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001799 goto fail;
1800 }
1801
1802 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1803
1804 /* extract useful information from dynamic section */
1805 for(d = si->dynamic; *d; d++){
1806 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1807 switch(*d++){
1808 case DT_HASH:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001809 si->nbucket = ((unsigned *) (base + *d))[0];
1810 si->nchain = ((unsigned *) (base + *d))[1];
1811 si->bucket = (unsigned *) (base + *d + 8);
1812 si->chain = (unsigned *) (base + *d + 8 + si->nbucket * 4);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001813 break;
1814 case DT_STRTAB:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001815 si->strtab = (const char *) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001816 break;
1817 case DT_SYMTAB:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001818 si->symtab = (Elf32_Sym *) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001819 break;
1820 case DT_PLTREL:
1821 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001822 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001823 goto fail;
1824 }
1825 break;
1826 case DT_JMPREL:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001827 si->plt_rel = (Elf32_Rel*) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001828 break;
1829 case DT_PLTRELSZ:
1830 si->plt_rel_count = *d / 8;
1831 break;
1832 case DT_REL:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001833 si->rel = (Elf32_Rel*) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001834 break;
1835 case DT_RELSZ:
1836 si->rel_count = *d / 8;
1837 break;
1838 case DT_PLTGOT:
1839 /* Save this in case we decide to do lazy binding. We don't yet. */
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001840 si->plt_got = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001841 break;
1842 case DT_DEBUG:
1843 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1844 *d = (int) &_r_debug;
1845 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001846 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001847 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001848 goto fail;
1849 case DT_INIT:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001850 si->init_func = (void (*)(void))(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001851 DEBUG("%5d %s constructors (init func) found at %p\n",
1852 pid, si->name, si->init_func);
1853 break;
1854 case DT_FINI:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001855 si->fini_func = (void (*)(void))(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001856 DEBUG("%5d %s destructors (fini func) found at %p\n",
1857 pid, si->name, si->fini_func);
1858 break;
1859 case DT_INIT_ARRAY:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001860 si->init_array = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001861 DEBUG("%5d %s constructors (init_array) found at %p\n",
1862 pid, si->name, si->init_array);
1863 break;
1864 case DT_INIT_ARRAYSZ:
1865 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1866 break;
1867 case DT_FINI_ARRAY:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001868 si->fini_array = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001869 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1870 pid, si->name, si->fini_array);
1871 break;
1872 case DT_FINI_ARRAYSZ:
1873 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1874 break;
1875 case DT_PREINIT_ARRAY:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001876 si->preinit_array = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001877 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1878 pid, si->name, si->preinit_array);
1879 break;
1880 case DT_PREINIT_ARRAYSZ:
1881 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1882 break;
1883 case DT_TEXTREL:
1884 /* TODO: make use of this. */
1885 /* this means that we might have to write into where the text
1886 * segment was loaded during relocation... Do something with
1887 * it.
1888 */
1889 DEBUG("%5d Text segment should be writable during relocation.\n",
1890 pid);
1891 break;
1892 }
1893 }
1894
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001895 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001896 pid, si->base, si->strtab, si->symtab);
1897
1898 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001899 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001900 goto fail;
1901 }
1902
Matt Fischer4fd42c12009-12-31 12:09:10 -06001903 /* if this is the main executable, then load all of the preloads now */
1904 if(si->flags & FLAG_EXE) {
1905 int i;
1906 memset(preloads, 0, sizeof(preloads));
1907 for(i = 0; ldpreload_names[i] != NULL; i++) {
1908 soinfo *lsi = find_library(ldpreload_names[i]);
1909 if(lsi == 0) {
1910 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1911 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1912 pid, ldpreload_names[i], si->name, tmp_err_buf);
1913 goto fail;
1914 }
1915 lsi->refcount++;
1916 preloads[i] = lsi;
1917 }
1918 }
1919
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001920 for(d = si->dynamic; *d; d += 2) {
1921 if(d[0] == DT_NEEDED){
1922 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001923 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001924 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001925 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001926 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001927 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001928 goto fail;
1929 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001930 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1931 of the DT_NEEDED entry itself, so that we can retrieve the
1932 soinfo directly later from the dynamic segment. This is a hack,
1933 but it allows us to map from DT_NEEDED to soinfo efficiently
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001934 later on when we resolve relocations, trying to look up a symbol
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001935 with dlsym().
1936 */
1937 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001938 lsi->refcount++;
1939 }
1940 }
1941
1942 if(si->plt_rel) {
1943 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
1944 if(reloc_library(si, si->plt_rel, si->plt_rel_count))
1945 goto fail;
1946 }
1947 if(si->rel) {
1948 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
1949 if(reloc_library(si, si->rel, si->rel_count))
1950 goto fail;
1951 }
1952
1953 si->flags |= FLAG_LINKED;
1954 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1955
1956#if 0
1957 /* This is the way that the old dynamic linker did protection of
1958 * non-writable areas. It would scan section headers and find where
1959 * .text ended (rather where .data/.bss began) and assume that this is
1960 * the upper range of the non-writable area. This is too coarse,
1961 * and is kept here for reference until we fully move away from single
1962 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1963 * that made this possible.
1964 */
1965 if(wr_offset < 0xffffffff){
1966 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1967 }
1968#else
1969 /* TODO: Verify that this does the right thing in all cases, as it
1970 * presently probably does not. It is possible that an ELF image will
1971 * come with multiple read-only segments. What we ought to do is scan
1972 * the program headers again and mprotect all the read-only segments.
1973 * To prevent re-scanning the program header, we would have to build a
1974 * list of loadable segments in si, and then scan that instead. */
1975 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1976 mprotect((void *)si->wrprotect_start,
1977 si->wrprotect_end - si->wrprotect_start,
1978 PROT_READ | PROT_EXEC);
1979 }
1980#endif
1981
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001982 if (si->gnu_relro_start != 0 && si->gnu_relro_len != 0) {
1983 Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
1984 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1985 if (mprotect((void *) start, len, PROT_READ) < 0) {
1986 DL_ERR("%5d GNU_RELRO mprotect of library '%s' failed: %d (%s)\n",
1987 pid, si->name, errno, strerror(errno));
1988 goto fail;
1989 }
1990 }
1991
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001992 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1993 stdout and stderr to close a security hole described in:
1994
1995 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1996
1997 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001998 if (program_is_setuid)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001999 nullify_closed_stdio ();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002000 notify_gdb_of_load(si);
2001 return 0;
2002
2003fail:
Dima Zavina7161902010-08-17 15:56:40 -07002004 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002005 si->flags |= FLAG_ERROR;
2006 return -1;
2007}
2008
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002009static void parse_library_path(const char *path, char *delim)
David Bartleybc3a5c22009-06-02 18:27:28 -07002010{
2011 size_t len;
2012 char *ldpaths_bufp = ldpaths_buf;
2013 int i = 0;
2014
2015 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
2016
2017 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
2018 if (*ldpaths[i] != '\0')
2019 ++i;
2020 }
2021
2022 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2023 * last char isn't '\0' (i.e. not originally a delim). */
2024 if (i > 0 && len >= sizeof(ldpaths_buf) &&
2025 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
2026 ldpaths[i - 1] = NULL;
2027 } else {
2028 ldpaths[i] = NULL;
2029 }
2030}
2031
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002032static void parse_preloads(const char *path, char *delim)
Matt Fischer4fd42c12009-12-31 12:09:10 -06002033{
2034 size_t len;
2035 char *ldpreloads_bufp = ldpreloads_buf;
2036 int i = 0;
2037
2038 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
2039
2040 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
2041 if (*ldpreload_names[i] != '\0') {
2042 ++i;
2043 }
2044 }
2045
2046 /* Forget the last path if we had to truncate; this occurs if the 2nd to
2047 * last char isn't '\0' (i.e. not originally a delim). */
2048 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
2049 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
2050 ldpreload_names[i - 1] = NULL;
2051 } else {
2052 ldpreload_names[i] = NULL;
2053 }
2054}
2055
Nick Kralevich468319c2011-11-11 15:53:17 -08002056/*
2057 * This code is called after the linker has linked itself and
2058 * fixed it's own GOT. It is safe to make references to externs
2059 * and other non-local data at this point.
2060 */
2061static unsigned __linker_init_post_relocation(unsigned **elfdata)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002062{
2063 static soinfo linker_soinfo;
2064
2065 int argc = (int) *elfdata;
2066 char **argv = (char**) (elfdata + 1);
Stephen Smalleybb440552012-01-20 10:59:15 -08002067 unsigned *vecs = (unsigned*) (argv + argc + 1);
2068 unsigned *v;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002069 soinfo *si;
2070 struct link_map * map;
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002071 const char *ldpath_env = NULL;
2072 const char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002073
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002074 /* NOTE: we store the elfdata pointer on a special location
2075 * of the temporary TLS area in order to pass it to
2076 * the C Library's runtime initializer.
2077 *
2078 * The initializer must clear the slot and reset the TLS
2079 * to point to a different location to ensure that no other
2080 * shared library constructor can access it.
2081 */
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +04002082 __libc_init_tls(elfdata);
2083
2084 pid = getpid();
2085
2086#if TIMING
2087 struct timeval t0, t1;
2088 gettimeofday(&t0, 0);
2089#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002090
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002091 /* Initialize environment functions, and get to the ELF aux vectors table */
2092 vecs = linker_env_init(vecs);
2093
Stephen Smalley861b42a2012-01-13 07:48:11 -05002094 /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
2095 has file caps, or caused a SELinux/AppArmor domain transition. */
2096 for (v = vecs; v[0]; v += 2) {
2097 if (v[0] == AT_SECURE) {
2098 /* kernel told us whether to enable secure mode */
2099 program_is_setuid = v[1];
2100 goto sanitize;
2101 }
2102 }
2103
2104 /* Kernel did not provide AT_SECURE - fall back on legacy test. */
2105 program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
2106
2107sanitize:
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002108 /* Sanitize environment if we're loading a setuid program */
2109 if (program_is_setuid)
2110 linker_env_secure();
2111
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002112 debugger_init();
2113
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002114 /* Get a few environment variables */
2115 {
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -07002116#if LINKER_DEBUG
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002117 const char* env;
2118 env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
2119 if (env)
2120 debug_verbosity = atoi(env);
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -07002121#endif
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002122
2123 /* Normally, these are cleaned by linker_env_secure, but the test
2124 * against program_is_setuid doesn't cost us anything */
2125 if (!program_is_setuid) {
2126 ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2127 ldpreload_env = linker_env_get("LD_PRELOAD");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002128 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002129 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002130
2131 INFO("[ android linker & debugger ]\n");
2132 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2133
2134 si = alloc_info(argv[0]);
2135 if(si == 0) {
2136 exit(-1);
2137 }
2138
2139 /* bootstrap the link map, the main exe always needs to be first */
2140 si->flags |= FLAG_EXE;
2141 map = &(si->linkmap);
2142
2143 map->l_addr = 0;
2144 map->l_name = argv[0];
2145 map->l_prev = NULL;
2146 map->l_next = NULL;
2147
2148 _r_debug.r_map = map;
2149 r_debug_tail = map;
2150
2151 /* gdb expects the linker to be in the debug shared object list,
2152 * and we need to make sure that the reported load address is zero.
2153 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
2154 * is. Don't use alloc_info(), because the linker shouldn't
2155 * be on the soinfo list.
2156 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002157 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002158 linker_soinfo.flags = 0;
2159 linker_soinfo.base = 0; // This is the important part; must be zero.
2160 insert_soinfo_into_debug_map(&linker_soinfo);
2161
2162 /* extract information passed from the kernel */
2163 while(vecs[0] != 0){
2164 switch(vecs[0]){
2165 case AT_PHDR:
2166 si->phdr = (Elf32_Phdr*) vecs[1];
2167 break;
2168 case AT_PHNUM:
2169 si->phnum = (int) vecs[1];
2170 break;
2171 case AT_ENTRY:
2172 si->entry = vecs[1];
2173 break;
2174 }
2175 vecs += 2;
2176 }
2177
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002178 /* Compute the value of si->base. We can't rely on the fact that
2179 * the first entry is the PHDR because this will not be true
2180 * for certain executables (e.g. some in the NDK unit test suite)
2181 */
2182 int nn;
2183 si->base = 0;
2184 for ( nn = 0; nn < si->phnum; nn++ ) {
2185 if (si->phdr[nn].p_type == PT_PHDR) {
2186 si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_vaddr;
2187 break;
2188 }
2189 }
Ji-Hwan Leef186a182012-05-31 20:20:36 +09002190 si->load_offset = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002191 si->dynamic = (unsigned *)-1;
2192 si->wrprotect_start = 0xffffffff;
2193 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002194 si->refcount = 1;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002195 si->gnu_relro_start = 0;
2196 si->gnu_relro_len = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002197
David Bartleybc3a5c22009-06-02 18:27:28 -07002198 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002199 if (ldpath_env)
David Bartleybc3a5c22009-06-02 18:27:28 -07002200 parse_library_path(ldpath_env, ":");
2201
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002202 if (ldpreload_env) {
Matt Fischer4fd42c12009-12-31 12:09:10 -06002203 parse_preloads(ldpreload_env, " :");
2204 }
2205
Dima Zavin2e855792009-05-20 18:28:09 -07002206 if(link_image(si, 0)) {
2207 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2208 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2209 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002210 exit(-1);
2211 }
2212
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04002213 call_constructors_recursive(si);
2214
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002215#if ALLOW_SYMBOLS_FROM_MAIN
2216 /* Set somain after we've loaded all the libraries in order to prevent
2217 * linking of symbols back to the main image, which is not set up at that
2218 * point yet.
2219 */
2220 somain = si;
2221#endif
2222
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002223#if TIMING
2224 gettimeofday(&t1,NULL);
2225 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2226 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2227 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2228 ));
2229#endif
2230#if STATS
2231 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2232 linker_stats.reloc[RELOC_ABSOLUTE],
2233 linker_stats.reloc[RELOC_RELATIVE],
2234 linker_stats.reloc[RELOC_COPY],
2235 linker_stats.reloc[RELOC_SYMBOL]);
2236#endif
2237#if COUNT_PAGES
2238 {
2239 unsigned n;
2240 unsigned i;
2241 unsigned count = 0;
2242 for(n = 0; n < 4096; n++){
2243 if(bitmask[n]){
2244 unsigned x = bitmask[n];
2245 for(i = 0; i < 8; i++){
2246 if(x & 1) count++;
2247 x >>= 1;
2248 }
2249 }
2250 }
2251 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2252 }
2253#endif
2254
2255#if TIMING || STATS || COUNT_PAGES
2256 fflush(stdout);
2257#endif
2258
2259 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2260 si->entry);
2261 return si->entry;
2262}
Nick Kralevich468319c2011-11-11 15:53:17 -08002263
2264/*
2265 * Find the value of AT_BASE passed to us by the kernel. This is the load
2266 * location of the linker.
2267 */
2268static unsigned find_linker_base(unsigned **elfdata) {
2269 int argc = (int) *elfdata;
2270 char **argv = (char**) (elfdata + 1);
2271 unsigned *vecs = (unsigned*) (argv + argc + 1);
2272 while (vecs[0] != 0) {
2273 vecs++;
2274 }
2275
2276 /* The end of the environment block is marked by two NULL pointers */
2277 vecs++;
2278
2279 while(vecs[0]) {
2280 if (vecs[0] == AT_BASE) {
2281 return vecs[1];
2282 }
2283 vecs += 2;
2284 }
2285
2286 return 0; // should never happen
2287}
2288
2289/*
2290 * This is the entry point for the linker, called from begin.S. This
2291 * method is responsible for fixing the linker's own relocations, and
2292 * then calling __linker_init_post_relocation().
2293 *
2294 * Because this method is called before the linker has fixed it's own
2295 * relocations, any attempt to reference an extern variable, extern
2296 * function, or other GOT reference will generate a segfault.
2297 */
2298unsigned __linker_init(unsigned **elfdata) {
2299 unsigned linker_addr = find_linker_base(elfdata);
2300 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
2301 Elf32_Phdr *phdr =
2302 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);
2303
2304 soinfo linker_so;
2305 memset(&linker_so, 0, sizeof(soinfo));
2306
2307 linker_so.base = linker_addr;
Ji-Hwan Leef186a182012-05-31 20:20:36 +09002308 linker_so.load_offset = 0;
Nick Kralevich468319c2011-11-11 15:53:17 -08002309 linker_so.dynamic = (unsigned *) -1;
2310 linker_so.phdr = phdr;
2311 linker_so.phnum = elf_hdr->e_phnum;
2312 linker_so.flags |= FLAG_LINKER;
2313 linker_so.wrprotect_start = 0xffffffff;
2314 linker_so.wrprotect_end = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002315 linker_so.gnu_relro_start = 0;
2316 linker_so.gnu_relro_len = 0;
Nick Kralevich468319c2011-11-11 15:53:17 -08002317
2318 if (link_image(&linker_so, 0)) {
2319 // It would be nice to print an error message, but if the linker
2320 // can't link itself, there's no guarantee that we'll be able to
2321 // call write() (because it involves a GOT reference).
2322 //
2323 // This situation should never occur unless the linker itself
2324 // is corrupt.
2325 exit(-1);
2326 }
2327
2328 // We have successfully fixed our own relocations. It's safe to run
2329 // the main part of the linker now.
2330 return __linker_init_post_relocation(elfdata);
2331}