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