linker.cpp revision 18a206c81d9743481e364384affd43306911283d
1/* 2 * Copyright (C) 2008, 2009 The Android Open Source Project 3 * 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 <dlfcn.h> 30#include <errno.h> 31#include <fcntl.h> 32#include <linux/auxvec.h> 33#include <pthread.h> 34#include <stdbool.h> 35#include <stdio.h> 36#include <stdlib.h> 37#include <string.h> 38#include <sys/atomics.h> 39#include <sys/mman.h> 40#include <sys/stat.h> 41#include <unistd.h> 42 43// Private C library headers. 44#include <private/bionic_tls.h> 45#include <private/logd.h> 46#include <private/ScopedPthreadMutexLocker.h> 47 48#include "linker.h" 49#include "linker_debug.h" 50#include "linker_environ.h" 51#include "linker_format.h" 52#include "linker_phdr.h" 53 54#define ALLOW_SYMBOLS_FROM_MAIN 1 55#define SO_MAX 128 56 57/* Assume average path length of 64 and max 8 paths */ 58#define LDPATH_BUFSIZE 512 59#define LDPATH_MAX 8 60 61#define LDPRELOAD_BUFSIZE 512 62#define LDPRELOAD_MAX 8 63 64/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<< 65 * 66 * Do NOT use malloc() and friends or pthread_*() code here. 67 * Don't use printf() either; it's caused mysterious memory 68 * corruption in the past. 69 * The linker runs before we bring up libc and it's easiest 70 * to make sure it does not depend on any complex libc features 71 * 72 * open issues / todo: 73 * 74 * - are we doing everything we should for ARM_COPY relocations? 75 * - cleaner error reporting 76 * - after linking, set as much stuff as possible to READONLY 77 * and NOEXEC 78 * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel 79 * headers provide versions that are negative... 80 * - allocate space for soinfo structs dynamically instead of 81 * having a hard limit (SO_MAX) 82 */ 83 84 85static int soinfo_link_image(soinfo *si); 86 87static int socount = 0; 88static soinfo sopool[SO_MAX]; 89static soinfo *freelist = NULL; 90static soinfo *solist = &libdl_info; 91static soinfo *sonext = &libdl_info; 92#if ALLOW_SYMBOLS_FROM_MAIN 93static soinfo *somain; /* main process, always the one after libdl_info */ 94#endif 95 96static char ldpaths_buf[LDPATH_BUFSIZE]; 97static const char *ldpaths[LDPATH_MAX + 1]; 98 99static char ldpreloads_buf[LDPRELOAD_BUFSIZE]; 100static const char *ldpreload_names[LDPRELOAD_MAX + 1]; 101 102static soinfo *preloads[LDPRELOAD_MAX + 1]; 103 104#if LINKER_DEBUG 105int debug_verbosity; 106#endif 107 108static int pid; 109 110enum RelocationKind { 111 kRelocAbsolute = 0, 112 kRelocRelative, 113 kRelocCopy, 114 kRelocSymbol, 115 kRelocMax 116}; 117 118#if STATS 119struct linker_stats_t { 120 int count[kRelocMax]; 121}; 122 123static linker_stats_t linker_stats; 124 125static void count_relocation(RelocationKind kind) { 126 ++linker_stats.count[kind]; 127} 128#else 129static void count_relocation(RelocationKind) { 130} 131#endif 132 133#if COUNT_PAGES 134static unsigned bitmask[4096]; 135#define MARK(offset) \ 136 do { \ 137 bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \ 138 } while(0) 139#else 140#define MARK(x) do {} while (0) 141#endif 142 143// You shouldn't try to call memory-allocating functions in the dynamic linker. 144// Guard against the most obvious ones. 145#define DISALLOW_ALLOCATION(return_type, name, ...) \ 146 return_type name __VA_ARGS__ \ 147 { \ 148 const char* msg = "ERROR: " #name " called from the dynamic linker!\n"; \ 149 __libc_android_log_write(ANDROID_LOG_FATAL, "linker", msg); \ 150 write(2, msg, sizeof(msg)); \ 151 abort(); \ 152 } 153#define UNUSED __attribute__((unused)) 154DISALLOW_ALLOCATION(void*, malloc, (size_t u UNUSED)); 155DISALLOW_ALLOCATION(void, free, (void* u UNUSED)); 156DISALLOW_ALLOCATION(void*, realloc, (void* u1 UNUSED, size_t u2 UNUSED)); 157DISALLOW_ALLOCATION(void*, calloc, (size_t u1 UNUSED, size_t u2 UNUSED)); 158 159static char tmp_err_buf[768]; 160static char __linker_dl_err_buf[768]; 161#define DL_ERR(fmt, x...) \ 162 do { \ 163 format_buffer(__linker_dl_err_buf, sizeof(__linker_dl_err_buf), fmt, ##x); \ 164 ERROR(fmt "\n", ##x); \ 165 } while(0) 166 167const char* linker_get_error() { 168 return &__linker_dl_err_buf[0]; 169} 170 171/* 172 * This function is an empty stub where GDB locates a breakpoint to get notified 173 * about linker activity. 174 */ 175extern "C" void __attribute__((noinline)) __attribute__((visibility("default"))) rtld_db_dlactivity(); 176 177static r_debug _r_debug = {1, NULL, &rtld_db_dlactivity, 178 RT_CONSISTENT, 0}; 179static link_map* r_debug_tail = 0; 180 181static pthread_mutex_t gDebugMutex = PTHREAD_MUTEX_INITIALIZER; 182 183static void insert_soinfo_into_debug_map(soinfo * info) { 184 // Copy the necessary fields into the debug structure. 185 link_map* map = &(info->linkmap); 186 map->l_addr = info->base; 187 map->l_name = (char*) info->name; 188 map->l_ld = (uintptr_t)info->dynamic; 189 190 /* Stick the new library at the end of the list. 191 * gdb tends to care more about libc than it does 192 * about leaf libraries, and ordering it this way 193 * reduces the back-and-forth over the wire. 194 */ 195 if (r_debug_tail) { 196 r_debug_tail->l_next = map; 197 map->l_prev = r_debug_tail; 198 map->l_next = 0; 199 } else { 200 _r_debug.r_map = map; 201 map->l_prev = 0; 202 map->l_next = 0; 203 } 204 r_debug_tail = map; 205} 206 207static void remove_soinfo_from_debug_map(soinfo* info) { 208 link_map* map = &(info->linkmap); 209 210 if (r_debug_tail == map) { 211 r_debug_tail = map->l_prev; 212 } 213 214 if (map->l_prev) { 215 map->l_prev->l_next = map->l_next; 216 } 217 if (map->l_next) { 218 map->l_next->l_prev = map->l_prev; 219 } 220} 221 222static void notify_gdb_of_load(soinfo* info) { 223 if (info->flags & FLAG_EXE) { 224 // GDB already knows about the main executable 225 return; 226 } 227 228 ScopedPthreadMutexLocker locker(&gDebugMutex); 229 230 _r_debug.r_state = RT_ADD; 231 rtld_db_dlactivity(); 232 233 insert_soinfo_into_debug_map(info); 234 235 _r_debug.r_state = RT_CONSISTENT; 236 rtld_db_dlactivity(); 237} 238 239static void notify_gdb_of_unload(soinfo* info) { 240 if (info->flags & FLAG_EXE) { 241 // GDB already knows about the main executable 242 return; 243 } 244 245 ScopedPthreadMutexLocker locker(&gDebugMutex); 246 247 _r_debug.r_state = RT_DELETE; 248 rtld_db_dlactivity(); 249 250 remove_soinfo_from_debug_map(info); 251 252 _r_debug.r_state = RT_CONSISTENT; 253 rtld_db_dlactivity(); 254} 255 256void notify_gdb_of_libraries() { 257 _r_debug.r_state = RT_ADD; 258 rtld_db_dlactivity(); 259 _r_debug.r_state = RT_CONSISTENT; 260 rtld_db_dlactivity(); 261} 262 263static soinfo *soinfo_alloc(const char *name) 264{ 265 if (strlen(name) >= SOINFO_NAME_LEN) { 266 DL_ERR("library name \"%s\" too long", name); 267 return NULL; 268 } 269 270 /* The freelist is populated when we call soinfo_free(), which in turn is 271 done only by dlclose(), which is not likely to be used. 272 */ 273 if (!freelist) { 274 if (socount == SO_MAX) { 275 DL_ERR("too many libraries when loading \"%s\"", name); 276 return NULL; 277 } 278 freelist = sopool + socount++; 279 freelist->next = NULL; 280 } 281 282 soinfo* si = freelist; 283 freelist = freelist->next; 284 285 /* Make sure we get a clean block of soinfo */ 286 memset(si, 0, sizeof(soinfo)); 287 strlcpy((char*) si->name, name, sizeof(si->name)); 288 sonext->next = si; 289 si->next = NULL; 290 si->refcount = 0; 291 sonext = si; 292 293 TRACE("%5d name %s: allocated soinfo @ %p\n", pid, name, si); 294 return si; 295} 296 297static void soinfo_free(soinfo* si) 298{ 299 if (si == NULL) { 300 return; 301 } 302 303 soinfo *prev = NULL, *trav; 304 305 TRACE("%5d name %s: freeing soinfo @ %p\n", pid, si->name, si); 306 307 for(trav = solist; trav != NULL; trav = trav->next){ 308 if (trav == si) 309 break; 310 prev = trav; 311 } 312 if (trav == NULL) { 313 /* si was not ni solist */ 314 DL_ERR("name \"%s\" is not in solist!", si->name); 315 return; 316 } 317 318 /* prev will never be NULL, because the first entry in solist is 319 always the static libdl_info. 320 */ 321 prev->next = si->next; 322 if (si == sonext) sonext = prev; 323 si->next = freelist; 324 freelist = si; 325} 326 327#ifdef ANDROID_ARM_LINKER 328 329/* For a given PC, find the .so that it belongs to. 330 * Returns the base address of the .ARM.exidx section 331 * for that .so, and the number of 8-byte entries 332 * in that section (via *pcount). 333 * 334 * Intended to be called by libc's __gnu_Unwind_Find_exidx(). 335 * 336 * This function is exposed via dlfcn.cpp and libdl.so. 337 */ 338_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount) 339{ 340 soinfo *si; 341 unsigned addr = (unsigned)pc; 342 343 for (si = solist; si != 0; si = si->next){ 344 if ((addr >= si->base) && (addr < (si->base + si->size))) { 345 *pcount = si->ARM_exidx_count; 346 return (_Unwind_Ptr)si->ARM_exidx; 347 } 348 } 349 *pcount = 0; 350 return NULL; 351} 352 353#elif defined(ANDROID_X86_LINKER) || defined(ANDROID_MIPS_LINKER) 354 355/* Here, we only have to provide a callback to iterate across all the 356 * loaded libraries. gcc_eh does the rest. */ 357int 358dl_iterate_phdr(int (*cb)(dl_phdr_info *info, size_t size, void *data), 359 void *data) 360{ 361 int rv = 0; 362 for (soinfo* si = solist; si != NULL; si = si->next) { 363 dl_phdr_info dl_info; 364 dl_info.dlpi_addr = si->linkmap.l_addr; 365 dl_info.dlpi_name = si->linkmap.l_name; 366 dl_info.dlpi_phdr = si->phdr; 367 dl_info.dlpi_phnum = si->phnum; 368 rv = cb(&dl_info, sizeof(dl_phdr_info), data); 369 if (rv != 0) { 370 break; 371 } 372 } 373 return rv; 374} 375 376#endif 377 378static Elf32_Sym *soinfo_elf_lookup(soinfo *si, unsigned hash, const char *name) 379{ 380 Elf32_Sym *s; 381 Elf32_Sym *symtab = si->symtab; 382 const char *strtab = si->strtab; 383 unsigned n; 384 385 TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", pid, 386 name, si->name, si->base, hash, hash % si->nbucket); 387 n = hash % si->nbucket; 388 389 for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){ 390 s = symtab + n; 391 if(strcmp(strtab + s->st_name, name)) continue; 392 393 /* only concern ourselves with global and weak symbol definitions */ 394 switch(ELF32_ST_BIND(s->st_info)){ 395 case STB_GLOBAL: 396 case STB_WEAK: 397 if(s->st_shndx == SHN_UNDEF) 398 continue; 399 400 TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", pid, 401 name, si->name, s->st_value, s->st_size); 402 return s; 403 } 404 } 405 406 return NULL; 407} 408 409static unsigned elfhash(const char *_name) 410{ 411 const unsigned char *name = (const unsigned char *) _name; 412 unsigned h = 0, g; 413 414 while(*name) { 415 h = (h << 4) + *name++; 416 g = h & 0xf0000000; 417 h ^= g; 418 h ^= g >> 24; 419 } 420 return h; 421} 422 423static Elf32_Sym * 424soinfo_do_lookup(soinfo *si, const char *name, Elf32_Addr *offset, 425 soinfo *needed[], bool ignore_local) 426{ 427 unsigned elf_hash = elfhash(name); 428 Elf32_Sym *s = NULL; 429 soinfo *lsi = si; 430 int i; 431 432 if (!ignore_local) { 433 /* Look for symbols in the local scope (the object who is 434 * searching). This happens with C++ templates on i386 for some 435 * reason. 436 * 437 * Notes on weak symbols: 438 * The ELF specs are ambiguous about treatment of weak definitions in 439 * dynamic linking. Some systems return the first definition found 440 * and some the first non-weak definition. This is system dependent. 441 * Here we return the first definition found for simplicity. */ 442 443 s = soinfo_elf_lookup(si, elf_hash, name); 444 if(s != NULL) 445 goto done; 446 } 447 448 /* Next, look for it in the preloads list */ 449 for(i = 0; preloads[i] != NULL; i++) { 450 lsi = preloads[i]; 451 s = soinfo_elf_lookup(lsi, elf_hash, name); 452 if(s != NULL) 453 goto done; 454 } 455 456 for(i = 0; needed[i] != NULL; i++) { 457 lsi = needed[i]; 458 DEBUG("%5d %s: looking up %s in %s\n", 459 pid, si->name, name, lsi->name); 460 s = soinfo_elf_lookup(lsi, elf_hash, name); 461 if (s != NULL) 462 goto done; 463 } 464 465#if ALLOW_SYMBOLS_FROM_MAIN 466 /* If we are resolving relocations while dlopen()ing a library, it's OK for 467 * the library to resolve a symbol that's defined in the executable itself, 468 * although this is rare and is generally a bad idea. 469 */ 470 if (somain) { 471 lsi = somain; 472 DEBUG("%5d %s: looking up %s in executable %s\n", 473 pid, si->name, name, lsi->name); 474 s = soinfo_elf_lookup(lsi, elf_hash, name); 475 } 476#endif 477 478done: 479 if(s != NULL) { 480 TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, " 481 "found in %s, base = 0x%08x, load bias = 0x%08x\n", 482 pid, si->name, name, s->st_value, 483 lsi->name, lsi->base, lsi->load_bias); 484 *offset = lsi->load_bias; 485 return s; 486 } 487 488 return NULL; 489} 490 491/* This is used by dl_sym(). It performs symbol lookup only within the 492 specified soinfo object and not in any of its dependencies. 493 */ 494Elf32_Sym *soinfo_lookup(soinfo *si, const char *name) 495{ 496 return soinfo_elf_lookup(si, elfhash(name), name); 497} 498 499/* This is used by dl_sym(). It performs a global symbol lookup. 500 */ 501Elf32_Sym *lookup(const char *name, soinfo **found, soinfo *start) 502{ 503 unsigned elf_hash = elfhash(name); 504 Elf32_Sym *s = NULL; 505 soinfo *si; 506 507 if(start == NULL) { 508 start = solist; 509 } 510 511 for(si = start; (s == NULL) && (si != NULL); si = si->next) 512 { 513 if(si->flags & FLAG_ERROR) 514 continue; 515 s = soinfo_elf_lookup(si, elf_hash, name); 516 if (s != NULL) { 517 *found = si; 518 break; 519 } 520 } 521 522 if(s != NULL) { 523 TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, " 524 "si->base = 0x%08x\n", pid, name, s->st_value, si->base); 525 return s; 526 } 527 528 return NULL; 529} 530 531soinfo *find_containing_library(const void *addr) 532{ 533 soinfo *si; 534 535 for(si = solist; si != NULL; si = si->next) 536 { 537 if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) { 538 return si; 539 } 540 } 541 542 return NULL; 543} 544 545Elf32_Sym *soinfo_find_symbol(soinfo* si, const void *addr) 546{ 547 unsigned int i; 548 unsigned soaddr = (unsigned)addr - si->base; 549 550 /* Search the library's symbol table for any defined symbol which 551 * contains this address */ 552 for(i=0; i<si->nchain; i++) { 553 Elf32_Sym *sym = &si->symtab[i]; 554 555 if(sym->st_shndx != SHN_UNDEF && 556 soaddr >= sym->st_value && 557 soaddr < sym->st_value + sym->st_size) { 558 return sym; 559 } 560 } 561 562 return NULL; 563} 564 565#if 0 566static void dump(soinfo *si) 567{ 568 Elf32_Sym *s = si->symtab; 569 unsigned n; 570 571 for(n = 0; n < si->nchain; n++) { 572 TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", pid, n, s, 573 s->st_info, s->st_shndx, s->st_value, s->st_size, 574 si->strtab + s->st_name); 575 s++; 576 } 577} 578#endif 579 580static const char * const sopaths[] = { 581 "/vendor/lib", 582 "/system/lib", 583 0 584}; 585 586static int _open_lib(const char* name) { 587 // TODO: why not just call open? 588 struct stat sb; 589 if (stat(name, &sb) == -1 || !S_ISREG(sb.st_mode)) { 590 return -1; 591 } 592 return TEMP_FAILURE_RETRY(open(name, O_RDONLY)); 593} 594 595static int open_library(const char *name) 596{ 597 int fd; 598 char buf[512]; 599 const char * const*path; 600 int n; 601 602 TRACE("[ %5d opening %s ]\n", pid, name); 603 604 if(name == 0) return -1; 605 if(strlen(name) > 256) return -1; 606 607 if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0)) 608 return fd; 609 610 for (path = ldpaths; *path; path++) { 611 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name); 612 if (n < 0 || n >= (int)sizeof(buf)) { 613 WARN("Ignoring very long library path: %s/%s\n", *path, name); 614 continue; 615 } 616 if ((fd = _open_lib(buf)) >= 0) 617 return fd; 618 } 619 for (path = sopaths; *path; path++) { 620 n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name); 621 if (n < 0 || n >= (int)sizeof(buf)) { 622 WARN("Ignoring very long library path: %s/%s\n", *path, name); 623 continue; 624 } 625 if ((fd = _open_lib(buf)) >= 0) 626 return fd; 627 } 628 629 return -1; 630} 631 632// Returns 'true' if the library is prelinked or on failure so we error out 633// either way. We no longer support prelinking. 634static bool is_prelinked(int fd, const char* name) 635{ 636 struct prelink_info_t { 637 long mmap_addr; 638 char tag[4]; // "PRE ". 639 }; 640 641 off_t sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END); 642 if (sz < 0) { 643 DL_ERR("lseek failed: %s", strerror(errno)); 644 return true; 645 } 646 647 prelink_info_t info; 648 int rc = TEMP_FAILURE_RETRY(read(fd, &info, sizeof(info))); 649 if (rc != sizeof(info)) { 650 DL_ERR("could not read prelink_info_t structure for \"%s\":", name, strerror(errno)); 651 return true; 652 } 653 654 if (memcmp(info.tag, "PRE ", 4) == 0) { 655 DL_ERR("prelinked libraries no longer supported: %s", name); 656 return true; 657 } 658 return false; 659} 660 661/* verify_elf_header 662 * Verifies the content of an ELF header. 663 * 664 * Args: 665 * 666 * Returns: 667 * 0 on success 668 * -1 if no valid ELF object is found @ base. 669 */ 670static int 671verify_elf_header(const Elf32_Ehdr* hdr) 672{ 673 if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1; 674 if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1; 675 if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1; 676 if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1; 677 if (hdr->e_type != ET_DYN) return -1; 678 679 /* TODO: Should we verify anything else in the header? */ 680#ifdef ANDROID_ARM_LINKER 681 if (hdr->e_machine != EM_ARM) return -1; 682#elif defined(ANDROID_X86_LINKER) 683 if (hdr->e_machine != EM_386) return -1; 684#elif defined(ANDROID_MIPS_LINKER) 685 if (hdr->e_machine != EM_MIPS) return -1; 686#endif 687 return 0; 688} 689 690struct scoped_fd { 691 ~scoped_fd() { 692 if (fd != -1) { 693 close(fd); 694 } 695 } 696 int fd; 697}; 698 699struct soinfo_ptr { 700 soinfo_ptr(const char* name) { 701 const char* bname = strrchr(name, '/'); 702 ptr = soinfo_alloc(bname ? bname + 1 : name); 703 } 704 ~soinfo_ptr() { 705 soinfo_free(ptr); 706 } 707 soinfo* release() { 708 soinfo* result = ptr; 709 ptr = NULL; 710 return result; 711 } 712 soinfo* ptr; 713}; 714 715// TODO: rewrite linker_phdr.h to use a class, then lose this. 716struct phdr_ptr { 717 phdr_ptr() : phdr_mmap(NULL) {} 718 ~phdr_ptr() { 719 if (phdr_mmap != NULL) { 720 phdr_table_unload(phdr_mmap, phdr_size); 721 } 722 } 723 void* phdr_mmap; 724 Elf32_Addr phdr_size; 725}; 726 727static soinfo* load_library(const char* name) 728{ 729 // Open the file. 730 scoped_fd fd; 731 fd.fd = open_library(name); 732 if (fd.fd == -1) { 733 DL_ERR("library \"%s\" not found", name); 734 return NULL; 735 } 736 737 // Read the ELF header. 738 Elf32_Ehdr header[1]; 739 int ret = TEMP_FAILURE_RETRY(read(fd.fd, (void*)header, sizeof(header))); 740 if (ret < 0) { 741 DL_ERR("can't read file \"%s\": %s", name, strerror(errno)); 742 return NULL; 743 } 744 if (ret != (int)sizeof(header)) { 745 DL_ERR("too small to be an ELF executable: %s", name); 746 return NULL; 747 } 748 if (verify_elf_header(header) < 0) { 749 DL_ERR("not a valid ELF executable: %s", name); 750 return NULL; 751 } 752 753 // Read the program header table. 754 const Elf32_Phdr* phdr_table; 755 phdr_ptr phdr_holder; 756 ret = phdr_table_load(fd.fd, header->e_phoff, header->e_phnum, 757 &phdr_holder.phdr_mmap, &phdr_holder.phdr_size, &phdr_table); 758 if (ret < 0) { 759 DL_ERR("can't load program header table: %s: %s", name, strerror(errno)); 760 return NULL; 761 } 762 size_t phdr_count = header->e_phnum; 763 764 // Get the load extents. 765 Elf32_Addr ext_sz = phdr_table_get_load_size(phdr_table, phdr_count); 766 TRACE("[ %5d - '%s' wants sz=0x%08x ]\n", pid, name, ext_sz); 767 if (ext_sz == 0) { 768 DL_ERR("no loadable segments in file: %s", name); 769 return NULL; 770 } 771 772 // We no longer support pre-linked libraries. 773 if (is_prelinked(fd.fd, name)) { 774 return NULL; 775 } 776 777 // Reserve address space for all loadable segments. 778 void* load_start = NULL; 779 Elf32_Addr load_size = 0; 780 Elf32_Addr load_bias = 0; 781 ret = phdr_table_reserve_memory(phdr_table, 782 phdr_count, 783 &load_start, 784 &load_size, 785 &load_bias); 786 if (ret < 0) { 787 DL_ERR("can't reserve %d bytes in address space for \"%s\": %s", 788 ext_sz, name, strerror(errno)); 789 return NULL; 790 } 791 792 TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n", 793 pid, name, load_start, load_size); 794 795 /* Map all the segments in our address space with default protections */ 796 ret = phdr_table_load_segments(phdr_table, 797 phdr_count, 798 load_bias, 799 fd.fd); 800 if (ret < 0) { 801 DL_ERR("can't map loadable segments for \"%s\": %s", 802 name, strerror(errno)); 803 return NULL; 804 } 805 806 soinfo_ptr si(name); 807 if (si.ptr == NULL) { 808 return NULL; 809 } 810 811 si.ptr->base = (Elf32_Addr) load_start; 812 si.ptr->size = load_size; 813 si.ptr->load_bias = load_bias; 814 si.ptr->flags = 0; 815 si.ptr->entry = 0; 816 si.ptr->dynamic = (unsigned *)-1; 817 si.ptr->phnum = phdr_count; 818 si.ptr->phdr = phdr_table_get_loaded_phdr(phdr_table, phdr_count, load_bias); 819 if (si.ptr->phdr == NULL) { 820 DL_ERR("can't find loaded PHDR for \"%s\"", name); 821 return NULL; 822 } 823 824 return si.release(); 825} 826 827static soinfo * 828init_library(soinfo *si) 829{ 830 /* At this point we know that whatever is loaded @ base is a valid ELF 831 * shared library whose segments are properly mapped in. */ 832 TRACE("[ %5d init_library base=0x%08x sz=0x%08x name='%s') ]\n", 833 pid, si->base, si->size, si->name); 834 835 if(soinfo_link_image(si)) { 836 munmap((void *)si->base, si->size); 837 return NULL; 838 } 839 840 return si; 841} 842 843static soinfo *find_loaded_library(const char *name) 844{ 845 soinfo *si; 846 const char *bname; 847 848 // TODO: don't use basename only for determining libraries 849 // http://code.google.com/p/android/issues/detail?id=6670 850 851 bname = strrchr(name, '/'); 852 bname = bname ? bname + 1 : name; 853 854 for(si = solist; si != NULL; si = si->next){ 855 if(!strcmp(bname, si->name)) { 856 return si; 857 } 858 } 859 return NULL; 860} 861 862soinfo *find_library(const char *name) 863{ 864 soinfo *si; 865 866#if ALLOW_SYMBOLS_FROM_MAIN 867 if (name == NULL) 868 return somain; 869#else 870 if (name == NULL) 871 return NULL; 872#endif 873 874 si = find_loaded_library(name); 875 if (si != NULL) { 876 if(si->flags & FLAG_ERROR) { 877 DL_ERR("\"%s\" failed to load previously", name); 878 return NULL; 879 } 880 if(si->flags & FLAG_LINKED) return si; 881 DL_ERR("OOPS: recursive link to \"%s\"", si->name); 882 return NULL; 883 } 884 885 TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", pid, name); 886 si = load_library(name); 887 if(si == NULL) 888 return NULL; 889 return init_library(si); 890} 891 892static void call_destructors(soinfo *si); 893 894int soinfo_unload(soinfo* si) { 895 if (si->refcount == 1) { 896 TRACE("%5d unloading '%s'\n", pid, si->name); 897 call_destructors(si); 898 899 for (unsigned* d = si->dynamic; *d; d += 2) { 900 if(d[0] == DT_NEEDED){ 901 soinfo *lsi = find_loaded_library(si->strtab + d[1]); 902 if (lsi) { 903 TRACE("%5d %s needs to unload %s\n", pid, 904 si->name, lsi->name); 905 soinfo_unload(lsi); 906 } else { 907 // TODO: should we return -1 in this case? 908 DL_ERR("\"%s\": could not unload dependent library", 909 si->name); 910 } 911 } 912 } 913 914 munmap((char *)si->base, si->size); 915 notify_gdb_of_unload(si); 916 soinfo_free(si); 917 si->refcount = 0; 918 } else { 919 si->refcount--; 920 PRINT("%5d not unloading '%s', decrementing refcount to %d\n", 921 pid, si->name, si->refcount); 922 } 923 return 0; 924} 925 926/* TODO: don't use unsigned for addrs below. It works, but is not 927 * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned 928 * long. 929 */ 930static int soinfo_relocate(soinfo *si, Elf32_Rel *rel, unsigned count, 931 soinfo *needed[]) 932{ 933 Elf32_Sym *symtab = si->symtab; 934 const char *strtab = si->strtab; 935 Elf32_Sym *s; 936 Elf32_Addr offset; 937 Elf32_Rel *start = rel; 938 939 for (size_t idx = 0; idx < count; ++idx, ++rel) { 940 unsigned type = ELF32_R_TYPE(rel->r_info); 941 unsigned sym = ELF32_R_SYM(rel->r_info); 942 unsigned reloc = (unsigned)(rel->r_offset + si->load_bias); 943 unsigned sym_addr = 0; 944 char *sym_name = NULL; 945 946 DEBUG("%5d Processing '%s' relocation at index %d\n", pid, 947 si->name, idx); 948 if (type == 0) { // R_*_NONE 949 continue; 950 } 951 if(sym != 0) { 952 sym_name = (char *)(strtab + symtab[sym].st_name); 953 bool ignore_local = false; 954#if defined(ANDROID_ARM_LINKER) 955 ignore_local = (type == R_ARM_COPY); 956#endif 957 s = soinfo_do_lookup(si, sym_name, &offset, needed, ignore_local); 958 if(s == NULL) { 959 /* We only allow an undefined symbol if this is a weak 960 reference.. */ 961 s = &symtab[sym]; 962 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) { 963 DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, si->name); 964 return -1; 965 } 966 967 /* IHI0044C AAELF 4.5.1.1: 968 969 Libraries are not searched to resolve weak references. 970 It is not an error for a weak reference to remain 971 unsatisfied. 972 973 During linking, the value of an undefined weak reference is: 974 - Zero if the relocation type is absolute 975 - The address of the place if the relocation is pc-relative 976 - The address of nominal base address if the relocation 977 type is base-relative. 978 */ 979 980 switch (type) { 981#if defined(ANDROID_ARM_LINKER) 982 case R_ARM_JUMP_SLOT: 983 case R_ARM_GLOB_DAT: 984 case R_ARM_ABS32: 985 case R_ARM_RELATIVE: /* Don't care. */ 986#elif defined(ANDROID_X86_LINKER) 987 case R_386_JMP_SLOT: 988 case R_386_GLOB_DAT: 989 case R_386_32: 990 case R_386_RELATIVE: /* Dont' care. */ 991#endif /* ANDROID_*_LINKER */ 992 /* sym_addr was initialized to be zero above or relocation 993 code below does not care about value of sym_addr. 994 No need to do anything. */ 995 break; 996 997#if defined(ANDROID_X86_LINKER) 998 case R_386_PC32: 999 sym_addr = reloc; 1000 break; 1001#endif /* ANDROID_X86_LINKER */ 1002 1003#if defined(ANDROID_ARM_LINKER) 1004 case R_ARM_COPY: 1005 /* Fall through. Can't really copy if weak symbol is 1006 not found in run-time. */ 1007#endif /* ANDROID_ARM_LINKER */ 1008 default: 1009 DL_ERR("unknown weak reloc type %d @ %p (%d)", 1010 type, rel, (int) (rel - start)); 1011 return -1; 1012 } 1013 } else { 1014 /* We got a definition. */ 1015#if 0 1016 if((base == 0) && (si->base != 0)){ 1017 /* linking from libraries to main image is bad */ 1018 DL_ERR("cannot locate \"%s\"...", 1019 strtab + symtab[sym].st_name); 1020 return -1; 1021 } 1022#endif 1023 sym_addr = (unsigned)(s->st_value + offset); 1024 } 1025 count_relocation(kRelocSymbol); 1026 } else { 1027 s = NULL; 1028 } 1029 1030/* TODO: This is ugly. Split up the relocations by arch into 1031 * different files. 1032 */ 1033 switch(type){ 1034#if defined(ANDROID_ARM_LINKER) 1035 case R_ARM_JUMP_SLOT: 1036 count_relocation(kRelocAbsolute); 1037 MARK(rel->r_offset); 1038 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid, 1039 reloc, sym_addr, sym_name); 1040 *((unsigned*)reloc) = sym_addr; 1041 break; 1042 case R_ARM_GLOB_DAT: 1043 count_relocation(kRelocAbsolute); 1044 MARK(rel->r_offset); 1045 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid, 1046 reloc, sym_addr, sym_name); 1047 *((unsigned*)reloc) = sym_addr; 1048 break; 1049 case R_ARM_ABS32: 1050 count_relocation(kRelocAbsolute); 1051 MARK(rel->r_offset); 1052 TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", pid, 1053 reloc, sym_addr, sym_name); 1054 *((unsigned*)reloc) += sym_addr; 1055 break; 1056 case R_ARM_REL32: 1057 count_relocation(kRelocRelative); 1058 MARK(rel->r_offset); 1059 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", pid, 1060 reloc, sym_addr, rel->r_offset, sym_name); 1061 *((unsigned*)reloc) += sym_addr - rel->r_offset; 1062 break; 1063#elif defined(ANDROID_X86_LINKER) 1064 case R_386_JMP_SLOT: 1065 count_relocation(kRelocAbsolute); 1066 MARK(rel->r_offset); 1067 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid, 1068 reloc, sym_addr, sym_name); 1069 *((unsigned*)reloc) = sym_addr; 1070 break; 1071 case R_386_GLOB_DAT: 1072 count_relocation(kRelocAbsolute); 1073 MARK(rel->r_offset); 1074 TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", pid, 1075 reloc, sym_addr, sym_name); 1076 *((unsigned*)reloc) = sym_addr; 1077 break; 1078#elif defined(ANDROID_MIPS_LINKER) 1079 case R_MIPS_JUMP_SLOT: 1080 count_relocation(kRelocAbsolute); 1081 MARK(rel->r_offset); 1082 TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", pid, 1083 reloc, sym_addr, sym_name); 1084 *((unsigned*)reloc) = sym_addr; 1085 break; 1086 case R_MIPS_REL32: 1087 count_relocation(kRelocAbsolute); 1088 MARK(rel->r_offset); 1089 TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x %s\n", pid, 1090 reloc, sym_addr, (sym_name) ? sym_name : "*SECTIONHDR*"); 1091 if (s) { 1092 *((unsigned*)reloc) += sym_addr; 1093 } else { 1094 *((unsigned*)reloc) += si->base; 1095 } 1096 break; 1097#endif /* ANDROID_*_LINKER */ 1098 1099#if defined(ANDROID_ARM_LINKER) 1100 case R_ARM_RELATIVE: 1101#elif defined(ANDROID_X86_LINKER) 1102 case R_386_RELATIVE: 1103#endif /* ANDROID_*_LINKER */ 1104 count_relocation(kRelocRelative); 1105 MARK(rel->r_offset); 1106 if (sym) { 1107 DL_ERR("odd RELATIVE form...", pid); 1108 return -1; 1109 } 1110 TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid, 1111 reloc, si->base); 1112 *((unsigned*)reloc) += si->base; 1113 break; 1114 1115#if defined(ANDROID_X86_LINKER) 1116 case R_386_32: 1117 count_relocation(kRelocRelative); 1118 MARK(rel->r_offset); 1119 1120 TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", pid, 1121 reloc, sym_addr, sym_name); 1122 *((unsigned *)reloc) += (unsigned)sym_addr; 1123 break; 1124 1125 case R_386_PC32: 1126 count_relocation(kRelocRelative); 1127 MARK(rel->r_offset); 1128 TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- " 1129 "+%08x (%08x - %08x) %s\n", pid, reloc, 1130 (sym_addr - reloc), sym_addr, reloc, sym_name); 1131 *((unsigned *)reloc) += (unsigned)(sym_addr - reloc); 1132 break; 1133#endif /* ANDROID_X86_LINKER */ 1134 1135#ifdef ANDROID_ARM_LINKER 1136 case R_ARM_COPY: 1137 if ((si->flags & FLAG_EXE) == 0) { 1138 /* 1139 * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf 1140 * 1141 * Section 4.7.1.10 "Dynamic relocations" 1142 * R_ARM_COPY may only appear in executable objects where e_type is 1143 * set to ET_EXEC. 1144 * 1145 * TODO: FLAG_EXE is set for both ET_DYN and ET_EXEC executables. 1146 * We should explicitly disallow ET_DYN executables from having 1147 * R_ARM_COPY relocations. 1148 */ 1149 DL_ERR("%s R_ARM_COPY relocations only supported for ET_EXEC", si->name); 1150 return -1; 1151 } 1152 count_relocation(kRelocCopy); 1153 MARK(rel->r_offset); 1154 TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", pid, 1155 reloc, s->st_size, sym_addr, sym_name); 1156 if (reloc == sym_addr) { 1157 DL_ERR("Internal linker error detected. reloc == symaddr"); 1158 return -1; 1159 } 1160 memcpy((void*)reloc, (void*)sym_addr, s->st_size); 1161 break; 1162#endif /* ANDROID_ARM_LINKER */ 1163 1164 default: 1165 DL_ERR("unknown reloc type %d @ %p (%d)", 1166 type, rel, (int) (rel - start)); 1167 return -1; 1168 } 1169 } 1170 return 0; 1171} 1172 1173#ifdef ANDROID_MIPS_LINKER 1174static int mips_relocate_got(soinfo* si, soinfo* needed[]) { 1175 unsigned *got; 1176 unsigned local_gotno, gotsym, symtabno; 1177 Elf32_Sym *symtab, *sym; 1178 unsigned g; 1179 1180 got = si->plt_got; 1181 local_gotno = si->mips_local_gotno; 1182 gotsym = si->mips_gotsym; 1183 symtabno = si->mips_symtabno; 1184 symtab = si->symtab; 1185 1186 /* 1187 * got[0] is address of lazy resolver function 1188 * got[1] may be used for a GNU extension 1189 * set it to a recognizable address in case someone calls it 1190 * (should be _rtld_bind_start) 1191 * FIXME: maybe this should be in a separate routine 1192 */ 1193 1194 if ((si->flags & FLAG_LINKER) == 0) { 1195 g = 0; 1196 got[g++] = 0xdeadbeef; 1197 if (got[g] & 0x80000000) { 1198 got[g++] = 0xdeadfeed; 1199 } 1200 /* 1201 * Relocate the local GOT entries need to be relocated 1202 */ 1203 for (; g < local_gotno; g++) { 1204 got[g] += si->load_bias; 1205 } 1206 } 1207 1208 /* Now for the global GOT entries */ 1209 sym = symtab + gotsym; 1210 got = si->plt_got + local_gotno; 1211 for (g = gotsym; g < symtabno; g++, sym++, got++) { 1212 const char *sym_name; 1213 unsigned base; 1214 Elf32_Sym *s; 1215 1216 /* This is an undefined reference... try to locate it */ 1217 sym_name = si->strtab + sym->st_name; 1218 s = soinfo_do_lookup(si, sym_name, &base, needed, false); 1219 if (s == NULL) { 1220 /* We only allow an undefined symbol if this is a weak 1221 reference.. */ 1222 s = &symtab[g]; 1223 if (ELF32_ST_BIND(s->st_info) != STB_WEAK) { 1224 DL_ERR("cannot locate \"%s\"...", sym_name); 1225 return -1; 1226 } 1227 *got = 0; 1228 } 1229 else { 1230 /* FIXME: is this sufficient? 1231 * For reference see NetBSD link loader 1232 * http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup 1233 */ 1234 *got = base + s->st_value; 1235 } 1236 } 1237 return 0; 1238} 1239#endif 1240 1241/* Please read the "Initialization and Termination functions" functions. 1242 * of the linker design note in bionic/linker/README.TXT to understand 1243 * what the following code is doing. 1244 * 1245 * The important things to remember are: 1246 * 1247 * DT_PREINIT_ARRAY must be called first for executables, and should 1248 * not appear in shared libraries. 1249 * 1250 * DT_INIT should be called before DT_INIT_ARRAY if both are present 1251 * 1252 * DT_FINI should be called after DT_FINI_ARRAY if both are present 1253 * 1254 * DT_FINI_ARRAY must be parsed in reverse order. 1255 */ 1256 1257static void call_array(unsigned *ctor, int count, int reverse) 1258{ 1259 int n, inc = 1; 1260 1261 if (reverse) { 1262 ctor += (count-1); 1263 inc = -1; 1264 } 1265 1266 for(n = count; n > 0; n--) { 1267 TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid, 1268 reverse ? "dtor" : "ctor", 1269 (unsigned)ctor, (unsigned)*ctor); 1270 void (*func)() = (void (*)()) *ctor; 1271 ctor += inc; 1272 if(((int) func == 0) || ((int) func == -1)) continue; 1273 TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func); 1274 func(); 1275 } 1276} 1277 1278static void soinfo_call_preinit_constructors(soinfo *si) 1279{ 1280 TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n", 1281 pid, (unsigned)si->preinit_array, si->preinit_array_count, 1282 si->name); 1283 call_array(si->preinit_array, si->preinit_array_count, 0); 1284 TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name); 1285} 1286 1287void soinfo_call_constructors(soinfo *si) 1288{ 1289 if (si->constructors_called) 1290 return; 1291 1292 // Set this before actually calling the constructors, otherwise it doesn't 1293 // protect against recursive constructor calls. One simple example of 1294 // constructor recursion is the libc debug malloc, which is implemented in 1295 // libc_malloc_debug_leak.so: 1296 // 1. The program depends on libc, so libc's constructor is called here. 1297 // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so. 1298 // 3. dlopen() calls soinfo_call_constructors() with the newly created 1299 // soinfo for libc_malloc_debug_leak.so. 1300 // 4. The debug so depends on libc, so soinfo_call_constructors() is 1301 // called again with the libc soinfo. If it doesn't trigger the early- 1302 // out above, the libc constructor will be called again (recursively!). 1303 si->constructors_called = 1; 1304 1305 if (!(si->flags & FLAG_EXE) && si->preinit_array) { 1306 DL_ERR("shared library \"%s\" has a preinit_array table @ 0x%08x. " 1307 "This is INVALID.", si->name, (unsigned) si->preinit_array); 1308 } 1309 1310 if (si->dynamic) { 1311 unsigned *d; 1312 for(d = si->dynamic; *d; d += 2) { 1313 if(d[0] == DT_NEEDED){ 1314 soinfo* lsi = find_loaded_library(si->strtab + d[1]); 1315 if (!lsi) { 1316 DL_ERR("\"%s\": could not initialize dependent library", 1317 si->name); 1318 } else { 1319 soinfo_call_constructors(lsi); 1320 } 1321 } 1322 } 1323 } 1324 1325 if (si->init_func) { 1326 TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid, 1327 (unsigned)si->init_func, si->name); 1328 si->init_func(); 1329 TRACE("[ %5d Done calling init_func for '%s' ]\n", pid, si->name); 1330 } 1331 1332 if (si->init_array) { 1333 TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid, 1334 (unsigned)si->init_array, si->init_array_count, si->name); 1335 call_array(si->init_array, si->init_array_count, 0); 1336 TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name); 1337 } 1338 1339} 1340 1341static void call_destructors(soinfo *si) 1342{ 1343 if (si->fini_array) { 1344 TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid, 1345 (unsigned)si->fini_array, si->fini_array_count, si->name); 1346 call_array(si->fini_array, si->fini_array_count, 1); 1347 TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name); 1348 } 1349 1350 if (si->fini_func) { 1351 TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid, 1352 (unsigned)si->fini_func, si->name); 1353 si->fini_func(); 1354 TRACE("[ %5d Done calling fini_func for '%s' ]\n", pid, si->name); 1355 } 1356} 1357 1358/* Force any of the closed stdin, stdout and stderr to be associated with 1359 /dev/null. */ 1360static int nullify_closed_stdio() { 1361 int dev_null, i, status; 1362 int return_value = 0; 1363 1364 dev_null = TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)); 1365 if (dev_null < 0) { 1366 DL_ERR("cannot open /dev/null: %s", strerror(errno)); 1367 return -1; 1368 } 1369 TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null); 1370 1371 /* If any of the stdio file descriptors is valid and not associated 1372 with /dev/null, dup /dev/null to it. */ 1373 for (i = 0; i < 3; i++) { 1374 /* If it is /dev/null already, we are done. */ 1375 if (i == dev_null) { 1376 continue; 1377 } 1378 1379 TRACE("[ %5d Nullifying stdio file descriptor %d]\n", pid, i); 1380 status = TEMP_FAILURE_RETRY(fcntl(i, F_GETFL)); 1381 1382 /* If file is opened, we are good. */ 1383 if (status != -1) { 1384 continue; 1385 } 1386 1387 /* The only error we allow is that the file descriptor does not 1388 exist, in which case we dup /dev/null to it. */ 1389 if (errno != EBADF) { 1390 DL_ERR("fcntl failed: %s", strerror(errno)); 1391 return_value = -1; 1392 continue; 1393 } 1394 1395 /* Try dupping /dev/null to this stdio file descriptor and 1396 repeat if there is a signal. Note that any errors in closing 1397 the stdio descriptor are lost. */ 1398 status = TEMP_FAILURE_RETRY(dup2(dev_null, i)); 1399 if (status < 0) { 1400 DL_ERR("dup2 failed: %s", strerror(errno)); 1401 return_value = -1; 1402 continue; 1403 } 1404 } 1405 1406 /* If /dev/null is not one of the stdio file descriptors, close it. */ 1407 if (dev_null > 2) { 1408 TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null); 1409 status = TEMP_FAILURE_RETRY(close(dev_null)); 1410 if (status == -1) { 1411 DL_ERR("close failed: %s", strerror(errno)); 1412 return_value = -1; 1413 } 1414 } 1415 1416 return return_value; 1417} 1418 1419static int soinfo_link_image(soinfo *si) 1420{ 1421 unsigned *d; 1422 /* "base" might wrap around UINT32_MAX. */ 1423 Elf32_Addr base = si->load_bias; 1424 const Elf32_Phdr *phdr = si->phdr; 1425 int phnum = si->phnum; 1426 int relocating_linker = (si->flags & FLAG_LINKER) != 0; 1427 soinfo **needed, **pneeded; 1428 size_t dynamic_count; 1429 1430 /* We can't debug anything until the linker is relocated */ 1431 if (!relocating_linker) { 1432 INFO("[ %5d linking %s ]\n", pid, si->name); 1433 DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", pid, 1434 si->base, si->flags); 1435 } 1436 1437 /* Extract dynamic section */ 1438 phdr_table_get_dynamic_section(phdr, phnum, base, &si->dynamic, 1439 &dynamic_count); 1440 if (si->dynamic == NULL) { 1441 if (!relocating_linker) { 1442 DL_ERR("missing PT_DYNAMIC?!"); 1443 } 1444 goto fail; 1445 } else { 1446 if (!relocating_linker) { 1447 DEBUG("%5d dynamic = %p\n", pid, si->dynamic); 1448 } 1449 } 1450 1451#ifdef ANDROID_ARM_LINKER 1452 (void) phdr_table_get_arm_exidx(phdr, phnum, base, 1453 &si->ARM_exidx, &si->ARM_exidx_count); 1454#endif 1455 1456 /* extract useful information from dynamic section */ 1457 for(d = si->dynamic; *d; d++){ 1458 DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", pid, d, d[0], d[1]); 1459 switch(*d++){ 1460 case DT_HASH: 1461 si->nbucket = ((unsigned *) (base + *d))[0]; 1462 si->nchain = ((unsigned *) (base + *d))[1]; 1463 si->bucket = (unsigned *) (base + *d + 8); 1464 si->chain = (unsigned *) (base + *d + 8 + si->nbucket * 4); 1465 break; 1466 case DT_STRTAB: 1467 si->strtab = (const char *) (base + *d); 1468 break; 1469 case DT_SYMTAB: 1470 si->symtab = (Elf32_Sym *) (base + *d); 1471 break; 1472 case DT_PLTREL: 1473 if(*d != DT_REL) { 1474 DL_ERR("DT_RELA not supported"); 1475 goto fail; 1476 } 1477 break; 1478 case DT_JMPREL: 1479 si->plt_rel = (Elf32_Rel*) (base + *d); 1480 break; 1481 case DT_PLTRELSZ: 1482 si->plt_rel_count = *d / 8; 1483 break; 1484 case DT_REL: 1485 si->rel = (Elf32_Rel*) (base + *d); 1486 break; 1487 case DT_RELSZ: 1488 si->rel_count = *d / 8; 1489 break; 1490 case DT_PLTGOT: 1491 /* Save this in case we decide to do lazy binding. We don't yet. */ 1492 si->plt_got = (unsigned *)(base + *d); 1493 break; 1494 case DT_DEBUG: 1495#if !defined(ANDROID_MIPS_LINKER) 1496 // Set the DT_DEBUG entry to the address of _r_debug for GDB 1497 *d = (int) &_r_debug; 1498#endif 1499 break; 1500 case DT_RELA: 1501 DL_ERR("DT_RELA not supported"); 1502 goto fail; 1503 case DT_INIT: 1504 si->init_func = (void (*)(void))(base + *d); 1505 DEBUG("%5d %s constructors (init func) found at %p\n", 1506 pid, si->name, si->init_func); 1507 break; 1508 case DT_FINI: 1509 si->fini_func = (void (*)(void))(base + *d); 1510 DEBUG("%5d %s destructors (fini func) found at %p\n", 1511 pid, si->name, si->fini_func); 1512 break; 1513 case DT_INIT_ARRAY: 1514 si->init_array = (unsigned *)(base + *d); 1515 DEBUG("%5d %s constructors (init_array) found at %p\n", 1516 pid, si->name, si->init_array); 1517 break; 1518 case DT_INIT_ARRAYSZ: 1519 si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr); 1520 break; 1521 case DT_FINI_ARRAY: 1522 si->fini_array = (unsigned *)(base + *d); 1523 DEBUG("%5d %s destructors (fini_array) found at %p\n", 1524 pid, si->name, si->fini_array); 1525 break; 1526 case DT_FINI_ARRAYSZ: 1527 si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr); 1528 break; 1529 case DT_PREINIT_ARRAY: 1530 si->preinit_array = (unsigned *)(base + *d); 1531 DEBUG("%5d %s constructors (preinit_array) found at %p\n", 1532 pid, si->name, si->preinit_array); 1533 break; 1534 case DT_PREINIT_ARRAYSZ: 1535 si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr); 1536 break; 1537 case DT_TEXTREL: 1538 si->has_text_relocations = true; 1539 break; 1540#if defined(ANDROID_MIPS_LINKER) 1541 case DT_NEEDED: 1542 case DT_STRSZ: 1543 case DT_SYMENT: 1544 case DT_RELENT: 1545 break; 1546 case DT_MIPS_RLD_MAP: 1547 // Set the DT_MIPS_RLD_MAP entry to the address of _r_debug for GDB. 1548 { 1549 r_debug** dp = (r_debug**) *d; 1550 *dp = &_r_debug; 1551 } 1552 break; 1553 case DT_MIPS_RLD_VERSION: 1554 case DT_MIPS_FLAGS: 1555 case DT_MIPS_BASE_ADDRESS: 1556 case DT_MIPS_UNREFEXTNO: 1557 case DT_MIPS_RWPLT: 1558 break; 1559 1560 case DT_MIPS_PLTGOT: 1561#if 0 1562 /* not yet... */ 1563 si->mips_pltgot = (unsigned *)(si->base + *d); 1564#endif 1565 break; 1566 1567 case DT_MIPS_SYMTABNO: 1568 si->mips_symtabno = *d; 1569 break; 1570 1571 case DT_MIPS_LOCAL_GOTNO: 1572 si->mips_local_gotno = *d; 1573 break; 1574 1575 case DT_MIPS_GOTSYM: 1576 si->mips_gotsym = *d; 1577 break; 1578 1579 default: 1580 DEBUG("%5d Unused DT entry: type 0x%08x arg 0x%08x\n", 1581 pid, d[-1], d[0]); 1582 break; 1583#endif 1584 } 1585 } 1586 1587 DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n", 1588 pid, si->base, si->strtab, si->symtab); 1589 1590 if((si->strtab == 0) || (si->symtab == 0)) { 1591 DL_ERR("missing essential tables"); 1592 goto fail; 1593 } 1594 1595 /* if this is the main executable, then load all of the preloads now */ 1596 if(si->flags & FLAG_EXE) { 1597 int i; 1598 memset(preloads, 0, sizeof(preloads)); 1599 for(i = 0; ldpreload_names[i] != NULL; i++) { 1600 soinfo *lsi = find_library(ldpreload_names[i]); 1601 if(lsi == 0) { 1602 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf)); 1603 DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s", 1604 ldpreload_names[i], si->name, tmp_err_buf); 1605 goto fail; 1606 } 1607 lsi->refcount++; 1608 preloads[i] = lsi; 1609 } 1610 } 1611 1612 /* dynamic_count is an upper bound for the number of needed libs */ 1613 pneeded = needed = (soinfo**) alloca((1 + dynamic_count) * sizeof(soinfo*)); 1614 1615 for(d = si->dynamic; *d; d += 2) { 1616 if(d[0] == DT_NEEDED){ 1617 DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]); 1618 soinfo *lsi = find_library(si->strtab + d[1]); 1619 if(lsi == 0) { 1620 strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf)); 1621 DL_ERR("could not load library \"%s\" needed by \"%s\"; caused by %s", 1622 si->strtab + d[1], si->name, tmp_err_buf); 1623 goto fail; 1624 } 1625 *pneeded++ = lsi; 1626 lsi->refcount++; 1627 } 1628 } 1629 *pneeded = NULL; 1630 1631 if (si->has_text_relocations) { 1632 /* Unprotect the segments, i.e. make them writable, to allow 1633 * text relocations to work properly. We will later call 1634 * phdr_table_protect_segments() after all of them are applied 1635 * and all constructors are run. 1636 */ 1637 if (phdr_table_unprotect_segments(si->phdr, si->phnum, si->load_bias) < 0) { 1638 DL_ERR("can't unprotect loadable segments for \"%s\": %s", 1639 si->name, strerror(errno)); 1640 goto fail; 1641 } 1642 } 1643 1644 if(si->plt_rel) { 1645 DEBUG("[ %5d relocating %s plt ]\n", pid, si->name ); 1646 if(soinfo_relocate(si, si->plt_rel, si->plt_rel_count, needed)) 1647 goto fail; 1648 } 1649 if(si->rel) { 1650 DEBUG("[ %5d relocating %s ]\n", pid, si->name ); 1651 if(soinfo_relocate(si, si->rel, si->rel_count, needed)) 1652 goto fail; 1653 } 1654 1655#ifdef ANDROID_MIPS_LINKER 1656 if(mips_relocate_got(si, needed)) { 1657 goto fail; 1658 } 1659#endif 1660 1661 si->flags |= FLAG_LINKED; 1662 DEBUG("[ %5d finished linking %s ]\n", pid, si->name); 1663 1664 if (si->has_text_relocations) { 1665 /* All relocations are done, we can protect our segments back to 1666 * read-only. */ 1667 if (phdr_table_protect_segments(si->phdr, si->phnum, si->load_bias) < 0) { 1668 DL_ERR("can't protect segments for \"%s\": %s", 1669 si->name, strerror(errno)); 1670 goto fail; 1671 } 1672 } 1673 1674 /* We can also turn on GNU RELRO protection */ 1675 if (phdr_table_protect_gnu_relro(si->phdr, si->phnum, si->load_bias) < 0) { 1676 DL_ERR("can't enable GNU RELRO protection for \"%s\": %s", 1677 si->name, strerror(errno)); 1678 goto fail; 1679 } 1680 1681 /* If this is a SET?ID program, dup /dev/null to opened stdin, 1682 stdout and stderr to close a security hole described in: 1683 1684 ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc 1685 1686 */ 1687 if (get_AT_SECURE()) { 1688 nullify_closed_stdio(); 1689 } 1690 notify_gdb_of_load(si); 1691 return 0; 1692 1693fail: 1694 ERROR("failed to link %s\n", si->name); 1695 si->flags |= FLAG_ERROR; 1696 return -1; 1697} 1698 1699static void parse_path(const char* path, const char* delimiters, 1700 const char** array, char* buf, size_t buf_size, size_t max_count) 1701{ 1702 if (path == NULL) { 1703 return; 1704 } 1705 1706 size_t len = strlcpy(buf, path, buf_size); 1707 1708 size_t i = 0; 1709 char* buf_p = buf; 1710 while (i < max_count && (array[i] = strsep(&buf_p, delimiters))) { 1711 if (*array[i] != '\0') { 1712 ++i; 1713 } 1714 } 1715 1716 // Forget the last path if we had to truncate; this occurs if the 2nd to 1717 // last char isn't '\0' (i.e. wasn't originally a delimiter). 1718 if (i > 0 && len >= buf_size && buf[buf_size - 2] != '\0') { 1719 array[i - 1] = NULL; 1720 } else { 1721 array[i] = NULL; 1722 } 1723} 1724 1725static void parse_LD_LIBRARY_PATH(const char* path) { 1726 parse_path(path, ":", ldpaths, 1727 ldpaths_buf, sizeof(ldpaths_buf), LDPATH_MAX); 1728} 1729 1730static void parse_LD_PRELOAD(const char* path) { 1731 // We have historically supported ':' as well as ' ' in LD_PRELOAD. 1732 parse_path(path, " :", ldpreload_names, 1733 ldpreloads_buf, sizeof(ldpreloads_buf), LDPRELOAD_MAX); 1734} 1735 1736/* 1737 * This code is called after the linker has linked itself and 1738 * fixed it's own GOT. It is safe to make references to externs 1739 * and other non-local data at this point. 1740 */ 1741static unsigned __linker_init_post_relocation(unsigned **elfdata, unsigned linker_base) 1742{ 1743 static soinfo linker_soinfo; 1744 1745 int argc = (int) *elfdata; 1746 char **argv = (char**) (elfdata + 1); 1747 unsigned *vecs = (unsigned*) (argv + argc + 1); 1748 1749 /* NOTE: we store the elfdata pointer on a special location 1750 * of the temporary TLS area in order to pass it to 1751 * the C Library's runtime initializer. 1752 * 1753 * The initializer must clear the slot and reset the TLS 1754 * to point to a different location to ensure that no other 1755 * shared library constructor can access it. 1756 */ 1757 __libc_init_tls(elfdata); 1758 1759 pid = getpid(); 1760 1761#if TIMING 1762 struct timeval t0, t1; 1763 gettimeofday(&t0, 0); 1764#endif 1765 1766 // Initialize environment functions, and get to the ELF aux vectors table. 1767 vecs = linker_env_init(vecs); 1768 1769 debugger_init(); 1770 1771 // Get a few environment variables. 1772#if LINKER_DEBUG 1773 { 1774 const char* env = linker_env_get("LD_DEBUG"); 1775 if (env != NULL) { 1776 debug_verbosity = atoi(env); 1777 } 1778 } 1779#endif 1780 1781 // Normally, these are cleaned by linker_env_init, but the test 1782 // doesn't cost us anything. 1783 const char* ldpath_env = NULL; 1784 const char* ldpreload_env = NULL; 1785 if (!get_AT_SECURE()) { 1786 ldpath_env = linker_env_get("LD_LIBRARY_PATH"); 1787 ldpreload_env = linker_env_get("LD_PRELOAD"); 1788 } 1789 1790 INFO("[ android linker & debugger ]\n"); 1791 DEBUG("%5d elfdata @ 0x%08x\n", pid, (unsigned)elfdata); 1792 1793 soinfo* si = soinfo_alloc(argv[0]); 1794 if (si == NULL) { 1795 exit(EXIT_FAILURE); 1796 } 1797 1798 /* bootstrap the link map, the main exe always needs to be first */ 1799 si->flags |= FLAG_EXE; 1800 link_map* map = &(si->linkmap); 1801 1802 map->l_addr = 0; 1803 map->l_name = argv[0]; 1804 map->l_prev = NULL; 1805 map->l_next = NULL; 1806 1807 _r_debug.r_map = map; 1808 r_debug_tail = map; 1809 1810 /* gdb expects the linker to be in the debug shared object list. 1811 * Without this, gdb has trouble locating the linker's ".text" 1812 * and ".plt" sections. Gdb could also potentially use this to 1813 * relocate the offset of our exported 'rtld_db_dlactivity' symbol. 1814 * Don't use soinfo_alloc(), because the linker shouldn't 1815 * be on the soinfo list. 1816 */ 1817 strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name); 1818 linker_soinfo.flags = 0; 1819 linker_soinfo.base = linker_base; 1820 /* 1821 * Set the dynamic field in the link map otherwise gdb will complain with 1822 * the following: 1823 * warning: .dynamic section for "/system/bin/linker" is not at the 1824 * expected address (wrong library or version mismatch?) 1825 */ 1826 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_base; 1827 Elf32_Phdr *phdr = 1828 (Elf32_Phdr *)((unsigned char *) linker_base + elf_hdr->e_phoff); 1829 phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base, 1830 &linker_soinfo.dynamic, NULL); 1831 insert_soinfo_into_debug_map(&linker_soinfo); 1832 1833 /* extract information passed from the kernel */ 1834 while (vecs[0] != 0){ 1835 switch(vecs[0]){ 1836 case AT_PHDR: 1837 si->phdr = (Elf32_Phdr*) vecs[1]; 1838 break; 1839 case AT_PHNUM: 1840 si->phnum = (int) vecs[1]; 1841 break; 1842 case AT_ENTRY: 1843 si->entry = vecs[1]; 1844 break; 1845 } 1846 vecs += 2; 1847 } 1848 1849 /* Compute the value of si->base. We can't rely on the fact that 1850 * the first entry is the PHDR because this will not be true 1851 * for certain executables (e.g. some in the NDK unit test suite) 1852 */ 1853 int nn; 1854 si->base = 0; 1855 si->size = phdr_table_get_load_size(si->phdr, si->phnum); 1856 si->load_bias = 0; 1857 for ( nn = 0; nn < si->phnum; nn++ ) { 1858 if (si->phdr[nn].p_type == PT_PHDR) { 1859 si->load_bias = (Elf32_Addr)si->phdr - si->phdr[nn].p_vaddr; 1860 si->base = (Elf32_Addr) si->phdr - si->phdr[nn].p_offset; 1861 break; 1862 } 1863 } 1864 si->dynamic = (unsigned *)-1; 1865 si->refcount = 1; 1866 1867 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid). 1868 parse_LD_LIBRARY_PATH(ldpath_env); 1869 parse_LD_PRELOAD(ldpreload_env); 1870 1871 if(soinfo_link_image(si)) { 1872 char errmsg[] = "CANNOT LINK EXECUTABLE\n"; 1873 write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf)); 1874 write(2, errmsg, sizeof(errmsg)); 1875 exit(EXIT_FAILURE); 1876 } 1877 1878 soinfo_call_preinit_constructors(si); 1879 1880 for (size_t i = 0; preloads[i] != NULL; ++i) { 1881 soinfo_call_constructors(preloads[i]); 1882 } 1883 1884 /*After the link_image, the si->base is initialized. 1885 *For so lib, the map->l_addr will be updated in notify_gdb_of_load. 1886 *We need to update this value for so exe here. So Unwind_Backtrace 1887 *for some arch like x86 could work correctly within so exe. 1888 */ 1889 map->l_addr = si->base; 1890 soinfo_call_constructors(si); 1891 1892#if ALLOW_SYMBOLS_FROM_MAIN 1893 /* Set somain after we've loaded all the libraries in order to prevent 1894 * linking of symbols back to the main image, which is not set up at that 1895 * point yet. 1896 */ 1897 somain = si; 1898#endif 1899 1900#if TIMING 1901 gettimeofday(&t1,NULL); 1902 PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) ( 1903 (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) - 1904 (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec) 1905 )); 1906#endif 1907#if STATS 1908 PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0], 1909 linker_stats.count[kRelocAbsolute], 1910 linker_stats.count[kRelocRelative], 1911 linker_stats.count[kRelocCopy], 1912 linker_stats.count[kRelocSymbol]); 1913#endif 1914#if COUNT_PAGES 1915 { 1916 unsigned n; 1917 unsigned i; 1918 unsigned count = 0; 1919 for(n = 0; n < 4096; n++){ 1920 if(bitmask[n]){ 1921 unsigned x = bitmask[n]; 1922 for(i = 0; i < 8; i++){ 1923 if(x & 1) count++; 1924 x >>= 1; 1925 } 1926 } 1927 } 1928 PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4); 1929 } 1930#endif 1931 1932#if TIMING || STATS || COUNT_PAGES 1933 fflush(stdout); 1934#endif 1935 1936 TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", pid, si->name, 1937 si->entry); 1938 return si->entry; 1939} 1940 1941/* 1942 * Find the value of AT_BASE passed to us by the kernel. This is the load 1943 * location of the linker. 1944 */ 1945static unsigned find_linker_base(unsigned **elfdata) { 1946 int argc = (int) *elfdata; 1947 char **argv = (char**) (elfdata + 1); 1948 unsigned *vecs = (unsigned*) (argv + argc + 1); 1949 while (vecs[0] != 0) { 1950 vecs++; 1951 } 1952 1953 /* The end of the environment block is marked by two NULL pointers */ 1954 vecs++; 1955 1956 while(vecs[0]) { 1957 if (vecs[0] == AT_BASE) { 1958 return vecs[1]; 1959 } 1960 vecs += 2; 1961 } 1962 1963 return 0; // should never happen 1964} 1965 1966/* Compute the load-bias of an existing executable. This shall only 1967 * be used to compute the load bias of an executable or shared library 1968 * that was loaded by the kernel itself. 1969 * 1970 * Input: 1971 * elf -> address of ELF header, assumed to be at the start of the file. 1972 * Return: 1973 * load bias, i.e. add the value of any p_vaddr in the file to get 1974 * the corresponding address in memory. 1975 */ 1976static Elf32_Addr 1977get_elf_exec_load_bias(const Elf32_Ehdr* elf) 1978{ 1979 Elf32_Addr offset = elf->e_phoff; 1980 const Elf32_Phdr* phdr_table = (const Elf32_Phdr*)((char*)elf + offset); 1981 const Elf32_Phdr* phdr_end = phdr_table + elf->e_phnum; 1982 const Elf32_Phdr* phdr; 1983 1984 for (phdr = phdr_table; phdr < phdr_end; phdr++) { 1985 if (phdr->p_type == PT_LOAD) { 1986 return (Elf32_Addr)elf + phdr->p_offset - phdr->p_vaddr; 1987 } 1988 } 1989 return 0; 1990} 1991 1992/* 1993 * This is the entry point for the linker, called from begin.S. This 1994 * method is responsible for fixing the linker's own relocations, and 1995 * then calling __linker_init_post_relocation(). 1996 * 1997 * Because this method is called before the linker has fixed it's own 1998 * relocations, any attempt to reference an extern variable, extern 1999 * function, or other GOT reference will generate a segfault. 2000 */ 2001extern "C" unsigned __linker_init(unsigned **elfdata) { 2002 unsigned linker_addr = find_linker_base(elfdata); 2003 Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *) linker_addr; 2004 Elf32_Phdr *phdr = 2005 (Elf32_Phdr *)((unsigned char *) linker_addr + elf_hdr->e_phoff); 2006 2007 soinfo linker_so; 2008 memset(&linker_so, 0, sizeof(soinfo)); 2009 2010 linker_so.base = linker_addr; 2011 linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum); 2012 linker_so.load_bias = get_elf_exec_load_bias(elf_hdr); 2013 linker_so.dynamic = (unsigned *) -1; 2014 linker_so.phdr = phdr; 2015 linker_so.phnum = elf_hdr->e_phnum; 2016 linker_so.flags |= FLAG_LINKER; 2017 2018 if (soinfo_link_image(&linker_so)) { 2019 // It would be nice to print an error message, but if the linker 2020 // can't link itself, there's no guarantee that we'll be able to 2021 // call write() (because it involves a GOT reference). 2022 // 2023 // This situation should never occur unless the linker itself 2024 // is corrupt. 2025 exit(EXIT_FAILURE); 2026 } 2027 2028 // We have successfully fixed our own relocations. It's safe to run 2029 // the main part of the linker now. 2030 unsigned start_address = __linker_init_post_relocation(elfdata, linker_addr); 2031 2032 // Return the address that the calling assembly stub should jump to. 2033 return start_address; 2034} 2035