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/mount.h> 41 #include <sys/mman.h> 42 #include <sys/stat.h> 43 #include <sys/uio.h> 44 #include <sys/ktrace.h> 45 46 #include <dlfcn.h> 47 #include <err.h> 48 #include <errno.h> 49 #include <fcntl.h> 50 #include <stdarg.h> 51 #include <stdio.h> 52 #include <stdlib.h> 53 #include <string.h> 54 #include <unistd.h> 55 56 #include "debug.h" 57 #include "rtld.h" 58 #include "libmap.h" 59 #include "rtld_tls.h" 60 61 #ifndef COMPAT_32BIT 62 #define PATH_RTLD "/libexec/ld-elf.so.1" 63 #else 64 #define PATH_RTLD "/libexec/ld-elf32.so.1" 65 #endif 66 67 /* Types. */ 68 typedef void (*func_ptr_type)(); 69 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg); 70 71 /* 72 * This structure provides a reentrant way to keep a list of objects and 73 * check which ones have already been processed in some way. 74 */ 75 typedef struct Struct_DoneList { 76 const Obj_Entry **objs; /* Array of object pointers */ 77 unsigned int num_alloc; /* Allocated size of the array */ 78 unsigned int num_used; /* Number of array slots used */ 79 } DoneList; 80 81 /* 82 * Function declarations. 83 */ 84 static const char *basename(const char *); 85 static void die(void) __dead2; 86 static void digest_dynamic(Obj_Entry *, int); 87 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *); 88 static Obj_Entry *dlcheck(void *); 89 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *); 90 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *); 91 static bool donelist_check(DoneList *, const Obj_Entry *); 92 static void errmsg_restore(char *); 93 static char *errmsg_save(void); 94 static void *fill_search_info(const char *, size_t, void *); 95 static char *find_library(const char *, const Obj_Entry *); 96 static const char *gethints(void); 97 static void init_dag(Obj_Entry *); 98 static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *); 99 static void init_rtld(caddr_t); 100 static void initlist_add_neededs(Needed_Entry *, Objlist *); 101 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *); 102 static bool is_exported(const Elf_Sym *); 103 static void linkmap_add(Obj_Entry *); 104 static void linkmap_delete(Obj_Entry *); 105 static int load_needed_objects(Obj_Entry *); 106 static int load_preload_objects(void); 107 static Obj_Entry *load_object(const char *, const Obj_Entry *); 108 static Obj_Entry *obj_from_addr(const void *); 109 static void objlist_call_fini(Objlist *, int *lockstate); 110 static void objlist_call_init(Objlist *, int *lockstate); 111 static void objlist_clear(Objlist *); 112 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *); 113 static void objlist_init(Objlist *); 114 static void objlist_push_head(Objlist *, Obj_Entry *); 115 static void objlist_push_tail(Objlist *, Obj_Entry *); 116 static void objlist_remove(Objlist *, Obj_Entry *); 117 static void objlist_remove_unref(Objlist *); 118 static void *path_enumerate(const char *, path_enum_proc, void *); 119 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *); 120 static int rtld_dirname(const char *, char *); 121 static void rtld_exit(void); 122 static char *search_library_path(const char *, const char *); 123 static const void **get_program_var_addr(const char *); 124 static void set_program_var(const char *, const void *); 125 static const Elf_Sym *symlook_default(const char *, unsigned long, 126 const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int); 127 static const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *, 128 const Obj_Entry **, const Ver_Entry *, int, DoneList *); 129 static const Elf_Sym *symlook_needed(const char *, unsigned long, 130 const Needed_Entry *, const Obj_Entry **, const Ver_Entry *, 131 int, DoneList *); 132 static void trace_loaded_objects(Obj_Entry *); 133 static void unlink_object(Obj_Entry *); 134 static void unload_object(Obj_Entry *); 135 static void unref_dag(Obj_Entry *); 136 static void ref_dag(Obj_Entry *); 137 static int rtld_verify_versions(const Objlist *); 138 static int rtld_verify_object_versions(Obj_Entry *); 139 static void object_add_name(Obj_Entry *, const char *); 140 static int object_match_name(const Obj_Entry *, const char *); 141 static void ld_utrace_log(int, void *, void *, size_t, int, const char *); 142 143 void r_debug_state(struct r_debug *, struct link_map *); 144 145 /* 146 * Data declarations. 147 */ 148 static char *error_message; /* Message for dlerror(), or NULL */ 149 struct r_debug r_debug; /* for GDB; */ 150 static bool libmap_disable; /* Disable libmap */ 151 static char *libmap_override; /* Maps to use in addition to libmap.conf */ 152 static bool trust; /* False for setuid and setgid programs */ 153 static bool dangerous_ld_env; /* True if environment variables have been 154 used to affect the libraries loaded */ 155 static char *ld_bind_now; /* Environment variable for immediate binding */ 156 static char *ld_debug; /* Environment variable for debugging */ 157 static char *ld_library_path; /* Environment variable for search path */ 158 static char *ld_preload; /* Environment variable for libraries to 159 load first */ 160 static char *ld_tracing; /* Called from ldd to print libs */ 161 static char *ld_utrace; /* Use utrace() to log events. */ 162 static Obj_Entry *obj_list; /* Head of linked list of shared objects */ 163 static Obj_Entry **obj_tail; /* Link field of last object in list */ 164 static Obj_Entry *obj_main; /* The main program shared object */ 165 static Obj_Entry obj_rtld; /* The dynamic linker shared object */ 166 static unsigned int obj_count; /* Number of objects in obj_list */ 167 static unsigned int obj_loads; /* Number of objects in obj_list */ 168 169 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */ 170 STAILQ_HEAD_INITIALIZER(list_global); 171 static Objlist list_main = /* Objects loaded at program startup */ 172 STAILQ_HEAD_INITIALIZER(list_main); 173 static Objlist list_fini = /* Objects needing fini() calls */ 174 STAILQ_HEAD_INITIALIZER(list_fini); 175 176 static Elf_Sym sym_zero; /* For resolving undefined weak refs. */ 177 178 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m); 179 180 extern Elf_Dyn _DYNAMIC; 181 #pragma weak _DYNAMIC 182 #ifndef RTLD_IS_DYNAMIC 183 #define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL) 184 #endif 185 186 /* 187 * These are the functions the dynamic linker exports to application 188 * programs. They are the only symbols the dynamic linker is willing 189 * to export from itself. 190 */ 191 static func_ptr_type exports[] = { 192 (func_ptr_type) &_rtld_error, 193 (func_ptr_type) &dlclose, 194 (func_ptr_type) &dlerror, 195 (func_ptr_type) &dlopen, 196 (func_ptr_type) &dlsym, 197 (func_ptr_type) &dlvsym, 198 (func_ptr_type) &dladdr, 199 (func_ptr_type) &dllockinit, 200 (func_ptr_type) &dlinfo, 201 (func_ptr_type) &_rtld_thread_init, 202 #ifdef __i386__ 203 (func_ptr_type) &___tls_get_addr, 204 #endif 205 (func_ptr_type) &__tls_get_addr, 206 (func_ptr_type) &_rtld_allocate_tls, 207 (func_ptr_type) &_rtld_free_tls, 208 (func_ptr_type) &dl_iterate_phdr, 209 NULL 210 }; 211 212 /* 213 * Global declarations normally provided by crt1. The dynamic linker is 214 * not built with crt1, so we have to provide them ourselves. 215 */ 216 char *__progname; 217 char **environ; 218 219 /* 220 * Globals to control TLS allocation. 221 */ 222 size_t tls_last_offset; /* Static TLS offset of last module */ 223 size_t tls_last_size; /* Static TLS size of last module */ 224 size_t tls_static_space; /* Static TLS space allocated */ 225 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */ 226 int tls_max_index = 1; /* Largest module index allocated */ 227 228 /* 229 * Fill in a DoneList with an allocation large enough to hold all of 230 * the currently-loaded objects. Keep this as a macro since it calls 231 * alloca and we want that to occur within the scope of the caller. 232 */ 233 #define donelist_init(dlp) \ 234 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \ 235 assert((dlp)->objs != NULL), \ 236 (dlp)->num_alloc = obj_count, \ 237 (dlp)->num_used = 0) 238 239 #define UTRACE_DLOPEN_START 1 240 #define UTRACE_DLOPEN_STOP 2 241 #define UTRACE_DLCLOSE_START 3 242 #define UTRACE_DLCLOSE_STOP 4 243 #define UTRACE_LOAD_OBJECT 5 244 #define UTRACE_UNLOAD_OBJECT 6 245 #define UTRACE_ADD_RUNDEP 7 246 #define UTRACE_PRELOAD_FINISHED 8 247 #define UTRACE_INIT_CALL 9 248 #define UTRACE_FINI_CALL 10 249 250 struct utrace_rtld { 251 char sig[4]; /* 'RTLD' */ 252 int event; 253 void *handle; 254 void *mapbase; /* Used for 'parent' and 'init/fini' */ 255 size_t mapsize; 256 int refcnt; /* Used for 'mode' */ 257 char name[MAXPATHLEN]; 258 }; 259 260 #define LD_UTRACE(e, h, mb, ms, r, n) do { \ 261 if (ld_utrace != NULL) \ 262 ld_utrace_log(e, h, mb, ms, r, n); \ 263 } while (0) 264 265 static void 266 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize, 267 int refcnt, const char *name) 268 { 269 struct utrace_rtld ut; 270 271 ut.sig[0] = 'R'; 272 ut.sig[1] = 'T'; 273 ut.sig[2] = 'L'; 274 ut.sig[3] = 'D'; 275 ut.event = event; 276 ut.handle = handle; 277 ut.mapbase = mapbase; 278 ut.mapsize = mapsize; 279 ut.refcnt = refcnt; 280 bzero(ut.name, sizeof(ut.name)); 281 if (name) 282 strlcpy(ut.name, name, sizeof(ut.name)); 283 utrace(&ut, sizeof(ut)); 284 } 285 286 /* 287 * Main entry point for dynamic linking. The first argument is the 288 * stack pointer. The stack is expected to be laid out as described 289 * in the SVR4 ABI specification, Intel 386 Processor Supplement. 290 * Specifically, the stack pointer points to a word containing 291 * ARGC. Following that in the stack is a null-terminated sequence 292 * of pointers to argument strings. Then comes a null-terminated 293 * sequence of pointers to environment strings. Finally, there is a 294 * sequence of "auxiliary vector" entries. 295 * 296 * The second argument points to a place to store the dynamic linker's 297 * exit procedure pointer and the third to a place to store the main 298 * program's object. 299 * 300 * The return value is the main program's entry point. 301 */ 302 func_ptr_type 303 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) 304 { 305 Elf_Auxinfo *aux_info[AT_COUNT]; 306 int i; 307 int argc; 308 char **argv; 309 char **env; 310 Elf_Auxinfo *aux; 311 Elf_Auxinfo *auxp; 312 const char *argv0; 313 Objlist_Entry *entry; 314 Obj_Entry *obj; 315 Obj_Entry **preload_tail; 316 Objlist initlist; 317 int lockstate; 318 319 /* 320 * On entry, the dynamic linker itself has not been relocated yet. 321 * Be very careful not to reference any global data until after 322 * init_rtld has returned. It is OK to reference file-scope statics 323 * and string constants, and to call static and global functions. 324 */ 325 326 /* Find the auxiliary vector on the stack. */ 327 argc = *sp++; 328 argv = (char **) sp; 329 sp += argc + 1; /* Skip over arguments and NULL terminator */ 330 env = (char **) sp; 331 while (*sp++ != 0) /* Skip over environment, and NULL terminator */ 332 ; 333 aux = (Elf_Auxinfo *) sp; 334 335 /* Digest the auxiliary vector. */ 336 for (i = 0; i < AT_COUNT; i++) 337 aux_info[i] = NULL; 338 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { 339 if (auxp->a_type < AT_COUNT) 340 aux_info[auxp->a_type] = auxp; 341 } 342 343 /* Initialize and relocate ourselves. */ 344 assert(aux_info[AT_BASE] != NULL); 345 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr); 346 347 __progname = obj_rtld.path; 348 argv0 = argv[0] != NULL ? argv[0] : "(null)"; 349 environ = env; 350 351 trust = !issetugid(); 352 353 ld_bind_now = getenv(LD_ "BIND_NOW"); 354 /* 355 * If the process is tainted, then we un-set the dangerous environment 356 * variables. The process will be marked as tainted until setuid(2) 357 * is called. If any child process calls setuid(2) we do not want any 358 * future processes to honor the potentially un-safe variables. 359 */ 360 if (!trust) { 361 unsetenv(LD_ "PRELOAD"); 362 unsetenv(LD_ "LIBMAP"); 363 unsetenv(LD_ "LIBRARY_PATH"); 364 unsetenv(LD_ "LIBMAP_DISABLE"); 365 unsetenv(LD_ "DEBUG"); 366 } 367 ld_debug = getenv(LD_ "DEBUG"); 368 libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL; 369 libmap_override = getenv(LD_ "LIBMAP"); 370 ld_library_path = getenv(LD_ "LIBRARY_PATH"); 371 ld_preload = getenv(LD_ "PRELOAD"); 372 dangerous_ld_env = libmap_disable || (libmap_override != NULL) || 373 (ld_library_path != NULL) || (ld_preload != NULL); 374 ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS"); 375 ld_utrace = getenv(LD_ "UTRACE"); 376 377 if (ld_debug != NULL && *ld_debug != '\0') 378 debug = 1; 379 dbg("%s is initialized, base address = %p", __progname, 380 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr); 381 dbg("RTLD dynamic = %p", obj_rtld.dynamic); 382 dbg("RTLD pltgot = %p", obj_rtld.pltgot); 383 384 /* 385 * Load the main program, or process its program header if it is 386 * already loaded. 387 */ 388 if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */ 389 int fd = aux_info[AT_EXECFD]->a_un.a_val; 390 dbg("loading main program"); 391 obj_main = map_object(fd, argv0, NULL); 392 close(fd); 393 if (obj_main == NULL) 394 die(); 395 } else { /* Main program already loaded. */ 396 const Elf_Phdr *phdr; 397 int phnum; 398 caddr_t entry; 399 400 dbg("processing main program's program header"); 401 assert(aux_info[AT_PHDR] != NULL); 402 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr; 403 assert(aux_info[AT_PHNUM] != NULL); 404 phnum = aux_info[AT_PHNUM]->a_un.a_val; 405 assert(aux_info[AT_PHENT] != NULL); 406 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr)); 407 assert(aux_info[AT_ENTRY] != NULL); 408 entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr; 409 if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL) 410 die(); 411 } 412 413 obj_main->path = xstrdup(argv0); 414 obj_main->mainprog = true; 415 416 /* 417 * Get the actual dynamic linker pathname from the executable if 418 * possible. (It should always be possible.) That ensures that 419 * gdb will find the right dynamic linker even if a non-standard 420 * one is being used. 421 */ 422 if (obj_main->interp != NULL && 423 strcmp(obj_main->interp, obj_rtld.path) != 0) { 424 free(obj_rtld.path); 425 obj_rtld.path = xstrdup(obj_main->interp); 426 __progname = obj_rtld.path; 427 } 428 429 digest_dynamic(obj_main, 0); 430 431 linkmap_add(obj_main); 432 linkmap_add(&obj_rtld); 433 434 /* Link the main program into the list of objects. */ 435 *obj_tail = obj_main; 436 obj_tail = &obj_main->next; 437 obj_count++; 438 obj_loads++; 439 /* Make sure we don't call the main program's init and fini functions. */ 440 obj_main->init = obj_main->fini = (Elf_Addr)NULL; 441 442 /* Initialize a fake symbol for resolving undefined weak references. */ 443 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE); 444 sym_zero.st_shndx = SHN_UNDEF; 445 446 if (!libmap_disable) 447 libmap_disable = (bool)lm_init(libmap_override); 448 449 dbg("loading LD_PRELOAD libraries"); 450 if (load_preload_objects() == -1) 451 die(); 452 preload_tail = obj_tail; 453 454 dbg("loading needed objects"); 455 if (load_needed_objects(obj_main) == -1) 456 die(); 457 458 /* Make a list of all objects loaded at startup. */ 459 for (obj = obj_list; obj != NULL; obj = obj->next) { 460 objlist_push_tail(&list_main, obj); 461 obj->refcount++; 462 } 463 464 dbg("checking for required versions"); 465 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing) 466 die(); 467 468 if (ld_tracing) { /* We're done */ 469 trace_loaded_objects(obj_main); 470 exit(0); 471 } 472 473 if (getenv(LD_ "DUMP_REL_PRE") != NULL) { 474 dump_relocations(obj_main); 475 exit (0); 476 } 477 478 /* setup TLS for main thread */ 479 dbg("initializing initial thread local storage"); 480 STAILQ_FOREACH(entry, &list_main, link) { 481 /* 482 * Allocate all the initial objects out of the static TLS 483 * block even if they didn't ask for it. 484 */ 485 allocate_tls_offset(entry->obj); 486 } 487 allocate_initial_tls(obj_list); 488 489 if (relocate_objects(obj_main, 490 ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1) 491 die(); 492 493 dbg("doing copy relocations"); 494 if (do_copy_relocations(obj_main) == -1) 495 die(); 496 497 if (getenv(LD_ "DUMP_REL_POST") != NULL) { 498 dump_relocations(obj_main); 499 exit (0); 500 } 501 502 dbg("initializing key program variables"); 503 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : ""); 504 set_program_var("environ", env); 505 506 dbg("initializing thread locks"); 507 lockdflt_init(); 508 509 /* Make a list of init functions to call. */ 510 objlist_init(&initlist); 511 initlist_add_objects(obj_list, preload_tail, &initlist); 512 513 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */ 514 515 lockstate = wlock_acquire(rtld_bind_lock); 516 objlist_call_init(&initlist, &lockstate); 517 objlist_clear(&initlist); 518 wlock_release(rtld_bind_lock, lockstate); 519 520 dbg("transferring control to program entry point = %p", obj_main->entry); 521 522 /* Return the exit procedure and the program entry point. */ 523 *exit_proc = rtld_exit; 524 *objp = obj_main; 525 return (func_ptr_type) obj_main->entry; 526 } 527 528 Elf_Addr 529 _rtld_bind(Obj_Entry *obj, Elf_Size reloff) 530 { 531 const Elf_Rel *rel; 532 const Elf_Sym *def; 533 const Obj_Entry *defobj; 534 Elf_Addr *where; 535 Elf_Addr target; 536 int lockstate; 537 538 lockstate = rlock_acquire(rtld_bind_lock); 539 if (obj->pltrel) 540 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff); 541 else 542 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff); 543 544 where = (Elf_Addr *) (obj->relocbase + rel->r_offset); 545 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL); 546 if (def == NULL) 547 die(); 548 549 target = (Elf_Addr)(defobj->relocbase + def->st_value); 550 551 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"", 552 defobj->strtab + def->st_name, basename(obj->path), 553 (void *)target, basename(defobj->path)); 554 555 /* 556 * Write the new contents for the jmpslot. Note that depending on 557 * architecture, the value which we need to return back to the 558 * lazy binding trampoline may or may not be the target 559 * address. The value returned from reloc_jmpslot() is the value 560 * that the trampoline needs. 561 */ 562 target = reloc_jmpslot(where, target, defobj, obj, rel); 563 rlock_release(rtld_bind_lock, lockstate); 564 return target; 565 } 566 567 /* 568 * Error reporting function. Use it like printf. If formats the message 569 * into a buffer, and sets things up so that the next call to dlerror() 570 * will return the message. 571 */ 572 void 573 _rtld_error(const char *fmt, ...) 574 { 575 static char buf[512]; 576 va_list ap; 577 578 va_start(ap, fmt); 579 vsnprintf(buf, sizeof buf, fmt, ap); 580 error_message = buf; 581 va_end(ap); 582 } 583 584 /* 585 * Return a dynamically-allocated copy of the current error message, if any. 586 */ 587 static char * 588 errmsg_save(void) 589 { 590 return error_message == NULL ? NULL : xstrdup(error_message); 591 } 592 593 /* 594 * Restore the current error message from a copy which was previously saved 595 * by errmsg_save(). The copy is freed. 596 */ 597 static void 598 errmsg_restore(char *saved_msg) 599 { 600 if (saved_msg == NULL) 601 error_message = NULL; 602 else { 603 _rtld_error("%s", saved_msg); 604 free(saved_msg); 605 } 606 } 607 608 static const char * 609 basename(const char *name) 610 { 611 const char *p = strrchr(name, '/'); 612 return p != NULL ? p + 1 : name; 613 } 614 615 static void 616 die(void) 617 { 618 const char *msg = dlerror(); 619 620 if (msg == NULL) 621 msg = "Fatal error"; 622 errx(1, "%s", msg); 623 } 624 625 /* 626 * Process a shared object's DYNAMIC section, and save the important 627 * information in its Obj_Entry structure. 628 */ 629 static void 630 digest_dynamic(Obj_Entry *obj, int early) 631 { 632 const Elf_Dyn *dynp; 633 Needed_Entry **needed_tail = &obj->needed; 634 const Elf_Dyn *dyn_rpath = NULL; 635 const Elf_Dyn *dyn_soname = NULL; 636 int plttype = DT_REL; 637 638 obj->bind_now = false; 639 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) { 640 switch (dynp->d_tag) { 641 642 case DT_REL: 643 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr); 644 break; 645 646 case DT_RELSZ: 647 obj->relsize = dynp->d_un.d_val; 648 break; 649 650 case DT_RELENT: 651 assert(dynp->d_un.d_val == sizeof(Elf_Rel)); 652 break; 653 654 case DT_JMPREL: 655 obj->pltrel = (const Elf_Rel *) 656 (obj->relocbase + dynp->d_un.d_ptr); 657 break; 658 659 case DT_PLTRELSZ: 660 obj->pltrelsize = dynp->d_un.d_val; 661 break; 662 663 case DT_RELA: 664 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr); 665 break; 666 667 case DT_RELASZ: 668 obj->relasize = dynp->d_un.d_val; 669 break; 670 671 case DT_RELAENT: 672 assert(dynp->d_un.d_val == sizeof(Elf_Rela)); 673 break; 674 675 case DT_PLTREL: 676 plttype = dynp->d_un.d_val; 677 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA); 678 break; 679 680 case DT_SYMTAB: 681 obj->symtab = (const Elf_Sym *) 682 (obj->relocbase + dynp->d_un.d_ptr); 683 break; 684 685 case DT_SYMENT: 686 assert(dynp->d_un.d_val == sizeof(Elf_Sym)); 687 break; 688 689 case DT_STRTAB: 690 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr); 691 break; 692 693 case DT_STRSZ: 694 obj->strsize = dynp->d_un.d_val; 695 break; 696 697 case DT_VERNEED: 698 obj->verneed = (const Elf_Verneed *) (obj->relocbase + 699 dynp->d_un.d_val); 700 break; 701 702 case DT_VERNEEDNUM: 703 obj->verneednum = dynp->d_un.d_val; 704 break; 705 706 case DT_VERDEF: 707 obj->verdef = (const Elf_Verdef *) (obj->relocbase + 708 dynp->d_un.d_val); 709 break; 710 711 case DT_VERDEFNUM: 712 obj->verdefnum = dynp->d_un.d_val; 713 break; 714 715 case DT_VERSYM: 716 obj->versyms = (const Elf_Versym *)(obj->relocbase + 717 dynp->d_un.d_val); 718 break; 719 720 case DT_HASH: 721 { 722 const Elf_Hashelt *hashtab = (const Elf_Hashelt *) 723 (obj->relocbase + dynp->d_un.d_ptr); 724 obj->nbuckets = hashtab[0]; 725 obj->nchains = hashtab[1]; 726 obj->buckets = hashtab + 2; 727 obj->chains = obj->buckets + obj->nbuckets; 728 } 729 break; 730 731 case DT_NEEDED: 732 if (!obj->rtld) { 733 Needed_Entry *nep = NEW(Needed_Entry); 734 nep->name = dynp->d_un.d_val; 735 nep->obj = NULL; 736 nep->next = NULL; 737 738 *needed_tail = nep; 739 needed_tail = &nep->next; 740 } 741 break; 742 743 case DT_PLTGOT: 744 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr); 745 break; 746 747 case DT_TEXTREL: 748 obj->textrel = true; 749 break; 750 751 case DT_SYMBOLIC: 752 obj->symbolic = true; 753 break; 754 755 case DT_RPATH: 756 case DT_RUNPATH: /* XXX: process separately */ 757 /* 758 * We have to wait until later to process this, because we 759 * might not have gotten the address of the string table yet. 760 */ 761 dyn_rpath = dynp; 762 break; 763 764 case DT_SONAME: 765 dyn_soname = dynp; 766 break; 767 768 case DT_INIT: 769 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 770 break; 771 772 case DT_FINI: 773 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 774 break; 775 776 /* 777 * Don't process DT_DEBUG on MIPS as the dynamic section 778 * is mapped read-only. DT_MIPS_RLD_MAP is used instead. 779 */ 780 781 #ifndef __mips__ 782 case DT_DEBUG: 783 /* XXX - not implemented yet */ 784 if (!early) 785 dbg("Filling in DT_DEBUG entry"); 786 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug; 787 break; 788 #endif 789 790 case DT_FLAGS: 791 if (dynp->d_un.d_val & DF_ORIGIN) { 792 obj->origin_path = xmalloc(PATH_MAX); 793 if (rtld_dirname(obj->path, obj->origin_path) == -1) 794 die(); 795 } 796 if (dynp->d_un.d_val & DF_SYMBOLIC) 797 obj->symbolic = true; 798 if (dynp->d_un.d_val & DF_TEXTREL) 799 obj->textrel = true; 800 if (dynp->d_un.d_val & DF_BIND_NOW) 801 obj->bind_now = true; 802 if (dynp->d_un.d_val & DF_STATIC_TLS) 803 ; 804 break; 805 #ifdef __mips__ 806 case DT_MIPS_LOCAL_GOTNO: 807 obj->local_gotno = dynp->d_un.d_val; 808 break; 809 810 case DT_MIPS_SYMTABNO: 811 obj->symtabno = dynp->d_un.d_val; 812 break; 813 814 case DT_MIPS_GOTSYM: 815 obj->gotsym = dynp->d_un.d_val; 816 break; 817 818 case DT_MIPS_RLD_MAP: 819 #ifdef notyet 820 if (!early) 821 dbg("Filling in DT_DEBUG entry"); 822 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug; 823 #endif 824 break; 825 #endif 826 827 default: 828 if (!early) { 829 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag, 830 (long)dynp->d_tag); 831 } 832 break; 833 } 834 } 835 836 obj->traced = false; 837 838 if (plttype == DT_RELA) { 839 obj->pltrela = (const Elf_Rela *) obj->pltrel; 840 obj->pltrel = NULL; 841 obj->pltrelasize = obj->pltrelsize; 842 obj->pltrelsize = 0; 843 } 844 845 if (dyn_rpath != NULL) 846 obj->rpath = obj->strtab + dyn_rpath->d_un.d_val; 847 848 if (dyn_soname != NULL) 849 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val); 850 } 851 852 /* 853 * Process a shared object's program header. This is used only for the 854 * main program, when the kernel has already loaded the main program 855 * into memory before calling the dynamic linker. It creates and 856 * returns an Obj_Entry structure. 857 */ 858 static Obj_Entry * 859 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path) 860 { 861 Obj_Entry *obj; 862 const Elf_Phdr *phlimit = phdr + phnum; 863 const Elf_Phdr *ph; 864 int nsegs = 0; 865 866 obj = obj_new(); 867 for (ph = phdr; ph < phlimit; ph++) { 868 switch (ph->p_type) { 869 870 case PT_PHDR: 871 if ((const Elf_Phdr *)ph->p_vaddr != phdr) { 872 _rtld_error("%s: invalid PT_PHDR", path); 873 return NULL; 874 } 875 obj->phdr = (const Elf_Phdr *) ph->p_vaddr; 876 obj->phsize = ph->p_memsz; 877 break; 878 879 case PT_INTERP: 880 obj->interp = (const char *) ph->p_vaddr; 881 break; 882 883 case PT_LOAD: 884 if (nsegs == 0) { /* First load segment */ 885 obj->vaddrbase = trunc_page(ph->p_vaddr); 886 obj->mapbase = (caddr_t) obj->vaddrbase; 887 obj->relocbase = obj->mapbase - obj->vaddrbase; 888 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) - 889 obj->vaddrbase; 890 } else { /* Last load segment */ 891 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) - 892 obj->vaddrbase; 893 } 894 nsegs++; 895 break; 896 897 case PT_DYNAMIC: 898 obj->dynamic = (const Elf_Dyn *) ph->p_vaddr; 899 break; 900 901 case PT_TLS: 902 obj->tlsindex = 1; 903 obj->tlssize = ph->p_memsz; 904 obj->tlsalign = ph->p_align; 905 obj->tlsinitsize = ph->p_filesz; 906 obj->tlsinit = (void*) ph->p_vaddr; 907 break; 908 } 909 } 910 if (nsegs < 1) { 911 _rtld_error("%s: too few PT_LOAD segments", path); 912 return NULL; 913 } 914 915 obj->entry = entry; 916 return obj; 917 } 918 919 static Obj_Entry * 920 dlcheck(void *handle) 921 { 922 Obj_Entry *obj; 923 924 for (obj = obj_list; obj != NULL; obj = obj->next) 925 if (obj == (Obj_Entry *) handle) 926 break; 927 928 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) { 929 _rtld_error("Invalid shared object handle %p", handle); 930 return NULL; 931 } 932 return obj; 933 } 934 935 /* 936 * If the given object is already in the donelist, return true. Otherwise 937 * add the object to the list and return false. 938 */ 939 static bool 940 donelist_check(DoneList *dlp, const Obj_Entry *obj) 941 { 942 unsigned int i; 943 944 for (i = 0; i < dlp->num_used; i++) 945 if (dlp->objs[i] == obj) 946 return true; 947 /* 948 * Our donelist allocation should always be sufficient. But if 949 * our threads locking isn't working properly, more shared objects 950 * could have been loaded since we allocated the list. That should 951 * never happen, but we'll handle it properly just in case it does. 952 */ 953 if (dlp->num_used < dlp->num_alloc) 954 dlp->objs[dlp->num_used++] = obj; 955 return false; 956 } 957 958 /* 959 * Hash function for symbol table lookup. Don't even think about changing 960 * this. It is specified by the System V ABI. 961 */ 962 unsigned long 963 elf_hash(const char *name) 964 { 965 const unsigned char *p = (const unsigned char *) name; 966 unsigned long h = 0; 967 unsigned long g; 968 969 while (*p != '\0') { 970 h = (h << 4) + *p++; 971 if ((g = h & 0xf0000000) != 0) 972 h ^= g >> 24; 973 h &= ~g; 974 } 975 return h; 976 } 977 978 /* 979 * Find the library with the given name, and return its full pathname. 980 * The returned string is dynamically allocated. Generates an error 981 * message and returns NULL if the library cannot be found. 982 * 983 * If the second argument is non-NULL, then it refers to an already- 984 * loaded shared object, whose library search path will be searched. 985 * 986 * The search order is: 987 * LD_LIBRARY_PATH 988 * rpath in the referencing file 989 * ldconfig hints 990 * /lib:/usr/lib 991 */ 992 static char * 993 find_library(const char *xname, const Obj_Entry *refobj) 994 { 995 char *pathname; 996 char *name; 997 998 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */ 999 if (xname[0] != '/' && !trust) { 1000 _rtld_error("Absolute pathname required for shared object \"%s\"", 1001 xname); 1002 return NULL; 1003 } 1004 return xstrdup(xname); 1005 } 1006 1007 if (libmap_disable || (refobj == NULL) || 1008 (name = lm_find(refobj->path, xname)) == NULL) 1009 name = (char *)xname; 1010 1011 dbg(" Searching for \"%s\"", name); 1012 1013 if ((pathname = search_library_path(name, ld_library_path)) != NULL || 1014 (refobj != NULL && 1015 (pathname = search_library_path(name, refobj->rpath)) != NULL) || 1016 (pathname = search_library_path(name, gethints())) != NULL || 1017 (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL) 1018 return pathname; 1019 1020 if(refobj != NULL && refobj->path != NULL) { 1021 _rtld_error("Shared object \"%s\" not found, required by \"%s\"", 1022 name, basename(refobj->path)); 1023 } else { 1024 _rtld_error("Shared object \"%s\" not found", name); 1025 } 1026 return NULL; 1027 } 1028 1029 /* 1030 * Given a symbol number in a referencing object, find the corresponding 1031 * definition of the symbol. Returns a pointer to the symbol, or NULL if 1032 * no definition was found. Returns a pointer to the Obj_Entry of the 1033 * defining object via the reference parameter DEFOBJ_OUT. 1034 */ 1035 const Elf_Sym * 1036 find_symdef(unsigned long symnum, const Obj_Entry *refobj, 1037 const Obj_Entry **defobj_out, int flags, SymCache *cache) 1038 { 1039 const Elf_Sym *ref; 1040 const Elf_Sym *def; 1041 const Obj_Entry *defobj; 1042 const Ver_Entry *ventry; 1043 const char *name; 1044 unsigned long hash; 1045 1046 /* 1047 * If we have already found this symbol, get the information from 1048 * the cache. 1049 */ 1050 if (symnum >= refobj->nchains) 1051 return NULL; /* Bad object */ 1052 if (cache != NULL && cache[symnum].sym != NULL) { 1053 *defobj_out = cache[symnum].obj; 1054 return cache[symnum].sym; 1055 } 1056 1057 ref = refobj->symtab + symnum; 1058 name = refobj->strtab + ref->st_name; 1059 defobj = NULL; 1060 1061 /* 1062 * We don't have to do a full scale lookup if the symbol is local. 1063 * We know it will bind to the instance in this load module; to 1064 * which we already have a pointer (ie ref). By not doing a lookup, 1065 * we not only improve performance, but it also avoids unresolvable 1066 * symbols when local symbols are not in the hash table. This has 1067 * been seen with the ia64 toolchain. 1068 */ 1069 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) { 1070 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) { 1071 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path, 1072 symnum); 1073 } 1074 ventry = fetch_ventry(refobj, symnum); 1075 hash = elf_hash(name); 1076 def = symlook_default(name, hash, refobj, &defobj, ventry, flags); 1077 } else { 1078 def = ref; 1079 defobj = refobj; 1080 } 1081 1082 /* 1083 * If we found no definition and the reference is weak, treat the 1084 * symbol as having the value zero. 1085 */ 1086 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) { 1087 def = &sym_zero; 1088 defobj = obj_main; 1089 } 1090 1091 if (def != NULL) { 1092 *defobj_out = defobj; 1093 /* Record the information in the cache to avoid subsequent lookups. */ 1094 if (cache != NULL) { 1095 cache[symnum].sym = def; 1096 cache[symnum].obj = defobj; 1097 } 1098 } else { 1099 if (refobj != &obj_rtld) 1100 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name); 1101 } 1102 return def; 1103 } 1104 1105 /* 1106 * Return the search path from the ldconfig hints file, reading it if 1107 * necessary. Returns NULL if there are problems with the hints file, 1108 * or if the search path there is empty. 1109 */ 1110 static const char * 1111 gethints(void) 1112 { 1113 static char *hints; 1114 1115 if (hints == NULL) { 1116 int fd; 1117 struct elfhints_hdr hdr; 1118 char *p; 1119 1120 /* Keep from trying again in case the hints file is bad. */ 1121 hints = ""; 1122 1123 if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1) 1124 return NULL; 1125 if (read(fd, &hdr, sizeof hdr) != sizeof hdr || 1126 hdr.magic != ELFHINTS_MAGIC || 1127 hdr.version != 1) { 1128 close(fd); 1129 return NULL; 1130 } 1131 p = xmalloc(hdr.dirlistlen + 1); 1132 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 || 1133 read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) { 1134 free(p); 1135 close(fd); 1136 return NULL; 1137 } 1138 hints = p; 1139 close(fd); 1140 } 1141 return hints[0] != '\0' ? hints : NULL; 1142 } 1143 1144 static void 1145 init_dag(Obj_Entry *root) 1146 { 1147 DoneList donelist; 1148 1149 donelist_init(&donelist); 1150 init_dag1(root, root, &donelist); 1151 } 1152 1153 static void 1154 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp) 1155 { 1156 const Needed_Entry *needed; 1157 1158 if (donelist_check(dlp, obj)) 1159 return; 1160 1161 obj->refcount++; 1162 objlist_push_tail(&obj->dldags, root); 1163 objlist_push_tail(&root->dagmembers, obj); 1164 for (needed = obj->needed; needed != NULL; needed = needed->next) 1165 if (needed->obj != NULL) 1166 init_dag1(root, needed->obj, dlp); 1167 } 1168 1169 /* 1170 * Initialize the dynamic linker. The argument is the address at which 1171 * the dynamic linker has been mapped into memory. The primary task of 1172 * this function is to relocate the dynamic linker. 1173 */ 1174 static void 1175 init_rtld(caddr_t mapbase) 1176 { 1177 Obj_Entry objtmp; /* Temporary rtld object */ 1178 1179 /* 1180 * Conjure up an Obj_Entry structure for the dynamic linker. 1181 * 1182 * The "path" member can't be initialized yet because string constatns 1183 * cannot yet be acessed. Below we will set it correctly. 1184 */ 1185 memset(&objtmp, 0, sizeof(objtmp)); 1186 objtmp.path = NULL; 1187 objtmp.rtld = true; 1188 objtmp.mapbase = mapbase; 1189 #ifdef PIC 1190 objtmp.relocbase = mapbase; 1191 #endif 1192 if (RTLD_IS_DYNAMIC()) { 1193 objtmp.dynamic = rtld_dynamic(&objtmp); 1194 digest_dynamic(&objtmp, 1); 1195 assert(objtmp.needed == NULL); 1196 #if !defined(__mips__) 1197 /* MIPS and SH{3,5} have a bogus DT_TEXTREL. */ 1198 assert(!objtmp.textrel); 1199 #endif 1200 1201 /* 1202 * Temporarily put the dynamic linker entry into the object list, so 1203 * that symbols can be found. 1204 */ 1205 1206 relocate_objects(&objtmp, true, &objtmp); 1207 } 1208 1209 /* Initialize the object list. */ 1210 obj_tail = &obj_list; 1211 1212 /* Now that non-local variables can be accesses, copy out obj_rtld. */ 1213 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld)); 1214 1215 /* Replace the path with a dynamically allocated copy. */ 1216 obj_rtld.path = xstrdup(PATH_RTLD); 1217 1218 r_debug.r_brk = r_debug_state; 1219 r_debug.r_state = RT_CONSISTENT; 1220 } 1221 1222 /* 1223 * Add the init functions from a needed object list (and its recursive 1224 * needed objects) to "list". This is not used directly; it is a helper 1225 * function for initlist_add_objects(). The write lock must be held 1226 * when this function is called. 1227 */ 1228 static void 1229 initlist_add_neededs(Needed_Entry *needed, Objlist *list) 1230 { 1231 /* Recursively process the successor needed objects. */ 1232 if (needed->next != NULL) 1233 initlist_add_neededs(needed->next, list); 1234 1235 /* Process the current needed object. */ 1236 if (needed->obj != NULL) 1237 initlist_add_objects(needed->obj, &needed->obj->next, list); 1238 } 1239 1240 /* 1241 * Scan all of the DAGs rooted in the range of objects from "obj" to 1242 * "tail" and add their init functions to "list". This recurses over 1243 * the DAGs and ensure the proper init ordering such that each object's 1244 * needed libraries are initialized before the object itself. At the 1245 * same time, this function adds the objects to the global finalization 1246 * list "list_fini" in the opposite order. The write lock must be 1247 * held when this function is called. 1248 */ 1249 static void 1250 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list) 1251 { 1252 if (obj->init_done) 1253 return; 1254 obj->init_done = true; 1255 1256 /* Recursively process the successor objects. */ 1257 if (&obj->next != tail) 1258 initlist_add_objects(obj->next, tail, list); 1259 1260 /* Recursively process the needed objects. */ 1261 if (obj->needed != NULL) 1262 initlist_add_neededs(obj->needed, list); 1263 1264 /* Add the object to the init list. */ 1265 if (obj->init != (Elf_Addr)NULL) 1266 objlist_push_tail(list, obj); 1267 1268 /* Add the object to the global fini list in the reverse order. */ 1269 if (obj->fini != (Elf_Addr)NULL) 1270 objlist_push_head(&list_fini, obj); 1271 } 1272 1273 #ifndef FPTR_TARGET 1274 #define FPTR_TARGET(f) ((Elf_Addr) (f)) 1275 #endif 1276 1277 static bool 1278 is_exported(const Elf_Sym *def) 1279 { 1280 Elf_Addr value; 1281 const func_ptr_type *p; 1282 1283 value = (Elf_Addr)(obj_rtld.relocbase + def->st_value); 1284 for (p = exports; *p != NULL; p++) 1285 if (FPTR_TARGET(*p) == value) 1286 return true; 1287 return false; 1288 } 1289 1290 /* 1291 * Given a shared object, traverse its list of needed objects, and load 1292 * each of them. Returns 0 on success. Generates an error message and 1293 * returns -1 on failure. 1294 */ 1295 static int 1296 load_needed_objects(Obj_Entry *first) 1297 { 1298 Obj_Entry *obj; 1299 1300 for (obj = first; obj != NULL; obj = obj->next) { 1301 Needed_Entry *needed; 1302 1303 for (needed = obj->needed; needed != NULL; needed = needed->next) { 1304 needed->obj = load_object(obj->strtab + needed->name, obj); 1305 if (needed->obj == NULL && !ld_tracing) 1306 return -1; 1307 } 1308 } 1309 1310 return 0; 1311 } 1312 1313 static int 1314 load_preload_objects(void) 1315 { 1316 char *p = ld_preload; 1317 static const char delim[] = " \t:;"; 1318 1319 if (p == NULL) 1320 return 0; 1321 1322 p += strspn(p, delim); 1323 while (*p != '\0') { 1324 size_t len = strcspn(p, delim); 1325 char savech; 1326 1327 savech = p[len]; 1328 p[len] = '\0'; 1329 if (load_object(p, NULL) == NULL) 1330 return -1; /* XXX - cleanup */ 1331 p[len] = savech; 1332 p += len; 1333 p += strspn(p, delim); 1334 } 1335 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL); 1336 return 0; 1337 } 1338 1339 /* 1340 * Load a shared object into memory, if it is not already loaded. 1341 * 1342 * Returns a pointer to the Obj_Entry for the object. Returns NULL 1343 * on failure. 1344 */ 1345 static Obj_Entry * 1346 load_object(const char *name, const Obj_Entry *refobj) 1347 { 1348 Obj_Entry *obj; 1349 int fd = -1; 1350 struct stat sb; 1351 char *path; 1352 1353 for (obj = obj_list->next; obj != NULL; obj = obj->next) 1354 if (object_match_name(obj, name)) 1355 return obj; 1356 1357 path = find_library(name, refobj); 1358 if (path == NULL) 1359 return NULL; 1360 1361 /* 1362 * If we didn't find a match by pathname, open the file and check 1363 * again by device and inode. This avoids false mismatches caused 1364 * by multiple links or ".." in pathnames. 1365 * 1366 * To avoid a race, we open the file and use fstat() rather than 1367 * using stat(). 1368 */ 1369 if ((fd = open(path, O_RDONLY)) == -1) { 1370 _rtld_error("Cannot open \"%s\"", path); 1371 free(path); 1372 return NULL; 1373 } 1374 if (fstat(fd, &sb) == -1) { 1375 _rtld_error("Cannot fstat \"%s\"", path); 1376 close(fd); 1377 free(path); 1378 return NULL; 1379 } 1380 for (obj = obj_list->next; obj != NULL; obj = obj->next) { 1381 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) { 1382 close(fd); 1383 break; 1384 } 1385 } 1386 if (obj != NULL) { 1387 object_add_name(obj, name); 1388 free(path); 1389 close(fd); 1390 return obj; 1391 } 1392 1393 /* First use of this object, so we must map it in */ 1394 obj = do_load_object(fd, name, path, &sb); 1395 if (obj == NULL) 1396 free(path); 1397 close(fd); 1398 1399 return obj; 1400 } 1401 1402 static Obj_Entry * 1403 do_load_object(int fd, const char *name, char *path, struct stat *sbp) 1404 { 1405 Obj_Entry *obj; 1406 struct statfs fs; 1407 1408 /* 1409 * but first, make sure that environment variables haven't been 1410 * used to circumvent the noexec flag on a filesystem. 1411 */ 1412 if (dangerous_ld_env) { 1413 if (fstatfs(fd, &fs) != 0) { 1414 _rtld_error("Cannot fstatfs \"%s\"", path); 1415 return NULL; 1416 } 1417 if (fs.f_flags & MNT_NOEXEC) { 1418 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname); 1419 return NULL; 1420 } 1421 } 1422 dbg("loading \"%s\"", path); 1423 obj = map_object(fd, path, sbp); 1424 if (obj == NULL) 1425 return NULL; 1426 1427 object_add_name(obj, name); 1428 obj->path = path; 1429 digest_dynamic(obj, 0); 1430 1431 *obj_tail = obj; 1432 obj_tail = &obj->next; 1433 obj_count++; 1434 obj_loads++; 1435 linkmap_add(obj); /* for GDB & dlinfo() */ 1436 1437 dbg(" %p .. %p: %s", obj->mapbase, 1438 obj->mapbase + obj->mapsize - 1, obj->path); 1439 if (obj->textrel) 1440 dbg(" WARNING: %s has impure text", obj->path); 1441 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 1442 obj->path); 1443 1444 return obj; 1445 } 1446 1447 static Obj_Entry * 1448 obj_from_addr(const void *addr) 1449 { 1450 Obj_Entry *obj; 1451 1452 for (obj = obj_list; obj != NULL; obj = obj->next) { 1453 if (addr < (void *) obj->mapbase) 1454 continue; 1455 if (addr < (void *) (obj->mapbase + obj->mapsize)) 1456 return obj; 1457 } 1458 return NULL; 1459 } 1460 1461 /* 1462 * Call the finalization functions for each of the objects in "list" 1463 * which are unreferenced. All of the objects are expected to have 1464 * non-NULL fini functions. 1465 */ 1466 static void 1467 objlist_call_fini(Objlist *list, int *lockstate) 1468 { 1469 Objlist_Entry *elm; 1470 char *saved_msg; 1471 1472 /* 1473 * Preserve the current error message since a fini function might 1474 * call into the dynamic linker and overwrite it. 1475 */ 1476 saved_msg = errmsg_save(); 1477 wlock_release(rtld_bind_lock, *lockstate); 1478 STAILQ_FOREACH(elm, list, link) { 1479 if (elm->obj->refcount == 0) { 1480 dbg("calling fini function for %s at %p", elm->obj->path, 1481 (void *)elm->obj->fini); 1482 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0, 1483 elm->obj->path); 1484 call_initfini_pointer(elm->obj, elm->obj->fini); 1485 } 1486 } 1487 *lockstate = wlock_acquire(rtld_bind_lock); 1488 errmsg_restore(saved_msg); 1489 } 1490 1491 /* 1492 * Call the initialization functions for each of the objects in 1493 * "list". All of the objects are expected to have non-NULL init 1494 * functions. 1495 */ 1496 static void 1497 objlist_call_init(Objlist *list, int *lockstate) 1498 { 1499 Objlist_Entry *elm; 1500 char *saved_msg; 1501 1502 /* 1503 * Preserve the current error message since an init function might 1504 * call into the dynamic linker and overwrite it. 1505 */ 1506 saved_msg = errmsg_save(); 1507 wlock_release(rtld_bind_lock, *lockstate); 1508 STAILQ_FOREACH(elm, list, link) { 1509 dbg("calling init function for %s at %p", elm->obj->path, 1510 (void *)elm->obj->init); 1511 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0, 1512 elm->obj->path); 1513 call_initfini_pointer(elm->obj, elm->obj->init); 1514 } 1515 *lockstate = wlock_acquire(rtld_bind_lock); 1516 errmsg_restore(saved_msg); 1517 } 1518 1519 static void 1520 objlist_clear(Objlist *list) 1521 { 1522 Objlist_Entry *elm; 1523 1524 while (!STAILQ_EMPTY(list)) { 1525 elm = STAILQ_FIRST(list); 1526 STAILQ_REMOVE_HEAD(list, link); 1527 free(elm); 1528 } 1529 } 1530 1531 static Objlist_Entry * 1532 objlist_find(Objlist *list, const Obj_Entry *obj) 1533 { 1534 Objlist_Entry *elm; 1535 1536 STAILQ_FOREACH(elm, list, link) 1537 if (elm->obj == obj) 1538 return elm; 1539 return NULL; 1540 } 1541 1542 static void 1543 objlist_init(Objlist *list) 1544 { 1545 STAILQ_INIT(list); 1546 } 1547 1548 static void 1549 objlist_push_head(Objlist *list, Obj_Entry *obj) 1550 { 1551 Objlist_Entry *elm; 1552 1553 elm = NEW(Objlist_Entry); 1554 elm->obj = obj; 1555 STAILQ_INSERT_HEAD(list, elm, link); 1556 } 1557 1558 static void 1559 objlist_push_tail(Objlist *list, Obj_Entry *obj) 1560 { 1561 Objlist_Entry *elm; 1562 1563 elm = NEW(Objlist_Entry); 1564 elm->obj = obj; 1565 STAILQ_INSERT_TAIL(list, elm, link); 1566 } 1567 1568 static void 1569 objlist_remove(Objlist *list, Obj_Entry *obj) 1570 { 1571 Objlist_Entry *elm; 1572 1573 if ((elm = objlist_find(list, obj)) != NULL) { 1574 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 1575 free(elm); 1576 } 1577 } 1578 1579 /* 1580 * Remove all of the unreferenced objects from "list". 1581 */ 1582 static void 1583 objlist_remove_unref(Objlist *list) 1584 { 1585 Objlist newlist; 1586 Objlist_Entry *elm; 1587 1588 STAILQ_INIT(&newlist); 1589 while (!STAILQ_EMPTY(list)) { 1590 elm = STAILQ_FIRST(list); 1591 STAILQ_REMOVE_HEAD(list, link); 1592 if (elm->obj->refcount == 0) 1593 free(elm); 1594 else 1595 STAILQ_INSERT_TAIL(&newlist, elm, link); 1596 } 1597 *list = newlist; 1598 } 1599 1600 /* 1601 * Relocate newly-loaded shared objects. The argument is a pointer to 1602 * the Obj_Entry for the first such object. All objects from the first 1603 * to the end of the list of objects are relocated. Returns 0 on success, 1604 * or -1 on failure. 1605 */ 1606 static int 1607 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj) 1608 { 1609 Obj_Entry *obj; 1610 1611 for (obj = first; obj != NULL; obj = obj->next) { 1612 if (obj != rtldobj) 1613 dbg("relocating \"%s\"", obj->path); 1614 if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL || 1615 obj->symtab == NULL || obj->strtab == NULL) { 1616 _rtld_error("%s: Shared object has no run-time symbol table", 1617 obj->path); 1618 return -1; 1619 } 1620 1621 if (obj->textrel) { 1622 /* There are relocations to the write-protected text segment. */ 1623 if (mprotect(obj->mapbase, obj->textsize, 1624 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) { 1625 _rtld_error("%s: Cannot write-enable text segment: %s", 1626 obj->path, strerror(errno)); 1627 return -1; 1628 } 1629 } 1630 1631 /* Process the non-PLT relocations. */ 1632 if (reloc_non_plt(obj, rtldobj)) 1633 return -1; 1634 1635 if (obj->textrel) { /* Re-protected the text segment. */ 1636 if (mprotect(obj->mapbase, obj->textsize, 1637 PROT_READ|PROT_EXEC) == -1) { 1638 _rtld_error("%s: Cannot write-protect text segment: %s", 1639 obj->path, strerror(errno)); 1640 return -1; 1641 } 1642 } 1643 1644 /* Process the PLT relocations. */ 1645 if (reloc_plt(obj) == -1) 1646 return -1; 1647 /* Relocate the jump slots if we are doing immediate binding. */ 1648 if (obj->bind_now || bind_now) 1649 if (reloc_jmpslots(obj) == -1) 1650 return -1; 1651 1652 1653 /* 1654 * Set up the magic number and version in the Obj_Entry. These 1655 * were checked in the crt1.o from the original ElfKit, so we 1656 * set them for backward compatibility. 1657 */ 1658 obj->magic = RTLD_MAGIC; 1659 obj->version = RTLD_VERSION; 1660 1661 /* Set the special PLT or GOT entries. */ 1662 init_pltgot(obj); 1663 } 1664 1665 return 0; 1666 } 1667 1668 /* 1669 * Cleanup procedure. It will be called (by the atexit mechanism) just 1670 * before the process exits. 1671 */ 1672 static void 1673 rtld_exit(void) 1674 { 1675 Obj_Entry *obj; 1676 int lockstate; 1677 1678 lockstate = wlock_acquire(rtld_bind_lock); 1679 dbg("rtld_exit()"); 1680 /* Clear all the reference counts so the fini functions will be called. */ 1681 for (obj = obj_list; obj != NULL; obj = obj->next) 1682 obj->refcount = 0; 1683 objlist_call_fini(&list_fini, &lockstate); 1684 /* No need to remove the items from the list, since we are exiting. */ 1685 if (!libmap_disable) 1686 lm_fini(); 1687 wlock_release(rtld_bind_lock, lockstate); 1688 } 1689 1690 static void * 1691 path_enumerate(const char *path, path_enum_proc callback, void *arg) 1692 { 1693 #ifdef COMPAT_32BIT 1694 const char *trans; 1695 #endif 1696 if (path == NULL) 1697 return (NULL); 1698 1699 path += strspn(path, ":;"); 1700 while (*path != '\0') { 1701 size_t len; 1702 char *res; 1703 1704 len = strcspn(path, ":;"); 1705 #ifdef COMPAT_32BIT 1706 trans = lm_findn(NULL, path, len); 1707 if (trans) 1708 res = callback(trans, strlen(trans), arg); 1709 else 1710 #endif 1711 res = callback(path, len, arg); 1712 1713 if (res != NULL) 1714 return (res); 1715 1716 path += len; 1717 path += strspn(path, ":;"); 1718 } 1719 1720 return (NULL); 1721 } 1722 1723 struct try_library_args { 1724 const char *name; 1725 size_t namelen; 1726 char *buffer; 1727 size_t buflen; 1728 }; 1729 1730 static void * 1731 try_library_path(const char *dir, size_t dirlen, void *param) 1732 { 1733 struct try_library_args *arg; 1734 1735 arg = param; 1736 if (*dir == '/' || trust) { 1737 char *pathname; 1738 1739 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 1740 return (NULL); 1741 1742 pathname = arg->buffer; 1743 strncpy(pathname, dir, dirlen); 1744 pathname[dirlen] = '/'; 1745 strcpy(pathname + dirlen + 1, arg->name); 1746 1747 dbg(" Trying \"%s\"", pathname); 1748 if (access(pathname, F_OK) == 0) { /* We found it */ 1749 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 1750 strcpy(pathname, arg->buffer); 1751 return (pathname); 1752 } 1753 } 1754 return (NULL); 1755 } 1756 1757 static char * 1758 search_library_path(const char *name, const char *path) 1759 { 1760 char *p; 1761 struct try_library_args arg; 1762 1763 if (path == NULL) 1764 return NULL; 1765 1766 arg.name = name; 1767 arg.namelen = strlen(name); 1768 arg.buffer = xmalloc(PATH_MAX); 1769 arg.buflen = PATH_MAX; 1770 1771 p = path_enumerate(path, try_library_path, &arg); 1772 1773 free(arg.buffer); 1774 1775 return (p); 1776 } 1777 1778 int 1779 dlclose(void *handle) 1780 { 1781 Obj_Entry *root; 1782 int lockstate; 1783 1784 lockstate = wlock_acquire(rtld_bind_lock); 1785 root = dlcheck(handle); 1786 if (root == NULL) { 1787 wlock_release(rtld_bind_lock, lockstate); 1788 return -1; 1789 } 1790 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount, 1791 root->path); 1792 1793 /* Unreference the object and its dependencies. */ 1794 root->dl_refcount--; 1795 1796 unref_dag(root); 1797 1798 if (root->refcount == 0) { 1799 /* 1800 * The object is no longer referenced, so we must unload it. 1801 * First, call the fini functions. 1802 */ 1803 objlist_call_fini(&list_fini, &lockstate); 1804 objlist_remove_unref(&list_fini); 1805 1806 /* Finish cleaning up the newly-unreferenced objects. */ 1807 GDB_STATE(RT_DELETE,&root->linkmap); 1808 unload_object(root); 1809 GDB_STATE(RT_CONSISTENT,NULL); 1810 } 1811 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL); 1812 wlock_release(rtld_bind_lock, lockstate); 1813 return 0; 1814 } 1815 1816 const char * 1817 dlerror(void) 1818 { 1819 char *msg = error_message; 1820 error_message = NULL; 1821 return msg; 1822 } 1823 1824 /* 1825 * This function is deprecated and has no effect. 1826 */ 1827 void 1828 dllockinit(void *context, 1829 void *(*lock_create)(void *context), 1830 void (*rlock_acquire)(void *lock), 1831 void (*wlock_acquire)(void *lock), 1832 void (*lock_release)(void *lock), 1833 void (*lock_destroy)(void *lock), 1834 void (*context_destroy)(void *context)) 1835 { 1836 static void *cur_context; 1837 static void (*cur_context_destroy)(void *); 1838 1839 /* Just destroy the context from the previous call, if necessary. */ 1840 if (cur_context_destroy != NULL) 1841 cur_context_destroy(cur_context); 1842 cur_context = context; 1843 cur_context_destroy = context_destroy; 1844 } 1845 1846 void * 1847 dlopen(const char *name, int mode) 1848 { 1849 Obj_Entry **old_obj_tail; 1850 Obj_Entry *obj; 1851 Objlist initlist; 1852 int result, lockstate; 1853 1854 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name); 1855 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 1856 if (ld_tracing != NULL) 1857 environ = (char **)*get_program_var_addr("environ"); 1858 1859 objlist_init(&initlist); 1860 1861 lockstate = wlock_acquire(rtld_bind_lock); 1862 GDB_STATE(RT_ADD,NULL); 1863 1864 old_obj_tail = obj_tail; 1865 obj = NULL; 1866 if (name == NULL) { 1867 obj = obj_main; 1868 obj->refcount++; 1869 } else { 1870 obj = load_object(name, obj_main); 1871 } 1872 1873 if (obj) { 1874 obj->dl_refcount++; 1875 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) 1876 objlist_push_tail(&list_global, obj); 1877 mode &= RTLD_MODEMASK; 1878 if (*old_obj_tail != NULL) { /* We loaded something new. */ 1879 assert(*old_obj_tail == obj); 1880 result = load_needed_objects(obj); 1881 init_dag(obj); 1882 if (result != -1) 1883 result = rtld_verify_versions(&obj->dagmembers); 1884 if (result != -1 && ld_tracing) 1885 goto trace; 1886 if (result == -1 || 1887 (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) { 1888 obj->dl_refcount--; 1889 unref_dag(obj); 1890 if (obj->refcount == 0) 1891 unload_object(obj); 1892 obj = NULL; 1893 } else { 1894 /* Make list of init functions to call. */ 1895 initlist_add_objects(obj, &obj->next, &initlist); 1896 } 1897 } else { 1898 1899 /* Bump the reference counts for objects on this DAG. */ 1900 ref_dag(obj); 1901 1902 if (ld_tracing) 1903 goto trace; 1904 } 1905 } 1906 1907 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0, 1908 name); 1909 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); 1910 1911 /* Call the init functions. */ 1912 objlist_call_init(&initlist, &lockstate); 1913 objlist_clear(&initlist); 1914 wlock_release(rtld_bind_lock, lockstate); 1915 return obj; 1916 trace: 1917 trace_loaded_objects(obj); 1918 wlock_release(rtld_bind_lock, lockstate); 1919 exit(0); 1920 } 1921 1922 static void * 1923 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve, 1924 int flags) 1925 { 1926 DoneList donelist; 1927 const Obj_Entry *obj, *defobj; 1928 const Elf_Sym *def, *symp; 1929 unsigned long hash; 1930 int lockstate; 1931 1932 hash = elf_hash(name); 1933 def = NULL; 1934 defobj = NULL; 1935 flags |= SYMLOOK_IN_PLT; 1936 1937 lockstate = rlock_acquire(rtld_bind_lock); 1938 if (handle == NULL || handle == RTLD_NEXT || 1939 handle == RTLD_DEFAULT || handle == RTLD_SELF) { 1940 1941 if ((obj = obj_from_addr(retaddr)) == NULL) { 1942 _rtld_error("Cannot determine caller's shared object"); 1943 rlock_release(rtld_bind_lock, lockstate); 1944 return NULL; 1945 } 1946 if (handle == NULL) { /* Just the caller's shared object. */ 1947 def = symlook_obj(name, hash, obj, ve, flags); 1948 defobj = obj; 1949 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 1950 handle == RTLD_SELF) { /* ... caller included */ 1951 if (handle == RTLD_NEXT) 1952 obj = obj->next; 1953 for (; obj != NULL; obj = obj->next) { 1954 if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) { 1955 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) { 1956 def = symp; 1957 defobj = obj; 1958 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 1959 break; 1960 } 1961 } 1962 } 1963 /* 1964 * Search the dynamic linker itself, and possibly resolve the 1965 * symbol from there. This is how the application links to 1966 * dynamic linker services such as dlopen. Only the values listed 1967 * in the "exports" array can be resolved from the dynamic linker. 1968 */ 1969 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 1970 symp = symlook_obj(name, hash, &obj_rtld, ve, flags); 1971 if (symp != NULL && is_exported(symp)) { 1972 def = symp; 1973 defobj = &obj_rtld; 1974 } 1975 } 1976 } else { 1977 assert(handle == RTLD_DEFAULT); 1978 def = symlook_default(name, hash, obj, &defobj, ve, flags); 1979 } 1980 } else { 1981 if ((obj = dlcheck(handle)) == NULL) { 1982 rlock_release(rtld_bind_lock, lockstate); 1983 return NULL; 1984 } 1985 1986 donelist_init(&donelist); 1987 if (obj->mainprog) { 1988 /* Search main program and all libraries loaded by it. */ 1989 def = symlook_list(name, hash, &list_main, &defobj, ve, flags, 1990 &donelist); 1991 } else { 1992 Needed_Entry fake; 1993 1994 /* Search the whole DAG rooted at the given object. */ 1995 fake.next = NULL; 1996 fake.obj = (Obj_Entry *)obj; 1997 fake.name = 0; 1998 def = symlook_needed(name, hash, &fake, &defobj, ve, flags, 1999 &donelist); 2000 } 2001 } 2002 2003 if (def != NULL) { 2004 rlock_release(rtld_bind_lock, lockstate); 2005 2006 /* 2007 * The value required by the caller is derived from the value 2008 * of the symbol. For the ia64 architecture, we need to 2009 * construct a function descriptor which the caller can use to 2010 * call the function with the right 'gp' value. For other 2011 * architectures and for non-functions, the value is simply 2012 * the relocated value of the symbol. 2013 */ 2014 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 2015 return make_function_pointer(def, defobj); 2016 else 2017 return defobj->relocbase + def->st_value; 2018 } 2019 2020 _rtld_error("Undefined symbol \"%s\"", name); 2021 rlock_release(rtld_bind_lock, lockstate); 2022 return NULL; 2023 } 2024 2025 void * 2026 dlsym(void *handle, const char *name) 2027 { 2028 return do_dlsym(handle, name, __builtin_return_address(0), NULL, 2029 SYMLOOK_DLSYM); 2030 } 2031 2032 void * 2033 dlvsym(void *handle, const char *name, const char *version) 2034 { 2035 Ver_Entry ventry; 2036 2037 ventry.name = version; 2038 ventry.file = NULL; 2039 ventry.hash = elf_hash(version); 2040 ventry.flags= 0; 2041 return do_dlsym(handle, name, __builtin_return_address(0), &ventry, 2042 SYMLOOK_DLSYM); 2043 } 2044 2045 int 2046 dladdr(const void *addr, Dl_info *info) 2047 { 2048 const Obj_Entry *obj; 2049 const Elf_Sym *def; 2050 void *symbol_addr; 2051 unsigned long symoffset; 2052 int lockstate; 2053 2054 lockstate = rlock_acquire(rtld_bind_lock); 2055 obj = obj_from_addr(addr); 2056 if (obj == NULL) { 2057 _rtld_error("No shared object contains address"); 2058 rlock_release(rtld_bind_lock, lockstate); 2059 return 0; 2060 } 2061 info->dli_fname = obj->path; 2062 info->dli_fbase = obj->mapbase; 2063 info->dli_saddr = (void *)0; 2064 info->dli_sname = NULL; 2065 2066 /* 2067 * Walk the symbol list looking for the symbol whose address is 2068 * closest to the address sent in. 2069 */ 2070 for (symoffset = 0; symoffset < obj->nchains; symoffset++) { 2071 def = obj->symtab + symoffset; 2072 2073 /* 2074 * For skip the symbol if st_shndx is either SHN_UNDEF or 2075 * SHN_COMMON. 2076 */ 2077 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 2078 continue; 2079 2080 /* 2081 * If the symbol is greater than the specified address, or if it 2082 * is further away from addr than the current nearest symbol, 2083 * then reject it. 2084 */ 2085 symbol_addr = obj->relocbase + def->st_value; 2086 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 2087 continue; 2088 2089 /* Update our idea of the nearest symbol. */ 2090 info->dli_sname = obj->strtab + def->st_name; 2091 info->dli_saddr = symbol_addr; 2092 2093 /* Exact match? */ 2094 if (info->dli_saddr == addr) 2095 break; 2096 } 2097 rlock_release(rtld_bind_lock, lockstate); 2098 return 1; 2099 } 2100 2101 int 2102 dlinfo(void *handle, int request, void *p) 2103 { 2104 const Obj_Entry *obj; 2105 int error, lockstate; 2106 2107 lockstate = rlock_acquire(rtld_bind_lock); 2108 2109 if (handle == NULL || handle == RTLD_SELF) { 2110 void *retaddr; 2111 2112 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 2113 if ((obj = obj_from_addr(retaddr)) == NULL) 2114 _rtld_error("Cannot determine caller's shared object"); 2115 } else 2116 obj = dlcheck(handle); 2117 2118 if (obj == NULL) { 2119 rlock_release(rtld_bind_lock, lockstate); 2120 return (-1); 2121 } 2122 2123 error = 0; 2124 switch (request) { 2125 case RTLD_DI_LINKMAP: 2126 *((struct link_map const **)p) = &obj->linkmap; 2127 break; 2128 case RTLD_DI_ORIGIN: 2129 error = rtld_dirname(obj->path, p); 2130 break; 2131 2132 case RTLD_DI_SERINFOSIZE: 2133 case RTLD_DI_SERINFO: 2134 error = do_search_info(obj, request, (struct dl_serinfo *)p); 2135 break; 2136 2137 default: 2138 _rtld_error("Invalid request %d passed to dlinfo()", request); 2139 error = -1; 2140 } 2141 2142 rlock_release(rtld_bind_lock, lockstate); 2143 2144 return (error); 2145 } 2146 2147 int 2148 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param) 2149 { 2150 struct dl_phdr_info phdr_info; 2151 const Obj_Entry *obj; 2152 int error, bind_lockstate, phdr_lockstate; 2153 2154 phdr_lockstate = wlock_acquire(rtld_phdr_lock); 2155 bind_lockstate = rlock_acquire(rtld_bind_lock); 2156 2157 error = 0; 2158 2159 for (obj = obj_list; obj != NULL; obj = obj->next) { 2160 phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase; 2161 phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ? 2162 STAILQ_FIRST(&obj->names)->name : obj->path; 2163 phdr_info.dlpi_phdr = obj->phdr; 2164 phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]); 2165 phdr_info.dlpi_tls_modid = obj->tlsindex; 2166 phdr_info.dlpi_tls_data = obj->tlsinit; 2167 phdr_info.dlpi_adds = obj_loads; 2168 phdr_info.dlpi_subs = obj_loads - obj_count; 2169 2170 if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0) 2171 break; 2172 2173 } 2174 rlock_release(rtld_bind_lock, bind_lockstate); 2175 wlock_release(rtld_phdr_lock, phdr_lockstate); 2176 2177 return (error); 2178 } 2179 2180 struct fill_search_info_args { 2181 int request; 2182 unsigned int flags; 2183 Dl_serinfo *serinfo; 2184 Dl_serpath *serpath; 2185 char *strspace; 2186 }; 2187 2188 static void * 2189 fill_search_info(const char *dir, size_t dirlen, void *param) 2190 { 2191 struct fill_search_info_args *arg; 2192 2193 arg = param; 2194 2195 if (arg->request == RTLD_DI_SERINFOSIZE) { 2196 arg->serinfo->dls_cnt ++; 2197 arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1; 2198 } else { 2199 struct dl_serpath *s_entry; 2200 2201 s_entry = arg->serpath; 2202 s_entry->dls_name = arg->strspace; 2203 s_entry->dls_flags = arg->flags; 2204 2205 strncpy(arg->strspace, dir, dirlen); 2206 arg->strspace[dirlen] = '\0'; 2207 2208 arg->strspace += dirlen + 1; 2209 arg->serpath++; 2210 } 2211 2212 return (NULL); 2213 } 2214 2215 static int 2216 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 2217 { 2218 struct dl_serinfo _info; 2219 struct fill_search_info_args args; 2220 2221 args.request = RTLD_DI_SERINFOSIZE; 2222 args.serinfo = &_info; 2223 2224 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 2225 _info.dls_cnt = 0; 2226 2227 path_enumerate(ld_library_path, fill_search_info, &args); 2228 path_enumerate(obj->rpath, fill_search_info, &args); 2229 path_enumerate(gethints(), fill_search_info, &args); 2230 path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args); 2231 2232 2233 if (request == RTLD_DI_SERINFOSIZE) { 2234 info->dls_size = _info.dls_size; 2235 info->dls_cnt = _info.dls_cnt; 2236 return (0); 2237 } 2238 2239 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { 2240 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); 2241 return (-1); 2242 } 2243 2244 args.request = RTLD_DI_SERINFO; 2245 args.serinfo = info; 2246 args.serpath = &info->dls_serpath[0]; 2247 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 2248 2249 args.flags = LA_SER_LIBPATH; 2250 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL) 2251 return (-1); 2252 2253 args.flags = LA_SER_RUNPATH; 2254 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL) 2255 return (-1); 2256 2257 args.flags = LA_SER_CONFIG; 2258 if (path_enumerate(gethints(), fill_search_info, &args) != NULL) 2259 return (-1); 2260 2261 args.flags = LA_SER_DEFAULT; 2262 if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL) 2263 return (-1); 2264 return (0); 2265 } 2266 2267 static int 2268 rtld_dirname(const char *path, char *bname) 2269 { 2270 const char *endp; 2271 2272 /* Empty or NULL string gets treated as "." */ 2273 if (path == NULL || *path == '\0') { 2274 bname[0] = '.'; 2275 bname[1] = '\0'; 2276 return (0); 2277 } 2278 2279 /* Strip trailing slashes */ 2280 endp = path + strlen(path) - 1; 2281 while (endp > path && *endp == '/') 2282 endp--; 2283 2284 /* Find the start of the dir */ 2285 while (endp > path && *endp != '/') 2286 endp--; 2287 2288 /* Either the dir is "/" or there are no slashes */ 2289 if (endp == path) { 2290 bname[0] = *endp == '/' ? '/' : '.'; 2291 bname[1] = '\0'; 2292 return (0); 2293 } else { 2294 do { 2295 endp--; 2296 } while (endp > path && *endp == '/'); 2297 } 2298 2299 if (endp - path + 2 > PATH_MAX) 2300 { 2301 _rtld_error("Filename is too long: %s", path); 2302 return(-1); 2303 } 2304 2305 strncpy(bname, path, endp - path + 1); 2306 bname[endp - path + 1] = '\0'; 2307 return (0); 2308 } 2309 2310 static void 2311 linkmap_add(Obj_Entry *obj) 2312 { 2313 struct link_map *l = &obj->linkmap; 2314 struct link_map *prev; 2315 2316 obj->linkmap.l_name = obj->path; 2317 obj->linkmap.l_addr = obj->mapbase; 2318 obj->linkmap.l_ld = obj->dynamic; 2319 #ifdef __mips__ 2320 /* GDB needs load offset on MIPS to use the symbols */ 2321 obj->linkmap.l_offs = obj->relocbase; 2322 #endif 2323 2324 if (r_debug.r_map == NULL) { 2325 r_debug.r_map = l; 2326 return; 2327 } 2328 2329 /* 2330 * Scan to the end of the list, but not past the entry for the 2331 * dynamic linker, which we want to keep at the very end. 2332 */ 2333 for (prev = r_debug.r_map; 2334 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 2335 prev = prev->l_next) 2336 ; 2337 2338 /* Link in the new entry. */ 2339 l->l_prev = prev; 2340 l->l_next = prev->l_next; 2341 if (l->l_next != NULL) 2342 l->l_next->l_prev = l; 2343 prev->l_next = l; 2344 } 2345 2346 static void 2347 linkmap_delete(Obj_Entry *obj) 2348 { 2349 struct link_map *l = &obj->linkmap; 2350 2351 if (l->l_prev == NULL) { 2352 if ((r_debug.r_map = l->l_next) != NULL) 2353 l->l_next->l_prev = NULL; 2354 return; 2355 } 2356 2357 if ((l->l_prev->l_next = l->l_next) != NULL) 2358 l->l_next->l_prev = l->l_prev; 2359 } 2360 2361 /* 2362 * Function for the debugger to set a breakpoint on to gain control. 2363 * 2364 * The two parameters allow the debugger to easily find and determine 2365 * what the runtime loader is doing and to whom it is doing it. 2366 * 2367 * When the loadhook trap is hit (r_debug_state, set at program 2368 * initialization), the arguments can be found on the stack: 2369 * 2370 * +8 struct link_map *m 2371 * +4 struct r_debug *rd 2372 * +0 RetAddr 2373 */ 2374 void 2375 r_debug_state(struct r_debug* rd, struct link_map *m) 2376 { 2377 } 2378 2379 /* 2380 * Get address of the pointer variable in the main program. 2381 */ 2382 static const void ** 2383 get_program_var_addr(const char *name) 2384 { 2385 const Obj_Entry *obj; 2386 unsigned long hash; 2387 2388 hash = elf_hash(name); 2389 for (obj = obj_main; obj != NULL; obj = obj->next) { 2390 const Elf_Sym *def; 2391 2392 if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) { 2393 const void **addr; 2394 2395 addr = (const void **)(obj->relocbase + def->st_value); 2396 return addr; 2397 } 2398 } 2399 return NULL; 2400 } 2401 2402 /* 2403 * Set a pointer variable in the main program to the given value. This 2404 * is used to set key variables such as "environ" before any of the 2405 * init functions are called. 2406 */ 2407 static void 2408 set_program_var(const char *name, const void *value) 2409 { 2410 const void **addr; 2411 2412 if ((addr = get_program_var_addr(name)) != NULL) { 2413 dbg("\"%s\": *%p <-- %p", name, addr, value); 2414 *addr = value; 2415 } 2416 } 2417 2418 /* 2419 * Given a symbol name in a referencing object, find the corresponding 2420 * definition of the symbol. Returns a pointer to the symbol, or NULL if 2421 * no definition was found. Returns a pointer to the Obj_Entry of the 2422 * defining object via the reference parameter DEFOBJ_OUT. 2423 */ 2424 static const Elf_Sym * 2425 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj, 2426 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags) 2427 { 2428 DoneList donelist; 2429 const Elf_Sym *def; 2430 const Elf_Sym *symp; 2431 const Obj_Entry *obj; 2432 const Obj_Entry *defobj; 2433 const Objlist_Entry *elm; 2434 def = NULL; 2435 defobj = NULL; 2436 donelist_init(&donelist); 2437 2438 /* Look first in the referencing object if linked symbolically. */ 2439 if (refobj->symbolic && !donelist_check(&donelist, refobj)) { 2440 symp = symlook_obj(name, hash, refobj, ventry, flags); 2441 if (symp != NULL) { 2442 def = symp; 2443 defobj = refobj; 2444 } 2445 } 2446 2447 /* Search all objects loaded at program start up. */ 2448 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 2449 symp = symlook_list(name, hash, &list_main, &obj, ventry, flags, 2450 &donelist); 2451 if (symp != NULL && 2452 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { 2453 def = symp; 2454 defobj = obj; 2455 } 2456 } 2457 2458 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 2459 STAILQ_FOREACH(elm, &list_global, link) { 2460 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK) 2461 break; 2462 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry, 2463 flags, &donelist); 2464 if (symp != NULL && 2465 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { 2466 def = symp; 2467 defobj = obj; 2468 } 2469 } 2470 2471 /* Search all dlopened DAGs containing the referencing object. */ 2472 STAILQ_FOREACH(elm, &refobj->dldags, link) { 2473 if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK) 2474 break; 2475 symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry, 2476 flags, &donelist); 2477 if (symp != NULL && 2478 (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { 2479 def = symp; 2480 defobj = obj; 2481 } 2482 } 2483 2484 /* 2485 * Search the dynamic linker itself, and possibly resolve the 2486 * symbol from there. This is how the application links to 2487 * dynamic linker services such as dlopen. Only the values listed 2488 * in the "exports" array can be resolved from the dynamic linker. 2489 */ 2490 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 2491 symp = symlook_obj(name, hash, &obj_rtld, ventry, flags); 2492 if (symp != NULL && is_exported(symp)) { 2493 def = symp; 2494 defobj = &obj_rtld; 2495 } 2496 } 2497 2498 if (def != NULL) 2499 *defobj_out = defobj; 2500 return def; 2501 } 2502 2503 static const Elf_Sym * 2504 symlook_list(const char *name, unsigned long hash, const Objlist *objlist, 2505 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags, 2506 DoneList *dlp) 2507 { 2508 const Elf_Sym *symp; 2509 const Elf_Sym *def; 2510 const Obj_Entry *defobj; 2511 const Objlist_Entry *elm; 2512 2513 def = NULL; 2514 defobj = NULL; 2515 STAILQ_FOREACH(elm, objlist, link) { 2516 if (donelist_check(dlp, elm->obj)) 2517 continue; 2518 if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) { 2519 if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) { 2520 def = symp; 2521 defobj = elm->obj; 2522 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 2523 break; 2524 } 2525 } 2526 } 2527 if (def != NULL) 2528 *defobj_out = defobj; 2529 return def; 2530 } 2531 2532 /* 2533 * Search the symbol table of a shared object and all objects needed 2534 * by it for a symbol of the given name. Search order is 2535 * breadth-first. Returns a pointer to the symbol, or NULL if no 2536 * definition was found. 2537 */ 2538 static const Elf_Sym * 2539 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed, 2540 const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags, 2541 DoneList *dlp) 2542 { 2543 const Elf_Sym *def, *def_w; 2544 const Needed_Entry *n; 2545 const Obj_Entry *obj, *defobj, *defobj1; 2546 2547 def = def_w = NULL; 2548 defobj = NULL; 2549 for (n = needed; n != NULL; n = n->next) { 2550 if ((obj = n->obj) == NULL || 2551 donelist_check(dlp, obj) || 2552 (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL) 2553 continue; 2554 defobj = obj; 2555 if (ELF_ST_BIND(def->st_info) != STB_WEAK) { 2556 *defobj_out = defobj; 2557 return (def); 2558 } 2559 } 2560 /* 2561 * There we come when either symbol definition is not found in 2562 * directly needed objects, or found symbol is weak. 2563 */ 2564 for (n = needed; n != NULL; n = n->next) { 2565 if ((obj = n->obj) == NULL) 2566 continue; 2567 def_w = symlook_needed(name, hash, obj->needed, &defobj1, 2568 ventry, flags, dlp); 2569 if (def_w == NULL) 2570 continue; 2571 if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) { 2572 def = def_w; 2573 defobj = defobj1; 2574 } 2575 if (ELF_ST_BIND(def_w->st_info) != STB_WEAK) 2576 break; 2577 } 2578 if (def != NULL) 2579 *defobj_out = defobj; 2580 return (def); 2581 } 2582 2583 /* 2584 * Search the symbol table of a single shared object for a symbol of 2585 * the given name and version, if requested. Returns a pointer to the 2586 * symbol, or NULL if no definition was found. 2587 * 2588 * The symbol's hash value is passed in for efficiency reasons; that 2589 * eliminates many recomputations of the hash value. 2590 */ 2591 const Elf_Sym * 2592 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj, 2593 const Ver_Entry *ventry, int flags) 2594 { 2595 unsigned long symnum; 2596 const Elf_Sym *vsymp; 2597 Elf_Versym verndx; 2598 int vcount; 2599 2600 if (obj->buckets == NULL) 2601 return NULL; 2602 2603 vsymp = NULL; 2604 vcount = 0; 2605 symnum = obj->buckets[hash % obj->nbuckets]; 2606 2607 for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) { 2608 const Elf_Sym *symp; 2609 const char *strp; 2610 2611 if (symnum >= obj->nchains) 2612 return NULL; /* Bad object */ 2613 2614 symp = obj->symtab + symnum; 2615 strp = obj->strtab + symp->st_name; 2616 2617 switch (ELF_ST_TYPE(symp->st_info)) { 2618 case STT_FUNC: 2619 case STT_NOTYPE: 2620 case STT_OBJECT: 2621 if (symp->st_value == 0) 2622 continue; 2623 /* fallthrough */ 2624 case STT_TLS: 2625 if (symp->st_shndx != SHN_UNDEF) 2626 break; 2627 #ifndef __mips__ 2628 else if (((flags & SYMLOOK_IN_PLT) == 0) && 2629 (ELF_ST_TYPE(symp->st_info) == STT_FUNC)) 2630 break; 2631 /* fallthrough */ 2632 #endif 2633 default: 2634 continue; 2635 } 2636 if (name[0] != strp[0] || strcmp(name, strp) != 0) 2637 continue; 2638 2639 if (ventry == NULL) { 2640 if (obj->versyms != NULL) { 2641 verndx = VER_NDX(obj->versyms[symnum]); 2642 if (verndx > obj->vernum) { 2643 _rtld_error("%s: symbol %s references wrong version %d", 2644 obj->path, obj->strtab + symnum, verndx); 2645 continue; 2646 } 2647 /* 2648 * If we are not called from dlsym (i.e. this is a normal 2649 * relocation from unversioned binary, accept the symbol 2650 * immediately if it happens to have first version after 2651 * this shared object became versioned. Otherwise, if 2652 * symbol is versioned and not hidden, remember it. If it 2653 * is the only symbol with this name exported by the 2654 * shared object, it will be returned as a match at the 2655 * end of the function. If symbol is global (verndx < 2) 2656 * accept it unconditionally. 2657 */ 2658 if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN) 2659 return symp; 2660 else if (verndx >= VER_NDX_GIVEN) { 2661 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) { 2662 if (vsymp == NULL) 2663 vsymp = symp; 2664 vcount ++; 2665 } 2666 continue; 2667 } 2668 } 2669 return symp; 2670 } else { 2671 if (obj->versyms == NULL) { 2672 if (object_match_name(obj, ventry->name)) { 2673 _rtld_error("%s: object %s should provide version %s for " 2674 "symbol %s", obj_rtld.path, obj->path, ventry->name, 2675 obj->strtab + symnum); 2676 continue; 2677 } 2678 } else { 2679 verndx = VER_NDX(obj->versyms[symnum]); 2680 if (verndx > obj->vernum) { 2681 _rtld_error("%s: symbol %s references wrong version %d", 2682 obj->path, obj->strtab + symnum, verndx); 2683 continue; 2684 } 2685 if (obj->vertab[verndx].hash != ventry->hash || 2686 strcmp(obj->vertab[verndx].name, ventry->name)) { 2687 /* 2688 * Version does not match. Look if this is a global symbol 2689 * and if it is not hidden. If global symbol (verndx < 2) 2690 * is available, use it. Do not return symbol if we are 2691 * called by dlvsym, because dlvsym looks for a specific 2692 * version and default one is not what dlvsym wants. 2693 */ 2694 if ((flags & SYMLOOK_DLSYM) || 2695 (obj->versyms[symnum] & VER_NDX_HIDDEN) || 2696 (verndx >= VER_NDX_GIVEN)) 2697 continue; 2698 } 2699 } 2700 return symp; 2701 } 2702 } 2703 return (vcount == 1) ? vsymp : NULL; 2704 } 2705 2706 static void 2707 trace_loaded_objects(Obj_Entry *obj) 2708 { 2709 char *fmt1, *fmt2, *fmt, *main_local, *list_containers; 2710 int c; 2711 2712 if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL) 2713 main_local = ""; 2714 2715 if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL) 2716 fmt1 = "\t%o => %p (%x)\n"; 2717 2718 if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL) 2719 fmt2 = "\t%o (%x)\n"; 2720 2721 list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL"); 2722 2723 for (; obj; obj = obj->next) { 2724 Needed_Entry *needed; 2725 char *name, *path; 2726 bool is_lib; 2727 2728 if (list_containers && obj->needed != NULL) 2729 printf("%s:\n", obj->path); 2730 for (needed = obj->needed; needed; needed = needed->next) { 2731 if (needed->obj != NULL) { 2732 if (needed->obj->traced && !list_containers) 2733 continue; 2734 needed->obj->traced = true; 2735 path = needed->obj->path; 2736 } else 2737 path = "not found"; 2738 2739 name = (char *)obj->strtab + needed->name; 2740 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */ 2741 2742 fmt = is_lib ? fmt1 : fmt2; 2743 while ((c = *fmt++) != '\0') { 2744 switch (c) { 2745 default: 2746 putchar(c); 2747 continue; 2748 case '\\': 2749 switch (c = *fmt) { 2750 case '\0': 2751 continue; 2752 case 'n': 2753 putchar('\n'); 2754 break; 2755 case 't': 2756 putchar('\t'); 2757 break; 2758 } 2759 break; 2760 case '%': 2761 switch (c = *fmt) { 2762 case '\0': 2763 continue; 2764 case '%': 2765 default: 2766 putchar(c); 2767 break; 2768 case 'A': 2769 printf("%s", main_local); 2770 break; 2771 case 'a': 2772 printf("%s", obj_main->path); 2773 break; 2774 case 'o': 2775 printf("%s", name); 2776 break; 2777 #if 0 2778 case 'm': 2779 printf("%d", sodp->sod_major); 2780 break; 2781 case 'n': 2782 printf("%d", sodp->sod_minor); 2783 break; 2784 #endif 2785 case 'p': 2786 printf("%s", path); 2787 break; 2788 case 'x': 2789 printf("%p", needed->obj ? needed->obj->mapbase : 0); 2790 break; 2791 } 2792 break; 2793 } 2794 ++fmt; 2795 } 2796 } 2797 } 2798 } 2799 2800 /* 2801 * Unload a dlopened object and its dependencies from memory and from 2802 * our data structures. It is assumed that the DAG rooted in the 2803 * object has already been unreferenced, and that the object has a 2804 * reference count of 0. 2805 */ 2806 static void 2807 unload_object(Obj_Entry *root) 2808 { 2809 Obj_Entry *obj; 2810 Obj_Entry **linkp; 2811 2812 assert(root->refcount == 0); 2813 2814 /* 2815 * Pass over the DAG removing unreferenced objects from 2816 * appropriate lists. 2817 */ 2818 unlink_object(root); 2819 2820 /* Unmap all objects that are no longer referenced. */ 2821 linkp = &obj_list->next; 2822 while ((obj = *linkp) != NULL) { 2823 if (obj->refcount == 0) { 2824 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 2825 obj->path); 2826 dbg("unloading \"%s\"", obj->path); 2827 munmap(obj->mapbase, obj->mapsize); 2828 linkmap_delete(obj); 2829 *linkp = obj->next; 2830 obj_count--; 2831 obj_free(obj); 2832 } else 2833 linkp = &obj->next; 2834 } 2835 obj_tail = linkp; 2836 } 2837 2838 static void 2839 unlink_object(Obj_Entry *root) 2840 { 2841 Objlist_Entry *elm; 2842 2843 if (root->refcount == 0) { 2844 /* Remove the object from the RTLD_GLOBAL list. */ 2845 objlist_remove(&list_global, root); 2846 2847 /* Remove the object from all objects' DAG lists. */ 2848 STAILQ_FOREACH(elm, &root->dagmembers, link) { 2849 objlist_remove(&elm->obj->dldags, root); 2850 if (elm->obj != root) 2851 unlink_object(elm->obj); 2852 } 2853 } 2854 } 2855 2856 static void 2857 ref_dag(Obj_Entry *root) 2858 { 2859 Objlist_Entry *elm; 2860 2861 STAILQ_FOREACH(elm, &root->dagmembers, link) 2862 elm->obj->refcount++; 2863 } 2864 2865 static void 2866 unref_dag(Obj_Entry *root) 2867 { 2868 Objlist_Entry *elm; 2869 2870 STAILQ_FOREACH(elm, &root->dagmembers, link) 2871 elm->obj->refcount--; 2872 } 2873 2874 /* 2875 * Common code for MD __tls_get_addr(). 2876 */ 2877 void * 2878 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset) 2879 { 2880 Elf_Addr* dtv = *dtvp; 2881 int lockstate; 2882 2883 /* Check dtv generation in case new modules have arrived */ 2884 if (dtv[0] != tls_dtv_generation) { 2885 Elf_Addr* newdtv; 2886 int to_copy; 2887 2888 lockstate = wlock_acquire(rtld_bind_lock); 2889 newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr)); 2890 to_copy = dtv[1]; 2891 if (to_copy > tls_max_index) 2892 to_copy = tls_max_index; 2893 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); 2894 newdtv[0] = tls_dtv_generation; 2895 newdtv[1] = tls_max_index; 2896 free(dtv); 2897 wlock_release(rtld_bind_lock, lockstate); 2898 *dtvp = newdtv; 2899 } 2900 2901 /* Dynamically allocate module TLS if necessary */ 2902 if (!dtv[index + 1]) { 2903 /* Signal safe, wlock will block out signals. */ 2904 lockstate = wlock_acquire(rtld_bind_lock); 2905 if (!dtv[index + 1]) 2906 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); 2907 wlock_release(rtld_bind_lock, lockstate); 2908 } 2909 return (void*) (dtv[index + 1] + offset); 2910 } 2911 2912 /* XXX not sure what variants to use for arm. */ 2913 2914 #if defined(__ia64__) || defined(__powerpc__) 2915 2916 /* 2917 * Allocate Static TLS using the Variant I method. 2918 */ 2919 void * 2920 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 2921 { 2922 Obj_Entry *obj; 2923 char *tcb; 2924 Elf_Addr **tls; 2925 Elf_Addr *dtv; 2926 Elf_Addr addr; 2927 int i; 2928 2929 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) 2930 return (oldtcb); 2931 2932 assert(tcbsize >= TLS_TCB_SIZE); 2933 tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize); 2934 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE); 2935 2936 if (oldtcb != NULL) { 2937 memcpy(tls, oldtcb, tls_static_space); 2938 free(oldtcb); 2939 2940 /* Adjust the DTV. */ 2941 dtv = tls[0]; 2942 for (i = 0; i < dtv[1]; i++) { 2943 if (dtv[i+2] >= (Elf_Addr)oldtcb && 2944 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) { 2945 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls; 2946 } 2947 } 2948 } else { 2949 dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr)); 2950 tls[0] = dtv; 2951 dtv[0] = tls_dtv_generation; 2952 dtv[1] = tls_max_index; 2953 2954 for (obj = objs; obj; obj = obj->next) { 2955 if (obj->tlsoffset) { 2956 addr = (Elf_Addr)tls + obj->tlsoffset; 2957 memset((void*) (addr + obj->tlsinitsize), 2958 0, obj->tlssize - obj->tlsinitsize); 2959 if (obj->tlsinit) 2960 memcpy((void*) addr, obj->tlsinit, 2961 obj->tlsinitsize); 2962 dtv[obj->tlsindex + 1] = addr; 2963 } 2964 } 2965 } 2966 2967 return (tcb); 2968 } 2969 2970 void 2971 free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 2972 { 2973 Elf_Addr *dtv; 2974 Elf_Addr tlsstart, tlsend; 2975 int dtvsize, i; 2976 2977 assert(tcbsize >= TLS_TCB_SIZE); 2978 2979 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE; 2980 tlsend = tlsstart + tls_static_space; 2981 2982 dtv = *(Elf_Addr **)tlsstart; 2983 dtvsize = dtv[1]; 2984 for (i = 0; i < dtvsize; i++) { 2985 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) { 2986 free((void*)dtv[i+2]); 2987 } 2988 } 2989 free(dtv); 2990 free(tcb); 2991 } 2992 2993 #endif 2994 2995 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \ 2996 defined(__arm__) || defined(__mips__) 2997 2998 /* 2999 * Allocate Static TLS using the Variant II method. 3000 */ 3001 void * 3002 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 3003 { 3004 Obj_Entry *obj; 3005 size_t size; 3006 char *tls; 3007 Elf_Addr *dtv, *olddtv; 3008 Elf_Addr segbase, oldsegbase, addr; 3009 int i; 3010 3011 size = round(tls_static_space, tcbalign); 3012 3013 assert(tcbsize >= 2*sizeof(Elf_Addr)); 3014 tls = calloc(1, size + tcbsize); 3015 dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr)); 3016 3017 segbase = (Elf_Addr)(tls + size); 3018 ((Elf_Addr*)segbase)[0] = segbase; 3019 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv; 3020 3021 dtv[0] = tls_dtv_generation; 3022 dtv[1] = tls_max_index; 3023 3024 if (oldtls) { 3025 /* 3026 * Copy the static TLS block over whole. 3027 */ 3028 oldsegbase = (Elf_Addr) oldtls; 3029 memcpy((void *)(segbase - tls_static_space), 3030 (const void *)(oldsegbase - tls_static_space), 3031 tls_static_space); 3032 3033 /* 3034 * If any dynamic TLS blocks have been created tls_get_addr(), 3035 * move them over. 3036 */ 3037 olddtv = ((Elf_Addr**)oldsegbase)[1]; 3038 for (i = 0; i < olddtv[1]; i++) { 3039 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) { 3040 dtv[i+2] = olddtv[i+2]; 3041 olddtv[i+2] = 0; 3042 } 3043 } 3044 3045 /* 3046 * We assume that this block was the one we created with 3047 * allocate_initial_tls(). 3048 */ 3049 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); 3050 } else { 3051 for (obj = objs; obj; obj = obj->next) { 3052 if (obj->tlsoffset) { 3053 addr = segbase - obj->tlsoffset; 3054 memset((void*) (addr + obj->tlsinitsize), 3055 0, obj->tlssize - obj->tlsinitsize); 3056 if (obj->tlsinit) 3057 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize); 3058 dtv[obj->tlsindex + 1] = addr; 3059 } 3060 } 3061 } 3062 3063 return (void*) segbase; 3064 } 3065 3066 void 3067 free_tls(void *tls, size_t tcbsize, size_t tcbalign) 3068 { 3069 size_t size; 3070 Elf_Addr* dtv; 3071 int dtvsize, i; 3072 Elf_Addr tlsstart, tlsend; 3073 3074 /* 3075 * Figure out the size of the initial TLS block so that we can 3076 * find stuff which ___tls_get_addr() allocated dynamically. 3077 */ 3078 size = round(tls_static_space, tcbalign); 3079 3080 dtv = ((Elf_Addr**)tls)[1]; 3081 dtvsize = dtv[1]; 3082 tlsend = (Elf_Addr) tls; 3083 tlsstart = tlsend - size; 3084 for (i = 0; i < dtvsize; i++) { 3085 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) { 3086 free((void*) dtv[i+2]); 3087 } 3088 } 3089 3090 free((void*) tlsstart); 3091 free((void*) dtv); 3092 } 3093 3094 #endif 3095 3096 /* 3097 * Allocate TLS block for module with given index. 3098 */ 3099 void * 3100 allocate_module_tls(int index) 3101 { 3102 Obj_Entry* obj; 3103 char* p; 3104 3105 for (obj = obj_list; obj; obj = obj->next) { 3106 if (obj->tlsindex == index) 3107 break; 3108 } 3109 if (!obj) { 3110 _rtld_error("Can't find module with TLS index %d", index); 3111 die(); 3112 } 3113 3114 p = malloc(obj->tlssize); 3115 memcpy(p, obj->tlsinit, obj->tlsinitsize); 3116 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 3117 3118 return p; 3119 } 3120 3121 bool 3122 allocate_tls_offset(Obj_Entry *obj) 3123 { 3124 size_t off; 3125 3126 if (obj->tls_done) 3127 return true; 3128 3129 if (obj->tlssize == 0) { 3130 obj->tls_done = true; 3131 return true; 3132 } 3133 3134 if (obj->tlsindex == 1) 3135 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign); 3136 else 3137 off = calculate_tls_offset(tls_last_offset, tls_last_size, 3138 obj->tlssize, obj->tlsalign); 3139 3140 /* 3141 * If we have already fixed the size of the static TLS block, we 3142 * must stay within that size. When allocating the static TLS, we 3143 * leave a small amount of space spare to be used for dynamically 3144 * loading modules which use static TLS. 3145 */ 3146 if (tls_static_space) { 3147 if (calculate_tls_end(off, obj->tlssize) > tls_static_space) 3148 return false; 3149 } 3150 3151 tls_last_offset = obj->tlsoffset = off; 3152 tls_last_size = obj->tlssize; 3153 obj->tls_done = true; 3154 3155 return true; 3156 } 3157 3158 void 3159 free_tls_offset(Obj_Entry *obj) 3160 { 3161 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \ 3162 defined(__arm__) || defined(__mips__) 3163 /* 3164 * If we were the last thing to allocate out of the static TLS 3165 * block, we give our space back to the 'allocator'. This is a 3166 * simplistic workaround to allow libGL.so.1 to be loaded and 3167 * unloaded multiple times. We only handle the Variant II 3168 * mechanism for now - this really needs a proper allocator. 3169 */ 3170 if (calculate_tls_end(obj->tlsoffset, obj->tlssize) 3171 == calculate_tls_end(tls_last_offset, tls_last_size)) { 3172 tls_last_offset -= obj->tlssize; 3173 tls_last_size = 0; 3174 } 3175 #endif 3176 } 3177 3178 void * 3179 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) 3180 { 3181 void *ret; 3182 int lockstate; 3183 3184 lockstate = wlock_acquire(rtld_bind_lock); 3185 ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign); 3186 wlock_release(rtld_bind_lock, lockstate); 3187 return (ret); 3188 } 3189 3190 void 3191 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 3192 { 3193 int lockstate; 3194 3195 lockstate = wlock_acquire(rtld_bind_lock); 3196 free_tls(tcb, tcbsize, tcbalign); 3197 wlock_release(rtld_bind_lock, lockstate); 3198 } 3199 3200 static void 3201 object_add_name(Obj_Entry *obj, const char *name) 3202 { 3203 Name_Entry *entry; 3204 size_t len; 3205 3206 len = strlen(name); 3207 entry = malloc(sizeof(Name_Entry) + len); 3208 3209 if (entry != NULL) { 3210 strcpy(entry->name, name); 3211 STAILQ_INSERT_TAIL(&obj->names, entry, link); 3212 } 3213 } 3214 3215 static int 3216 object_match_name(const Obj_Entry *obj, const char *name) 3217 { 3218 Name_Entry *entry; 3219 3220 STAILQ_FOREACH(entry, &obj->names, link) { 3221 if (strcmp(name, entry->name) == 0) 3222 return (1); 3223 } 3224 return (0); 3225 } 3226 3227 static Obj_Entry * 3228 locate_dependency(const Obj_Entry *obj, const char *name) 3229 { 3230 const Objlist_Entry *entry; 3231 const Needed_Entry *needed; 3232 3233 STAILQ_FOREACH(entry, &list_main, link) { 3234 if (object_match_name(entry->obj, name)) 3235 return entry->obj; 3236 } 3237 3238 for (needed = obj->needed; needed != NULL; needed = needed->next) { 3239 if (needed->obj == NULL) 3240 continue; 3241 if (object_match_name(needed->obj, name)) 3242 return needed->obj; 3243 } 3244 _rtld_error("%s: Unexpected inconsistency: dependency %s not found", 3245 obj->path, name); 3246 die(); 3247 } 3248 3249 static int 3250 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj, 3251 const Elf_Vernaux *vna) 3252 { 3253 const Elf_Verdef *vd; 3254 const char *vername; 3255 3256 vername = refobj->strtab + vna->vna_name; 3257 vd = depobj->verdef; 3258 if (vd == NULL) { 3259 _rtld_error("%s: version %s required by %s not defined", 3260 depobj->path, vername, refobj->path); 3261 return (-1); 3262 } 3263 for (;;) { 3264 if (vd->vd_version != VER_DEF_CURRENT) { 3265 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 3266 depobj->path, vd->vd_version); 3267 return (-1); 3268 } 3269 if (vna->vna_hash == vd->vd_hash) { 3270 const Elf_Verdaux *aux = (const Elf_Verdaux *) 3271 ((char *)vd + vd->vd_aux); 3272 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0) 3273 return (0); 3274 } 3275 if (vd->vd_next == 0) 3276 break; 3277 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next); 3278 } 3279 if (vna->vna_flags & VER_FLG_WEAK) 3280 return (0); 3281 _rtld_error("%s: version %s required by %s not found", 3282 depobj->path, vername, refobj->path); 3283 return (-1); 3284 } 3285 3286 static int 3287 rtld_verify_object_versions(Obj_Entry *obj) 3288 { 3289 const Elf_Verneed *vn; 3290 const Elf_Verdef *vd; 3291 const Elf_Verdaux *vda; 3292 const Elf_Vernaux *vna; 3293 const Obj_Entry *depobj; 3294 int maxvernum, vernum; 3295 3296 maxvernum = 0; 3297 /* 3298 * Walk over defined and required version records and figure out 3299 * max index used by any of them. Do very basic sanity checking 3300 * while there. 3301 */ 3302 vn = obj->verneed; 3303 while (vn != NULL) { 3304 if (vn->vn_version != VER_NEED_CURRENT) { 3305 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry", 3306 obj->path, vn->vn_version); 3307 return (-1); 3308 } 3309 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux); 3310 for (;;) { 3311 vernum = VER_NEED_IDX(vna->vna_other); 3312 if (vernum > maxvernum) 3313 maxvernum = vernum; 3314 if (vna->vna_next == 0) 3315 break; 3316 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next); 3317 } 3318 if (vn->vn_next == 0) 3319 break; 3320 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next); 3321 } 3322 3323 vd = obj->verdef; 3324 while (vd != NULL) { 3325 if (vd->vd_version != VER_DEF_CURRENT) { 3326 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 3327 obj->path, vd->vd_version); 3328 return (-1); 3329 } 3330 vernum = VER_DEF_IDX(vd->vd_ndx); 3331 if (vernum > maxvernum) 3332 maxvernum = vernum; 3333 if (vd->vd_next == 0) 3334 break; 3335 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next); 3336 } 3337 3338 if (maxvernum == 0) 3339 return (0); 3340 3341 /* 3342 * Store version information in array indexable by version index. 3343 * Verify that object version requirements are satisfied along the 3344 * way. 3345 */ 3346 obj->vernum = maxvernum + 1; 3347 obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry)); 3348 3349 vd = obj->verdef; 3350 while (vd != NULL) { 3351 if ((vd->vd_flags & VER_FLG_BASE) == 0) { 3352 vernum = VER_DEF_IDX(vd->vd_ndx); 3353 assert(vernum <= maxvernum); 3354 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux); 3355 obj->vertab[vernum].hash = vd->vd_hash; 3356 obj->vertab[vernum].name = obj->strtab + vda->vda_name; 3357 obj->vertab[vernum].file = NULL; 3358 obj->vertab[vernum].flags = 0; 3359 } 3360 if (vd->vd_next == 0) 3361 break; 3362 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next); 3363 } 3364 3365 vn = obj->verneed; 3366 while (vn != NULL) { 3367 depobj = locate_dependency(obj, obj->strtab + vn->vn_file); 3368 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux); 3369 for (;;) { 3370 if (check_object_provided_version(obj, depobj, vna)) 3371 return (-1); 3372 vernum = VER_NEED_IDX(vna->vna_other); 3373 assert(vernum <= maxvernum); 3374 obj->vertab[vernum].hash = vna->vna_hash; 3375 obj->vertab[vernum].name = obj->strtab + vna->vna_name; 3376 obj->vertab[vernum].file = obj->strtab + vn->vn_file; 3377 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ? 3378 VER_INFO_HIDDEN : 0; 3379 if (vna->vna_next == 0) 3380 break; 3381 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next); 3382 } 3383 if (vn->vn_next == 0) 3384 break; 3385 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next); 3386 } 3387 return 0; 3388 } 3389 3390 static int 3391 rtld_verify_versions(const Objlist *objlist) 3392 { 3393 Objlist_Entry *entry; 3394 int rc; 3395 3396 rc = 0; 3397 STAILQ_FOREACH(entry, objlist, link) { 3398 /* 3399 * Skip dummy objects or objects that have their version requirements 3400 * already checked. 3401 */ 3402 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL) 3403 continue; 3404 if (rtld_verify_object_versions(entry->obj) == -1) { 3405 rc = -1; 3406 if (ld_tracing == NULL) 3407 break; 3408 } 3409 } 3410 if (rc == 0 || ld_tracing != NULL) 3411 rc = rtld_verify_object_versions(&obj_rtld); 3412 return rc; 3413 } 3414 3415 const Ver_Entry * 3416 fetch_ventry(const Obj_Entry *obj, unsigned long symnum) 3417 { 3418 Elf_Versym vernum; 3419 3420 if (obj->vertab) { 3421 vernum = VER_NDX(obj->versyms[symnum]); 3422 if (vernum >= obj->vernum) { 3423 _rtld_error("%s: symbol %s has wrong verneed value %d", 3424 obj->path, obj->strtab + symnum, vernum); 3425 } else if (obj->vertab[vernum].hash != 0) { 3426 return &obj->vertab[vernum]; 3427 } 3428 } 3429 return NULL; 3430 } 3431