1 /*- 2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra. 3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>. 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * 26 * $FreeBSD$ 27 */ 28 29 /* 30 * Dynamic linker for ELF. 31 * 32 * John Polstra <jdp@polstra.com>. 33 */ 34 35 #ifndef __GNUC__ 36 #error "GCC is needed to compile this file" 37 #endif 38 39 #include <sys/param.h> 40 #include <sys/mman.h> 41 #include <sys/stat.h> 42 43 #include <dlfcn.h> 44 #include <err.h> 45 #include <errno.h> 46 #include <fcntl.h> 47 #include <stdarg.h> 48 #include <stdio.h> 49 #include <stdlib.h> 50 #include <string.h> 51 #include <unistd.h> 52 53 #include "debug.h" 54 #include "rtld.h" 55 #include "libmap.h" 56 #include "rtld_tls.h" 57 58 #ifndef COMPAT_32BIT 59 #define PATH_RTLD "/libexec/ld-elf.so.1" 60 #else 61 #define PATH_RTLD "/libexec/ld-elf32.so.1" 62 #endif 63 64 /* Types. */ 65 typedef void (*func_ptr_type)(); 66 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg); 67 68 /* 69 * This structure provides a reentrant way to keep a list of objects and 70 * check which ones have already been processed in some way. 71 */ 72 typedef struct Struct_DoneList { 73 const Obj_Entry **objs; /* Array of object pointers */ 74 unsigned int num_alloc; /* Allocated size of the array */ 75 unsigned int num_used; /* Number of array slots used */ 76 } DoneList; 77 78 /* 79 * Function declarations. 80 */ 81 static const char *basename(const char *); 82 static void die(void); 83 static void digest_dynamic(Obj_Entry *, int); 84 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *); 85 static Obj_Entry *dlcheck(void *); 86 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *); 87 static bool donelist_check(DoneList *, const Obj_Entry *); 88 static void errmsg_restore(char *); 89 static char *errmsg_save(void); 90 static void *fill_search_info(const char *, size_t, void *); 91 static char *find_library(const char *, const Obj_Entry *); 92 static const char *gethints(void); 93 static void init_dag(Obj_Entry *); 94 static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *); 95 static void init_rtld(caddr_t); 96 static void initlist_add_neededs(Needed_Entry *needed, Objlist *list); 97 static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, 98 Objlist *list); 99 static bool is_exported(const Elf_Sym *); 100 static void linkmap_add(Obj_Entry *); 101 static void linkmap_delete(Obj_Entry *); 102 static int load_needed_objects(Obj_Entry *); 103 static int load_preload_objects(void); 104 static Obj_Entry *load_object(char *); 105 static Obj_Entry *obj_from_addr(const void *); 106 static void objlist_call_fini(Objlist *); 107 static void objlist_call_init(Objlist *); 108 static void objlist_clear(Objlist *); 109 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *); 110 static void objlist_init(Objlist *); 111 static void objlist_push_head(Objlist *, Obj_Entry *); 112 static void objlist_push_tail(Objlist *, Obj_Entry *); 113 static void objlist_remove(Objlist *, Obj_Entry *); 114 static void objlist_remove_unref(Objlist *); 115 static void *path_enumerate(const char *, path_enum_proc, void *); 116 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *); 117 static int rtld_dirname(const char *, char *); 118 static void rtld_exit(void); 119 static char *search_library_path(const char *, const char *); 120 static const void **get_program_var_addr(const char *name); 121 static void set_program_var(const char *, const void *); 122 static const Elf_Sym *symlook_default(const char *, unsigned long hash, 123 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt); 124 static const Elf_Sym *symlook_list(const char *, unsigned long, 125 Objlist *, const Obj_Entry **, bool in_plt, DoneList *); 126 static void trace_loaded_objects(Obj_Entry *obj); 127 static void unlink_object(Obj_Entry *); 128 static void unload_object(Obj_Entry *); 129 static void unref_dag(Obj_Entry *); 130 static void ref_dag(Obj_Entry *); 131 132 void r_debug_state(struct r_debug*, struct link_map*); 133 134 /* 135 * Data declarations. 136 */ 137 static char *error_message; /* Message for dlerror(), or NULL */ 138 struct r_debug r_debug; /* for GDB; */ 139 static bool libmap_disable; /* Disable libmap */ 140 static char *libmap_override; /* Maps to use in addition to libmap.conf */ 141 static bool trust; /* False for setuid and setgid programs */ 142 static char *ld_bind_now; /* Environment variable for immediate binding */ 143 static char *ld_debug; /* Environment variable for debugging */ 144 static char *ld_library_path; /* Environment variable for search path */ 145 static char *ld_preload; /* Environment variable for libraries to 146 load first */ 147 static char *ld_tracing; /* Called from ldd to print libs */ 148 static Obj_Entry *obj_list; /* Head of linked list of shared objects */ 149 static Obj_Entry **obj_tail; /* Link field of last object in list */ 150 static Obj_Entry *obj_main; /* The main program shared object */ 151 static Obj_Entry obj_rtld; /* The dynamic linker shared object */ 152 static unsigned int obj_count; /* Number of objects in obj_list */ 153 154 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */ 155 STAILQ_HEAD_INITIALIZER(list_global); 156 static Objlist list_main = /* Objects loaded at program startup */ 157 STAILQ_HEAD_INITIALIZER(list_main); 158 static Objlist list_fini = /* Objects needing fini() calls */ 159 STAILQ_HEAD_INITIALIZER(list_fini); 160 161 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */ 162 163 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m); 164 165 extern Elf_Dyn _DYNAMIC; 166 #pragma weak _DYNAMIC 167 #ifndef RTLD_IS_DYNAMIC 168 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL) 169 #endif 170 171 /* 172 * These are the functions the dynamic linker exports to application 173 * programs. They are the only symbols the dynamic linker is willing 174 * to export from itself. 175 */ 176 static func_ptr_type exports[] = { 177 (func_ptr_type) &_rtld_error, 178 (func_ptr_type) &dlclose, 179 (func_ptr_type) &dlerror, 180 (func_ptr_type) &dlopen, 181 (func_ptr_type) &dlsym, 182 (func_ptr_type) &dladdr, 183 (func_ptr_type) &dllockinit, 184 (func_ptr_type) &dlinfo, 185 (func_ptr_type) &_rtld_thread_init, 186 #ifdef __i386__ 187 (func_ptr_type) &___tls_get_addr, 188 #endif 189 (func_ptr_type) &__tls_get_addr, 190 (func_ptr_type) &_rtld_allocate_tls, 191 (func_ptr_type) &_rtld_free_tls, 192 NULL 193 }; 194 195 /* 196 * Global declarations normally provided by crt1. The dynamic linker is 197 * not built with crt1, so we have to provide them ourselves. 198 */ 199 char *__progname; 200 char **environ; 201 202 /* 203 * Globals to control TLS allocation. 204 */ 205 size_t tls_last_offset; /* Static TLS offset of last module */ 206 size_t tls_last_size; /* Static TLS size of last module */ 207 size_t tls_static_space; /* Static TLS space allocated */ 208 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */ 209 int tls_max_index = 1; /* Largest module index allocated */ 210 211 /* 212 * Fill in a DoneList with an allocation large enough to hold all of 213 * the currently-loaded objects. Keep this as a macro since it calls 214 * alloca and we want that to occur within the scope of the caller. 215 */ 216 #define donelist_init(dlp) \ 217 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \ 218 assert((dlp)->objs != NULL), \ 219 (dlp)->num_alloc = obj_count, \ 220 (dlp)->num_used = 0) 221 222 /* 223 * Main entry point for dynamic linking. The first argument is the 224 * stack pointer. The stack is expected to be laid out as described 225 * in the SVR4 ABI specification, Intel 386 Processor Supplement. 226 * Specifically, the stack pointer points to a word containing 227 * ARGC. Following that in the stack is a null-terminated sequence 228 * of pointers to argument strings. Then comes a null-terminated 229 * sequence of pointers to environment strings. Finally, there is a 230 * sequence of "auxiliary vector" entries. 231 * 232 * The second argument points to a place to store the dynamic linker's 233 * exit procedure pointer and the third to a place to store the main 234 * program's object. 235 * 236 * The return value is the main program's entry point. 237 */ 238 func_ptr_type 239 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) 240 { 241 Elf_Auxinfo *aux_info[AT_COUNT]; 242 int i; 243 int argc; 244 char **argv; 245 char **env; 246 Elf_Auxinfo *aux; 247 Elf_Auxinfo *auxp; 248 const char *argv0; 249 Objlist_Entry *entry; 250 Obj_Entry *obj; 251 Obj_Entry **preload_tail; 252 Objlist initlist; 253 int lockstate; 254 255 /* 256 * On entry, the dynamic linker itself has not been relocated yet. 257 * Be very careful not to reference any global data until after 258 * init_rtld has returned. It is OK to reference file-scope statics 259 * and string constants, and to call static and global functions. 260 */ 261 262 /* Find the auxiliary vector on the stack. */ 263 argc = *sp++; 264 argv = (char **) sp; 265 sp += argc + 1; /* Skip over arguments and NULL terminator */ 266 env = (char **) sp; 267 while (*sp++ != 0) /* Skip over environment, and NULL terminator */ 268 ; 269 aux = (Elf_Auxinfo *) sp; 270 271 /* Digest the auxiliary vector. */ 272 for (i = 0; i < AT_COUNT; i++) 273 aux_info[i] = NULL; 274 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { 275 if (auxp->a_type < AT_COUNT) 276 aux_info[auxp->a_type] = auxp; 277 } 278 279 /* Initialize and relocate ourselves. */ 280 assert(aux_info[AT_BASE] != NULL); 281 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr); 282 283 __progname = obj_rtld.path; 284 argv0 = argv[0] != NULL ? argv[0] : "(null)"; 285 environ = env; 286 287 trust = !issetugid(); 288 289 ld_bind_now = getenv(LD_ "BIND_NOW"); 290 if (trust) { 291 ld_debug = getenv(LD_ "DEBUG"); 292 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL; 293 libmap_override = getenv(LD_ "LIBMAP"); 294 ld_library_path = getenv(LD_ "LIBRARY_PATH"); 295 ld_preload = getenv(LD_ "PRELOAD"); 296 } 297 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS"); 298 299 if (ld_debug != NULL && *ld_debug != '\0') 300 debug = 1; 301 dbg("%s is initialized, base address = %p", __progname, 302 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr); 303 dbg("RTLD dynamic = %p", obj_rtld.dynamic); 304 dbg("RTLD pltgot = %p", obj_rtld.pltgot); 305 306 /* 307 * Load the main program, or process its program header if it is 308 * already loaded. 309 */ 310 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */ 311 int fd = aux_info[AT_EXECFD]->a_un.a_val; 312 dbg("loading main program"); 313 obj_main = map_object(fd, argv0, NULL); 314 close(fd); 315 if (obj_main == NULL) 316 die(); 317 } else { /* Main program already loaded. */ 318 const Elf_Phdr *phdr; 319 int phnum; 320 caddr_t entry; 321 322 dbg("processing main program's program header"); 323 assert(aux_info[AT_PHDR] != NULL); 324 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr; 325 assert(aux_info[AT_PHNUM] != NULL); 326 phnum = aux_info[AT_PHNUM]->a_un.a_val; 327 assert(aux_info[AT_PHENT] != NULL); 328 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr)); 329 assert(aux_info[AT_ENTRY] != NULL); 330 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr; 331 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL) 332 die(); 333 } 334 335 obj_main->path = xstrdup(argv0); 336 obj_main->mainprog = true; 337 338 /* 339 * Get the actual dynamic linker pathname from the executable if 340 * possible. (It should always be possible.) That ensures that 341 * gdb will find the right dynamic linker even if a non-standard 342 * one is being used. 343 */ 344 if (obj_main->interp != NULL && 345 strcmp(obj_main->interp, obj_rtld.path) != 0) { 346 free(obj_rtld.path); 347 obj_rtld.path = xstrdup(obj_main->interp); 348 __progname = obj_rtld.path; 349 } 350 351 digest_dynamic(obj_main, 0); 352 353 linkmap_add(obj_main); 354 linkmap_add(&obj_rtld); 355 356 /* Link the main program into the list of objects. */ 357 *obj_tail = obj_main; 358 obj_tail = &obj_main->next; 359 obj_count++; 360 /* Make sure we don't call the main program's init and fini functions. */ 361 obj_main->init = obj_main->fini = (Elf_Addr)NULL; 362 363 /* Initialize a fake symbol for resolving undefined weak references. */ 364 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE); 365 sym_zero.st_shndx = SHN_UNDEF; 366 367 if (!libmap_disable) 368 libmap_disable = (bool)lm_init(libmap_override); 369 370 dbg("loading LD_PRELOAD libraries"); 371 if (load_preload_objects() == -1) 372 die(); 373 preload_tail = obj_tail; 374 375 dbg("loading needed objects"); 376 if (load_needed_objects(obj_main) == -1) 377 die(); 378 379 /* Make a list of all objects loaded at startup. */ 380 for (obj = obj_list; obj != NULL; obj = obj->next) { 381 objlist_push_tail(&list_main, obj); 382 obj->refcount++; 383 } 384 385 if (ld_tracing) { /* We're done */ 386 trace_loaded_objects(obj_main); 387 exit(0); 388 } 389 390 if (getenv(LD_ "DUMP_REL_PRE") != NULL) { 391 dump_relocations(obj_main); 392 exit (0); 393 } 394 395 /* setup TLS for main thread */ 396 dbg("initializing initial thread local storage"); 397 STAILQ_FOREACH(entry, &list_main, link) { 398 /* 399 * Allocate all the initial objects out of the static TLS 400 * block even if they didn't ask for it. 401 */ 402 allocate_tls_offset(entry->obj); 403 } 404 allocate_initial_tls(obj_list); 405 406 if (relocate_objects(obj_main, 407 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1) 408 die(); 409 410 dbg("doing copy relocations"); 411 if (do_copy_relocations(obj_main) == -1) 412 die(); 413 414 if (getenv(LD_ "DUMP_REL_POST") != NULL) { 415 dump_relocations(obj_main); 416 exit (0); 417 } 418 419 dbg("initializing key program variables"); 420 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : ""); 421 set_program_var("environ", env); 422 423 dbg("initializing thread locks"); 424 lockdflt_init(); 425 426 /* Make a list of init functions to call. */ 427 objlist_init(&initlist); 428 initlist_add_objects(obj_list, preload_tail, &initlist); 429 430 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */ 431 432 objlist_call_init(&initlist); 433 lockstate = wlock_acquire(rtld_bind_lock); 434 objlist_clear(&initlist); 435 wlock_release(rtld_bind_lock, lockstate); 436 437 dbg("transferring control to program entry point = %p", obj_main->entry); 438 439 /* Return the exit procedure and the program entry point. */ 440 *exit_proc = rtld_exit; 441 *objp = obj_main; 442 return (func_ptr_type) obj_main->entry; 443 } 444 445 Elf_Addr 446 _rtld_bind(Obj_Entry *obj, Elf_Word reloff) 447 { 448 const Elf_Rel *rel; 449 const Elf_Sym *def; 450 const Obj_Entry *defobj; 451 Elf_Addr *where; 452 Elf_Addr target; 453 int lockstate; 454 455 lockstate = rlock_acquire(rtld_bind_lock); 456 if (obj->pltrel) 457 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff); 458 else 459 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff); 460 461 where = (Elf_Addr *) (obj->relocbase + rel->r_offset); 462 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL); 463 if (def == NULL) 464 die(); 465 466 target = (Elf_Addr)(defobj->relocbase + def->st_value); 467 468 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"", 469 defobj->strtab + def->st_name, basename(obj->path), 470 (void *)target, basename(defobj->path)); 471 472 /* 473 * Write the new contents for the jmpslot. Note that depending on 474 * architecture, the value which we need to return back to the 475 * lazy binding trampoline may or may not be the target 476 * address. The value returned from reloc_jmpslot() is the value 477 * that the trampoline needs. 478 */ 479 target = reloc_jmpslot(where, target, defobj, obj, rel); 480 rlock_release(rtld_bind_lock, lockstate); 481 return target; 482 } 483 484 /* 485 * Error reporting function. Use it like printf. If formats the message 486 * into a buffer, and sets things up so that the next call to dlerror() 487 * will return the message. 488 */ 489 void 490 _rtld_error(const char *fmt, ...) 491 { 492 static char buf[512]; 493 va_list ap; 494 495 va_start(ap, fmt); 496 vsnprintf(buf, sizeof buf, fmt, ap); 497 error_message = buf; 498 va_end(ap); 499 } 500 501 /* 502 * Return a dynamically-allocated copy of the current error message, if any. 503 */ 504 static char * 505 errmsg_save(void) 506 { 507 return error_message == NULL ? NULL : xstrdup(error_message); 508 } 509 510 /* 511 * Restore the current error message from a copy which was previously saved 512 * by errmsg_save(). The copy is freed. 513 */ 514 static void 515 errmsg_restore(char *saved_msg) 516 { 517 if (saved_msg == NULL) 518 error_message = NULL; 519 else { 520 _rtld_error("%s", saved_msg); 521 free(saved_msg); 522 } 523 } 524 525 static const char * 526 basename(const char *name) 527 { 528 const char *p = strrchr(name, '/'); 529 return p != NULL ? p + 1 : name; 530 } 531 532 static void 533 die(void) 534 { 535 const char *msg = dlerror(); 536 537 if (msg == NULL) 538 msg = "Fatal error"; 539 errx(1, "%s", msg); 540 } 541 542 /* 543 * Process a shared object's DYNAMIC section, and save the important 544 * information in its Obj_Entry structure. 545 */ 546 static void 547 digest_dynamic(Obj_Entry *obj, int early) 548 { 549 const Elf_Dyn *dynp; 550 Needed_Entry **needed_tail = &obj->needed; 551 const Elf_Dyn *dyn_rpath = NULL; 552 int plttype = DT_REL; 553 554 obj->bind_now = false; 555 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) { 556 switch (dynp->d_tag) { 557 558 case DT_REL: 559 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr); 560 break; 561 562 case DT_RELSZ: 563 obj->relsize = dynp->d_un.d_val; 564 break; 565 566 case DT_RELENT: 567 assert(dynp->d_un.d_val == sizeof(Elf_Rel)); 568 break; 569 570 case DT_JMPREL: 571 obj->pltrel = (const Elf_Rel *) 572 (obj->relocbase + dynp->d_un.d_ptr); 573 break; 574 575 case DT_PLTRELSZ: 576 obj->pltrelsize = dynp->d_un.d_val; 577 break; 578 579 case DT_RELA: 580 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr); 581 break; 582 583 case DT_RELASZ: 584 obj->relasize = dynp->d_un.d_val; 585 break; 586 587 case DT_RELAENT: 588 assert(dynp->d_un.d_val == sizeof(Elf_Rela)); 589 break; 590 591 case DT_PLTREL: 592 plttype = dynp->d_un.d_val; 593 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA); 594 break; 595 596 case DT_SYMTAB: 597 obj->symtab = (const Elf_Sym *) 598 (obj->relocbase + dynp->d_un.d_ptr); 599 break; 600 601 case DT_SYMENT: 602 assert(dynp->d_un.d_val == sizeof(Elf_Sym)); 603 break; 604 605 case DT_STRTAB: 606 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr); 607 break; 608 609 case DT_STRSZ: 610 obj->strsize = dynp->d_un.d_val; 611 break; 612 613 case DT_HASH: 614 { 615 const Elf_Hashelt *hashtab = (const Elf_Hashelt *) 616 (obj->relocbase + dynp->d_un.d_ptr); 617 obj->nbuckets = hashtab[0]; 618 obj->nchains = hashtab[1]; 619 obj->buckets = hashtab + 2; 620 obj->chains = obj->buckets + obj->nbuckets; 621 } 622 break; 623 624 case DT_NEEDED: 625 if (!obj->rtld) { 626 Needed_Entry *nep = NEW(Needed_Entry); 627 nep->name = dynp->d_un.d_val; 628 nep->obj = NULL; 629 nep->next = NULL; 630 631 *needed_tail = nep; 632 needed_tail = &nep->next; 633 } 634 break; 635 636 case DT_PLTGOT: 637 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr); 638 break; 639 640 case DT_TEXTREL: 641 obj->textrel = true; 642 break; 643 644 case DT_SYMBOLIC: 645 obj->symbolic = true; 646 break; 647 648 case DT_RPATH: 649 case DT_RUNPATH: /* XXX: process separately */ 650 /* 651 * We have to wait until later to process this, because we 652 * might not have gotten the address of the string table yet. 653 */ 654 dyn_rpath = dynp; 655 break; 656 657 case DT_SONAME: 658 /* Not used by the dynamic linker. */ 659 break; 660 661 case DT_INIT: 662 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 663 break; 664 665 case DT_FINI: 666 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 667 break; 668 669 case DT_DEBUG: 670 /* XXX - not implemented yet */ 671 if (!early) 672 dbg("Filling in DT_DEBUG entry"); 673 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug; 674 break; 675 676 case DT_FLAGS: 677 if (dynp->d_un.d_val & DF_ORIGIN) { 678 obj->origin_path = xmalloc(PATH_MAX); 679 if (rtld_dirname(obj->path, obj->origin_path) == -1) 680 die(); 681 } 682 if (dynp->d_un.d_val & DF_SYMBOLIC) 683 obj->symbolic = true; 684 if (dynp->d_un.d_val & DF_TEXTREL) 685 obj->textrel = true; 686 if (dynp->d_un.d_val & DF_BIND_NOW) 687 obj->bind_now = true; 688 if (dynp->d_un.d_val & DF_STATIC_TLS) 689 ; 690 break; 691 692 default: 693 if (!early) { 694 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag, 695 (long)dynp->d_tag); 696 } 697 break; 698 } 699 } 700 701 obj->traced = false; 702 703 if (plttype == DT_RELA) { 704 obj->pltrela = (const Elf_Rela *) obj->pltrel; 705 obj->pltrel = NULL; 706 obj->pltrelasize = obj->pltrelsize; 707 obj->pltrelsize = 0; 708 } 709 710 if (dyn_rpath != NULL) 711 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val; 712 } 713 714 /* 715 * Process a shared object's program header. This is used only for the 716 * main program, when the kernel has already loaded the main program 717 * into memory before calling the dynamic linker. It creates and 718 * returns an Obj_Entry structure. 719 */ 720 static Obj_Entry * 721 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path) 722 { 723 Obj_Entry *obj; 724 const Elf_Phdr *phlimit = phdr + phnum; 725 const Elf_Phdr *ph; 726 int nsegs = 0; 727 728 obj = obj_new(); 729 for (ph = phdr; ph < phlimit; ph++) { 730 switch (ph->p_type) { 731 732 case PT_PHDR: 733 if ((const Elf_Phdr *)ph->p_vaddr != phdr) { 734 _rtld_error("%s: invalid PT_PHDR", path); 735 return NULL; 736 } 737 obj->phdr = (const Elf_Phdr *) ph->p_vaddr; 738 obj->phsize = ph->p_memsz; 739 break; 740 741 case PT_INTERP: 742 obj->interp = (const char *) ph->p_vaddr; 743 break; 744 745 case PT_LOAD: 746 if (nsegs == 0) { /* First load segment */ 747 obj->vaddrbase = trunc_page(ph->p_vaddr); 748 obj->mapbase = (caddr_t) obj->vaddrbase; 749 obj->relocbase = obj->mapbase - obj->vaddrbase; 750 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) - 751 obj->vaddrbase; 752 } else { /* Last load segment */ 753 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) - 754 obj->vaddrbase; 755 } 756 nsegs++; 757 break; 758 759 case PT_DYNAMIC: 760 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr; 761 break; 762 763 case PT_TLS: 764 obj->tlsindex = 1; 765 obj->tlssize = ph->p_memsz; 766 obj->tlsalign = ph->p_align; 767 obj->tlsinitsize = ph->p_filesz; 768 obj->tlsinit = (void*) ph->p_vaddr; 769 break; 770 } 771 } 772 if (nsegs < 1) { 773 _rtld_error("%s: too few PT_LOAD segments", path); 774 return NULL; 775 } 776 777 obj->entry = entry; 778 return obj; 779 } 780 781 static Obj_Entry * 782 dlcheck(void *handle) 783 { 784 Obj_Entry *obj; 785 786 for (obj = obj_list; obj != NULL; obj = obj->next) 787 if (obj == (Obj_Entry *) handle) 788 break; 789 790 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) { 791 _rtld_error("Invalid shared object handle %p", handle); 792 return NULL; 793 } 794 return obj; 795 } 796 797 /* 798 * If the given object is already in the donelist, return true. Otherwise 799 * add the object to the list and return false. 800 */ 801 static bool 802 donelist_check(DoneList *dlp, const Obj_Entry *obj) 803 { 804 unsigned int i; 805 806 for (i = 0; i < dlp->num_used; i++) 807 if (dlp->objs[i] == obj) 808 return true; 809 /* 810 * Our donelist allocation should always be sufficient. But if 811 * our threads locking isn't working properly, more shared objects 812 * could have been loaded since we allocated the list. That should 813 * never happen, but we'll handle it properly just in case it does. 814 */ 815 if (dlp->num_used < dlp->num_alloc) 816 dlp->objs[dlp->num_used++] = obj; 817 return false; 818 } 819 820 /* 821 * Hash function for symbol table lookup. Don't even think about changing 822 * this. It is specified by the System V ABI. 823 */ 824 unsigned long 825 elf_hash(const char *name) 826 { 827 const unsigned char *p = (const unsigned char *) name; 828 unsigned long h = 0; 829 unsigned long g; 830 831 while (*p != '\0') { 832 h = (h << 4) + *p++; 833 if ((g = h & 0xf0000000) != 0) 834 h ^= g >> 24; 835 h &= ~g; 836 } 837 return h; 838 } 839 840 /* 841 * Find the library with the given name, and return its full pathname. 842 * The returned string is dynamically allocated. Generates an error 843 * message and returns NULL if the library cannot be found. 844 * 845 * If the second argument is non-NULL, then it refers to an already- 846 * loaded shared object, whose library search path will be searched. 847 * 848 * The search order is: 849 * LD_LIBRARY_PATH 850 * rpath in the referencing file 851 * ldconfig hints 852 * /lib:/usr/lib 853 */ 854 static char * 855 find_library(const char *xname, const Obj_Entry *refobj) 856 { 857 char *pathname; 858 char *name; 859 860 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */ 861 if (xname[0] != '/' && !trust) { 862 _rtld_error("Absolute pathname required for shared object \"%s\"", 863 xname); 864 return NULL; 865 } 866 return xstrdup(xname); 867 } 868 869 if (libmap_disable || (refobj == NULL) || 870 (name = lm_find(refobj->path, xname)) == NULL) 871 name = (char *)xname; 872 873 dbg(" Searching for \"%s\"", name); 874 875 if ((pathname = search_library_path(name, ld_library_path)) != NULL || 876 (refobj != NULL && 877 (pathname = search_library_path(name, refobj->rpath)) != NULL) || 878 (pathname = search_library_path(name, gethints())) != NULL || 879 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL) 880 return pathname; 881 882 if(refobj != NULL && refobj->path != NULL) { 883 _rtld_error("Shared object \"%s\" not found, required by \"%s\"", 884 name, basename(refobj->path)); 885 } else { 886 _rtld_error("Shared object \"%s\" not found", name); 887 } 888 return NULL; 889 } 890 891 /* 892 * Given a symbol number in a referencing object, find the corresponding 893 * definition of the symbol. Returns a pointer to the symbol, or NULL if 894 * no definition was found. Returns a pointer to the Obj_Entry of the 895 * defining object via the reference parameter DEFOBJ_OUT. 896 */ 897 const Elf_Sym * 898 find_symdef(unsigned long symnum, const Obj_Entry *refobj, 899 const Obj_Entry **defobj_out, bool in_plt, SymCache *cache) 900 { 901 const Elf_Sym *ref; 902 const Elf_Sym *def; 903 const Obj_Entry *defobj; 904 const char *name; 905 unsigned long hash; 906 907 /* 908 * If we have already found this symbol, get the information from 909 * the cache. 910 */ 911 if (symnum >= refobj->nchains) 912 return NULL; /* Bad object */ 913 if (cache != NULL && cache[symnum].sym != NULL) { 914 *defobj_out = cache[symnum].obj; 915 return cache[symnum].sym; 916 } 917 918 ref = refobj->symtab + symnum; 919 name = refobj->strtab + ref->st_name; 920 defobj = NULL; 921 922 /* 923 * We don't have to do a full scale lookup if the symbol is local. 924 * We know it will bind to the instance in this load module; to 925 * which we already have a pointer (ie ref). By not doing a lookup, 926 * we not only improve performance, but it also avoids unresolvable 927 * symbols when local symbols are not in the hash table. This has 928 * been seen with the ia64 toolchain. 929 */ 930 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) { 931 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) { 932 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path, 933 symnum); 934 } 935 hash = elf_hash(name); 936 def = symlook_default(name, hash, refobj, &defobj, in_plt); 937 } else { 938 def = ref; 939 defobj = refobj; 940 } 941 942 /* 943 * If we found no definition and the reference is weak, treat the 944 * symbol as having the value zero. 945 */ 946 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) { 947 def = &sym_zero; 948 defobj = obj_main; 949 } 950 951 if (def != NULL) { 952 *defobj_out = defobj; 953 /* Record the information in the cache to avoid subsequent lookups. */ 954 if (cache != NULL) { 955 cache[symnum].sym = def; 956 cache[symnum].obj = defobj; 957 } 958 } else { 959 if (refobj != &obj_rtld) 960 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name); 961 } 962 return def; 963 } 964 965 /* 966 * Return the search path from the ldconfig hints file, reading it if 967 * necessary. Returns NULL if there are problems with the hints file, 968 * or if the search path there is empty. 969 */ 970 static const char * 971 gethints(void) 972 { 973 static char *hints; 974 975 if (hints == NULL) { 976 int fd; 977 struct elfhints_hdr hdr; 978 char *p; 979 980 /* Keep from trying again in case the hints file is bad. */ 981 hints = ""; 982 983 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1) 984 return NULL; 985 if (read(fd, &hdr, sizeof hdr) != sizeof hdr || 986 hdr.magic != ELFHINTS_MAGIC || 987 hdr.version != 1) { 988 close(fd); 989 return NULL; 990 } 991 p = xmalloc(hdr.dirlistlen + 1); 992 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 || 993 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) { 994 free(p); 995 close(fd); 996 return NULL; 997 } 998 hints = p; 999 close(fd); 1000 } 1001 return hints[0] != '\0' ? hints : NULL; 1002 } 1003 1004 static void 1005 init_dag(Obj_Entry *root) 1006 { 1007 DoneList donelist; 1008 1009 donelist_init(&donelist); 1010 init_dag1(root, root, &donelist); 1011 } 1012 1013 static void 1014 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp) 1015 { 1016 const Needed_Entry *needed; 1017 1018 if (donelist_check(dlp, obj)) 1019 return; 1020 1021 obj->refcount++; 1022 objlist_push_tail(&obj->dldags, root); 1023 objlist_push_tail(&root->dagmembers, obj); 1024 for (needed = obj->needed; needed != NULL; needed = needed->next) 1025 if (needed->obj != NULL) 1026 init_dag1(root, needed->obj, dlp); 1027 } 1028 1029 /* 1030 * Initialize the dynamic linker. The argument is the address at which 1031 * the dynamic linker has been mapped into memory. The primary task of 1032 * this function is to relocate the dynamic linker. 1033 */ 1034 static void 1035 init_rtld(caddr_t mapbase) 1036 { 1037 Obj_Entry objtmp; /* Temporary rtld object */ 1038 1039 /* 1040 * Conjure up an Obj_Entry structure for the dynamic linker. 1041 * 1042 * The "path" member can't be initialized yet because string constatns 1043 * cannot yet be acessed. Below we will set it correctly. 1044 */ 1045 memset(&objtmp, 0, sizeof(objtmp)); 1046 objtmp.path = NULL; 1047 objtmp.rtld = true; 1048 objtmp.mapbase = mapbase; 1049 #ifdef PIC 1050 objtmp.relocbase = mapbase; 1051 #endif 1052 if (RTLD_IS_DYNAMIC()) { 1053 objtmp.dynamic = rtld_dynamic(&objtmp); 1054 digest_dynamic(&objtmp, 1); 1055 assert(objtmp.needed == NULL); 1056 assert(!objtmp.textrel); 1057 1058 /* 1059 * Temporarily put the dynamic linker entry into the object list, so 1060 * that symbols can be found. 1061 */ 1062 1063 relocate_objects(&objtmp, true, &objtmp); 1064 } 1065 1066 /* Initialize the object list. */ 1067 obj_tail = &obj_list; 1068 1069 /* Now that non-local variables can be accesses, copy out obj_rtld. */ 1070 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld)); 1071 1072 /* Replace the path with a dynamically allocated copy. */ 1073 obj_rtld.path = xstrdup(PATH_RTLD); 1074 1075 r_debug.r_brk = r_debug_state; 1076 r_debug.r_state = RT_CONSISTENT; 1077 } 1078 1079 /* 1080 * Add the init functions from a needed object list (and its recursive 1081 * needed objects) to "list". This is not used directly; it is a helper 1082 * function for initlist_add_objects(). The write lock must be held 1083 * when this function is called. 1084 */ 1085 static void 1086 initlist_add_neededs(Needed_Entry *needed, Objlist *list) 1087 { 1088 /* Recursively process the successor needed objects. */ 1089 if (needed->next != NULL) 1090 initlist_add_neededs(needed->next, list); 1091 1092 /* Process the current needed object. */ 1093 if (needed->obj != NULL) 1094 initlist_add_objects(needed->obj, &needed->obj->next, list); 1095 } 1096 1097 /* 1098 * Scan all of the DAGs rooted in the range of objects from "obj" to 1099 * "tail" and add their init functions to "list". This recurses over 1100 * the DAGs and ensure the proper init ordering such that each object's 1101 * needed libraries are initialized before the object itself. At the 1102 * same time, this function adds the objects to the global finalization 1103 * list "list_fini" in the opposite order. The write lock must be 1104 * held when this function is called. 1105 */ 1106 static void 1107 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list) 1108 { 1109 if (obj->init_done) 1110 return; 1111 obj->init_done = true; 1112 1113 /* Recursively process the successor objects. */ 1114 if (&obj->next != tail) 1115 initlist_add_objects(obj->next, tail, list); 1116 1117 /* Recursively process the needed objects. */ 1118 if (obj->needed != NULL) 1119 initlist_add_neededs(obj->needed, list); 1120 1121 /* Add the object to the init list. */ 1122 if (obj->init != (Elf_Addr)NULL) 1123 objlist_push_tail(list, obj); 1124 1125 /* Add the object to the global fini list in the reverse order. */ 1126 if (obj->fini != (Elf_Addr)NULL) 1127 objlist_push_head(&list_fini, obj); 1128 } 1129 1130 #ifndef FPTR_TARGET 1131 #define FPTR_TARGET(f) ((Elf_Addr) (f)) 1132 #endif 1133 1134 static bool 1135 is_exported(const Elf_Sym *def) 1136 { 1137 Elf_Addr value; 1138 const func_ptr_type *p; 1139 1140 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value); 1141 for (p = exports; *p != NULL; p++) 1142 if (FPTR_TARGET(*p) == value) 1143 return true; 1144 return false; 1145 } 1146 1147 /* 1148 * Given a shared object, traverse its list of needed objects, and load 1149 * each of them. Returns 0 on success. Generates an error message and 1150 * returns -1 on failure. 1151 */ 1152 static int 1153 load_needed_objects(Obj_Entry *first) 1154 { 1155 Obj_Entry *obj; 1156 1157 for (obj = first; obj != NULL; obj = obj->next) { 1158 Needed_Entry *needed; 1159 1160 for (needed = obj->needed; needed != NULL; needed = needed->next) { 1161 const char *name = obj->strtab + needed->name; 1162 char *path = find_library(name, obj); 1163 1164 needed->obj = NULL; 1165 if (path == NULL && !ld_tracing) 1166 return -1; 1167 1168 if (path) { 1169 needed->obj = load_object(path); 1170 if (needed->obj == NULL && !ld_tracing) 1171 return -1; /* XXX - cleanup */ 1172 } 1173 } 1174 } 1175 1176 return 0; 1177 } 1178 1179 static int 1180 load_preload_objects(void) 1181 { 1182 char *p = ld_preload; 1183 static const char delim[] = " \t:;"; 1184 1185 if (p == NULL) 1186 return 0; 1187 1188 p += strspn(p, delim); 1189 while (*p != '\0') { 1190 size_t len = strcspn(p, delim); 1191 char *path; 1192 char savech; 1193 1194 savech = p[len]; 1195 p[len] = '\0'; 1196 if ((path = find_library(p, NULL)) == NULL) 1197 return -1; 1198 if (load_object(path) == NULL) 1199 return -1; /* XXX - cleanup */ 1200 p[len] = savech; 1201 p += len; 1202 p += strspn(p, delim); 1203 } 1204 return 0; 1205 } 1206 1207 /* 1208 * Load a shared object into memory, if it is not already loaded. The 1209 * argument must be a string allocated on the heap. This function assumes 1210 * responsibility for freeing it when necessary. 1211 * 1212 * Returns a pointer to the Obj_Entry for the object. Returns NULL 1213 * on failure. 1214 */ 1215 static Obj_Entry * 1216 load_object(char *path) 1217 { 1218 Obj_Entry *obj; 1219 int fd = -1; 1220 struct stat sb; 1221 1222 for (obj = obj_list->next; obj != NULL; obj = obj->next) 1223 if (strcmp(obj->path, path) == 0) 1224 break; 1225 1226 /* 1227 * If we didn't find a match by pathname, open the file and check 1228 * again by device and inode. This avoids false mismatches caused 1229 * by multiple links or ".." in pathnames. 1230 * 1231 * To avoid a race, we open the file and use fstat() rather than 1232 * using stat(). 1233 */ 1234 if (obj == NULL) { 1235 if ((fd = open(path, O_RDONLY)) == -1) { 1236 _rtld_error("Cannot open \"%s\"", path); 1237 return NULL; 1238 } 1239 if (fstat(fd, &sb) == -1) { 1240 _rtld_error("Cannot fstat \"%s\"", path); 1241 close(fd); 1242 return NULL; 1243 } 1244 for (obj = obj_list->next; obj != NULL; obj = obj->next) { 1245 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) { 1246 close(fd); 1247 break; 1248 } 1249 } 1250 } 1251 1252 if (obj == NULL) { /* First use of this object, so we must map it in */ 1253 dbg("loading \"%s\"", path); 1254 obj = map_object(fd, path, &sb); 1255 close(fd); 1256 if (obj == NULL) { 1257 free(path); 1258 return NULL; 1259 } 1260 1261 obj->path = path; 1262 digest_dynamic(obj, 0); 1263 1264 *obj_tail = obj; 1265 obj_tail = &obj->next; 1266 obj_count++; 1267 linkmap_add(obj); /* for GDB & dlinfo() */ 1268 1269 dbg(" %p .. %p: %s", obj->mapbase, 1270 obj->mapbase + obj->mapsize - 1, obj->path); 1271 if (obj->textrel) 1272 dbg(" WARNING: %s has impure text", obj->path); 1273 } else 1274 free(path); 1275 1276 return obj; 1277 } 1278 1279 static Obj_Entry * 1280 obj_from_addr(const void *addr) 1281 { 1282 Obj_Entry *obj; 1283 1284 for (obj = obj_list; obj != NULL; obj = obj->next) { 1285 if (addr < (void *) obj->mapbase) 1286 continue; 1287 if (addr < (void *) (obj->mapbase + obj->mapsize)) 1288 return obj; 1289 } 1290 return NULL; 1291 } 1292 1293 /* 1294 * Call the finalization functions for each of the objects in "list" 1295 * which are unreferenced. All of the objects are expected to have 1296 * non-NULL fini functions. 1297 */ 1298 static void 1299 objlist_call_fini(Objlist *list) 1300 { 1301 Objlist_Entry *elm; 1302 char *saved_msg; 1303 1304 /* 1305 * Preserve the current error message since a fini function might 1306 * call into the dynamic linker and overwrite it. 1307 */ 1308 saved_msg = errmsg_save(); 1309 STAILQ_FOREACH(elm, list, link) { 1310 if (elm->obj->refcount == 0) { 1311 dbg("calling fini function for %s at %p", elm->obj->path, 1312 (void *)elm->obj->fini); 1313 call_initfini_pointer(elm->obj, elm->obj->fini); 1314 } 1315 } 1316 errmsg_restore(saved_msg); 1317 } 1318 1319 /* 1320 * Call the initialization functions for each of the objects in 1321 * "list". All of the objects are expected to have non-NULL init 1322 * functions. 1323 */ 1324 static void 1325 objlist_call_init(Objlist *list) 1326 { 1327 Objlist_Entry *elm; 1328 char *saved_msg; 1329 1330 /* 1331 * Preserve the current error message since an init function might 1332 * call into the dynamic linker and overwrite it. 1333 */ 1334 saved_msg = errmsg_save(); 1335 STAILQ_FOREACH(elm, list, link) { 1336 dbg("calling init function for %s at %p", elm->obj->path, 1337 (void *)elm->obj->init); 1338 call_initfini_pointer(elm->obj, elm->obj->init); 1339 } 1340 errmsg_restore(saved_msg); 1341 } 1342 1343 static void 1344 objlist_clear(Objlist *list) 1345 { 1346 Objlist_Entry *elm; 1347 1348 while (!STAILQ_EMPTY(list)) { 1349 elm = STAILQ_FIRST(list); 1350 STAILQ_REMOVE_HEAD(list, link); 1351 free(elm); 1352 } 1353 } 1354 1355 static Objlist_Entry * 1356 objlist_find(Objlist *list, const Obj_Entry *obj) 1357 { 1358 Objlist_Entry *elm; 1359 1360 STAILQ_FOREACH(elm, list, link) 1361 if (elm->obj == obj) 1362 return elm; 1363 return NULL; 1364 } 1365 1366 static void 1367 objlist_init(Objlist *list) 1368 { 1369 STAILQ_INIT(list); 1370 } 1371 1372 static void 1373 objlist_push_head(Objlist *list, Obj_Entry *obj) 1374 { 1375 Objlist_Entry *elm; 1376 1377 elm = NEW(Objlist_Entry); 1378 elm->obj = obj; 1379 STAILQ_INSERT_HEAD(list, elm, link); 1380 } 1381 1382 static void 1383 objlist_push_tail(Objlist *list, Obj_Entry *obj) 1384 { 1385 Objlist_Entry *elm; 1386 1387 elm = NEW(Objlist_Entry); 1388 elm->obj = obj; 1389 STAILQ_INSERT_TAIL(list, elm, link); 1390 } 1391 1392 static void 1393 objlist_remove(Objlist *list, Obj_Entry *obj) 1394 { 1395 Objlist_Entry *elm; 1396 1397 if ((elm = objlist_find(list, obj)) != NULL) { 1398 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 1399 free(elm); 1400 } 1401 } 1402 1403 /* 1404 * Remove all of the unreferenced objects from "list". 1405 */ 1406 static void 1407 objlist_remove_unref(Objlist *list) 1408 { 1409 Objlist newlist; 1410 Objlist_Entry *elm; 1411 1412 STAILQ_INIT(&newlist); 1413 while (!STAILQ_EMPTY(list)) { 1414 elm = STAILQ_FIRST(list); 1415 STAILQ_REMOVE_HEAD(list, link); 1416 if (elm->obj->refcount == 0) 1417 free(elm); 1418 else 1419 STAILQ_INSERT_TAIL(&newlist, elm, link); 1420 } 1421 *list = newlist; 1422 } 1423 1424 /* 1425 * Relocate newly-loaded shared objects. The argument is a pointer to 1426 * the Obj_Entry for the first such object. All objects from the first 1427 * to the end of the list of objects are relocated. Returns 0 on success, 1428 * or -1 on failure. 1429 */ 1430 static int 1431 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj) 1432 { 1433 Obj_Entry *obj; 1434 1435 for (obj = first; obj != NULL; obj = obj->next) { 1436 if (obj != rtldobj) 1437 dbg("relocating \"%s\"", obj->path); 1438 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL || 1439 obj->symtab == NULL || obj->strtab == NULL) { 1440 _rtld_error("%s: Shared object has no run-time symbol table", 1441 obj->path); 1442 return -1; 1443 } 1444 1445 if (obj->textrel) { 1446 /* There are relocations to the write-protected text segment. */ 1447 if (mprotect(obj->mapbase, obj->textsize, 1448 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) { 1449 _rtld_error("%s: Cannot write-enable text segment: %s", 1450 obj->path, strerror(errno)); 1451 return -1; 1452 } 1453 } 1454 1455 /* Process the non-PLT relocations. */ 1456 if (reloc_non_plt(obj, rtldobj)) 1457 return -1; 1458 1459 if (obj->textrel) { /* Re-protected the text segment. */ 1460 if (mprotect(obj->mapbase, obj->textsize, 1461 PROT_READ|PROT_EXEC) == -1) { 1462 _rtld_error("%s: Cannot write-protect text segment: %s", 1463 obj->path, strerror(errno)); 1464 return -1; 1465 } 1466 } 1467 1468 /* Process the PLT relocations. */ 1469 if (reloc_plt(obj) == -1) 1470 return -1; 1471 /* Relocate the jump slots if we are doing immediate binding. */ 1472 if (obj->bind_now || bind_now) 1473 if (reloc_jmpslots(obj) == -1) 1474 return -1; 1475 1476 1477 /* 1478 * Set up the magic number and version in the Obj_Entry. These 1479 * were checked in the crt1.o from the original ElfKit, so we 1480 * set them for backward compatibility. 1481 */ 1482 obj->magic = RTLD_MAGIC; 1483 obj->version = RTLD_VERSION; 1484 1485 /* Set the special PLT or GOT entries. */ 1486 init_pltgot(obj); 1487 } 1488 1489 return 0; 1490 } 1491 1492 /* 1493 * Cleanup procedure. It will be called (by the atexit mechanism) just 1494 * before the process exits. 1495 */ 1496 static void 1497 rtld_exit(void) 1498 { 1499 Obj_Entry *obj; 1500 1501 dbg("rtld_exit()"); 1502 /* Clear all the reference counts so the fini functions will be called. */ 1503 for (obj = obj_list; obj != NULL; obj = obj->next) 1504 obj->refcount = 0; 1505 objlist_call_fini(&list_fini); 1506 /* No need to remove the items from the list, since we are exiting. */ 1507 if (!libmap_disable) 1508 lm_fini(); 1509 } 1510 1511 static void * 1512 path_enumerate(const char *path, path_enum_proc callback, void *arg) 1513 { 1514 #ifdef COMPAT_32BIT 1515 const char *trans; 1516 #endif 1517 if (path == NULL) 1518 return (NULL); 1519 1520 path += strspn(path, ":;"); 1521 while (*path != '\0') { 1522 size_t len; 1523 char *res; 1524 1525 len = strcspn(path, ":;"); 1526 #ifdef COMPAT_32BIT 1527 trans = lm_findn(NULL, path, len); 1528 if (trans) 1529 res = callback(trans, strlen(trans), arg); 1530 else 1531 #endif 1532 res = callback(path, len, arg); 1533 1534 if (res != NULL) 1535 return (res); 1536 1537 path += len; 1538 path += strspn(path, ":;"); 1539 } 1540 1541 return (NULL); 1542 } 1543 1544 struct try_library_args { 1545 const char *name; 1546 size_t namelen; 1547 char *buffer; 1548 size_t buflen; 1549 }; 1550 1551 static void * 1552 try_library_path(const char *dir, size_t dirlen, void *param) 1553 { 1554 struct try_library_args *arg; 1555 1556 arg = param; 1557 if (*dir == '/' || trust) { 1558 char *pathname; 1559 1560 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 1561 return (NULL); 1562 1563 pathname = arg->buffer; 1564 strncpy(pathname, dir, dirlen); 1565 pathname[dirlen] = '/'; 1566 strcpy(pathname + dirlen + 1, arg->name); 1567 1568 dbg(" Trying \"%s\"", pathname); 1569 if (access(pathname, F_OK) == 0) { /* We found it */ 1570 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 1571 strcpy(pathname, arg->buffer); 1572 return (pathname); 1573 } 1574 } 1575 return (NULL); 1576 } 1577 1578 static char * 1579 search_library_path(const char *name, const char *path) 1580 { 1581 char *p; 1582 struct try_library_args arg; 1583 1584 if (path == NULL) 1585 return NULL; 1586 1587 arg.name = name; 1588 arg.namelen = strlen(name); 1589 arg.buffer = xmalloc(PATH_MAX); 1590 arg.buflen = PATH_MAX; 1591 1592 p = path_enumerate(path, try_library_path, &arg); 1593 1594 free(arg.buffer); 1595 1596 return (p); 1597 } 1598 1599 int 1600 dlclose(void *handle) 1601 { 1602 Obj_Entry *root; 1603 int lockstate; 1604 1605 lockstate = wlock_acquire(rtld_bind_lock); 1606 root = dlcheck(handle); 1607 if (root == NULL) { 1608 wlock_release(rtld_bind_lock, lockstate); 1609 return -1; 1610 } 1611 1612 /* Unreference the object and its dependencies. */ 1613 root->dl_refcount--; 1614 1615 unref_dag(root); 1616 1617 if (root->refcount == 0) { 1618 /* 1619 * The object is no longer referenced, so we must unload it. 1620 * First, call the fini functions with no locks held. 1621 */ 1622 wlock_release(rtld_bind_lock, lockstate); 1623 objlist_call_fini(&list_fini); 1624 lockstate = wlock_acquire(rtld_bind_lock); 1625 objlist_remove_unref(&list_fini); 1626 1627 /* Finish cleaning up the newly-unreferenced objects. */ 1628 GDB_STATE(RT_DELETE,&root->linkmap); 1629 unload_object(root); 1630 GDB_STATE(RT_CONSISTENT,NULL); 1631 } 1632 wlock_release(rtld_bind_lock, lockstate); 1633 return 0; 1634 } 1635 1636 const char * 1637 dlerror(void) 1638 { 1639 char *msg = error_message; 1640 error_message = NULL; 1641 return msg; 1642 } 1643 1644 /* 1645 * This function is deprecated and has no effect. 1646 */ 1647 void 1648 dllockinit(void *context, 1649 void *(*lock_create)(void *context), 1650 void (*rlock_acquire)(void *lock), 1651 void (*wlock_acquire)(void *lock), 1652 void (*lock_release)(void *lock), 1653 void (*lock_destroy)(void *lock), 1654 void (*context_destroy)(void *context)) 1655 { 1656 static void *cur_context; 1657 static void (*cur_context_destroy)(void *); 1658 1659 /* Just destroy the context from the previous call, if necessary. */ 1660 if (cur_context_destroy != NULL) 1661 cur_context_destroy(cur_context); 1662 cur_context = context; 1663 cur_context_destroy = context_destroy; 1664 } 1665 1666 void * 1667 dlopen(const char *name, int mode) 1668 { 1669 Obj_Entry **old_obj_tail; 1670 Obj_Entry *obj; 1671 Objlist initlist; 1672 int result, lockstate; 1673 1674 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 1675 if (ld_tracing != NULL) 1676 environ = (char **)*get_program_var_addr("environ"); 1677 1678 objlist_init(&initlist); 1679 1680 lockstate = wlock_acquire(rtld_bind_lock); 1681 GDB_STATE(RT_ADD,NULL); 1682 1683 old_obj_tail = obj_tail; 1684 obj = NULL; 1685 if (name == NULL) { 1686 obj = obj_main; 1687 obj->refcount++; 1688 } else { 1689 char *path = find_library(name, obj_main); 1690 if (path != NULL) 1691 obj = load_object(path); 1692 } 1693 1694 if (obj) { 1695 obj->dl_refcount++; 1696 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) 1697 objlist_push_tail(&list_global, obj); 1698 mode &= RTLD_MODEMASK; 1699 if (*old_obj_tail != NULL) { /* We loaded something new. */ 1700 assert(*old_obj_tail == obj); 1701 1702 result = load_needed_objects(obj); 1703 if (result != -1 && ld_tracing) 1704 goto trace; 1705 1706 if (result == -1 || 1707 (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW, 1708 &obj_rtld)) == -1) { 1709 obj->dl_refcount--; 1710 unref_dag(obj); 1711 if (obj->refcount == 0) 1712 unload_object(obj); 1713 obj = NULL; 1714 } else { 1715 /* Make list of init functions to call. */ 1716 initlist_add_objects(obj, &obj->next, &initlist); 1717 } 1718 } else { 1719 1720 /* Bump the reference counts for objects on this DAG. */ 1721 ref_dag(obj); 1722 1723 if (ld_tracing) 1724 goto trace; 1725 } 1726 } 1727 1728 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); 1729 1730 /* Call the init functions with no locks held. */ 1731 wlock_release(rtld_bind_lock, lockstate); 1732 objlist_call_init(&initlist); 1733 lockstate = wlock_acquire(rtld_bind_lock); 1734 objlist_clear(&initlist); 1735 wlock_release(rtld_bind_lock, lockstate); 1736 return obj; 1737 trace: 1738 trace_loaded_objects(obj); 1739 wlock_release(rtld_bind_lock, lockstate); 1740 exit(0); 1741 } 1742 1743 void * 1744 dlsym(void *handle, const char *name) 1745 { 1746 const Obj_Entry *obj; 1747 unsigned long hash; 1748 const Elf_Sym *def; 1749 const Obj_Entry *defobj; 1750 int lockstate; 1751 1752 hash = elf_hash(name); 1753 def = NULL; 1754 defobj = NULL; 1755 1756 lockstate = rlock_acquire(rtld_bind_lock); 1757 if (handle == NULL || handle == RTLD_NEXT || 1758 handle == RTLD_DEFAULT || handle == RTLD_SELF) { 1759 void *retaddr; 1760 1761 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 1762 if ((obj = obj_from_addr(retaddr)) == NULL) { 1763 _rtld_error("Cannot determine caller's shared object"); 1764 rlock_release(rtld_bind_lock, lockstate); 1765 return NULL; 1766 } 1767 if (handle == NULL) { /* Just the caller's shared object. */ 1768 def = symlook_obj(name, hash, obj, true); 1769 defobj = obj; 1770 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 1771 handle == RTLD_SELF) { /* ... caller included */ 1772 if (handle == RTLD_NEXT) 1773 obj = obj->next; 1774 for (; obj != NULL; obj = obj->next) { 1775 if ((def = symlook_obj(name, hash, obj, true)) != NULL) { 1776 defobj = obj; 1777 break; 1778 } 1779 } 1780 } else { 1781 assert(handle == RTLD_DEFAULT); 1782 def = symlook_default(name, hash, obj, &defobj, true); 1783 } 1784 } else { 1785 if ((obj = dlcheck(handle)) == NULL) { 1786 rlock_release(rtld_bind_lock, lockstate); 1787 return NULL; 1788 } 1789 1790 if (obj->mainprog) { 1791 DoneList donelist; 1792 1793 /* Search main program and all libraries loaded by it. */ 1794 donelist_init(&donelist); 1795 def = symlook_list(name, hash, &list_main, &defobj, true, 1796 &donelist); 1797 } else { 1798 /* 1799 * XXX - This isn't correct. The search should include the whole 1800 * DAG rooted at the given object. 1801 */ 1802 def = symlook_obj(name, hash, obj, true); 1803 defobj = obj; 1804 } 1805 } 1806 1807 if (def != NULL) { 1808 rlock_release(rtld_bind_lock, lockstate); 1809 1810 /* 1811 * The value required by the caller is derived from the value 1812 * of the symbol. For the ia64 architecture, we need to 1813 * construct a function descriptor which the caller can use to 1814 * call the function with the right 'gp' value. For other 1815 * architectures and for non-functions, the value is simply 1816 * the relocated value of the symbol. 1817 */ 1818 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 1819 return make_function_pointer(def, defobj); 1820 else 1821 return defobj->relocbase + def->st_value; 1822 } 1823 1824 _rtld_error("Undefined symbol \"%s\"", name); 1825 rlock_release(rtld_bind_lock, lockstate); 1826 return NULL; 1827 } 1828 1829 int 1830 dladdr(const void *addr, Dl_info *info) 1831 { 1832 const Obj_Entry *obj; 1833 const Elf_Sym *def; 1834 void *symbol_addr; 1835 unsigned long symoffset; 1836 int lockstate; 1837 1838 lockstate = rlock_acquire(rtld_bind_lock); 1839 obj = obj_from_addr(addr); 1840 if (obj == NULL) { 1841 _rtld_error("No shared object contains address"); 1842 rlock_release(rtld_bind_lock, lockstate); 1843 return 0; 1844 } 1845 info->dli_fname = obj->path; 1846 info->dli_fbase = obj->mapbase; 1847 info->dli_saddr = (void *)0; 1848 info->dli_sname = NULL; 1849 1850 /* 1851 * Walk the symbol list looking for the symbol whose address is 1852 * closest to the address sent in. 1853 */ 1854 for (symoffset = 0; symoffset < obj->nchains; symoffset++) { 1855 def = obj->symtab + symoffset; 1856 1857 /* 1858 * For skip the symbol if st_shndx is either SHN_UNDEF or 1859 * SHN_COMMON. 1860 */ 1861 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 1862 continue; 1863 1864 /* 1865 * If the symbol is greater than the specified address, or if it 1866 * is further away from addr than the current nearest symbol, 1867 * then reject it. 1868 */ 1869 symbol_addr = obj->relocbase + def->st_value; 1870 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 1871 continue; 1872 1873 /* Update our idea of the nearest symbol. */ 1874 info->dli_sname = obj->strtab + def->st_name; 1875 info->dli_saddr = symbol_addr; 1876 1877 /* Exact match? */ 1878 if (info->dli_saddr == addr) 1879 break; 1880 } 1881 rlock_release(rtld_bind_lock, lockstate); 1882 return 1; 1883 } 1884 1885 int 1886 dlinfo(void *handle, int request, void *p) 1887 { 1888 const Obj_Entry *obj; 1889 int error, lockstate; 1890 1891 lockstate = rlock_acquire(rtld_bind_lock); 1892 1893 if (handle == NULL || handle == RTLD_SELF) { 1894 void *retaddr; 1895 1896 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 1897 if ((obj = obj_from_addr(retaddr)) == NULL) 1898 _rtld_error("Cannot determine caller's shared object"); 1899 } else 1900 obj = dlcheck(handle); 1901 1902 if (obj == NULL) { 1903 rlock_release(rtld_bind_lock, lockstate); 1904 return (-1); 1905 } 1906 1907 error = 0; 1908 switch (request) { 1909 case RTLD_DI_LINKMAP: 1910 *((struct link_map const **)p) = &obj->linkmap; 1911 break; 1912 case RTLD_DI_ORIGIN: 1913 error = rtld_dirname(obj->path, p); 1914 break; 1915 1916 case RTLD_DI_SERINFOSIZE: 1917 case RTLD_DI_SERINFO: 1918 error = do_search_info(obj, request, (struct dl_serinfo *)p); 1919 break; 1920 1921 default: 1922 _rtld_error("Invalid request %d passed to dlinfo()", request); 1923 error = -1; 1924 } 1925 1926 rlock_release(rtld_bind_lock, lockstate); 1927 1928 return (error); 1929 } 1930 1931 struct fill_search_info_args { 1932 int request; 1933 unsigned int flags; 1934 Dl_serinfo *serinfo; 1935 Dl_serpath *serpath; 1936 char *strspace; 1937 }; 1938 1939 static void * 1940 fill_search_info(const char *dir, size_t dirlen, void *param) 1941 { 1942 struct fill_search_info_args *arg; 1943 1944 arg = param; 1945 1946 if (arg->request == RTLD_DI_SERINFOSIZE) { 1947 arg->serinfo->dls_cnt ++; 1948 arg->serinfo->dls_size += dirlen + 1; 1949 } else { 1950 struct dl_serpath *s_entry; 1951 1952 s_entry = arg->serpath; 1953 s_entry->dls_name = arg->strspace; 1954 s_entry->dls_flags = arg->flags; 1955 1956 strncpy(arg->strspace, dir, dirlen); 1957 arg->strspace[dirlen] = '\0'; 1958 1959 arg->strspace += dirlen + 1; 1960 arg->serpath++; 1961 } 1962 1963 return (NULL); 1964 } 1965 1966 static int 1967 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 1968 { 1969 struct dl_serinfo _info; 1970 struct fill_search_info_args args; 1971 1972 args.request = RTLD_DI_SERINFOSIZE; 1973 args.serinfo = &_info; 1974 1975 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 1976 _info.dls_cnt = 0; 1977 1978 path_enumerate(ld_library_path, fill_search_info, &args); 1979 path_enumerate(obj->rpath, fill_search_info, &args); 1980 path_enumerate(gethints(), fill_search_info, &args); 1981 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args); 1982 1983 1984 if (request == RTLD_DI_SERINFOSIZE) { 1985 info->dls_size = _info.dls_size; 1986 info->dls_cnt = _info.dls_cnt; 1987 return (0); 1988 } 1989 1990 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { 1991 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); 1992 return (-1); 1993 } 1994 1995 args.request = RTLD_DI_SERINFO; 1996 args.serinfo = info; 1997 args.serpath = &info->dls_serpath[0]; 1998 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 1999 2000 args.flags = LA_SER_LIBPATH; 2001 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL) 2002 return (-1); 2003 2004 args.flags = LA_SER_RUNPATH; 2005 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL) 2006 return (-1); 2007 2008 args.flags = LA_SER_CONFIG; 2009 if (path_enumerate(gethints(), fill_search_info, &args) != NULL) 2010 return (-1); 2011 2012 args.flags = LA_SER_DEFAULT; 2013 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL) 2014 return (-1); 2015 return (0); 2016 } 2017 2018 static int 2019 rtld_dirname(const char *path, char *bname) 2020 { 2021 const char *endp; 2022 2023 /* Empty or NULL string gets treated as "." */ 2024 if (path == NULL || *path == '\0') { 2025 bname[0] = '.'; 2026 bname[1] = '\0'; 2027 return (0); 2028 } 2029 2030 /* Strip trailing slashes */ 2031 endp = path + strlen(path) - 1; 2032 while (endp > path && *endp == '/') 2033 endp--; 2034 2035 /* Find the start of the dir */ 2036 while (endp > path && *endp != '/') 2037 endp--; 2038 2039 /* Either the dir is "/" or there are no slashes */ 2040 if (endp == path) { 2041 bname[0] = *endp == '/' ? '/' : '.'; 2042 bname[1] = '\0'; 2043 return (0); 2044 } else { 2045 do { 2046 endp--; 2047 } while (endp > path && *endp == '/'); 2048 } 2049 2050 if (endp - path + 2 > PATH_MAX) 2051 { 2052 _rtld_error("Filename is too long: %s", path); 2053 return(-1); 2054 } 2055 2056 strncpy(bname, path, endp - path + 1); 2057 bname[endp - path + 1] = '\0'; 2058 return (0); 2059 } 2060 2061 static void 2062 linkmap_add(Obj_Entry *obj) 2063 { 2064 struct link_map *l = &obj->linkmap; 2065 struct link_map *prev; 2066 2067 obj->linkmap.l_name = obj->path; 2068 obj->linkmap.l_addr = obj->mapbase; 2069 obj->linkmap.l_ld = obj->dynamic; 2070 #ifdef __mips__ 2071 /* GDB needs load offset on MIPS to use the symbols */ 2072 obj->linkmap.l_offs = obj->relocbase; 2073 #endif 2074 2075 if (r_debug.r_map == NULL) { 2076 r_debug.r_map = l; 2077 return; 2078 } 2079 2080 /* 2081 * Scan to the end of the list, but not past the entry for the 2082 * dynamic linker, which we want to keep at the very end. 2083 */ 2084 for (prev = r_debug.r_map; 2085 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 2086 prev = prev->l_next) 2087 ; 2088 2089 /* Link in the new entry. */ 2090 l->l_prev = prev; 2091 l->l_next = prev->l_next; 2092 if (l->l_next != NULL) 2093 l->l_next->l_prev = l; 2094 prev->l_next = l; 2095 } 2096 2097 static void 2098 linkmap_delete(Obj_Entry *obj) 2099 { 2100 struct link_map *l = &obj->linkmap; 2101 2102 if (l->l_prev == NULL) { 2103 if ((r_debug.r_map = l->l_next) != NULL) 2104 l->l_next->l_prev = NULL; 2105 return; 2106 } 2107 2108 if ((l->l_prev->l_next = l->l_next) != NULL) 2109 l->l_next->l_prev = l->l_prev; 2110 } 2111 2112 /* 2113 * Function for the debugger to set a breakpoint on to gain control. 2114 * 2115 * The two parameters allow the debugger to easily find and determine 2116 * what the runtime loader is doing and to whom it is doing it. 2117 * 2118 * When the loadhook trap is hit (r_debug_state, set at program 2119 * initialization), the arguments can be found on the stack: 2120 * 2121 * +8 struct link_map *m 2122 * +4 struct r_debug *rd 2123 * +0 RetAddr 2124 */ 2125 void 2126 r_debug_state(struct r_debug* rd, struct link_map *m) 2127 { 2128 } 2129 2130 /* 2131 * Get address of the pointer variable in the main program. 2132 */ 2133 static const void ** 2134 get_program_var_addr(const char *name) 2135 { 2136 const Obj_Entry *obj; 2137 unsigned long hash; 2138 2139 hash = elf_hash(name); 2140 for (obj = obj_main; obj != NULL; obj = obj->next) { 2141 const Elf_Sym *def; 2142 2143 if ((def = symlook_obj(name, hash, obj, false)) != NULL) { 2144 const void **addr; 2145 2146 addr = (const void **)(obj->relocbase + def->st_value); 2147 return addr; 2148 } 2149 } 2150 return NULL; 2151 } 2152 2153 /* 2154 * Set a pointer variable in the main program to the given value. This 2155 * is used to set key variables such as "environ" before any of the 2156 * init functions are called. 2157 */ 2158 static void 2159 set_program_var(const char *name, const void *value) 2160 { 2161 const void **addr; 2162 2163 if ((addr = get_program_var_addr(name)) != NULL) { 2164 dbg("\"%s\": *%p <-- %p", name, addr, value); 2165 *addr = value; 2166 } 2167 } 2168 2169 /* 2170 * Given a symbol name in a referencing object, find the corresponding 2171 * definition of the symbol. Returns a pointer to the symbol, or NULL if 2172 * no definition was found. Returns a pointer to the Obj_Entry of the 2173 * defining object via the reference parameter DEFOBJ_OUT. 2174 */ 2175 static const Elf_Sym * 2176 symlook_default(const char *name, unsigned long hash, 2177 const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt) 2178 { 2179 DoneList donelist; 2180 const Elf_Sym *def; 2181 const Elf_Sym *symp; 2182 const Obj_Entry *obj; 2183 const Obj_Entry *defobj; 2184 const Objlist_Entry *elm; 2185 def = NULL; 2186 defobj = NULL; 2187 donelist_init(&donelist); 2188 2189 /* Look first in the referencing object if linked symbolically. */ 2190 if (refobj->symbolic && !donelist_check(&donelist, refobj)) { 2191 symp = symlook_obj(name, hash, refobj, in_plt); 2192 if (symp != NULL) { 2193 def = symp; 2194 defobj = refobj; 2195 } 2196 } 2197 2198 /* Search all objects loaded at program start up. */ 2199 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 2200 symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist); 2201 if (symp != NULL && 2202 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { 2203 def = symp; 2204 defobj = obj; 2205 } 2206 } 2207 2208 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 2209 STAILQ_FOREACH(elm, &list_global, link) { 2210 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK) 2211 break; 2212 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt, 2213 &donelist); 2214 if (symp != NULL && 2215 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { 2216 def = symp; 2217 defobj = obj; 2218 } 2219 } 2220 2221 /* Search all dlopened DAGs containing the referencing object. */ 2222 STAILQ_FOREACH(elm, &refobj->dldags, link) { 2223 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK) 2224 break; 2225 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt, 2226 &donelist); 2227 if (symp != NULL && 2228 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { 2229 def = symp; 2230 defobj = obj; 2231 } 2232 } 2233 2234 /* 2235 * Search the dynamic linker itself, and possibly resolve the 2236 * symbol from there. This is how the application links to 2237 * dynamic linker services such as dlopen. Only the values listed 2238 * in the "exports" array can be resolved from the dynamic linker. 2239 */ 2240 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 2241 symp = symlook_obj(name, hash, &obj_rtld, in_plt); 2242 if (symp != NULL && is_exported(symp)) { 2243 def = symp; 2244 defobj = &obj_rtld; 2245 } 2246 } 2247 2248 if (def != NULL) 2249 *defobj_out = defobj; 2250 return def; 2251 } 2252 2253 static const Elf_Sym * 2254 symlook_list(const char *name, unsigned long hash, Objlist *objlist, 2255 const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp) 2256 { 2257 const Elf_Sym *symp; 2258 const Elf_Sym *def; 2259 const Obj_Entry *defobj; 2260 const Objlist_Entry *elm; 2261 2262 def = NULL; 2263 defobj = NULL; 2264 STAILQ_FOREACH(elm, objlist, link) { 2265 if (donelist_check(dlp, elm->obj)) 2266 continue; 2267 if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) { 2268 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) { 2269 def = symp; 2270 defobj = elm->obj; 2271 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 2272 break; 2273 } 2274 } 2275 } 2276 if (def != NULL) 2277 *defobj_out = defobj; 2278 return def; 2279 } 2280 2281 /* 2282 * Search the symbol table of a single shared object for a symbol of 2283 * the given name. Returns a pointer to the symbol, or NULL if no 2284 * definition was found. 2285 * 2286 * The symbol's hash value is passed in for efficiency reasons; that 2287 * eliminates many recomputations of the hash value. 2288 */ 2289 const Elf_Sym * 2290 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj, 2291 bool in_plt) 2292 { 2293 if (obj->buckets != NULL) { 2294 unsigned long symnum = obj->buckets[hash % obj->nbuckets]; 2295 2296 while (symnum != STN_UNDEF) { 2297 const Elf_Sym *symp; 2298 const char *strp; 2299 2300 if (symnum >= obj->nchains) 2301 return NULL; /* Bad object */ 2302 symp = obj->symtab + symnum; 2303 strp = obj->strtab + symp->st_name; 2304 2305 if (name[0] == strp[0] && strcmp(name, strp) == 0) 2306 return symp->st_shndx != SHN_UNDEF || 2307 (!in_plt && symp->st_value != 0 && 2308 ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL; 2309 2310 symnum = obj->chains[symnum]; 2311 } 2312 } 2313 return NULL; 2314 } 2315 2316 static void 2317 trace_loaded_objects(Obj_Entry *obj) 2318 { 2319 char *fmt1, *fmt2, *fmt, *main_local, *list_containers; 2320 int c; 2321 2322 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL) 2323 main_local = ""; 2324 2325 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL) 2326 fmt1 = "\t%o => %p (%x)\n"; 2327 2328 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL) 2329 fmt2 = "\t%o (%x)\n"; 2330 2331 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL"); 2332 2333 for (; obj; obj = obj->next) { 2334 Needed_Entry *needed; 2335 char *name, *path; 2336 bool is_lib; 2337 2338 if (list_containers && obj->needed != NULL) 2339 printf("%s:\n", obj->path); 2340 for (needed = obj->needed; needed; needed = needed->next) { 2341 if (needed->obj != NULL) { 2342 if (needed->obj->traced && !list_containers) 2343 continue; 2344 needed->obj->traced = true; 2345 path = needed->obj->path; 2346 } else 2347 path = "not found"; 2348 2349 name = (char *)obj->strtab + needed->name; 2350 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */ 2351 2352 fmt = is_lib ? fmt1 : fmt2; 2353 while ((c = *fmt++) != '\0') { 2354 switch (c) { 2355 default: 2356 putchar(c); 2357 continue; 2358 case '\\': 2359 switch (c = *fmt) { 2360 case '\0': 2361 continue; 2362 case 'n': 2363 putchar('\n'); 2364 break; 2365 case 't': 2366 putchar('\t'); 2367 break; 2368 } 2369 break; 2370 case '%': 2371 switch (c = *fmt) { 2372 case '\0': 2373 continue; 2374 case '%': 2375 default: 2376 putchar(c); 2377 break; 2378 case 'A': 2379 printf("%s", main_local); 2380 break; 2381 case 'a': 2382 printf("%s", obj_main->path); 2383 break; 2384 case 'o': 2385 printf("%s", name); 2386 break; 2387 #if 0 2388 case 'm': 2389 printf("%d", sodp->sod_major); 2390 break; 2391 case 'n': 2392 printf("%d", sodp->sod_minor); 2393 break; 2394 #endif 2395 case 'p': 2396 printf("%s", path); 2397 break; 2398 case 'x': 2399 printf("%p", needed->obj ? needed->obj->mapbase : 0); 2400 break; 2401 } 2402 break; 2403 } 2404 ++fmt; 2405 } 2406 } 2407 } 2408 } 2409 2410 /* 2411 * Unload a dlopened object and its dependencies from memory and from 2412 * our data structures. It is assumed that the DAG rooted in the 2413 * object has already been unreferenced, and that the object has a 2414 * reference count of 0. 2415 */ 2416 static void 2417 unload_object(Obj_Entry *root) 2418 { 2419 Obj_Entry *obj; 2420 Obj_Entry **linkp; 2421 2422 assert(root->refcount == 0); 2423 2424 /* 2425 * Pass over the DAG removing unreferenced objects from 2426 * appropriate lists. 2427 */ 2428 unlink_object(root); 2429 2430 /* Unmap all objects that are no longer referenced. */ 2431 linkp = &obj_list->next; 2432 while ((obj = *linkp) != NULL) { 2433 if (obj->refcount == 0) { 2434 dbg("unloading \"%s\"", obj->path); 2435 munmap(obj->mapbase, obj->mapsize); 2436 linkmap_delete(obj); 2437 *linkp = obj->next; 2438 obj_count--; 2439 obj_free(obj); 2440 } else 2441 linkp = &obj->next; 2442 } 2443 obj_tail = linkp; 2444 } 2445 2446 static void 2447 unlink_object(Obj_Entry *root) 2448 { 2449 Objlist_Entry *elm; 2450 2451 if (root->refcount == 0) { 2452 /* Remove the object from the RTLD_GLOBAL list. */ 2453 objlist_remove(&list_global, root); 2454 2455 /* Remove the object from all objects' DAG lists. */ 2456 STAILQ_FOREACH(elm, &root->dagmembers , link) { 2457 objlist_remove(&elm->obj->dldags, root); 2458 if (elm->obj != root) 2459 unlink_object(elm->obj); 2460 } 2461 } 2462 } 2463 2464 static void 2465 ref_dag(Obj_Entry *root) 2466 { 2467 Objlist_Entry *elm; 2468 2469 STAILQ_FOREACH(elm, &root->dagmembers , link) 2470 elm->obj->refcount++; 2471 } 2472 2473 static void 2474 unref_dag(Obj_Entry *root) 2475 { 2476 Objlist_Entry *elm; 2477 2478 STAILQ_FOREACH(elm, &root->dagmembers , link) 2479 elm->obj->refcount--; 2480 } 2481 2482 /* 2483 * Common code for MD __tls_get_addr(). 2484 */ 2485 void * 2486 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset) 2487 { 2488 Elf_Addr* dtv = *dtvp; 2489 2490 /* Check dtv generation in case new modules have arrived */ 2491 if (dtv[0] != tls_dtv_generation) { 2492 Elf_Addr* newdtv; 2493 int to_copy; 2494 2495 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr)); 2496 to_copy = dtv[1]; 2497 if (to_copy > tls_max_index) 2498 to_copy = tls_max_index; 2499 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); 2500 newdtv[0] = tls_dtv_generation; 2501 newdtv[1] = tls_max_index; 2502 free(dtv); 2503 *dtvp = newdtv; 2504 } 2505 2506 /* Dynamically allocate module TLS if necessary */ 2507 if (!dtv[index + 1]) 2508 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); 2509 2510 return (void*) (dtv[index + 1] + offset); 2511 } 2512 2513 /* XXX not sure what variants to use for arm. */ 2514 2515 #if defined(__ia64__) || defined(__alpha__) || defined(__powerpc__) 2516 2517 /* 2518 * Allocate Static TLS using the Variant I method. 2519 */ 2520 void * 2521 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 2522 { 2523 Obj_Entry *obj; 2524 size_t size; 2525 char *tls; 2526 Elf_Addr *dtv, *olddtv; 2527 Elf_Addr addr; 2528 int i; 2529 2530 size = tls_static_space; 2531 2532 tls = malloc(size); 2533 dtv = malloc((tls_max_index + 2) * sizeof(Elf_Addr)); 2534 2535 *(Elf_Addr**) tls = dtv; 2536 2537 dtv[0] = tls_dtv_generation; 2538 dtv[1] = tls_max_index; 2539 2540 if (oldtls) { 2541 /* 2542 * Copy the static TLS block over whole. 2543 */ 2544 memcpy(tls + tcbsize, oldtls + tcbsize, tls_static_space - tcbsize); 2545 2546 /* 2547 * If any dynamic TLS blocks have been created tls_get_addr(), 2548 * move them over. 2549 */ 2550 olddtv = *(Elf_Addr**) oldtls; 2551 for (i = 0; i < olddtv[1]; i++) { 2552 if (olddtv[i+2] < (Elf_Addr)oldtls || 2553 olddtv[i+2] > (Elf_Addr)oldtls + tls_static_space) { 2554 dtv[i+2] = olddtv[i+2]; 2555 olddtv[i+2] = 0; 2556 } 2557 } 2558 2559 /* 2560 * We assume that all tls blocks are allocated with the same 2561 * size and alignment. 2562 */ 2563 free_tls(oldtls, tcbsize, tcbalign); 2564 } else { 2565 for (obj = objs; obj; obj = obj->next) { 2566 if (obj->tlsoffset) { 2567 addr = (Elf_Addr)tls + obj->tlsoffset; 2568 memset((void*) (addr + obj->tlsinitsize), 2569 0, obj->tlssize - obj->tlsinitsize); 2570 if (obj->tlsinit) 2571 memcpy((void*) addr, obj->tlsinit, 2572 obj->tlsinitsize); 2573 dtv[obj->tlsindex + 1] = addr; 2574 } else if (obj->tlsindex) { 2575 dtv[obj->tlsindex + 1] = 0; 2576 } 2577 } 2578 } 2579 2580 return tls; 2581 } 2582 2583 void 2584 free_tls(void *tls, size_t tcbsize, size_t tcbalign) 2585 { 2586 size_t size; 2587 Elf_Addr* dtv; 2588 int dtvsize, i; 2589 Elf_Addr tlsstart, tlsend; 2590 2591 /* 2592 * Figure out the size of the initial TLS block so that we can 2593 * find stuff which __tls_get_addr() allocated dynamically. 2594 */ 2595 size = tls_static_space; 2596 2597 dtv = ((Elf_Addr**)tls)[0]; 2598 dtvsize = dtv[1]; 2599 tlsstart = (Elf_Addr) tls; 2600 tlsend = tlsstart + size; 2601 for (i = 0; i < dtvsize; i++) { 2602 if (dtv[i+2] < tlsstart || dtv[i+2] > tlsend) { 2603 free((void*) dtv[i+2]); 2604 } 2605 } 2606 2607 free((void*) tlsstart); 2608 } 2609 2610 #endif 2611 2612 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \ 2613 defined(__arm__) 2614 2615 /* 2616 * Allocate Static TLS using the Variant II method. 2617 */ 2618 void * 2619 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 2620 { 2621 Obj_Entry *obj; 2622 size_t size; 2623 char *tls; 2624 Elf_Addr *dtv, *olddtv; 2625 Elf_Addr segbase, oldsegbase, addr; 2626 int i; 2627 2628 size = round(tls_static_space, tcbalign); 2629 2630 assert(tcbsize >= 2*sizeof(Elf_Addr)); 2631 tls = malloc(size + tcbsize); 2632 dtv = malloc((tls_max_index + 2) * sizeof(Elf_Addr)); 2633 2634 segbase = (Elf_Addr)(tls + size); 2635 ((Elf_Addr*)segbase)[0] = segbase; 2636 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv; 2637 2638 dtv[0] = tls_dtv_generation; 2639 dtv[1] = tls_max_index; 2640 2641 if (oldtls) { 2642 /* 2643 * Copy the static TLS block over whole. 2644 */ 2645 oldsegbase = (Elf_Addr) oldtls; 2646 memcpy((void *)(segbase - tls_static_space), 2647 (const void *)(oldsegbase - tls_static_space), 2648 tls_static_space); 2649 2650 /* 2651 * If any dynamic TLS blocks have been created tls_get_addr(), 2652 * move them over. 2653 */ 2654 olddtv = ((Elf_Addr**)oldsegbase)[1]; 2655 for (i = 0; i < olddtv[1]; i++) { 2656 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) { 2657 dtv[i+2] = olddtv[i+2]; 2658 olddtv[i+2] = 0; 2659 } 2660 } 2661 2662 /* 2663 * We assume that this block was the one we created with 2664 * allocate_initial_tls(). 2665 */ 2666 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); 2667 } else { 2668 for (obj = objs; obj; obj = obj->next) { 2669 if (obj->tlsoffset) { 2670 addr = segbase - obj->tlsoffset; 2671 memset((void*) (addr + obj->tlsinitsize), 2672 0, obj->tlssize - obj->tlsinitsize); 2673 if (obj->tlsinit) 2674 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize); 2675 dtv[obj->tlsindex + 1] = addr; 2676 } else if (obj->tlsindex) { 2677 dtv[obj->tlsindex + 1] = 0; 2678 } 2679 } 2680 } 2681 2682 return (void*) segbase; 2683 } 2684 2685 void 2686 free_tls(void *tls, size_t tcbsize, size_t tcbalign) 2687 { 2688 size_t size; 2689 Elf_Addr* dtv; 2690 int dtvsize, i; 2691 Elf_Addr tlsstart, tlsend; 2692 2693 /* 2694 * Figure out the size of the initial TLS block so that we can 2695 * find stuff which ___tls_get_addr() allocated dynamically. 2696 */ 2697 size = round(tls_static_space, tcbalign); 2698 2699 dtv = ((Elf_Addr**)tls)[1]; 2700 dtvsize = dtv[1]; 2701 tlsend = (Elf_Addr) tls; 2702 tlsstart = tlsend - size; 2703 for (i = 0; i < dtvsize; i++) { 2704 if (dtv[i+2] < tlsstart || dtv[i+2] > tlsend) { 2705 free((void*) dtv[i+2]); 2706 } 2707 } 2708 2709 free((void*) tlsstart); 2710 } 2711 2712 #endif 2713 2714 /* 2715 * Allocate TLS block for module with given index. 2716 */ 2717 void * 2718 allocate_module_tls(int index) 2719 { 2720 Obj_Entry* obj; 2721 char* p; 2722 2723 for (obj = obj_list; obj; obj = obj->next) { 2724 if (obj->tlsindex == index) 2725 break; 2726 } 2727 if (!obj) { 2728 _rtld_error("Can't find module with TLS index %d", index); 2729 die(); 2730 } 2731 2732 p = malloc(obj->tlssize); 2733 memcpy(p, obj->tlsinit, obj->tlsinitsize); 2734 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 2735 2736 return p; 2737 } 2738 2739 bool 2740 allocate_tls_offset(Obj_Entry *obj) 2741 { 2742 size_t off; 2743 2744 if (obj->tls_done) 2745 return true; 2746 2747 if (obj->tlssize == 0) { 2748 obj->tls_done = true; 2749 return true; 2750 } 2751 2752 if (obj->tlsindex == 1) 2753 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign); 2754 else 2755 off = calculate_tls_offset(tls_last_offset, tls_last_size, 2756 obj->tlssize, obj->tlsalign); 2757 2758 /* 2759 * If we have already fixed the size of the static TLS block, we 2760 * must stay within that size. When allocating the static TLS, we 2761 * leave a small amount of space spare to be used for dynamically 2762 * loading modules which use static TLS. 2763 */ 2764 if (tls_static_space) { 2765 if (calculate_tls_end(off, obj->tlssize) > tls_static_space) 2766 return false; 2767 } 2768 2769 tls_last_offset = obj->tlsoffset = off; 2770 tls_last_size = obj->tlssize; 2771 obj->tls_done = true; 2772 2773 return true; 2774 } 2775 2776 void * 2777 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) 2778 { 2779 return allocate_tls(obj_list, oldtls, tcbsize, tcbalign); 2780 } 2781 2782 void 2783 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 2784 { 2785 free_tls(tcb, tcbsize, tcbalign); 2786 } 2787