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