blob: c725d0209727ad3851ae2f8cb7ffa54baaa31a73 [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"
David 'Digit' Turner23363ed2012-06-18 18:13:49 +020053#include "linker_phdr.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080054
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070055#define ALLOW_SYMBOLS_FROM_MAIN 1
Kenny Root72f9a5c2011-02-10 17:02:21 -080056#define SO_MAX 128
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080057
David Bartleybc3a5c22009-06-02 18:27:28 -070058/* Assume average path length of 64 and max 8 paths */
59#define LDPATH_BUFSIZE 512
60#define LDPATH_MAX 8
61
Matt Fischer4fd42c12009-12-31 12:09:10 -060062#define LDPRELOAD_BUFSIZE 512
63#define LDPRELOAD_MAX 8
64
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080065/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
66 *
67 * Do NOT use malloc() and friends or pthread_*() code here.
68 * Don't use printf() either; it's caused mysterious memory
69 * corruption in the past.
70 * The linker runs before we bring up libc and it's easiest
71 * to make sure it does not depend on any complex libc features
72 *
73 * open issues / todo:
74 *
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080075 * - are we doing everything we should for ARM_COPY relocations?
76 * - cleaner error reporting
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080077 * - after linking, set as much stuff as possible to READONLY
78 * and NOEXEC
79 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
80 * headers provide versions that are negative...
81 * - allocate space for soinfo structs dynamically instead of
82 * having a hard limit (64)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080083*/
84
85
David 'Digit' Turner16084162012-06-12 16:25:37 +020086static int soinfo_link_image(soinfo *si, unsigned wr_offset);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087
88static int socount = 0;
89static soinfo sopool[SO_MAX];
90static soinfo *freelist = NULL;
91static soinfo *solist = &libdl_info;
92static soinfo *sonext = &libdl_info;
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -070093#if ALLOW_SYMBOLS_FROM_MAIN
94static soinfo *somain; /* main process, always the one after libdl_info */
95#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080096
Iliyan Malchevaf7315a2009-10-16 17:50:42 -070097
Iliyan Malchev6ed80c82009-09-28 19:38:04 -070098static inline int validate_soinfo(soinfo *si)
99{
100 return (si >= sopool && si < sopool + SO_MAX) ||
101 si == &libdl_info;
102}
103
David Bartleybc3a5c22009-06-02 18:27:28 -0700104static char ldpaths_buf[LDPATH_BUFSIZE];
105static const char *ldpaths[LDPATH_MAX + 1];
106
Matt Fischer4fd42c12009-12-31 12:09:10 -0600107static char ldpreloads_buf[LDPRELOAD_BUFSIZE];
108static const char *ldpreload_names[LDPRELOAD_MAX + 1];
109
110static soinfo *preloads[LDPRELOAD_MAX + 1];
111
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -0700112#if LINKER_DEBUG
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800113int debug_verbosity;
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -0700114#endif
115
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800116static int pid;
117
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100118/* This boolean is set if the program being loaded is setuid */
119static int program_is_setuid;
120
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800121#if STATS
122struct _link_stats linker_stats;
123#endif
124
125#if COUNT_PAGES
126unsigned bitmask[4096];
127#endif
128
129#ifndef PT_ARM_EXIDX
130#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
131#endif
132
Dima Zavin2e855792009-05-20 18:28:09 -0700133#define HOODLUM(name, ret, ...) \
134 ret name __VA_ARGS__ \
135 { \
136 char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
137 write(2, errstr, sizeof(errstr)); \
138 abort(); \
139 }
140HOODLUM(malloc, void *, (size_t size));
141HOODLUM(free, void, (void *ptr));
142HOODLUM(realloc, void *, (void *ptr, size_t size));
143HOODLUM(calloc, void *, (size_t cnt, size_t size));
144
Dima Zavin03531952009-05-29 17:30:25 -0700145static char tmp_err_buf[768];
Dima Zavin2e855792009-05-20 18:28:09 -0700146static char __linker_dl_err_buf[768];
147#define DL_ERR(fmt, x...) \
148 do { \
David 'Digit' Turner5c734642010-01-20 12:36:51 -0800149 format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), \
Dima Zavin2e855792009-05-20 18:28:09 -0700150 "%s[%d]: " fmt, __func__, __LINE__, ##x); \
Erik Gillingd00d23a2009-07-22 17:06:11 -0700151 ERROR(fmt "\n", ##x); \
Dima Zavin2e855792009-05-20 18:28:09 -0700152 } while(0)
153
154const char *linker_get_error(void)
155{
156 return (const char *)&__linker_dl_err_buf[0];
157}
158
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800159/*
160 * This function is an empty stub where GDB locates a breakpoint to get notified
161 * about linker activity.
162 */
163extern void __attribute__((noinline)) rtld_db_dlactivity(void);
164
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800165static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
166 RT_CONSISTENT, 0};
167static struct link_map *r_debug_tail = 0;
168
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700169static pthread_mutex_t _r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800170
171static void insert_soinfo_into_debug_map(soinfo * info)
172{
173 struct link_map * map;
174
175 /* Copy the necessary fields into the debug structure.
176 */
177 map = &(info->linkmap);
178 map->l_addr = info->base;
179 map->l_name = (char*) info->name;
Thinker K.F Li5cf640c2009-07-03 19:40:32 +0800180 map->l_ld = (uintptr_t)info->dynamic;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800181
182 /* Stick the new library at the end of the list.
183 * gdb tends to care more about libc than it does
184 * about leaf libraries, and ordering it this way
185 * reduces the back-and-forth over the wire.
186 */
187 if (r_debug_tail) {
188 r_debug_tail->l_next = map;
189 map->l_prev = r_debug_tail;
190 map->l_next = 0;
191 } else {
192 _r_debug.r_map = map;
193 map->l_prev = 0;
194 map->l_next = 0;
195 }
196 r_debug_tail = map;
197}
198
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700199static void remove_soinfo_from_debug_map(soinfo * info)
200{
201 struct link_map * map = &(info->linkmap);
202
203 if (r_debug_tail == map)
204 r_debug_tail = map->l_prev;
205
206 if (map->l_prev) map->l_prev->l_next = map->l_next;
207 if (map->l_next) map->l_next->l_prev = map->l_prev;
208}
209
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800210void notify_gdb_of_load(soinfo * info)
211{
212 if (info->flags & FLAG_EXE) {
213 // GDB already knows about the main executable
214 return;
215 }
216
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700217 pthread_mutex_lock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800218
219 _r_debug.r_state = RT_ADD;
220 rtld_db_dlactivity();
221
222 insert_soinfo_into_debug_map(info);
223
224 _r_debug.r_state = RT_CONSISTENT;
225 rtld_db_dlactivity();
226
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -0700227 pthread_mutex_unlock(&_r_debug_lock);
228}
229
230void notify_gdb_of_unload(soinfo * info)
231{
232 if (info->flags & FLAG_EXE) {
233 // GDB already knows about the main executable
234 return;
235 }
236
237 pthread_mutex_lock(&_r_debug_lock);
238
239 _r_debug.r_state = RT_DELETE;
240 rtld_db_dlactivity();
241
242 remove_soinfo_from_debug_map(info);
243
244 _r_debug.r_state = RT_CONSISTENT;
245 rtld_db_dlactivity();
246
247 pthread_mutex_unlock(&_r_debug_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248}
249
250void notify_gdb_of_libraries()
251{
252 _r_debug.r_state = RT_ADD;
253 rtld_db_dlactivity();
254 _r_debug.r_state = RT_CONSISTENT;
255 rtld_db_dlactivity();
256}
257
David 'Digit' Turner16084162012-06-12 16:25:37 +0200258static soinfo *soinfo_alloc(const char *name)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800259{
260 soinfo *si;
261
262 if(strlen(name) >= SOINFO_NAME_LEN) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700263 DL_ERR("%5d library name %s too long", pid, name);
Doug Kwan94304352009-10-23 18:11:40 -0700264 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800265 }
266
David 'Digit' Turner16084162012-06-12 16:25:37 +0200267 /* The freelist is populated when we call soinfo_free(), which in turn is
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800268 done only by dlclose(), which is not likely to be used.
269 */
270 if (!freelist) {
271 if(socount == SO_MAX) {
Erik Gillingd00d23a2009-07-22 17:06:11 -0700272 DL_ERR("%5d too many libraries when loading %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800273 return NULL;
274 }
275 freelist = sopool + socount++;
276 freelist->next = NULL;
277 }
278
279 si = freelist;
280 freelist = freelist->next;
281
282 /* Make sure we get a clean block of soinfo */
283 memset(si, 0, sizeof(soinfo));
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100284 strlcpy((char*) si->name, name, sizeof(si->name));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800285 sonext->next = si;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800286 si->next = NULL;
287 si->refcount = 0;
288 sonext = si;
289
290 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si);
291 return si;
292}
293
David 'Digit' Turner16084162012-06-12 16:25:37 +0200294static void soinfo_free(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800295{
296 soinfo *prev = NULL, *trav;
297
298 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si);
299
300 for(trav = solist; trav != NULL; trav = trav->next){
301 if (trav == si)
302 break;
303 prev = trav;
304 }
305 if (trav == NULL) {
306 /* si was not ni solist */
Erik Gillingd00d23a2009-07-22 17:06:11 -0700307 DL_ERR("%5d name %s is not in solist!", pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800308 return;
309 }
310
David 'Digit' Turnerbe575592010-12-16 19:52:02 +0100311 /* prev will never be NULL, because the first entry in solist is
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800312 always the static libdl_info.
313 */
314 prev->next = si->next;
315 if (si == sonext) sonext = prev;
316 si->next = freelist;
317 freelist = si;
318}
319
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800320const char *addr_to_name(unsigned addr)
321{
322 soinfo *si;
323
324 for(si = solist; si != 0; si = si->next){
325 if((addr >= si->base) && (addr < (si->base + si->size))) {
326 return si->name;
327 }
328 }
329
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330 return "";
331}
332
333/* For a given PC, find the .so that it belongs to.
334 * Returns the base address of the .ARM.exidx section
335 * for that .so, and the number of 8-byte entries
336 * in that section (via *pcount).
337 *
338 * Intended to be called by libc's __gnu_Unwind_Find_exidx().
339 *
340 * This function is exposed via dlfcn.c and libdl.so.
341 */
342#ifdef ANDROID_ARM_LINKER
343_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
344{
345 soinfo *si;
346 unsigned addr = (unsigned)pc;
347
Nick Kralevich468319c2011-11-11 15:53:17 -0800348 for (si = solist; si != 0; si = si->next){
349 if ((addr >= si->base) && (addr < (si->base + si->size))) {
350 *pcount = si->ARM_exidx_count;
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900351 return (_Unwind_Ptr)si->ARM_exidx;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800352 }
353 }
354 *pcount = 0;
355 return NULL;
356}
David 'Digit' Turner70b16682012-01-30 17:17:58 +0100357#elif defined(ANDROID_X86_LINKER)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800358/* Here, we only have to provide a callback to iterate across all the
359 * loaded libraries. gcc_eh does the rest. */
360int
361dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
362 void *data)
363{
364 soinfo *si;
365 struct dl_phdr_info dl_info;
366 int rv = 0;
367
368 for (si = solist; si != NULL; si = si->next) {
369 dl_info.dlpi_addr = si->linkmap.l_addr;
370 dl_info.dlpi_name = si->linkmap.l_name;
371 dl_info.dlpi_phdr = si->phdr;
372 dl_info.dlpi_phnum = si->phnum;
373 rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
374 if (rv != 0)
375 break;
376 }
377 return rv;
378}
379#endif
380
David 'Digit' Turner16084162012-06-12 16:25:37 +0200381static Elf32_Sym *soinfo_elf_lookup(soinfo *si, unsigned hash, const char *name)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800382{
383 Elf32_Sym *s;
384 Elf32_Sym *symtab = si->symtab;
385 const char *strtab = si->strtab;
386 unsigned n;
387
388 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid,
389 name, si->name, si->base, hash, hash % si->nbucket);
390 n = hash % si->nbucket;
391
392 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
393 s = symtab + n;
394 if(strcmp(strtab + s->st_name, name)) continue;
395
Doug Kwane8238072009-10-26 12:05:23 -0700396 /* only concern ourselves with global and weak symbol definitions */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800397 switch(ELF32_ST_BIND(s->st_info)){
398 case STB_GLOBAL:
Doug Kwane8238072009-10-26 12:05:23 -0700399 case STB_WEAK:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800400 /* no section == undefined */
401 if(s->st_shndx == 0) continue;
402
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800403 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid,
404 name, si->name, s->st_value, s->st_size);
405 return s;
406 }
407 }
408
Doug Kwan94304352009-10-23 18:11:40 -0700409 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800410}
411
412static unsigned elfhash(const char *_name)
413{
414 const unsigned char *name = (const unsigned char *) _name;
415 unsigned h = 0, g;
416
417 while(*name) {
418 h = (h << 4) + *name++;
419 g = h & 0xf0000000;
420 h ^= g;
421 h ^= g >> 24;
422 }
423 return h;
424}
425
426static Elf32_Sym *
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +0200427soinfo_do_lookup(soinfo *si, const char *name, Elf32_Addr *offset)
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700428{
Doug Kwan94304352009-10-23 18:11:40 -0700429 unsigned elf_hash = elfhash(name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700430 Elf32_Sym *s;
431 unsigned *d;
432 soinfo *lsi = si;
Matt Fischer4fd42c12009-12-31 12:09:10 -0600433 int i;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700434
Nick Kralevich468319c2011-11-11 15:53:17 -0800435 /* Look for symbols in the local scope (the object who is
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700436 * searching). This happens with C++ templates on i386 for some
Doug Kwane8238072009-10-26 12:05:23 -0700437 * reason.
438 *
439 * Notes on weak symbols:
440 * The ELF specs are ambigious about treatment of weak definitions in
441 * dynamic linking. Some systems return the first definition found
442 * and some the first non-weak definition. This is system dependent.
443 * Here we return the first definition found for simplicity. */
Nick Kralevich468319c2011-11-11 15:53:17 -0800444
David 'Digit' Turner16084162012-06-12 16:25:37 +0200445 s = soinfo_elf_lookup(si, elf_hash, name);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700446 if(s != NULL)
447 goto done;
448
Matt Fischer4fd42c12009-12-31 12:09:10 -0600449 /* Next, look for it in the preloads list */
450 for(i = 0; preloads[i] != NULL; i++) {
451 lsi = preloads[i];
David 'Digit' Turner16084162012-06-12 16:25:37 +0200452 s = soinfo_elf_lookup(lsi, elf_hash, name);
Matt Fischer4fd42c12009-12-31 12:09:10 -0600453 if(s != NULL)
454 goto done;
455 }
456
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700457 for(d = si->dynamic; *d; d += 2) {
458 if(d[0] == DT_NEEDED){
459 lsi = (soinfo *)d[1];
460 if (!validate_soinfo(lsi)) {
461 DL_ERR("%5d bad DT_NEEDED pointer in %s",
462 pid, si->name);
Doug Kwan94304352009-10-23 18:11:40 -0700463 return NULL;
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700464 }
465
466 DEBUG("%5d %s: looking up %s in %s\n",
467 pid, si->name, name, lsi->name);
David 'Digit' Turner16084162012-06-12 16:25:37 +0200468 s = soinfo_elf_lookup(lsi, elf_hash, name);
Min-su, Kim3cab22c2010-01-19 10:05:33 +0900469 if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700470 goto done;
471 }
472 }
473
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700474#if ALLOW_SYMBOLS_FROM_MAIN
475 /* If we are resolving relocations while dlopen()ing a library, it's OK for
476 * the library to resolve a symbol that's defined in the executable itself,
477 * although this is rare and is generally a bad idea.
478 */
479 if (somain) {
480 lsi = somain;
481 DEBUG("%5d %s: looking up %s in executable %s\n",
482 pid, si->name, name, lsi->name);
David 'Digit' Turner16084162012-06-12 16:25:37 +0200483 s = soinfo_elf_lookup(lsi, elf_hash, name);
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -0700484 }
485#endif
486
Iliyan Malchev6ed80c82009-09-28 19:38:04 -0700487done:
488 if(s != NULL) {
489 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +0200490 "found in %s, base = 0x%08x, load bias = 0x%08x\n",
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900491 pid, si->name, name, s->st_value,
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +0200492 lsi->name, lsi->base, lsi->load_bias);
493 *offset = lsi->load_bias;
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 */
David 'Digit' Turner16084162012-06-12 16:25:37 +0200503Elf32_Sym *soinfo_lookup(soinfo *si, const char *name)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800504{
David 'Digit' Turner16084162012-06-12 16:25:37 +0200505 return soinfo_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;
David 'Digit' Turner16084162012-06-12 16:25:37 +0200524 s = soinfo_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
David 'Digit' Turner16084162012-06-12 16:25:37 +0200554Elf32_Sym *soinfo_find_symbol(soinfo* si, const void *addr)
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
David 'Digit' Turner16084162012-06-12 16:25:37 +0200589static const char * const 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)) {
David 'Digit' Turner16084162012-06-12 16:25:37 +0200601 if ((fd = TEMP_FAILURE_RETRY(open(name, O_RDONLY))) >= 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800602 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];
David 'Digit' Turner16084162012-06-12 16:25:37 +0200612 const char * const*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
David 'Digit' Turner16084162012-06-12 16:25:37 +0200664 if (TEMP_FAILURE_RETRY(read(fd, &info, sizeof(info)) != sizeof(info))) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800665 WARN("Could not read prelink_info_t structure for `%s`\n", name);
666 return 0;
667 }
668
David 'Digit' Turner16084162012-06-12 16:25:37 +0200669 if (memcmp(info.tag, "PRE ", 4)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800670 WARN("`%s` is not a prelinked library\n", name);
671 return 0;
672 }
673
674 return (unsigned long)info.mmap_addr;
675}
676
David 'Digit' Turner16084162012-06-12 16:25:37 +0200677/* verify_elf_header
678 * Verifies the content of an ELF header.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800679 *
680 * Args:
681 *
682 * Returns:
683 * 0 on success
684 * -1 if no valid ELF object is found @ base.
685 */
686static int
David 'Digit' Turner16084162012-06-12 16:25:37 +0200687verify_elf_header(const Elf32_Ehdr* hdr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800688{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800689 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
690 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
691 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
692 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
693
694 /* TODO: Should we verify anything else in the header? */
Zhenghua Wang897815a2011-10-19 00:29:14 +0800695#ifdef ANDROID_ARM_LINKER
696 if (hdr->e_machine != EM_ARM) return -1;
697#elif defined(ANDROID_X86_LINKER)
698 if (hdr->e_machine != EM_386) return -1;
699#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800700 return 0;
701}
702
703
Nick Kralevich66259862012-03-16 13:06:12 -0700704/* reserve_mem_region
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800705 *
706 * This function reserves a chunk of memory to be used for mapping in
Nick Kralevich66259862012-03-16 13:06:12 -0700707 * a prelinked shared library. We reserve the entire memory region here, and
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800708 * then the rest of the linker will relocate the individual loadable
709 * segments into the correct locations within this memory range.
710 *
711 * Args:
Nick Kralevich66259862012-03-16 13:06:12 -0700712 * si->base: The requested base of the allocation.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800713 * si->size: The size of the allocation.
714 *
715 * Returns:
716 * -1 on failure, and 0 on success. On success, si->base will contain
717 * the virtual address at which the library will be mapped.
718 */
719
David 'Digit' Turner16084162012-06-12 16:25:37 +0200720static int soinfo_reserve_mem_region(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800721{
Nick Kralevich66259862012-03-16 13:06:12 -0700722 void *base = mmap((void *)si->base, si->size, PROT_NONE,
Chris Dearmandb4bce02011-03-10 10:48:14 -0800723 MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800724 if (base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700725 DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700726 "as requested, will try general pool: %d (%s)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800727 pid, (si->base ? "" : "non-"), si->name, si->base,
728 errno, strerror(errno));
729 return -1;
730 } else if (base != (void *)si->base) {
Dima Zavin2e855792009-05-20 18:28:09 -0700731 DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700732 "not at 0x%08x", pid, (si->base ? "" : "non-"),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800733 si->name, (unsigned)base, si->base);
734 munmap(base, si->size);
735 return -1;
736 }
737 return 0;
738}
739
David 'Digit' Turner16084162012-06-12 16:25:37 +0200740static int soinfo_alloc_mem_region(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800741{
742 if (si->base) {
743 /* Attempt to mmap a prelinked library. */
David 'Digit' Turner16084162012-06-12 16:25:37 +0200744 return soinfo_reserve_mem_region(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800745 }
746
Shih-wei Liao48527c32011-07-17 12:32:43 -0700747 /* This is not a prelinked library, so we use the kernel's default
748 allocator.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800749 */
Shih-wei Liao48527c32011-07-17 12:32:43 -0700750
Nick Kralevich66259862012-03-16 13:06:12 -0700751 void *base = mmap(NULL, si->size, PROT_NONE,
Shih-wei Liao48527c32011-07-17 12:32:43 -0700752 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
753 if (base == MAP_FAILED) {
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200754 DL_ERR("%5d mmap of library '%s' failed (%d bytes): %d (%s)\n",
755 pid, si->name, si->size,
Shih-wei Liao48527c32011-07-17 12:32:43 -0700756 errno, strerror(errno));
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200757 return -1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800758 }
Shih-wei Liao48527c32011-07-17 12:32:43 -0700759 si->base = (unsigned) base;
760 PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
761 pid, si->name, si->base);
762 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800763}
764
765#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
766#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
767 MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
768 MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
769/* load_segments
770 *
771 * This function loads all the loadable (PT_LOAD) segments into memory
772 * at their appropriate memory offsets off the base address.
773 *
774 * Args:
775 * fd: Open file descriptor to the library to load.
776 * header: Pointer to a header page that contains the ELF header.
777 * This is needed since we haven't mapped in the real file yet.
778 * si: ptr to soinfo struct describing the shared object.
779 *
780 * Returns:
781 * 0 on success, -1 on failure.
782 */
783static int
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200784soinfo_load_segments(soinfo* si, int fd, const Elf32_Phdr* phdr_table, int phdr_count, Elf32_Addr ehdr_phoff)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800785{
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200786 const Elf32_Phdr *phdr = phdr_table;
787 const Elf32_Phdr *phdr0 = 0; /* program header for the first LOAD segment */
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900788 Elf32_Addr base;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800789 int cnt;
790 unsigned len;
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800791 Elf32_Addr tmp;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800792 unsigned char *pbase;
793 unsigned char *extra_base;
794 unsigned extra_len;
795 unsigned total_sz = 0;
796
797 si->wrprotect_start = 0xffffffff;
798 si->wrprotect_end = 0;
799
800 TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
801 pid, si->name, (unsigned)si->base);
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900802
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200803 for (cnt = 0; cnt < phdr_count; ++cnt, ++phdr) {
David 'Digit' Turner16084162012-06-12 16:25:37 +0200804
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900805 if (phdr->p_type == PT_LOAD) {
806 phdr0 = phdr;
807 /*
808 * ELF specification section 2-2.
809 *
810 * PT_LOAD: "Loadable segment entries in the program
811 * header table appear in ascending order, sorted on the
812 * p_vaddr member."
813 */
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +0200814 si->load_bias = si->base - PAGE_START(phdr->p_vaddr);
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900815 break;
816 }
817 }
David 'Digit' Turner16084162012-06-12 16:25:37 +0200818
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900819 /* "base" might wrap around UINT32_MAX. */
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +0200820 base = si->load_bias;
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900821
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800822 /* Now go through all the PT_LOAD segments and map them into memory
823 * at the appropriate locations. */
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200824 phdr = phdr_table;
825 for (cnt = 0; cnt < phdr_count; ++cnt, ++phdr) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800826 if (phdr->p_type == PT_LOAD) {
827 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
828 /* we want to map in the segment on a page boundary */
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200829 tmp = base + PAGE_START(phdr->p_vaddr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800830 /* add the # of bytes we masked off above to the total length. */
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200831 len = phdr->p_filesz + PAGE_OFFSET(phdr->p_vaddr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800832
833 TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
834 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", pid, si->name,
835 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800836 pbase = mmap((void *)tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800837 MAP_PRIVATE | MAP_FIXED, fd,
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200838 PAGE_START(phdr->p_offset));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800839 if (pbase == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700840 DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700841 "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800842 (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
843 goto fail;
844 }
845
846 /* If 'len' didn't end on page boundary, and it's a writable
847 * segment, zero-fill the rest. */
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200848 if (PAGE_OFFSET(len) > 0 && (phdr->p_flags & PF_W) != 0)
849 memset((void *)(pbase + len), 0, PAGE_SIZE - PAGE_OFFSET(len));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800850
851 /* Check to see if we need to extend the map for this segment to
852 * cover the diff between filesz and memsz (i.e. for bss).
853 *
854 * base _+---------------------+ page boundary
855 * . .
856 * | |
857 * . .
858 * pbase _+---------------------+ page boundary
859 * | |
860 * . .
861 * base + p_vaddr _| |
862 * . \ \ .
863 * . | filesz | .
864 * pbase + len _| / | |
865 * <0 pad> . . .
866 * extra_base _+------------|--------+ page boundary
867 * / . . .
868 * | . . .
869 * | +------------|--------+ page boundary
870 * extra_len-> | | | |
871 * | . | memsz .
872 * | . | .
873 * \ _| / |
874 * . .
875 * | |
876 * _+---------------------+ page boundary
877 */
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200878 tmp = (Elf32_Addr)PAGE_END((unsigned)pbase + len);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800879 if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
880 extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
881 TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
882 "(0x%08x) ]\n", pid, si->name, (unsigned)tmp, extra_len);
883 /* map in the extra page(s) as anonymous into the range.
884 * This is probably not necessary as we already mapped in
885 * the entire region previously, but we just want to be
886 * sure. This will also set the right flags on the region
887 * (though we can probably accomplish the same thing with
888 * mprotect).
889 */
890 extra_base = mmap((void *)tmp, extra_len,
891 PFLAGS_TO_PROT(phdr->p_flags),
892 MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
893 -1, 0);
894 if (extra_base == MAP_FAILED) {
Dima Zavin2e855792009-05-20 18:28:09 -0700895 DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
Erik Gillingd00d23a2009-07-22 17:06:11 -0700896 " (0x%08x) ]", pid, si->name, (unsigned)tmp,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800897 extra_len);
898 goto fail;
899 }
900 /* TODO: Check if we need to memset-0 this region.
901 * Anonymous mappings are zero-filled copy-on-writes, so we
902 * shouldn't need to. */
903 TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
904 "(0x%08x)\n", pid, si->name, (unsigned)extra_base,
905 extra_len);
906 }
907 /* set the len here to show the full extent of the segment we
908 * just loaded, mostly for debugging */
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200909 len = PAGE_END((unsigned)base + phdr->p_vaddr + phdr->p_memsz) - (unsigned)pbase;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800910 TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
911 "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
912 (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
913 total_sz += len;
914 /* Make the section writable just in case we'll have to write to
915 * it during relocation (i.e. text segment). However, we will
916 * remember what range of addresses should be write protected.
917 *
918 */
919 if (!(phdr->p_flags & PF_W)) {
920 if ((unsigned)pbase < si->wrprotect_start)
921 si->wrprotect_start = (unsigned)pbase;
922 if (((unsigned)pbase + len) > si->wrprotect_end)
923 si->wrprotect_end = (unsigned)pbase + len;
924 mprotect(pbase, len,
925 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
926 }
927 } else if (phdr->p_type == PT_DYNAMIC) {
928 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
929 /* this segment contains the dynamic linking information */
930 si->dynamic = (unsigned *)(base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800931 } else if (phdr->p_type == PT_GNU_RELRO) {
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900932 if (((base + phdr->p_vaddr) >= si->base + si->size)
933 || ((base + phdr->p_vaddr + phdr->p_memsz) > si->base + si->size)
934 || ((base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
Nick Kralevich9ec0f032012-02-28 10:40:00 -0800935 DL_ERR("%d invalid GNU_RELRO in '%s' "
936 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
937 phdr->p_vaddr, phdr->p_memsz);
938 goto fail;
939 }
940 si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
941 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800942 } else {
943#ifdef ANDROID_ARM_LINKER
944 if (phdr->p_type == PT_ARM_EXIDX) {
945 DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", pid);
946 /* exidx entries (used for stack unwinding) are 8 bytes each.
947 */
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900948 si->ARM_exidx = (unsigned *)(base + phdr->p_vaddr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800949 si->ARM_exidx_count = phdr->p_memsz / 8;
950 }
951#endif
952 }
953
954 }
955
956 /* Sanity check */
957 if (total_sz > si->size) {
Dima Zavin2e855792009-05-20 18:28:09 -0700958 DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
Erik Gillingd00d23a2009-07-22 17:06:11 -0700959 "greater than what was allocated (0x%08x). THIS IS BAD!",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800960 pid, total_sz, si->name, si->size);
961 goto fail;
962 }
963
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900964 /* vaddr : Real virtual address in process' address space.
965 * p_vaddr : Relative virtual address in ELF object
966 * p_offset : File offset in ELF object
967 *
968 * vaddr p_vaddr p_offset
969 * ----- ------------ --------
970 * base 0
David 'Digit' Turnera6545f42012-06-18 11:15:54 +0200971 * si->base PAGE_START(phdr0->p_vaddr)
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900972 * phdr0->p_vaddr phdr0->p_offset
973 * phdr ehdr->e_phoff
974 */
975 si->phdr = (Elf32_Phdr *)(base + phdr0->p_vaddr +
David 'Digit' Turner23363ed2012-06-18 18:13:49 +0200976 ehdr_phoff - phdr0->p_offset);
977 si->phnum = phdr_count;
Ji-Hwan Leef186a182012-05-31 20:20:36 +0900978
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800979 TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
980 "Total memory footprint: 0x%08x bytes ]\n", pid, si->name,
981 (unsigned)si->base, si->size);
982 return 0;
983
984fail:
985 /* We can just blindly unmap the entire region even though some things
986 * were mapped in originally with anonymous and others could have been
987 * been mapped in from the file before we failed. The kernel will unmap
988 * all the pages in the range, irrespective of how they got there.
989 */
990 munmap((void *)si->base, si->size);
991 si->flags |= FLAG_ERROR;
992 return -1;
993}
994
995/* TODO: Implement this to take care of the fact that Android ARM
996 * ELF objects shove everything into a single loadable segment that has the
997 * write bit set. wr_offset is then used to set non-(data|bss) pages to be
998 * non-writable.
999 */
1000#if 0
1001static unsigned
1002get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
1003{
1004 Elf32_Shdr *shdr_start;
1005 Elf32_Shdr *shdr;
1006 int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
1007 int cnt;
1008 unsigned wr_offset = 0xffffffff;
1009
1010 shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
David 'Digit' Turnera6545f42012-06-18 11:15:54 +02001011 PAGE_START(ehdr->e_shoff));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001012 if (shdr_start == MAP_FAILED) {
1013 WARN("%5d - Could not read section header info from '%s'. Will not "
1014 "not be able to determine write-protect offset.\n", pid, name);
1015 return (unsigned)-1;
1016 }
1017
1018 for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
1019 if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
1020 (shdr->sh_addr < wr_offset)) {
1021 wr_offset = shdr->sh_addr;
1022 }
1023 }
1024
1025 munmap(shdr_start, shdr_sz);
1026 return wr_offset;
1027}
1028#endif
1029
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001030
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001031static soinfo *
1032load_library(const char *name)
1033{
1034 int fd = open_library(name);
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001035 int ret, cnt;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001036 unsigned ext_sz;
1037 unsigned req_base;
Erik Gillingfde86422009-07-28 20:28:19 -07001038 const char *bname;
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001039 struct stat sb;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001040 soinfo *si = NULL;
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001041 Elf32_Ehdr header[1];
1042 int phdr_count;
1043 void* phdr_mmap = NULL;
1044 Elf32_Addr phdr_size;
1045 const Elf32_Phdr* phdr_table;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001046
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001047 if (fd == -1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001048 DL_ERR("Library '%s' not found", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001049 return NULL;
Dima Zavin2e855792009-05-20 18:28:09 -07001050 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001051
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001052 /* Read the ELF header first */
1053 ret = TEMP_FAILURE_RETRY(read(fd, (void*)header, sizeof(header)));
1054 if (ret < 0) {
1055 DL_ERR("%5d can't read file %s: %s", pid, name, strerror(errno));
1056 goto fail;
1057 }
1058 if (ret != (int)sizeof(header)) {
1059 DL_ERR("%5d too small to be an ELF executable: %s", pid, name);
1060 goto fail;
1061 }
1062 if (verify_elf_header(header) < 0) {
1063 DL_ERR("%5d not a valid ELF executable: %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001064 goto fail;
1065 }
1066
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001067 /* Then read the program header table */
1068 ret = phdr_table_load(fd, header->e_phoff, header->e_phnum,
1069 &phdr_mmap, &phdr_size, &phdr_table);
1070 if (ret < 0) {
1071 DL_ERR("%5d can't load program header table: %s: %s", pid,
1072 name, strerror(errno));
1073 goto fail;
1074 }
1075 phdr_count = header->e_phnum;
1076
1077 /* Get the load extents and the prelinked load address, if any */
1078 ext_sz = phdr_table_get_load_size(phdr_table, phdr_count);
1079 if (ext_sz == 0) {
1080 DL_ERR("%5d no loadable segments in file: %s", pid, name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001081 goto fail;
1082 }
1083
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001084 req_base = (unsigned) is_prelinked(fd, name);
1085 if (req_base == (unsigned)-1) {
1086 DL_ERR("%5d can't read end of library: %s: %s", pid, name,
1087 strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001088 goto fail;
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001089 }
1090 if (req_base != 0) {
1091 TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
1092 pid, name, req_base);
1093 } else {
1094 TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", pid, name);
1095 }
David 'Digit' Turner16084162012-06-12 16:25:37 +02001096
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001097 TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", pid, name,
1098 (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
1099
1100 /* Now configure the soinfo struct where we'll store all of our data
1101 * for the ELF object. If the loading fails, we waste the entry, but
1102 * same thing would happen if we failed during linking. Configuring the
1103 * soinfo struct here is a lot more convenient.
1104 */
Erik Gillingfde86422009-07-28 20:28:19 -07001105 bname = strrchr(name, '/');
David 'Digit' Turner16084162012-06-12 16:25:37 +02001106 si = soinfo_alloc(bname ? bname + 1 : name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001107 if (si == NULL)
1108 goto fail;
1109
1110 /* Carve out a chunk of memory where we will map in the individual
1111 * segments */
1112 si->base = req_base;
1113 si->size = ext_sz;
1114 si->flags = 0;
1115 si->entry = 0;
1116 si->dynamic = (unsigned *)-1;
David 'Digit' Turner16084162012-06-12 16:25:37 +02001117 if (soinfo_alloc_mem_region(si) < 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001118 goto fail;
1119
1120 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
1121 pid, name, (void *)si->base, (unsigned) ext_sz);
1122
1123 /* Now actually load the library's segments into right places in memory */
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001124 if (soinfo_load_segments(si, fd, phdr_table, phdr_count, header->e_phoff) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001125 goto fail;
1126 }
1127
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001128 phdr_table_unload(phdr_mmap, phdr_size);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001129 close(fd);
1130 return si;
1131
1132fail:
David 'Digit' Turner16084162012-06-12 16:25:37 +02001133 if (si) soinfo_free(si);
David 'Digit' Turner23363ed2012-06-18 18:13:49 +02001134 if (phdr_mmap != NULL) {
1135 phdr_table_unload(phdr_mmap, phdr_size);
1136 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001137 close(fd);
1138 return NULL;
1139}
1140
1141static soinfo *
1142init_library(soinfo *si)
1143{
1144 unsigned wr_offset = 0xffffffff;
1145
1146 /* At this point we know that whatever is loaded @ base is a valid ELF
1147 * shared library whose segments are properly mapped in. */
1148 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n",
1149 pid, si->base, si->size, si->name);
1150
David 'Digit' Turner16084162012-06-12 16:25:37 +02001151 if(soinfo_link_image(si, wr_offset)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001152 /* We failed to link. However, we can only restore libbase
1153 ** if no additional libraries have moved it since we updated it.
1154 */
1155 munmap((void *)si->base, si->size);
1156 return NULL;
1157 }
1158
1159 return si;
1160}
1161
1162soinfo *find_library(const char *name)
1163{
1164 soinfo *si;
David 'Digit' Turner67748092010-07-21 16:18:21 -07001165 const char *bname;
1166
1167#if ALLOW_SYMBOLS_FROM_MAIN
1168 if (name == NULL)
1169 return somain;
1170#else
1171 if (name == NULL)
1172 return NULL;
1173#endif
1174
1175 bname = strrchr(name, '/');
Erik Gillingfde86422009-07-28 20:28:19 -07001176 bname = bname ? bname + 1 : name;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001177
1178 for(si = solist; si != 0; si = si->next){
Erik Gillingfde86422009-07-28 20:28:19 -07001179 if(!strcmp(bname, si->name)) {
Erik Gilling30eb4022009-08-13 16:05:30 -07001180 if(si->flags & FLAG_ERROR) {
1181 DL_ERR("%5d '%s' failed to load previously", pid, bname);
1182 return NULL;
1183 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001184 if(si->flags & FLAG_LINKED) return si;
Erik Gillingd00d23a2009-07-22 17:06:11 -07001185 DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
Dima Zavin2e855792009-05-20 18:28:09 -07001186 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001187 }
1188 }
1189
1190 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name);
1191 si = load_library(name);
1192 if(si == NULL)
1193 return NULL;
1194 return init_library(si);
1195}
1196
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001197/* TODO:
1198 * notify gdb of unload
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001199 * for non-prelinked libraries, find a way to decrement libbase
1200 */
1201static void call_destructors(soinfo *si);
David 'Digit' Turner16084162012-06-12 16:25:37 +02001202unsigned soinfo_unload(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001203{
1204 unsigned *d;
1205 if (si->refcount == 1) {
1206 TRACE("%5d unloading '%s'\n", pid, si->name);
1207 call_destructors(si);
1208
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001209 /*
1210 * Make sure that we undo the PT_GNU_RELRO protections we added
David 'Digit' Turner16084162012-06-12 16:25:37 +02001211 * in soinfo_link_image. This is needed to undo the DT_NEEDED hack below.
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001212 */
1213 if ((si->gnu_relro_start != 0) && (si->gnu_relro_len != 0)) {
David 'Digit' Turnera6545f42012-06-18 11:15:54 +02001214 Elf32_Addr start = PAGE_START(si->gnu_relro_start);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001215 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1216 if (mprotect((void *) start, len, PROT_READ | PROT_WRITE) < 0)
1217 DL_ERR("%5d %s: could not undo GNU_RELRO protections. "
1218 "Expect a crash soon. errno=%d (%s)",
1219 pid, si->name, errno, strerror(errno));
1220
1221 }
1222
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001223 for(d = si->dynamic; *d; d += 2) {
1224 if(d[0] == DT_NEEDED){
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001225 soinfo *lsi = (soinfo *)d[1];
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001226
1227 // The next line will segfault if the we don't undo the
1228 // PT_GNU_RELRO protections (see comments above and in
David 'Digit' Turner16084162012-06-12 16:25:37 +02001229 // soinfo_link_image().
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001230 d[1] = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001231
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001232 if (validate_soinfo(lsi)) {
1233 TRACE("%5d %s needs to unload %s\n", pid,
1234 si->name, lsi->name);
David 'Digit' Turner16084162012-06-12 16:25:37 +02001235 soinfo_unload(lsi);
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001236 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001237 else
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001238 DL_ERR("%5d %s: could not unload dependent library",
1239 pid, si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 }
1241 }
1242
1243 munmap((char *)si->base, si->size);
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001244 notify_gdb_of_unload(si);
David 'Digit' Turner16084162012-06-12 16:25:37 +02001245 soinfo_free(si);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246 si->refcount = 0;
1247 }
1248 else {
1249 si->refcount--;
1250 PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
1251 pid, si->name, si->refcount);
1252 }
1253 return si->refcount;
1254}
1255
1256/* TODO: don't use unsigned for addrs below. It works, but is not
1257 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
1258 * long.
1259 */
David 'Digit' Turner16084162012-06-12 16:25:37 +02001260static int soinfo_relocate(soinfo *si, Elf32_Rel *rel, unsigned count)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001261{
1262 Elf32_Sym *symtab = si->symtab;
1263 const char *strtab = si->strtab;
1264 Elf32_Sym *s;
1265 unsigned base;
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001266 Elf32_Addr offset;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001267 Elf32_Rel *start = rel;
1268 unsigned idx;
1269
1270 for (idx = 0; idx < count; ++idx) {
1271 unsigned type = ELF32_R_TYPE(rel->r_info);
1272 unsigned sym = ELF32_R_SYM(rel->r_info);
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02001273 unsigned reloc = (unsigned)(rel->r_offset + si->load_bias);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001274 unsigned sym_addr = 0;
1275 char *sym_name = NULL;
1276
1277 DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
1278 si->name, idx);
1279 if(sym != 0) {
Dima Zavind1b40d82009-05-12 10:59:09 -07001280 sym_name = (char *)(strtab + symtab[sym].st_name);
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02001281 s = soinfo_do_lookup(si, sym_name, &offset);
Doug Kwane8238072009-10-26 12:05:23 -07001282 if(s == NULL) {
1283 /* We only allow an undefined symbol if this is a weak
1284 reference.. */
1285 s = &symtab[sym];
1286 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
1287 DL_ERR("%5d cannot locate '%s'...\n", pid, sym_name);
1288 return -1;
1289 }
1290
1291 /* IHI0044C AAELF 4.5.1.1:
1292
1293 Libraries are not searched to resolve weak references.
1294 It is not an error for a weak reference to remain
1295 unsatisfied.
1296
1297 During linking, the value of an undefined weak reference is:
1298 - Zero if the relocation type is absolute
1299 - The address of the place if the relocation is pc-relative
1300 - The address of nominial base address if the relocation
1301 type is base-relative.
1302 */
1303
1304 switch (type) {
1305#if defined(ANDROID_ARM_LINKER)
1306 case R_ARM_JUMP_SLOT:
1307 case R_ARM_GLOB_DAT:
1308 case R_ARM_ABS32:
1309 case R_ARM_RELATIVE: /* Don't care. */
1310 case R_ARM_NONE: /* Don't care. */
1311#elif defined(ANDROID_X86_LINKER)
1312 case R_386_JUMP_SLOT:
1313 case R_386_GLOB_DAT:
1314 case R_386_32:
1315 case R_386_RELATIVE: /* Dont' care. */
1316#endif /* ANDROID_*_LINKER */
1317 /* sym_addr was initialized to be zero above or relocation
1318 code below does not care about value of sym_addr.
1319 No need to do anything. */
1320 break;
1321
1322#if defined(ANDROID_X86_LINKER)
1323 case R_386_PC32:
1324 sym_addr = reloc;
1325 break;
1326#endif /* ANDROID_X86_LINKER */
1327
1328#if defined(ANDROID_ARM_LINKER)
1329 case R_ARM_COPY:
1330 /* Fall through. Can't really copy if weak symbol is
1331 not found in run-time. */
1332#endif /* ANDROID_ARM_LINKER */
1333 default:
1334 DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
1335 pid, type, rel, (int) (rel - start));
1336 return -1;
1337 }
1338 } else {
1339 /* We got a definition. */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001340#if 0
1341 if((base == 0) && (si->base != 0)){
1342 /* linking from libraries to main image is bad */
Erik Gillingd00d23a2009-07-22 17:06:11 -07001343 DL_ERR("%5d cannot locate '%s'...",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001344 pid, strtab + symtab[sym].st_name);
1345 return -1;
1346 }
1347#endif
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02001348 sym_addr = (unsigned)(s->st_value + offset);
Doug Kwane8238072009-10-26 12:05:23 -07001349 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001350 COUNT_RELOC(RELOC_SYMBOL);
1351 } else {
Doug Kwane8238072009-10-26 12:05:23 -07001352 s = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001353 }
1354
1355/* TODO: This is ugly. Split up the relocations by arch into
1356 * different files.
1357 */
1358 switch(type){
1359#if defined(ANDROID_ARM_LINKER)
1360 case R_ARM_JUMP_SLOT:
1361 COUNT_RELOC(RELOC_ABSOLUTE);
1362 MARK(rel->r_offset);
1363 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1364 reloc, sym_addr, sym_name);
1365 *((unsigned*)reloc) = sym_addr;
1366 break;
1367 case R_ARM_GLOB_DAT:
1368 COUNT_RELOC(RELOC_ABSOLUTE);
1369 MARK(rel->r_offset);
1370 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1371 reloc, sym_addr, sym_name);
1372 *((unsigned*)reloc) = sym_addr;
1373 break;
1374 case R_ARM_ABS32:
1375 COUNT_RELOC(RELOC_ABSOLUTE);
1376 MARK(rel->r_offset);
1377 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid,
1378 reloc, sym_addr, sym_name);
1379 *((unsigned*)reloc) += sym_addr;
1380 break;
David 'Digit' Turner34ea5112009-11-17 14:56:26 -08001381 case R_ARM_REL32:
1382 COUNT_RELOC(RELOC_RELATIVE);
1383 MARK(rel->r_offset);
1384 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid,
1385 reloc, sym_addr, rel->r_offset, sym_name);
1386 *((unsigned*)reloc) += sym_addr - rel->r_offset;
1387 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001388#elif defined(ANDROID_X86_LINKER)
1389 case R_386_JUMP_SLOT:
1390 COUNT_RELOC(RELOC_ABSOLUTE);
1391 MARK(rel->r_offset);
1392 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid,
1393 reloc, sym_addr, sym_name);
1394 *((unsigned*)reloc) = sym_addr;
1395 break;
1396 case R_386_GLOB_DAT:
1397 COUNT_RELOC(RELOC_ABSOLUTE);
1398 MARK(rel->r_offset);
1399 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid,
1400 reloc, sym_addr, sym_name);
1401 *((unsigned*)reloc) = sym_addr;
1402 break;
1403#endif /* ANDROID_*_LINKER */
1404
1405#if defined(ANDROID_ARM_LINKER)
1406 case R_ARM_RELATIVE:
1407#elif defined(ANDROID_X86_LINKER)
1408 case R_386_RELATIVE:
1409#endif /* ANDROID_*_LINKER */
1410 COUNT_RELOC(RELOC_RELATIVE);
1411 MARK(rel->r_offset);
1412 if(sym){
Erik Gillingd00d23a2009-07-22 17:06:11 -07001413 DL_ERR("%5d odd RELATIVE form...", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001414 return -1;
1415 }
1416 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
1417 reloc, si->base);
1418 *((unsigned*)reloc) += si->base;
1419 break;
1420
1421#if defined(ANDROID_X86_LINKER)
1422 case R_386_32:
1423 COUNT_RELOC(RELOC_RELATIVE);
1424 MARK(rel->r_offset);
1425
1426 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid,
1427 reloc, sym_addr, sym_name);
1428 *((unsigned *)reloc) += (unsigned)sym_addr;
1429 break;
1430
1431 case R_386_PC32:
1432 COUNT_RELOC(RELOC_RELATIVE);
1433 MARK(rel->r_offset);
1434 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
1435 "+%08x (%08x - %08x) %s\n", pid, reloc,
1436 (sym_addr - reloc), sym_addr, reloc, sym_name);
1437 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
1438 break;
1439#endif /* ANDROID_X86_LINKER */
1440
1441#ifdef ANDROID_ARM_LINKER
1442 case R_ARM_COPY:
1443 COUNT_RELOC(RELOC_COPY);
1444 MARK(rel->r_offset);
1445 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid,
1446 reloc, s->st_size, sym_addr, sym_name);
1447 memcpy((void*)reloc, (void*)sym_addr, s->st_size);
1448 break;
Iliyan Malchev5e12d7e2009-03-24 19:02:00 -07001449 case R_ARM_NONE:
1450 break;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001451#endif /* ANDROID_ARM_LINKER */
1452
1453 default:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001454 DL_ERR("%5d unknown reloc type %d @ %p (%d)",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001455 pid, type, rel, (int) (rel - start));
1456 return -1;
1457 }
1458 rel++;
1459 }
1460 return 0;
1461}
1462
David 'Digit' Turner82156792009-05-18 14:37:41 +02001463/* Please read the "Initialization and Termination functions" functions.
1464 * of the linker design note in bionic/linker/README.TXT to understand
1465 * what the following code is doing.
1466 *
1467 * The important things to remember are:
1468 *
1469 * DT_PREINIT_ARRAY must be called first for executables, and should
1470 * not appear in shared libraries.
1471 *
1472 * DT_INIT should be called before DT_INIT_ARRAY if both are present
1473 *
1474 * DT_FINI should be called after DT_FINI_ARRAY if both are present
1475 *
1476 * DT_FINI_ARRAY must be parsed in reverse order.
1477 */
1478
1479static void call_array(unsigned *ctor, int count, int reverse)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001480{
David 'Digit' Turner82156792009-05-18 14:37:41 +02001481 int n, inc = 1;
1482
1483 if (reverse) {
1484 ctor += (count-1);
1485 inc = -1;
1486 }
1487
1488 for(n = count; n > 0; n--) {
1489 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
1490 reverse ? "dtor" : "ctor",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001491 (unsigned)ctor, (unsigned)*ctor);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001492 void (*func)() = (void (*)()) *ctor;
1493 ctor += inc;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001494 if(((int) func == 0) || ((int) func == -1)) continue;
1495 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
1496 func();
1497 }
1498}
1499
David 'Digit' Turner16084162012-06-12 16:25:37 +02001500void soinfo_call_constructors(soinfo *si)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001501{
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001502 if (si->constructors_called)
1503 return;
1504
Jesse Hallf5d16932012-01-30 15:39:57 -08001505 // Set this before actually calling the constructors, otherwise it doesn't
1506 // protect against recursive constructor calls. One simple example of
1507 // constructor recursion is the libc debug malloc, which is implemented in
1508 // libc_malloc_debug_leak.so:
1509 // 1. The program depends on libc, so libc's constructor is called here.
1510 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
David 'Digit' Turner16084162012-06-12 16:25:37 +02001511 // 3. dlopen() calls soinfo_call_constructors() with the newly created
Jesse Hallf5d16932012-01-30 15:39:57 -08001512 // soinfo for libc_malloc_debug_leak.so.
David 'Digit' Turner16084162012-06-12 16:25:37 +02001513 // 4. The debug so depends on libc, so soinfo_call_constructors() is
Jesse Hallf5d16932012-01-30 15:39:57 -08001514 // called again with the libc soinfo. If it doesn't trigger the early-
1515 // out above, the libc constructor will be called again (recursively!).
1516 si->constructors_called = 1;
1517
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001518 if (si->flags & FLAG_EXE) {
1519 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
1520 pid, (unsigned)si->preinit_array, si->preinit_array_count,
1521 si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001522 call_array(si->preinit_array, si->preinit_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001523 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
1524 } else {
1525 if (si->preinit_array) {
Dima Zavin2e855792009-05-20 18:28:09 -07001526 DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
Erik Gillingd00d23a2009-07-22 17:06:11 -07001527 " This is INVALID.", pid, si->name,
Dima Zavin2e855792009-05-20 18:28:09 -07001528 (unsigned)si->preinit_array);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001529 }
1530 }
1531
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001532 if (si->dynamic) {
1533 unsigned *d;
1534 for(d = si->dynamic; *d; d += 2) {
1535 if(d[0] == DT_NEEDED){
1536 soinfo* lsi = (soinfo *)d[1];
1537 if (!validate_soinfo(lsi)) {
1538 DL_ERR("%5d bad DT_NEEDED pointer in %s",
1539 pid, si->name);
1540 } else {
David 'Digit' Turner16084162012-06-12 16:25:37 +02001541 soinfo_call_constructors(lsi);
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001542 }
1543 }
1544 }
1545 }
1546
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001547 if (si->init_func) {
1548 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
1549 (unsigned)si->init_func, si->name);
1550 si->init_func();
1551 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name);
1552 }
1553
1554 if (si->init_array) {
1555 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
1556 (unsigned)si->init_array, si->init_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001557 call_array(si->init_array, si->init_array_count, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001558 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
1559 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001560
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04001561}
David 'Digit' Turner82156792009-05-18 14:37:41 +02001562
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001563static void call_destructors(soinfo *si)
1564{
1565 if (si->fini_array) {
1566 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
1567 (unsigned)si->fini_array, si->fini_array_count, si->name);
David 'Digit' Turner82156792009-05-18 14:37:41 +02001568 call_array(si->fini_array, si->fini_array_count, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001569 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
1570 }
1571
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001572 if (si->fini_func) {
1573 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
1574 (unsigned)si->fini_func, si->name);
1575 si->fini_func();
1576 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name);
1577 }
1578}
1579
1580/* Force any of the closed stdin, stdout and stderr to be associated with
1581 /dev/null. */
1582static int nullify_closed_stdio (void)
1583{
1584 int dev_null, i, status;
1585 int return_value = 0;
1586
David 'Digit' Turner16084162012-06-12 16:25:37 +02001587 dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001588 if (dev_null < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001589 DL_ERR("Cannot open /dev/null.");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001590 return -1;
1591 }
1592 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
1593
1594 /* If any of the stdio file descriptors is valid and not associated
1595 with /dev/null, dup /dev/null to it. */
1596 for (i = 0; i < 3; i++) {
1597 /* If it is /dev/null already, we are done. */
1598 if (i == dev_null)
1599 continue;
1600
1601 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i);
1602 /* The man page of fcntl does not say that fcntl(..,F_GETFL)
1603 can be interrupted but we do this just to be safe. */
1604 do {
1605 status = fcntl(i, F_GETFL);
1606 } while (status < 0 && errno == EINTR);
1607
1608 /* If file is openned, we are good. */
1609 if (status >= 0)
1610 continue;
1611
1612 /* The only error we allow is that the file descriptor does not
1613 exist, in which case we dup /dev/null to it. */
1614 if (errno != EBADF) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001615 DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616 return_value = -1;
1617 continue;
1618 }
1619
1620 /* Try dupping /dev/null to this stdio file descriptor and
1621 repeat if there is a signal. Note that any errors in closing
1622 the stdio descriptor are lost. */
1623 do {
1624 status = dup2(dev_null, i);
1625 } while (status < 0 && errno == EINTR);
Dima Zavin2e855792009-05-20 18:28:09 -07001626
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001627 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001628 DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001629 return_value = -1;
1630 continue;
1631 }
1632 }
1633
1634 /* If /dev/null is not one of the stdio file descriptors, close it. */
1635 if (dev_null > 2) {
1636 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
Dima Zavin2e855792009-05-20 18:28:09 -07001637 do {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001638 status = close(dev_null);
1639 } while (status < 0 && errno == EINTR);
1640
1641 if (status < 0) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001642 DL_ERR("nullify_stdio: close error %s", strerror(errno));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001643 return_value = -1;
1644 }
1645 }
1646
1647 return return_value;
1648}
1649
David 'Digit' Turner16084162012-06-12 16:25:37 +02001650static int soinfo_link_image(soinfo *si, unsigned wr_offset)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001651{
1652 unsigned *d;
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001653 /* "base" might wrap around UINT32_MAX. */
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02001654 Elf32_Addr base = si->load_bias;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001655 Elf32_Phdr *phdr = si->phdr;
1656 int phnum = si->phnum;
1657
1658 INFO("[ %5d linking %s ]\n", pid, si->name);
1659 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid,
1660 si->base, si->flags);
1661
Nick Kralevich468319c2011-11-11 15:53:17 -08001662 if (si->flags & (FLAG_EXE | FLAG_LINKER)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001663 /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
Ji-Hwan Lee75917c82012-05-25 22:36:00 +09001664 * linkage info if this is the executable or the linker itself.
Nick Kralevich468319c2011-11-11 15:53:17 -08001665 * If this was a dynamic lib, that would have been done at load time.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001666 *
1667 * TODO: It's unfortunate that small pieces of this are
1668 * repeated from the load_library routine. Refactor this just
1669 * slightly to reuse these bits.
1670 */
1671 si->size = 0;
1672 for(; phnum > 0; --phnum, ++phdr) {
1673#ifdef ANDROID_ARM_LINKER
1674 if(phdr->p_type == PT_ARM_EXIDX) {
1675 /* exidx entries (used for stack unwinding) are 8 bytes each.
1676 */
Evgeniy Stepanov20bc0612012-06-22 14:52:52 +04001677 si->ARM_exidx = (unsigned *)(base + phdr->p_vaddr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001678 si->ARM_exidx_count = phdr->p_memsz / 8;
1679 }
1680#endif
1681 if (phdr->p_type == PT_LOAD) {
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001682 /* For the executable, we use the si->size field only in
1683 dl_unwind_find_exidx(), so the meaning of si->size
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001684 is not the size of the executable; it is the distance
1685 between the load location of the executable and the last
1686 address of the loadable part of the executable.
1687 We use the range [si->base, si->base + si->size) to
1688 determine whether a PC value falls within the executable
1689 section. Of course, if a value is between si->base and
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001690 (base + phdr->p_vaddr), it's not in the executable
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001691 section, but a) we shouldn't be asking for such a value
1692 anyway, and b) if we have to provide an EXIDX for such a
1693 value, then the executable's EXIDX is probably the better
1694 choice.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001695 */
1696 DEBUG_DUMP_PHDR(phdr, "PT_LOAD", pid);
1697 if (phdr->p_vaddr + phdr->p_memsz > si->size)
1698 si->size = phdr->p_vaddr + phdr->p_memsz;
1699 /* try to remember what range of addresses should be write
1700 * protected */
1701 if (!(phdr->p_flags & PF_W)) {
1702 unsigned _end;
1703
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001704 if (base + phdr->p_vaddr < si->wrprotect_start)
1705 si->wrprotect_start = base + phdr->p_vaddr;
David 'Digit' Turnera6545f42012-06-18 11:15:54 +02001706 _end = PAGE_END(base + phdr->p_vaddr + phdr->p_memsz);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001707 if (_end > si->wrprotect_end)
1708 si->wrprotect_end = _end;
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001709 /* Make the section writable just in case we'll have to
1710 * write to it during relocation (i.e. text segment).
1711 * However, we will remember what range of addresses
1712 * should be write protected.
1713 */
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001714 mprotect((void *) (base + phdr->p_vaddr),
Nick Kralevichd9ad6232011-10-20 14:57:56 -07001715 phdr->p_memsz,
1716 PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717 }
1718 } else if (phdr->p_type == PT_DYNAMIC) {
1719 if (si->dynamic != (unsigned *)-1) {
Dima Zavin2e855792009-05-20 18:28:09 -07001720 DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
Erik Gillingd00d23a2009-07-22 17:06:11 -07001721 "Segment at 0x%08x, previously one found at 0x%08x",
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001722 pid, si->name, base + phdr->p_vaddr,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001723 (unsigned)si->dynamic);
1724 goto fail;
1725 }
1726 DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", pid);
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001727 si->dynamic = (unsigned *) (base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001728 } else if (phdr->p_type == PT_GNU_RELRO) {
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001729 if ((base + phdr->p_vaddr >= si->base + si->size)
1730 || ((base + phdr->p_vaddr + phdr->p_memsz) > si->base + si->size)
1731 || ((base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001732 DL_ERR("%d invalid GNU_RELRO in '%s' "
1733 "p_vaddr=0x%08x p_memsz=0x%08x", pid, si->name,
1734 phdr->p_vaddr, phdr->p_memsz);
1735 goto fail;
1736 }
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001737 si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001738 si->gnu_relro_len = (unsigned) phdr->p_memsz;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001739 }
1740 }
1741 }
1742
1743 if (si->dynamic == (unsigned *)-1) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001744 DL_ERR("%5d missing PT_DYNAMIC?!", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001745 goto fail;
1746 }
1747
1748 DEBUG("%5d dynamic = %p\n", pid, si->dynamic);
1749
1750 /* extract useful information from dynamic section */
1751 for(d = si->dynamic; *d; d++){
1752 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]);
1753 switch(*d++){
1754 case DT_HASH:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001755 si->nbucket = ((unsigned *) (base + *d))[0];
1756 si->nchain = ((unsigned *) (base + *d))[1];
1757 si->bucket = (unsigned *) (base + *d + 8);
1758 si->chain = (unsigned *) (base + *d + 8 + si->nbucket * 4);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001759 break;
1760 case DT_STRTAB:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001761 si->strtab = (const char *) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001762 break;
1763 case DT_SYMTAB:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001764 si->symtab = (Elf32_Sym *) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001765 break;
1766 case DT_PLTREL:
1767 if(*d != DT_REL) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001768 DL_ERR("DT_RELA not supported");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001769 goto fail;
1770 }
1771 break;
1772 case DT_JMPREL:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001773 si->plt_rel = (Elf32_Rel*) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001774 break;
1775 case DT_PLTRELSZ:
1776 si->plt_rel_count = *d / 8;
1777 break;
1778 case DT_REL:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001779 si->rel = (Elf32_Rel*) (base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001780 break;
1781 case DT_RELSZ:
1782 si->rel_count = *d / 8;
1783 break;
1784 case DT_PLTGOT:
1785 /* Save this in case we decide to do lazy binding. We don't yet. */
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001786 si->plt_got = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001787 break;
1788 case DT_DEBUG:
1789 // Set the DT_DEBUG entry to the addres of _r_debug for GDB
1790 *d = (int) &_r_debug;
1791 break;
Shin-ichiro KAWASAKIad13c572009-11-06 10:36:37 +09001792 case DT_RELA:
Erik Gillingd00d23a2009-07-22 17:06:11 -07001793 DL_ERR("%5d DT_RELA not supported", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001794 goto fail;
1795 case DT_INIT:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001796 si->init_func = (void (*)(void))(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001797 DEBUG("%5d %s constructors (init func) found at %p\n",
1798 pid, si->name, si->init_func);
1799 break;
1800 case DT_FINI:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001801 si->fini_func = (void (*)(void))(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001802 DEBUG("%5d %s destructors (fini func) found at %p\n",
1803 pid, si->name, si->fini_func);
1804 break;
1805 case DT_INIT_ARRAY:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001806 si->init_array = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001807 DEBUG("%5d %s constructors (init_array) found at %p\n",
1808 pid, si->name, si->init_array);
1809 break;
1810 case DT_INIT_ARRAYSZ:
1811 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1812 break;
1813 case DT_FINI_ARRAY:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001814 si->fini_array = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001815 DEBUG("%5d %s destructors (fini_array) found at %p\n",
1816 pid, si->name, si->fini_array);
1817 break;
1818 case DT_FINI_ARRAYSZ:
1819 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1820 break;
1821 case DT_PREINIT_ARRAY:
Ji-Hwan Leef186a182012-05-31 20:20:36 +09001822 si->preinit_array = (unsigned *)(base + *d);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001823 DEBUG("%5d %s constructors (preinit_array) found at %p\n",
1824 pid, si->name, si->preinit_array);
1825 break;
1826 case DT_PREINIT_ARRAYSZ:
1827 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
1828 break;
1829 case DT_TEXTREL:
1830 /* TODO: make use of this. */
1831 /* this means that we might have to write into where the text
1832 * segment was loaded during relocation... Do something with
1833 * it.
1834 */
1835 DEBUG("%5d Text segment should be writable during relocation.\n",
1836 pid);
1837 break;
1838 }
1839 }
1840
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001841 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001842 pid, si->base, si->strtab, si->symtab);
1843
1844 if((si->strtab == 0) || (si->symtab == 0)) {
Erik Gillingd00d23a2009-07-22 17:06:11 -07001845 DL_ERR("%5d missing essential tables", pid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001846 goto fail;
1847 }
1848
Matt Fischer4fd42c12009-12-31 12:09:10 -06001849 /* if this is the main executable, then load all of the preloads now */
1850 if(si->flags & FLAG_EXE) {
1851 int i;
1852 memset(preloads, 0, sizeof(preloads));
1853 for(i = 0; ldpreload_names[i] != NULL; i++) {
1854 soinfo *lsi = find_library(ldpreload_names[i]);
1855 if(lsi == 0) {
1856 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
1857 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
1858 pid, ldpreload_names[i], si->name, tmp_err_buf);
1859 goto fail;
1860 }
1861 lsi->refcount++;
1862 preloads[i] = lsi;
1863 }
1864 }
1865
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001866 for(d = si->dynamic; *d; d += 2) {
1867 if(d[0] == DT_NEEDED){
1868 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
Dima Zavin2e855792009-05-20 18:28:09 -07001869 soinfo *lsi = find_library(si->strtab + d[1]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001870 if(lsi == 0) {
Dima Zavin03531952009-05-29 17:30:25 -07001871 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
Erik Gillingd00d23a2009-07-22 17:06:11 -07001872 DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
Dima Zavin03531952009-05-29 17:30:25 -07001873 pid, si->strtab + d[1], si->name, tmp_err_buf);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001874 goto fail;
1875 }
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001876 /* Save the soinfo of the loaded DT_NEEDED library in the payload
1877 of the DT_NEEDED entry itself, so that we can retrieve the
1878 soinfo directly later from the dynamic segment. This is a hack,
1879 but it allows us to map from DT_NEEDED to soinfo efficiently
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001880 later on when we resolve relocations, trying to look up a symbol
Iliyan Malchev6ed80c82009-09-28 19:38:04 -07001881 with dlsym().
1882 */
1883 d[1] = (unsigned)lsi;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001884 lsi->refcount++;
1885 }
1886 }
1887
1888 if(si->plt_rel) {
1889 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name );
David 'Digit' Turner16084162012-06-12 16:25:37 +02001890 if(soinfo_relocate(si, si->plt_rel, si->plt_rel_count))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001891 goto fail;
1892 }
1893 if(si->rel) {
1894 DEBUG("[ %5d relocating %s ]\n", pid, si->name );
David 'Digit' Turner16084162012-06-12 16:25:37 +02001895 if(soinfo_relocate(si, si->rel, si->rel_count))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001896 goto fail;
1897 }
1898
1899 si->flags |= FLAG_LINKED;
1900 DEBUG("[ %5d finished linking %s ]\n", pid, si->name);
1901
1902#if 0
1903 /* This is the way that the old dynamic linker did protection of
1904 * non-writable areas. It would scan section headers and find where
1905 * .text ended (rather where .data/.bss began) and assume that this is
1906 * the upper range of the non-writable area. This is too coarse,
1907 * and is kept here for reference until we fully move away from single
1908 * segment elf objects. See the code in get_wr_offset (also #if'd 0)
1909 * that made this possible.
1910 */
1911 if(wr_offset < 0xffffffff){
1912 mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
1913 }
1914#else
1915 /* TODO: Verify that this does the right thing in all cases, as it
1916 * presently probably does not. It is possible that an ELF image will
1917 * come with multiple read-only segments. What we ought to do is scan
1918 * the program headers again and mprotect all the read-only segments.
1919 * To prevent re-scanning the program header, we would have to build a
1920 * list of loadable segments in si, and then scan that instead. */
1921 if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
1922 mprotect((void *)si->wrprotect_start,
1923 si->wrprotect_end - si->wrprotect_start,
1924 PROT_READ | PROT_EXEC);
1925 }
1926#endif
1927
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001928 if (si->gnu_relro_start != 0 && si->gnu_relro_len != 0) {
David 'Digit' Turnera6545f42012-06-18 11:15:54 +02001929 Elf32_Addr start = PAGE_START(si->gnu_relro_start);
Nick Kralevich9ec0f032012-02-28 10:40:00 -08001930 unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
1931 if (mprotect((void *) start, len, PROT_READ) < 0) {
1932 DL_ERR("%5d GNU_RELRO mprotect of library '%s' failed: %d (%s)\n",
1933 pid, si->name, errno, strerror(errno));
1934 goto fail;
1935 }
1936 }
1937
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001938 /* If this is a SET?ID program, dup /dev/null to opened stdin,
1939 stdout and stderr to close a security hole described in:
1940
1941 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
1942
1943 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001944 if (program_is_setuid)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001945 nullify_closed_stdio ();
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001946 notify_gdb_of_load(si);
1947 return 0;
1948
1949fail:
Dima Zavina7161902010-08-17 15:56:40 -07001950 ERROR("failed to link %s\n", si->name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001951 si->flags |= FLAG_ERROR;
1952 return -1;
1953}
1954
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001955static void parse_library_path(const char *path, char *delim)
David Bartleybc3a5c22009-06-02 18:27:28 -07001956{
1957 size_t len;
1958 char *ldpaths_bufp = ldpaths_buf;
1959 int i = 0;
1960
1961 len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
1962
1963 while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
1964 if (*ldpaths[i] != '\0')
1965 ++i;
1966 }
1967
1968 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1969 * last char isn't '\0' (i.e. not originally a delim). */
1970 if (i > 0 && len >= sizeof(ldpaths_buf) &&
1971 ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
1972 ldpaths[i - 1] = NULL;
1973 } else {
1974 ldpaths[i] = NULL;
1975 }
1976}
1977
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01001978static void parse_preloads(const char *path, char *delim)
Matt Fischer4fd42c12009-12-31 12:09:10 -06001979{
1980 size_t len;
1981 char *ldpreloads_bufp = ldpreloads_buf;
1982 int i = 0;
1983
1984 len = strlcpy(ldpreloads_buf, path, sizeof(ldpreloads_buf));
1985
1986 while (i < LDPRELOAD_MAX && (ldpreload_names[i] = strsep(&ldpreloads_bufp, delim))) {
1987 if (*ldpreload_names[i] != '\0') {
1988 ++i;
1989 }
1990 }
1991
1992 /* Forget the last path if we had to truncate; this occurs if the 2nd to
1993 * last char isn't '\0' (i.e. not originally a delim). */
1994 if (i > 0 && len >= sizeof(ldpreloads_buf) &&
1995 ldpreloads_buf[sizeof(ldpreloads_buf) - 2] != '\0') {
1996 ldpreload_names[i - 1] = NULL;
1997 } else {
1998 ldpreload_names[i] = NULL;
1999 }
2000}
2001
Nick Kralevich468319c2011-11-11 15:53:17 -08002002/*
2003 * This code is called after the linker has linked itself and
2004 * fixed it's own GOT. It is safe to make references to externs
2005 * and other non-local data at this point.
2006 */
2007static unsigned __linker_init_post_relocation(unsigned **elfdata)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002008{
2009 static soinfo linker_soinfo;
2010
2011 int argc = (int) *elfdata;
2012 char **argv = (char**) (elfdata + 1);
Stephen Smalleybb440552012-01-20 10:59:15 -08002013 unsigned *vecs = (unsigned*) (argv + argc + 1);
2014 unsigned *v;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002015 soinfo *si;
2016 struct link_map * map;
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002017 const char *ldpath_env = NULL;
2018 const char *ldpreload_env = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002019
David 'Digit' Turneref0bd182009-07-17 17:55:01 +02002020 /* NOTE: we store the elfdata pointer on a special location
2021 * of the temporary TLS area in order to pass it to
2022 * the C Library's runtime initializer.
2023 *
2024 * The initializer must clear the slot and reset the TLS
2025 * to point to a different location to ensure that no other
2026 * shared library constructor can access it.
2027 */
Evgeniy Stepanov1a78fbb2012-03-22 18:01:53 +04002028 __libc_init_tls(elfdata);
2029
2030 pid = getpid();
2031
2032#if TIMING
2033 struct timeval t0, t1;
2034 gettimeofday(&t0, 0);
2035#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002036
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002037 /* Initialize environment functions, and get to the ELF aux vectors table */
2038 vecs = linker_env_init(vecs);
2039
Stephen Smalley861b42a2012-01-13 07:48:11 -05002040 /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
2041 has file caps, or caused a SELinux/AppArmor domain transition. */
2042 for (v = vecs; v[0]; v += 2) {
2043 if (v[0] == AT_SECURE) {
2044 /* kernel told us whether to enable secure mode */
2045 program_is_setuid = v[1];
2046 goto sanitize;
2047 }
2048 }
2049
2050 /* Kernel did not provide AT_SECURE - fall back on legacy test. */
2051 program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
2052
2053sanitize:
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002054 /* Sanitize environment if we're loading a setuid program */
2055 if (program_is_setuid)
2056 linker_env_secure();
2057
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002058 debugger_init();
2059
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002060 /* Get a few environment variables */
2061 {
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -07002062#if LINKER_DEBUG
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002063 const char* env;
2064 env = linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
2065 if (env)
2066 debug_verbosity = atoi(env);
Nick Kralevich8c4f3ce2012-04-04 12:43:32 -07002067#endif
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002068
2069 /* Normally, these are cleaned by linker_env_secure, but the test
2070 * against program_is_setuid doesn't cost us anything */
2071 if (!program_is_setuid) {
2072 ldpath_env = linker_env_get("LD_LIBRARY_PATH");
2073 ldpreload_env = linker_env_get("LD_PRELOAD");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002074 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002075 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002076
2077 INFO("[ android linker & debugger ]\n");
2078 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata);
2079
David 'Digit' Turner16084162012-06-12 16:25:37 +02002080 si = soinfo_alloc(argv[0]);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002081 if(si == 0) {
2082 exit(-1);
2083 }
2084
2085 /* bootstrap the link map, the main exe always needs to be first */
2086 si->flags |= FLAG_EXE;
2087 map = &(si->linkmap);
2088
2089 map->l_addr = 0;
2090 map->l_name = argv[0];
2091 map->l_prev = NULL;
2092 map->l_next = NULL;
2093
2094 _r_debug.r_map = map;
2095 r_debug_tail = map;
2096
2097 /* gdb expects the linker to be in the debug shared object list,
2098 * and we need to make sure that the reported load address is zero.
2099 * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
David 'Digit' Turner16084162012-06-12 16:25:37 +02002100 * is. Don't use soinfo_alloc(), because the linker shouldn't
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002101 * be on the soinfo list.
2102 */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002103 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002104 linker_soinfo.flags = 0;
2105 linker_soinfo.base = 0; // This is the important part; must be zero.
2106 insert_soinfo_into_debug_map(&linker_soinfo);
2107
2108 /* extract information passed from the kernel */
2109 while(vecs[0] != 0){
2110 switch(vecs[0]){
2111 case AT_PHDR:
2112 si->phdr = (Elf32_Phdr*) vecs[1];
2113 break;
2114 case AT_PHNUM:
2115 si->phnum = (int) vecs[1];
2116 break;
2117 case AT_ENTRY:
2118 si->entry = vecs[1];
2119 break;
2120 }
2121 vecs += 2;
2122 }
2123
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002124 /* Compute the value of si->base. We can't rely on the fact that
2125 * the first entry is the PHDR because this will not be true
2126 * for certain executables (e.g. some in the NDK unit test suite)
2127 */
2128 int nn;
2129 si->base = 0;
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02002130 si->load_bias = 0;
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002131 for ( nn = 0; nn < si->phnum; nn++ ) {
2132 if (si->phdr[nn].p_type == PT_PHDR) {
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02002133 si->load_bias = (Elf32_Addr)si->phdr - si->phdr[nn].p_vaddr;
2134 si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_offset;
David 'Digit' Turner8180b082011-11-15 17:17:28 +01002135 break;
2136 }
2137 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002138 si->dynamic = (unsigned *)-1;
2139 si->wrprotect_start = 0xffffffff;
2140 si->wrprotect_end = 0;
David 'Digit' Turner67748092010-07-21 16:18:21 -07002141 si->refcount = 1;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002142 si->gnu_relro_start = 0;
2143 si->gnu_relro_len = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002144
David Bartleybc3a5c22009-06-02 18:27:28 -07002145 /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002146 if (ldpath_env)
David Bartleybc3a5c22009-06-02 18:27:28 -07002147 parse_library_path(ldpath_env, ":");
2148
David 'Digit' Turnerbe575592010-12-16 19:52:02 +01002149 if (ldpreload_env) {
Matt Fischer4fd42c12009-12-31 12:09:10 -06002150 parse_preloads(ldpreload_env, " :");
2151 }
2152
David 'Digit' Turner16084162012-06-12 16:25:37 +02002153 if(soinfo_link_image(si, 0)) {
Dima Zavin2e855792009-05-20 18:28:09 -07002154 char errmsg[] = "CANNOT LINK EXECUTABLE\n";
2155 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
2156 write(2, errmsg, sizeof(errmsg));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002157 exit(-1);
2158 }
2159
David 'Digit' Turner16084162012-06-12 16:25:37 +02002160 soinfo_call_constructors(si);
Evgeniy Stepanove83c56d2011-12-21 13:03:54 +04002161
Iliyan Malchev4a9afcb2009-09-29 11:43:20 -07002162#if ALLOW_SYMBOLS_FROM_MAIN
2163 /* Set somain after we've loaded all the libraries in order to prevent
2164 * linking of symbols back to the main image, which is not set up at that
2165 * point yet.
2166 */
2167 somain = si;
2168#endif
2169
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002170#if TIMING
2171 gettimeofday(&t1,NULL);
2172 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
2173 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
2174 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
2175 ));
2176#endif
2177#if STATS
2178 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
2179 linker_stats.reloc[RELOC_ABSOLUTE],
2180 linker_stats.reloc[RELOC_RELATIVE],
2181 linker_stats.reloc[RELOC_COPY],
2182 linker_stats.reloc[RELOC_SYMBOL]);
2183#endif
2184#if COUNT_PAGES
2185 {
2186 unsigned n;
2187 unsigned i;
2188 unsigned count = 0;
2189 for(n = 0; n < 4096; n++){
2190 if(bitmask[n]){
2191 unsigned x = bitmask[n];
2192 for(i = 0; i < 8; i++){
2193 if(x & 1) count++;
2194 x >>= 1;
2195 }
2196 }
2197 }
2198 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
2199 }
2200#endif
2201
2202#if TIMING || STATS || COUNT_PAGES
2203 fflush(stdout);
2204#endif
2205
2206 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name,
2207 si->entry);
2208 return si->entry;
2209}
Nick Kralevich468319c2011-11-11 15:53:17 -08002210
2211/*
2212 * Find the value of AT_BASE passed to us by the kernel. This is the load
2213 * location of the linker.
2214 */
2215static unsigned find_linker_base(unsigned **elfdata) {
2216 int argc = (int) *elfdata;
2217 char **argv = (char**) (elfdata + 1);
2218 unsigned *vecs = (unsigned*) (argv + argc + 1);
2219 while (vecs[0] != 0) {
2220 vecs++;
2221 }
2222
2223 /* The end of the environment block is marked by two NULL pointers */
2224 vecs++;
2225
2226 while(vecs[0]) {
2227 if (vecs[0] == AT_BASE) {
2228 return vecs[1];
2229 }
2230 vecs += 2;
2231 }
2232
2233 return 0; // should never happen
2234}
2235
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02002236/* Compute the load-bias of an existing executable. This shall only
2237 * be used to compute the load bias of an executable or shared library
2238 * that was loaded by the kernel itself.
2239 *
2240 * Input:
2241 * elf -> address of ELF header, assumed to be at the start of the file.
2242 * Return:
2243 * load bias, i.e. add the value of any p_vaddr in the file to get
2244 * the corresponding address in memory.
2245 */
2246static Elf32_Addr
2247get_elf_exec_load_bias(const Elf32_Ehdr* elf)
2248{
2249 Elf32_Addr offset = elf->e_phoff;
2250 const Elf32_Phdr* phdr_table = (const Elf32_Phdr*)((char*)elf + offset);
2251 const Elf32_Phdr* phdr_end = phdr_table + elf->e_phnum;
2252 const Elf32_Phdr* phdr;
2253
2254 for (phdr = phdr_table; phdr < phdr_end; phdr++) {
2255 if (phdr->p_type == PT_LOAD) {
2256 return (Elf32_Addr)elf + phdr->p_offset - phdr->p_vaddr;
2257 }
2258 }
2259 return 0;
2260}
2261
Nick Kralevich468319c2011-11-11 15:53:17 -08002262/*
2263 * This is the entry point for the linker, called from begin.S. This
2264 * method is responsible for fixing the linker's own relocations, and
2265 * then calling __linker_init_post_relocation().
2266 *
2267 * Because this method is called before the linker has fixed it's own
2268 * relocations, any attempt to reference an extern variable, extern
2269 * function, or other GOT reference will generate a segfault.
2270 */
2271unsigned __linker_init(unsigned **elfdata) {
2272 unsigned linker_addr = find_linker_base(elfdata);
2273 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr;
2274 Elf32_Phdr *phdr =
2275 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff);
2276
2277 soinfo linker_so;
2278 memset(&linker_so, 0, sizeof(soinfo));
2279
2280 linker_so.base = linker_addr;
David 'Digit' Turnerbea23e52012-06-18 23:38:46 +02002281 linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
Nick Kralevich468319c2011-11-11 15:53:17 -08002282 linker_so.dynamic = (unsigned *) -1;
2283 linker_so.phdr = phdr;
2284 linker_so.phnum = elf_hdr->e_phnum;
2285 linker_so.flags |= FLAG_LINKER;
2286 linker_so.wrprotect_start = 0xffffffff;
2287 linker_so.wrprotect_end = 0;
Nick Kralevich9ec0f032012-02-28 10:40:00 -08002288 linker_so.gnu_relro_start = 0;
2289 linker_so.gnu_relro_len = 0;
Nick Kralevich468319c2011-11-11 15:53:17 -08002290
David 'Digit' Turner16084162012-06-12 16:25:37 +02002291 if (soinfo_link_image(&linker_so, 0)) {
Nick Kralevich468319c2011-11-11 15:53:17 -08002292 // It would be nice to print an error message, but if the linker
2293 // can't link itself, there's no guarantee that we'll be able to
2294 // call write() (because it involves a GOT reference).
2295 //
2296 // This situation should never occur unless the linker itself
2297 // is corrupt.
2298 exit(-1);
2299 }
2300
2301 // We have successfully fixed our own relocations. It's safe to run
2302 // the main part of the linker now.
2303 return __linker_init_post_relocation(elfdata);
2304}