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