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