1 /*- 2 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra. 3 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>. 4 * Copyright 2009-2012 Konstantin Belousov <kib@FreeBSD.ORG>. 5 * Copyright 2012 John Marino <draco@marino.st>. 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 * 28 * $FreeBSD$ 29 */ 30 31 /* 32 * Dynamic linker for ELF. 33 * 34 * John Polstra <jdp@polstra.com>. 35 */ 36 37 #include <sys/param.h> 38 #include <sys/mount.h> 39 #include <sys/mman.h> 40 #include <sys/stat.h> 41 #include <sys/sysctl.h> 42 #include <sys/uio.h> 43 #include <sys/utsname.h> 44 #include <sys/ktrace.h> 45 46 #include <dlfcn.h> 47 #include <err.h> 48 #include <errno.h> 49 #include <fcntl.h> 50 #include <stdarg.h> 51 #include <stdio.h> 52 #include <stdlib.h> 53 #include <string.h> 54 #include <unistd.h> 55 56 #include "debug.h" 57 #include "rtld.h" 58 #include "libmap.h" 59 #include "paths.h" 60 #include "rtld_tls.h" 61 #include "rtld_printf.h" 62 #include "rtld_utrace.h" 63 #include "notes.h" 64 65 /* Types. */ 66 typedef void (*func_ptr_type)(); 67 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg); 68 69 /* 70 * Function declarations. 71 */ 72 static const char *basename(const char *); 73 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **, 74 const Elf_Dyn **, const Elf_Dyn **); 75 static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *, 76 const Elf_Dyn *); 77 static void digest_dynamic(Obj_Entry *, int); 78 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *); 79 static Obj_Entry *dlcheck(void *); 80 static int dlclose_locked(void *, RtldLockState *); 81 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj, 82 int lo_flags, int mode, RtldLockState *lockstate); 83 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int); 84 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *); 85 static bool donelist_check(DoneList *, const Obj_Entry *); 86 static void errmsg_restore(char *); 87 static char *errmsg_save(void); 88 static void *fill_search_info(const char *, size_t, void *); 89 static char *find_library(const char *, const Obj_Entry *, int *); 90 static const char *gethints(bool); 91 static void hold_object(Obj_Entry *); 92 static void unhold_object(Obj_Entry *); 93 static void init_dag(Obj_Entry *); 94 static void init_marker(Obj_Entry *); 95 static void init_pagesizes(Elf_Auxinfo **aux_info); 96 static void init_rtld(caddr_t, Elf_Auxinfo **); 97 static void initlist_add_neededs(Needed_Entry *, Objlist *); 98 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *); 99 static void linkmap_add(Obj_Entry *); 100 static void linkmap_delete(Obj_Entry *); 101 static void load_filtees(Obj_Entry *, int flags, RtldLockState *); 102 static void unload_filtees(Obj_Entry *, RtldLockState *); 103 static int load_needed_objects(Obj_Entry *, int); 104 static int load_preload_objects(void); 105 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int); 106 static void map_stacks_exec(RtldLockState *); 107 static int obj_enforce_relro(Obj_Entry *); 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_put_after(Objlist *, Obj_Entry *, Obj_Entry *); 117 static void objlist_remove(Objlist *, Obj_Entry *); 118 static int parse_libdir(const char *); 119 static void *path_enumerate(const char *, path_enum_proc, void *); 120 static void release_object(Obj_Entry *); 121 static int relocate_object_dag(Obj_Entry *root, bool bind_now, 122 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate); 123 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, 124 int flags, RtldLockState *lockstate); 125 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int, 126 RtldLockState *); 127 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now, 128 int flags, RtldLockState *lockstate); 129 static int rtld_dirname(const char *, char *); 130 static int rtld_dirname_abs(const char *, char *); 131 static void *rtld_dlopen(const char *name, int fd, int mode); 132 static void rtld_exit(void); 133 static char *search_library_path(const char *, const char *); 134 static char *search_library_pathfds(const char *, const char *, int *); 135 static const void **get_program_var_addr(const char *, RtldLockState *); 136 static void set_program_var(const char *, const void *); 137 static int symlook_default(SymLook *, const Obj_Entry *refobj); 138 static int symlook_global(SymLook *, DoneList *); 139 static void symlook_init_from_req(SymLook *, const SymLook *); 140 static int symlook_list(SymLook *, const Objlist *, DoneList *); 141 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *); 142 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *); 143 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *); 144 static void trace_loaded_objects(Obj_Entry *); 145 static void unlink_object(Obj_Entry *); 146 static void unload_object(Obj_Entry *, RtldLockState *lockstate); 147 static void unref_dag(Obj_Entry *); 148 static void ref_dag(Obj_Entry *); 149 static char *origin_subst_one(Obj_Entry *, char *, const char *, 150 const char *, bool); 151 static char *origin_subst(Obj_Entry *, char *); 152 static bool obj_resolve_origin(Obj_Entry *obj); 153 static void preinit_main(void); 154 static int rtld_verify_versions(const Objlist *); 155 static int rtld_verify_object_versions(Obj_Entry *); 156 static void object_add_name(Obj_Entry *, const char *); 157 static int object_match_name(const Obj_Entry *, const char *); 158 static void ld_utrace_log(int, void *, void *, size_t, int, const char *); 159 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj, 160 struct dl_phdr_info *phdr_info); 161 static uint32_t gnu_hash(const char *); 162 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *, 163 const unsigned long); 164 165 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported; 166 void _r_debug_postinit(struct link_map *) __noinline __exported; 167 168 int __sys_openat(int, const char *, int, ...); 169 170 /* 171 * Data declarations. 172 */ 173 static char *error_message; /* Message for dlerror(), or NULL */ 174 struct r_debug r_debug __exported; /* for GDB; */ 175 static bool libmap_disable; /* Disable libmap */ 176 static bool ld_loadfltr; /* Immediate filters processing */ 177 static char *libmap_override; /* Maps to use in addition to libmap.conf */ 178 static bool trust; /* False for setuid and setgid programs */ 179 static bool dangerous_ld_env; /* True if environment variables have been 180 used to affect the libraries loaded */ 181 bool ld_bind_not; /* Disable PLT update */ 182 static char *ld_bind_now; /* Environment variable for immediate binding */ 183 static char *ld_debug; /* Environment variable for debugging */ 184 static char *ld_library_path; /* Environment variable for search path */ 185 static char *ld_library_dirs; /* Environment variable for library descriptors */ 186 static char *ld_preload; /* Environment variable for libraries to 187 load first */ 188 static char *ld_elf_hints_path; /* Environment variable for alternative hints path */ 189 static char *ld_tracing; /* Called from ldd to print libs */ 190 static char *ld_utrace; /* Use utrace() to log events. */ 191 static struct obj_entry_q obj_list; /* Queue of all loaded objects */ 192 static Obj_Entry *obj_main; /* The main program shared object */ 193 static Obj_Entry obj_rtld; /* The dynamic linker shared object */ 194 static unsigned int obj_count; /* Number of objects in obj_list */ 195 static unsigned int obj_loads; /* Number of loads of objects (gen count) */ 196 197 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */ 198 STAILQ_HEAD_INITIALIZER(list_global); 199 static Objlist list_main = /* Objects loaded at program startup */ 200 STAILQ_HEAD_INITIALIZER(list_main); 201 static Objlist list_fini = /* Objects needing fini() calls */ 202 STAILQ_HEAD_INITIALIZER(list_fini); 203 204 Elf_Sym sym_zero; /* For resolving undefined weak refs. */ 205 206 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m); 207 208 extern Elf_Dyn _DYNAMIC; 209 #pragma weak _DYNAMIC 210 211 int dlclose(void *) __exported; 212 char *dlerror(void) __exported; 213 void *dlopen(const char *, int) __exported; 214 void *fdlopen(int, int) __exported; 215 void *dlsym(void *, const char *) __exported; 216 dlfunc_t dlfunc(void *, const char *) __exported; 217 void *dlvsym(void *, const char *, const char *) __exported; 218 int dladdr(const void *, Dl_info *) __exported; 219 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *), 220 void (*)(void *), void (*)(void *), void (*)(void *)) __exported; 221 int dlinfo(void *, int , void *) __exported; 222 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported; 223 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported; 224 int _rtld_get_stack_prot(void) __exported; 225 int _rtld_is_dlopened(void *) __exported; 226 void _rtld_error(const char *, ...) __exported; 227 228 int npagesizes, osreldate; 229 size_t *pagesizes; 230 231 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0}; 232 233 static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC; 234 static int max_stack_flags; 235 236 /* 237 * Global declarations normally provided by crt1. The dynamic linker is 238 * not built with crt1, so we have to provide them ourselves. 239 */ 240 char *__progname; 241 char **environ; 242 243 /* 244 * Used to pass argc, argv to init functions. 245 */ 246 int main_argc; 247 char **main_argv; 248 249 /* 250 * Globals to control TLS allocation. 251 */ 252 size_t tls_last_offset; /* Static TLS offset of last module */ 253 size_t tls_last_size; /* Static TLS size of last module */ 254 size_t tls_static_space; /* Static TLS space allocated */ 255 size_t tls_static_max_align; 256 int tls_dtv_generation = 1; /* Used to detect when dtv size changes */ 257 int tls_max_index = 1; /* Largest module index allocated */ 258 259 bool ld_library_path_rpath = false; 260 261 /* 262 * Globals for path names, and such 263 */ 264 char *ld_elf_hints_default = _PATH_ELF_HINTS; 265 char *ld_path_libmap_conf = _PATH_LIBMAP_CONF; 266 char *ld_path_rtld = _PATH_RTLD; 267 char *ld_standard_library_path = STANDARD_LIBRARY_PATH; 268 char *ld_env_prefix = LD_; 269 270 /* 271 * Fill in a DoneList with an allocation large enough to hold all of 272 * the currently-loaded objects. Keep this as a macro since it calls 273 * alloca and we want that to occur within the scope of the caller. 274 */ 275 #define donelist_init(dlp) \ 276 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \ 277 assert((dlp)->objs != NULL), \ 278 (dlp)->num_alloc = obj_count, \ 279 (dlp)->num_used = 0) 280 281 #define LD_UTRACE(e, h, mb, ms, r, n) do { \ 282 if (ld_utrace != NULL) \ 283 ld_utrace_log(e, h, mb, ms, r, n); \ 284 } while (0) 285 286 static void 287 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize, 288 int refcnt, const char *name) 289 { 290 struct utrace_rtld ut; 291 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG; 292 293 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig)); 294 ut.event = event; 295 ut.handle = handle; 296 ut.mapbase = mapbase; 297 ut.mapsize = mapsize; 298 ut.refcnt = refcnt; 299 bzero(ut.name, sizeof(ut.name)); 300 if (name) 301 strlcpy(ut.name, name, sizeof(ut.name)); 302 utrace(&ut, sizeof(ut)); 303 } 304 305 #ifdef RTLD_VARIANT_ENV_NAMES 306 /* 307 * construct the env variable based on the type of binary that's 308 * running. 309 */ 310 static inline const char * 311 _LD(const char *var) 312 { 313 static char buffer[128]; 314 315 strlcpy(buffer, ld_env_prefix, sizeof(buffer)); 316 strlcat(buffer, var, sizeof(buffer)); 317 return (buffer); 318 } 319 #else 320 #define _LD(x) LD_ x 321 #endif 322 323 /* 324 * Main entry point for dynamic linking. The first argument is the 325 * stack pointer. The stack is expected to be laid out as described 326 * in the SVR4 ABI specification, Intel 386 Processor Supplement. 327 * Specifically, the stack pointer points to a word containing 328 * ARGC. Following that in the stack is a null-terminated sequence 329 * of pointers to argument strings. Then comes a null-terminated 330 * sequence of pointers to environment strings. Finally, there is a 331 * sequence of "auxiliary vector" entries. 332 * 333 * The second argument points to a place to store the dynamic linker's 334 * exit procedure pointer and the third to a place to store the main 335 * program's object. 336 * 337 * The return value is the main program's entry point. 338 */ 339 func_ptr_type 340 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) 341 { 342 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT]; 343 Objlist_Entry *entry; 344 Obj_Entry *last_interposer, *obj, *preload_tail; 345 const Elf_Phdr *phdr; 346 Objlist initlist; 347 RtldLockState lockstate; 348 Elf_Addr *argcp; 349 char **argv, *argv0, **env, **envp, *kexecpath, *library_path_rpath; 350 caddr_t imgentry; 351 char buf[MAXPATHLEN]; 352 int argc, fd, i, mib[2], phnum; 353 size_t len; 354 355 /* 356 * On entry, the dynamic linker itself has not been relocated yet. 357 * Be very careful not to reference any global data until after 358 * init_rtld has returned. It is OK to reference file-scope statics 359 * and string constants, and to call static and global functions. 360 */ 361 362 /* Find the auxiliary vector on the stack. */ 363 argcp = sp; 364 argc = *sp++; 365 argv = (char **) sp; 366 sp += argc + 1; /* Skip over arguments and NULL terminator */ 367 env = (char **) sp; 368 while (*sp++ != 0) /* Skip over environment, and NULL terminator */ 369 ; 370 aux = (Elf_Auxinfo *) sp; 371 372 /* Digest the auxiliary vector. */ 373 for (i = 0; i < AT_COUNT; i++) 374 aux_info[i] = NULL; 375 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { 376 if (auxp->a_type < AT_COUNT) 377 aux_info[auxp->a_type] = auxp; 378 } 379 380 /* Initialize and relocate ourselves. */ 381 assert(aux_info[AT_BASE] != NULL); 382 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info); 383 384 __progname = obj_rtld.path; 385 argv0 = argv[0] != NULL ? argv[0] : "(null)"; 386 environ = env; 387 main_argc = argc; 388 main_argv = argv; 389 390 if (aux_info[AT_CANARY] != NULL && 391 aux_info[AT_CANARY]->a_un.a_ptr != NULL) { 392 i = aux_info[AT_CANARYLEN]->a_un.a_val; 393 if (i > sizeof(__stack_chk_guard)) 394 i = sizeof(__stack_chk_guard); 395 memcpy(__stack_chk_guard, aux_info[AT_CANARY]->a_un.a_ptr, i); 396 } else { 397 mib[0] = CTL_KERN; 398 mib[1] = KERN_ARND; 399 400 len = sizeof(__stack_chk_guard); 401 if (sysctl(mib, 2, __stack_chk_guard, &len, NULL, 0) == -1 || 402 len != sizeof(__stack_chk_guard)) { 403 /* If sysctl was unsuccessful, use the "terminator canary". */ 404 ((unsigned char *)(void *)__stack_chk_guard)[0] = 0; 405 ((unsigned char *)(void *)__stack_chk_guard)[1] = 0; 406 ((unsigned char *)(void *)__stack_chk_guard)[2] = '\n'; 407 ((unsigned char *)(void *)__stack_chk_guard)[3] = 255; 408 } 409 } 410 411 trust = !issetugid(); 412 413 md_abi_variant_hook(aux_info); 414 415 fd = -1; 416 if (aux_info[AT_EXECFD] != NULL) { 417 fd = aux_info[AT_EXECFD]->a_un.a_val; 418 } else { 419 assert(aux_info[AT_PHDR] != NULL); 420 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr; 421 if (phdr == obj_rtld.phdr) { 422 dbg("opening main program in direct exec mode"); 423 if (argc >= 2) { 424 argv0 = argv[1]; 425 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY); 426 if (fd == -1) { 427 rtld_printf("Opening %s: %s\n", argv0, 428 rtld_strerror(errno)); 429 rtld_die(); 430 } 431 432 /* 433 * For direct exec mode, argv[0] is the interpreter 434 * name, we must remove it and shift arguments left by 435 * 1 before invoking binary main. Since stack layout 436 * places environment pointers and aux vectors right 437 * after the terminating NULL, we must shift 438 * environment and aux as well. 439 * XXX Shift will be > 1 when options are implemented. 440 */ 441 do { 442 *argv = *(argv + 1); 443 argv++; 444 } while (*argv != NULL); 445 *argcp -= 1; 446 main_argc = argc - 1; 447 environ = env = envp = argv; 448 do { 449 *envp = *(envp + 1); 450 envp++; 451 } while (*envp != NULL); 452 aux = auxp = (Elf_Auxinfo *)envp; 453 auxpf = (Elf_Auxinfo *)(envp + 1); 454 for (;; auxp++, auxpf++) { 455 *auxp = *auxpf; 456 if (auxp->a_type == AT_NULL) 457 break; 458 } 459 } else { 460 rtld_printf("no binary\n"); 461 rtld_die(); 462 } 463 } 464 } 465 466 ld_bind_now = getenv(_LD("BIND_NOW")); 467 468 /* 469 * If the process is tainted, then we un-set the dangerous environment 470 * variables. The process will be marked as tainted until setuid(2) 471 * is called. If any child process calls setuid(2) we do not want any 472 * future processes to honor the potentially un-safe variables. 473 */ 474 if (!trust) { 475 if (unsetenv(_LD("PRELOAD")) || unsetenv(_LD("LIBMAP")) || 476 unsetenv(_LD("LIBRARY_PATH")) || unsetenv(_LD("LIBRARY_PATH_FDS")) || 477 unsetenv(_LD("LIBMAP_DISABLE")) || unsetenv(_LD("BIND_NOT")) || 478 unsetenv(_LD("DEBUG")) || unsetenv(_LD("ELF_HINTS_PATH")) || 479 unsetenv(_LD("LOADFLTR")) || unsetenv(_LD("LIBRARY_PATH_RPATH"))) { 480 _rtld_error("environment corrupt; aborting"); 481 rtld_die(); 482 } 483 } 484 ld_debug = getenv(_LD("DEBUG")); 485 if (ld_bind_now == NULL) 486 ld_bind_not = getenv(_LD("BIND_NOT")) != NULL; 487 libmap_disable = getenv(_LD("LIBMAP_DISABLE")) != NULL; 488 libmap_override = getenv(_LD("LIBMAP")); 489 ld_library_path = getenv(_LD("LIBRARY_PATH")); 490 ld_library_dirs = getenv(_LD("LIBRARY_PATH_FDS")); 491 ld_preload = getenv(_LD("PRELOAD")); 492 ld_elf_hints_path = getenv(_LD("ELF_HINTS_PATH")); 493 ld_loadfltr = getenv(_LD("LOADFLTR")) != NULL; 494 library_path_rpath = getenv(_LD("LIBRARY_PATH_RPATH")); 495 if (library_path_rpath != NULL) { 496 if (library_path_rpath[0] == 'y' || 497 library_path_rpath[0] == 'Y' || 498 library_path_rpath[0] == '1') 499 ld_library_path_rpath = true; 500 else 501 ld_library_path_rpath = false; 502 } 503 dangerous_ld_env = libmap_disable || (libmap_override != NULL) || 504 (ld_library_path != NULL) || (ld_preload != NULL) || 505 (ld_elf_hints_path != NULL) || ld_loadfltr; 506 ld_tracing = getenv(_LD("TRACE_LOADED_OBJECTS")); 507 ld_utrace = getenv(_LD("UTRACE")); 508 509 if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0) 510 ld_elf_hints_path = ld_elf_hints_default; 511 512 if (ld_debug != NULL && *ld_debug != '\0') 513 debug = 1; 514 dbg("%s is initialized, base address = %p", __progname, 515 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr); 516 dbg("RTLD dynamic = %p", obj_rtld.dynamic); 517 dbg("RTLD pltgot = %p", obj_rtld.pltgot); 518 519 dbg("initializing thread locks"); 520 lockdflt_init(); 521 522 /* 523 * Load the main program, or process its program header if it is 524 * already loaded. 525 */ 526 if (fd != -1) { /* Load the main program. */ 527 dbg("loading main program"); 528 obj_main = map_object(fd, argv0, NULL); 529 close(fd); 530 if (obj_main == NULL) 531 rtld_die(); 532 max_stack_flags = obj->stack_flags; 533 } else { /* Main program already loaded. */ 534 dbg("processing main program's program header"); 535 assert(aux_info[AT_PHDR] != NULL); 536 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr; 537 assert(aux_info[AT_PHNUM] != NULL); 538 phnum = aux_info[AT_PHNUM]->a_un.a_val; 539 assert(aux_info[AT_PHENT] != NULL); 540 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr)); 541 assert(aux_info[AT_ENTRY] != NULL); 542 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr; 543 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL) 544 rtld_die(); 545 } 546 547 if (aux_info[AT_EXECPATH] != NULL && fd == -1) { 548 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr; 549 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath); 550 if (kexecpath[0] == '/') 551 obj_main->path = kexecpath; 552 else if (getcwd(buf, sizeof(buf)) == NULL || 553 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) || 554 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf)) 555 obj_main->path = xstrdup(argv0); 556 else 557 obj_main->path = xstrdup(buf); 558 } else { 559 dbg("No AT_EXECPATH or direct exec"); 560 obj_main->path = xstrdup(argv0); 561 } 562 dbg("obj_main path %s", obj_main->path); 563 obj_main->mainprog = true; 564 565 if (aux_info[AT_STACKPROT] != NULL && 566 aux_info[AT_STACKPROT]->a_un.a_val != 0) 567 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val; 568 569 #ifndef COMPAT_32BIT 570 /* 571 * Get the actual dynamic linker pathname from the executable if 572 * possible. (It should always be possible.) That ensures that 573 * gdb will find the right dynamic linker even if a non-standard 574 * one is being used. 575 */ 576 if (obj_main->interp != NULL && 577 strcmp(obj_main->interp, obj_rtld.path) != 0) { 578 free(obj_rtld.path); 579 obj_rtld.path = xstrdup(obj_main->interp); 580 __progname = obj_rtld.path; 581 } 582 #endif 583 584 digest_dynamic(obj_main, 0); 585 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", 586 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu, 587 obj_main->dynsymcount); 588 589 linkmap_add(obj_main); 590 linkmap_add(&obj_rtld); 591 592 /* Link the main program into the list of objects. */ 593 TAILQ_INSERT_HEAD(&obj_list, obj_main, next); 594 obj_count++; 595 obj_loads++; 596 597 /* Initialize a fake symbol for resolving undefined weak references. */ 598 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE); 599 sym_zero.st_shndx = SHN_UNDEF; 600 sym_zero.st_value = -(uintptr_t)obj_main->relocbase; 601 602 if (!libmap_disable) 603 libmap_disable = (bool)lm_init(libmap_override); 604 605 dbg("loading LD_PRELOAD libraries"); 606 if (load_preload_objects() == -1) 607 rtld_die(); 608 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q)); 609 610 dbg("loading needed objects"); 611 if (load_needed_objects(obj_main, 0) == -1) 612 rtld_die(); 613 614 /* Make a list of all objects loaded at startup. */ 615 last_interposer = obj_main; 616 TAILQ_FOREACH(obj, &obj_list, next) { 617 if (obj->marker) 618 continue; 619 if (obj->z_interpose && obj != obj_main) { 620 objlist_put_after(&list_main, last_interposer, obj); 621 last_interposer = obj; 622 } else { 623 objlist_push_tail(&list_main, obj); 624 } 625 obj->refcount++; 626 } 627 628 dbg("checking for required versions"); 629 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing) 630 rtld_die(); 631 632 if (ld_tracing) { /* We're done */ 633 trace_loaded_objects(obj_main); 634 exit(0); 635 } 636 637 if (getenv(_LD("DUMP_REL_PRE")) != NULL) { 638 dump_relocations(obj_main); 639 exit (0); 640 } 641 642 /* 643 * Processing tls relocations requires having the tls offsets 644 * initialized. Prepare offsets before starting initial 645 * relocation processing. 646 */ 647 dbg("initializing initial thread local storage offsets"); 648 STAILQ_FOREACH(entry, &list_main, link) { 649 /* 650 * Allocate all the initial objects out of the static TLS 651 * block even if they didn't ask for it. 652 */ 653 allocate_tls_offset(entry->obj); 654 } 655 656 if (relocate_objects(obj_main, 657 ld_bind_now != NULL && *ld_bind_now != '\0', 658 &obj_rtld, SYMLOOK_EARLY, NULL) == -1) 659 rtld_die(); 660 661 dbg("doing copy relocations"); 662 if (do_copy_relocations(obj_main) == -1) 663 rtld_die(); 664 665 dbg("enforcing main obj relro"); 666 if (obj_enforce_relro(obj_main) == -1) 667 rtld_die(); 668 669 if (getenv(_LD("DUMP_REL_POST")) != NULL) { 670 dump_relocations(obj_main); 671 exit (0); 672 } 673 674 /* 675 * Setup TLS for main thread. This must be done after the 676 * relocations are processed, since tls initialization section 677 * might be the subject for relocations. 678 */ 679 dbg("initializing initial thread local storage"); 680 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list))); 681 682 dbg("initializing key program variables"); 683 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : ""); 684 set_program_var("environ", env); 685 set_program_var("__elf_aux_vector", aux); 686 687 /* Make a list of init functions to call. */ 688 objlist_init(&initlist); 689 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)), 690 preload_tail, &initlist); 691 692 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */ 693 694 map_stacks_exec(NULL); 695 ifunc_init(aux); 696 697 dbg("resolving ifuncs"); 698 if (resolve_objects_ifunc(obj_main, 699 ld_bind_now != NULL && *ld_bind_now != '\0', SYMLOOK_EARLY, 700 NULL) == -1) 701 rtld_die(); 702 703 if (!obj_main->crt_no_init) { 704 /* 705 * Make sure we don't call the main program's init and fini 706 * functions for binaries linked with old crt1 which calls 707 * _init itself. 708 */ 709 obj_main->init = obj_main->fini = (Elf_Addr)NULL; 710 obj_main->preinit_array = obj_main->init_array = 711 obj_main->fini_array = (Elf_Addr)NULL; 712 } 713 714 wlock_acquire(rtld_bind_lock, &lockstate); 715 if (obj_main->crt_no_init) 716 preinit_main(); 717 objlist_call_init(&initlist, &lockstate); 718 _r_debug_postinit(&obj_main->linkmap); 719 objlist_clear(&initlist); 720 dbg("loading filtees"); 721 TAILQ_FOREACH(obj, &obj_list, next) { 722 if (obj->marker) 723 continue; 724 if (ld_loadfltr || obj->z_loadfltr) 725 load_filtees(obj, 0, &lockstate); 726 } 727 lock_release(rtld_bind_lock, &lockstate); 728 729 dbg("transferring control to program entry point = %p", obj_main->entry); 730 731 /* Return the exit procedure and the program entry point. */ 732 *exit_proc = rtld_exit; 733 *objp = obj_main; 734 return (func_ptr_type) obj_main->entry; 735 } 736 737 void * 738 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def) 739 { 740 void *ptr; 741 Elf_Addr target; 742 743 ptr = (void *)make_function_pointer(def, obj); 744 target = call_ifunc_resolver(ptr); 745 return ((void *)target); 746 } 747 748 /* 749 * NB: MIPS uses a private version of this function (_mips_rtld_bind). 750 * Changes to this function should be applied there as well. 751 */ 752 Elf_Addr 753 _rtld_bind(Obj_Entry *obj, Elf_Size reloff) 754 { 755 const Elf_Rel *rel; 756 const Elf_Sym *def; 757 const Obj_Entry *defobj; 758 Elf_Addr *where; 759 Elf_Addr target; 760 RtldLockState lockstate; 761 762 rlock_acquire(rtld_bind_lock, &lockstate); 763 if (sigsetjmp(lockstate.env, 0) != 0) 764 lock_upgrade(rtld_bind_lock, &lockstate); 765 if (obj->pltrel) 766 rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff); 767 else 768 rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff); 769 770 where = (Elf_Addr *) (obj->relocbase + rel->r_offset); 771 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT, 772 NULL, &lockstate); 773 if (def == NULL) 774 rtld_die(); 775 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 776 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def); 777 else 778 target = (Elf_Addr)(defobj->relocbase + def->st_value); 779 780 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"", 781 defobj->strtab + def->st_name, basename(obj->path), 782 (void *)target, basename(defobj->path)); 783 784 /* 785 * Write the new contents for the jmpslot. Note that depending on 786 * architecture, the value which we need to return back to the 787 * lazy binding trampoline may or may not be the target 788 * address. The value returned from reloc_jmpslot() is the value 789 * that the trampoline needs. 790 */ 791 target = reloc_jmpslot(where, target, defobj, obj, rel); 792 lock_release(rtld_bind_lock, &lockstate); 793 return target; 794 } 795 796 /* 797 * Error reporting function. Use it like printf. If formats the message 798 * into a buffer, and sets things up so that the next call to dlerror() 799 * will return the message. 800 */ 801 void 802 _rtld_error(const char *fmt, ...) 803 { 804 static char buf[512]; 805 va_list ap; 806 807 va_start(ap, fmt); 808 rtld_vsnprintf(buf, sizeof buf, fmt, ap); 809 error_message = buf; 810 va_end(ap); 811 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, error_message); 812 } 813 814 /* 815 * Return a dynamically-allocated copy of the current error message, if any. 816 */ 817 static char * 818 errmsg_save(void) 819 { 820 return error_message == NULL ? NULL : xstrdup(error_message); 821 } 822 823 /* 824 * Restore the current error message from a copy which was previously saved 825 * by errmsg_save(). The copy is freed. 826 */ 827 static void 828 errmsg_restore(char *saved_msg) 829 { 830 if (saved_msg == NULL) 831 error_message = NULL; 832 else { 833 _rtld_error("%s", saved_msg); 834 free(saved_msg); 835 } 836 } 837 838 static const char * 839 basename(const char *name) 840 { 841 const char *p = strrchr(name, '/'); 842 return p != NULL ? p + 1 : name; 843 } 844 845 static struct utsname uts; 846 847 static char * 848 origin_subst_one(Obj_Entry *obj, char *real, const char *kw, 849 const char *subst, bool may_free) 850 { 851 char *p, *p1, *res, *resp; 852 int subst_len, kw_len, subst_count, old_len, new_len; 853 854 kw_len = strlen(kw); 855 856 /* 857 * First, count the number of the keyword occurrences, to 858 * preallocate the final string. 859 */ 860 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) { 861 p1 = strstr(p, kw); 862 if (p1 == NULL) 863 break; 864 } 865 866 /* 867 * If the keyword is not found, just return. 868 * 869 * Return non-substituted string if resolution failed. We 870 * cannot do anything more reasonable, the failure mode of the 871 * caller is unresolved library anyway. 872 */ 873 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj))) 874 return (may_free ? real : xstrdup(real)); 875 if (obj != NULL) 876 subst = obj->origin_path; 877 878 /* 879 * There is indeed something to substitute. Calculate the 880 * length of the resulting string, and allocate it. 881 */ 882 subst_len = strlen(subst); 883 old_len = strlen(real); 884 new_len = old_len + (subst_len - kw_len) * subst_count; 885 res = xmalloc(new_len + 1); 886 887 /* 888 * Now, execute the substitution loop. 889 */ 890 for (p = real, resp = res, *resp = '\0';;) { 891 p1 = strstr(p, kw); 892 if (p1 != NULL) { 893 /* Copy the prefix before keyword. */ 894 memcpy(resp, p, p1 - p); 895 resp += p1 - p; 896 /* Keyword replacement. */ 897 memcpy(resp, subst, subst_len); 898 resp += subst_len; 899 *resp = '\0'; 900 p = p1 + kw_len; 901 } else 902 break; 903 } 904 905 /* Copy to the end of string and finish. */ 906 strcat(resp, p); 907 if (may_free) 908 free(real); 909 return (res); 910 } 911 912 static char * 913 origin_subst(Obj_Entry *obj, char *real) 914 { 915 char *res1, *res2, *res3, *res4; 916 917 if (obj == NULL || !trust) 918 return (xstrdup(real)); 919 if (uts.sysname[0] == '\0') { 920 if (uname(&uts) != 0) { 921 _rtld_error("utsname failed: %d", errno); 922 return (NULL); 923 } 924 } 925 res1 = origin_subst_one(obj, real, "$ORIGIN", NULL, false); 926 res2 = origin_subst_one(NULL, res1, "$OSNAME", uts.sysname, true); 927 res3 = origin_subst_one(NULL, res2, "$OSREL", uts.release, true); 928 res4 = origin_subst_one(NULL, res3, "$PLATFORM", uts.machine, true); 929 return (res4); 930 } 931 932 void 933 rtld_die(void) 934 { 935 const char *msg = dlerror(); 936 937 if (msg == NULL) 938 msg = "Fatal error"; 939 rtld_fdputstr(STDERR_FILENO, msg); 940 rtld_fdputchar(STDERR_FILENO, '\n'); 941 _exit(1); 942 } 943 944 /* 945 * Process a shared object's DYNAMIC section, and save the important 946 * information in its Obj_Entry structure. 947 */ 948 static void 949 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath, 950 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath) 951 { 952 const Elf_Dyn *dynp; 953 Needed_Entry **needed_tail = &obj->needed; 954 Needed_Entry **needed_filtees_tail = &obj->needed_filtees; 955 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees; 956 const Elf_Hashelt *hashtab; 957 const Elf32_Word *hashval; 958 Elf32_Word bkt, nmaskwords; 959 int bloom_size32; 960 int plttype = DT_REL; 961 962 *dyn_rpath = NULL; 963 *dyn_soname = NULL; 964 *dyn_runpath = NULL; 965 966 obj->bind_now = false; 967 for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) { 968 switch (dynp->d_tag) { 969 970 case DT_REL: 971 obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr); 972 break; 973 974 case DT_RELSZ: 975 obj->relsize = dynp->d_un.d_val; 976 break; 977 978 case DT_RELENT: 979 assert(dynp->d_un.d_val == sizeof(Elf_Rel)); 980 break; 981 982 case DT_JMPREL: 983 obj->pltrel = (const Elf_Rel *) 984 (obj->relocbase + dynp->d_un.d_ptr); 985 break; 986 987 case DT_PLTRELSZ: 988 obj->pltrelsize = dynp->d_un.d_val; 989 break; 990 991 case DT_RELA: 992 obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr); 993 break; 994 995 case DT_RELASZ: 996 obj->relasize = dynp->d_un.d_val; 997 break; 998 999 case DT_RELAENT: 1000 assert(dynp->d_un.d_val == sizeof(Elf_Rela)); 1001 break; 1002 1003 case DT_PLTREL: 1004 plttype = dynp->d_un.d_val; 1005 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA); 1006 break; 1007 1008 case DT_SYMTAB: 1009 obj->symtab = (const Elf_Sym *) 1010 (obj->relocbase + dynp->d_un.d_ptr); 1011 break; 1012 1013 case DT_SYMENT: 1014 assert(dynp->d_un.d_val == sizeof(Elf_Sym)); 1015 break; 1016 1017 case DT_STRTAB: 1018 obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr); 1019 break; 1020 1021 case DT_STRSZ: 1022 obj->strsize = dynp->d_un.d_val; 1023 break; 1024 1025 case DT_VERNEED: 1026 obj->verneed = (const Elf_Verneed *) (obj->relocbase + 1027 dynp->d_un.d_val); 1028 break; 1029 1030 case DT_VERNEEDNUM: 1031 obj->verneednum = dynp->d_un.d_val; 1032 break; 1033 1034 case DT_VERDEF: 1035 obj->verdef = (const Elf_Verdef *) (obj->relocbase + 1036 dynp->d_un.d_val); 1037 break; 1038 1039 case DT_VERDEFNUM: 1040 obj->verdefnum = dynp->d_un.d_val; 1041 break; 1042 1043 case DT_VERSYM: 1044 obj->versyms = (const Elf_Versym *)(obj->relocbase + 1045 dynp->d_un.d_val); 1046 break; 1047 1048 case DT_HASH: 1049 { 1050 hashtab = (const Elf_Hashelt *)(obj->relocbase + 1051 dynp->d_un.d_ptr); 1052 obj->nbuckets = hashtab[0]; 1053 obj->nchains = hashtab[1]; 1054 obj->buckets = hashtab + 2; 1055 obj->chains = obj->buckets + obj->nbuckets; 1056 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 && 1057 obj->buckets != NULL; 1058 } 1059 break; 1060 1061 case DT_GNU_HASH: 1062 { 1063 hashtab = (const Elf_Hashelt *)(obj->relocbase + 1064 dynp->d_un.d_ptr); 1065 obj->nbuckets_gnu = hashtab[0]; 1066 obj->symndx_gnu = hashtab[1]; 1067 nmaskwords = hashtab[2]; 1068 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords; 1069 obj->maskwords_bm_gnu = nmaskwords - 1; 1070 obj->shift2_gnu = hashtab[3]; 1071 obj->bloom_gnu = (Elf_Addr *) (hashtab + 4); 1072 obj->buckets_gnu = hashtab + 4 + bloom_size32; 1073 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu - 1074 obj->symndx_gnu; 1075 /* Number of bitmask words is required to be power of 2 */ 1076 obj->valid_hash_gnu = powerof2(nmaskwords) && 1077 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL; 1078 } 1079 break; 1080 1081 case DT_NEEDED: 1082 if (!obj->rtld) { 1083 Needed_Entry *nep = NEW(Needed_Entry); 1084 nep->name = dynp->d_un.d_val; 1085 nep->obj = NULL; 1086 nep->next = NULL; 1087 1088 *needed_tail = nep; 1089 needed_tail = &nep->next; 1090 } 1091 break; 1092 1093 case DT_FILTER: 1094 if (!obj->rtld) { 1095 Needed_Entry *nep = NEW(Needed_Entry); 1096 nep->name = dynp->d_un.d_val; 1097 nep->obj = NULL; 1098 nep->next = NULL; 1099 1100 *needed_filtees_tail = nep; 1101 needed_filtees_tail = &nep->next; 1102 } 1103 break; 1104 1105 case DT_AUXILIARY: 1106 if (!obj->rtld) { 1107 Needed_Entry *nep = NEW(Needed_Entry); 1108 nep->name = dynp->d_un.d_val; 1109 nep->obj = NULL; 1110 nep->next = NULL; 1111 1112 *needed_aux_filtees_tail = nep; 1113 needed_aux_filtees_tail = &nep->next; 1114 } 1115 break; 1116 1117 case DT_PLTGOT: 1118 obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr); 1119 break; 1120 1121 case DT_TEXTREL: 1122 obj->textrel = true; 1123 break; 1124 1125 case DT_SYMBOLIC: 1126 obj->symbolic = true; 1127 break; 1128 1129 case DT_RPATH: 1130 /* 1131 * We have to wait until later to process this, because we 1132 * might not have gotten the address of the string table yet. 1133 */ 1134 *dyn_rpath = dynp; 1135 break; 1136 1137 case DT_SONAME: 1138 *dyn_soname = dynp; 1139 break; 1140 1141 case DT_RUNPATH: 1142 *dyn_runpath = dynp; 1143 break; 1144 1145 case DT_INIT: 1146 obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 1147 break; 1148 1149 case DT_PREINIT_ARRAY: 1150 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1151 break; 1152 1153 case DT_PREINIT_ARRAYSZ: 1154 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr); 1155 break; 1156 1157 case DT_INIT_ARRAY: 1158 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1159 break; 1160 1161 case DT_INIT_ARRAYSZ: 1162 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr); 1163 break; 1164 1165 case DT_FINI: 1166 obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 1167 break; 1168 1169 case DT_FINI_ARRAY: 1170 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1171 break; 1172 1173 case DT_FINI_ARRAYSZ: 1174 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr); 1175 break; 1176 1177 /* 1178 * Don't process DT_DEBUG on MIPS as the dynamic section 1179 * is mapped read-only. DT_MIPS_RLD_MAP is used instead. 1180 */ 1181 1182 #ifndef __mips__ 1183 case DT_DEBUG: 1184 if (!early) 1185 dbg("Filling in DT_DEBUG entry"); 1186 ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug; 1187 break; 1188 #endif 1189 1190 case DT_FLAGS: 1191 if (dynp->d_un.d_val & DF_ORIGIN) 1192 obj->z_origin = true; 1193 if (dynp->d_un.d_val & DF_SYMBOLIC) 1194 obj->symbolic = true; 1195 if (dynp->d_un.d_val & DF_TEXTREL) 1196 obj->textrel = true; 1197 if (dynp->d_un.d_val & DF_BIND_NOW) 1198 obj->bind_now = true; 1199 /*if (dynp->d_un.d_val & DF_STATIC_TLS) 1200 ;*/ 1201 break; 1202 #ifdef __mips__ 1203 case DT_MIPS_LOCAL_GOTNO: 1204 obj->local_gotno = dynp->d_un.d_val; 1205 break; 1206 1207 case DT_MIPS_SYMTABNO: 1208 obj->symtabno = dynp->d_un.d_val; 1209 break; 1210 1211 case DT_MIPS_GOTSYM: 1212 obj->gotsym = dynp->d_un.d_val; 1213 break; 1214 1215 case DT_MIPS_RLD_MAP: 1216 *((Elf_Addr *)(dynp->d_un.d_ptr)) = (Elf_Addr) &r_debug; 1217 break; 1218 #endif 1219 1220 #ifdef __powerpc64__ 1221 case DT_PPC64_GLINK: 1222 obj->glink = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); 1223 break; 1224 #endif 1225 1226 case DT_FLAGS_1: 1227 if (dynp->d_un.d_val & DF_1_NOOPEN) 1228 obj->z_noopen = true; 1229 if (dynp->d_un.d_val & DF_1_ORIGIN) 1230 obj->z_origin = true; 1231 if (dynp->d_un.d_val & DF_1_GLOBAL) 1232 obj->z_global = true; 1233 if (dynp->d_un.d_val & DF_1_BIND_NOW) 1234 obj->bind_now = true; 1235 if (dynp->d_un.d_val & DF_1_NODELETE) 1236 obj->z_nodelete = true; 1237 if (dynp->d_un.d_val & DF_1_LOADFLTR) 1238 obj->z_loadfltr = true; 1239 if (dynp->d_un.d_val & DF_1_INTERPOSE) 1240 obj->z_interpose = true; 1241 if (dynp->d_un.d_val & DF_1_NODEFLIB) 1242 obj->z_nodeflib = true; 1243 break; 1244 1245 default: 1246 if (!early) { 1247 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag, 1248 (long)dynp->d_tag); 1249 } 1250 break; 1251 } 1252 } 1253 1254 obj->traced = false; 1255 1256 if (plttype == DT_RELA) { 1257 obj->pltrela = (const Elf_Rela *) obj->pltrel; 1258 obj->pltrel = NULL; 1259 obj->pltrelasize = obj->pltrelsize; 1260 obj->pltrelsize = 0; 1261 } 1262 1263 /* Determine size of dynsym table (equal to nchains of sysv hash) */ 1264 if (obj->valid_hash_sysv) 1265 obj->dynsymcount = obj->nchains; 1266 else if (obj->valid_hash_gnu) { 1267 obj->dynsymcount = 0; 1268 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) { 1269 if (obj->buckets_gnu[bkt] == 0) 1270 continue; 1271 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]]; 1272 do 1273 obj->dynsymcount++; 1274 while ((*hashval++ & 1u) == 0); 1275 } 1276 obj->dynsymcount += obj->symndx_gnu; 1277 } 1278 } 1279 1280 static bool 1281 obj_resolve_origin(Obj_Entry *obj) 1282 { 1283 1284 if (obj->origin_path != NULL) 1285 return (true); 1286 obj->origin_path = xmalloc(PATH_MAX); 1287 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1); 1288 } 1289 1290 static void 1291 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath, 1292 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath) 1293 { 1294 1295 if (obj->z_origin && !obj_resolve_origin(obj)) 1296 rtld_die(); 1297 1298 if (dyn_runpath != NULL) { 1299 obj->runpath = (char *)obj->strtab + dyn_runpath->d_un.d_val; 1300 obj->runpath = origin_subst(obj, obj->runpath); 1301 } else if (dyn_rpath != NULL) { 1302 obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val; 1303 obj->rpath = origin_subst(obj, obj->rpath); 1304 } 1305 if (dyn_soname != NULL) 1306 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val); 1307 } 1308 1309 static void 1310 digest_dynamic(Obj_Entry *obj, int early) 1311 { 1312 const Elf_Dyn *dyn_rpath; 1313 const Elf_Dyn *dyn_soname; 1314 const Elf_Dyn *dyn_runpath; 1315 1316 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath); 1317 digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath); 1318 } 1319 1320 /* 1321 * Process a shared object's program header. This is used only for the 1322 * main program, when the kernel has already loaded the main program 1323 * into memory before calling the dynamic linker. It creates and 1324 * returns an Obj_Entry structure. 1325 */ 1326 static Obj_Entry * 1327 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path) 1328 { 1329 Obj_Entry *obj; 1330 const Elf_Phdr *phlimit = phdr + phnum; 1331 const Elf_Phdr *ph; 1332 Elf_Addr note_start, note_end; 1333 int nsegs = 0; 1334 1335 obj = obj_new(); 1336 for (ph = phdr; ph < phlimit; ph++) { 1337 if (ph->p_type != PT_PHDR) 1338 continue; 1339 1340 obj->phdr = phdr; 1341 obj->phsize = ph->p_memsz; 1342 obj->relocbase = (caddr_t)phdr - ph->p_vaddr; 1343 break; 1344 } 1345 1346 obj->stack_flags = PF_X | PF_R | PF_W; 1347 1348 for (ph = phdr; ph < phlimit; ph++) { 1349 switch (ph->p_type) { 1350 1351 case PT_INTERP: 1352 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase); 1353 break; 1354 1355 case PT_LOAD: 1356 if (nsegs == 0) { /* First load segment */ 1357 obj->vaddrbase = trunc_page(ph->p_vaddr); 1358 obj->mapbase = obj->vaddrbase + obj->relocbase; 1359 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) - 1360 obj->vaddrbase; 1361 } else { /* Last load segment */ 1362 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) - 1363 obj->vaddrbase; 1364 } 1365 nsegs++; 1366 break; 1367 1368 case PT_DYNAMIC: 1369 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase); 1370 break; 1371 1372 case PT_TLS: 1373 obj->tlsindex = 1; 1374 obj->tlssize = ph->p_memsz; 1375 obj->tlsalign = ph->p_align; 1376 obj->tlsinitsize = ph->p_filesz; 1377 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase); 1378 break; 1379 1380 case PT_GNU_STACK: 1381 obj->stack_flags = ph->p_flags; 1382 break; 1383 1384 case PT_GNU_RELRO: 1385 obj->relro_page = obj->relocbase + trunc_page(ph->p_vaddr); 1386 obj->relro_size = round_page(ph->p_memsz); 1387 break; 1388 1389 case PT_NOTE: 1390 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr; 1391 note_end = note_start + ph->p_filesz; 1392 digest_notes(obj, note_start, note_end); 1393 break; 1394 } 1395 } 1396 if (nsegs < 1) { 1397 _rtld_error("%s: too few PT_LOAD segments", path); 1398 return NULL; 1399 } 1400 1401 obj->entry = entry; 1402 return obj; 1403 } 1404 1405 void 1406 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end) 1407 { 1408 const Elf_Note *note; 1409 const char *note_name; 1410 uintptr_t p; 1411 1412 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end; 1413 note = (const Elf_Note *)((const char *)(note + 1) + 1414 roundup2(note->n_namesz, sizeof(Elf32_Addr)) + 1415 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) { 1416 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) || 1417 note->n_descsz != sizeof(int32_t)) 1418 continue; 1419 if (note->n_type != NT_FREEBSD_ABI_TAG && 1420 note->n_type != NT_FREEBSD_NOINIT_TAG) 1421 continue; 1422 note_name = (const char *)(note + 1); 1423 if (strncmp(NOTE_FREEBSD_VENDOR, note_name, 1424 sizeof(NOTE_FREEBSD_VENDOR)) != 0) 1425 continue; 1426 switch (note->n_type) { 1427 case NT_FREEBSD_ABI_TAG: 1428 /* FreeBSD osrel note */ 1429 p = (uintptr_t)(note + 1); 1430 p += roundup2(note->n_namesz, sizeof(Elf32_Addr)); 1431 obj->osrel = *(const int32_t *)(p); 1432 dbg("note osrel %d", obj->osrel); 1433 break; 1434 case NT_FREEBSD_NOINIT_TAG: 1435 /* FreeBSD 'crt does not call init' note */ 1436 obj->crt_no_init = true; 1437 dbg("note crt_no_init"); 1438 break; 1439 } 1440 } 1441 } 1442 1443 static Obj_Entry * 1444 dlcheck(void *handle) 1445 { 1446 Obj_Entry *obj; 1447 1448 TAILQ_FOREACH(obj, &obj_list, next) { 1449 if (obj == (Obj_Entry *) handle) 1450 break; 1451 } 1452 1453 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) { 1454 _rtld_error("Invalid shared object handle %p", handle); 1455 return NULL; 1456 } 1457 return obj; 1458 } 1459 1460 /* 1461 * If the given object is already in the donelist, return true. Otherwise 1462 * add the object to the list and return false. 1463 */ 1464 static bool 1465 donelist_check(DoneList *dlp, const Obj_Entry *obj) 1466 { 1467 unsigned int i; 1468 1469 for (i = 0; i < dlp->num_used; i++) 1470 if (dlp->objs[i] == obj) 1471 return true; 1472 /* 1473 * Our donelist allocation should always be sufficient. But if 1474 * our threads locking isn't working properly, more shared objects 1475 * could have been loaded since we allocated the list. That should 1476 * never happen, but we'll handle it properly just in case it does. 1477 */ 1478 if (dlp->num_used < dlp->num_alloc) 1479 dlp->objs[dlp->num_used++] = obj; 1480 return false; 1481 } 1482 1483 /* 1484 * Hash function for symbol table lookup. Don't even think about changing 1485 * this. It is specified by the System V ABI. 1486 */ 1487 unsigned long 1488 elf_hash(const char *name) 1489 { 1490 const unsigned char *p = (const unsigned char *) name; 1491 unsigned long h = 0; 1492 unsigned long g; 1493 1494 while (*p != '\0') { 1495 h = (h << 4) + *p++; 1496 if ((g = h & 0xf0000000) != 0) 1497 h ^= g >> 24; 1498 h &= ~g; 1499 } 1500 return h; 1501 } 1502 1503 /* 1504 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits 1505 * unsigned in case it's implemented with a wider type. 1506 */ 1507 static uint32_t 1508 gnu_hash(const char *s) 1509 { 1510 uint32_t h; 1511 unsigned char c; 1512 1513 h = 5381; 1514 for (c = *s; c != '\0'; c = *++s) 1515 h = h * 33 + c; 1516 return (h & 0xffffffff); 1517 } 1518 1519 1520 /* 1521 * Find the library with the given name, and return its full pathname. 1522 * The returned string is dynamically allocated. Generates an error 1523 * message and returns NULL if the library cannot be found. 1524 * 1525 * If the second argument is non-NULL, then it refers to an already- 1526 * loaded shared object, whose library search path will be searched. 1527 * 1528 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its 1529 * descriptor (which is close-on-exec) will be passed out via the third 1530 * argument. 1531 * 1532 * The search order is: 1533 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1) 1534 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1) 1535 * LD_LIBRARY_PATH 1536 * DT_RUNPATH in the referencing file 1537 * ldconfig hints (if -z nodefaultlib, filter out default library directories 1538 * from list) 1539 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib 1540 * 1541 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined. 1542 */ 1543 static char * 1544 find_library(const char *xname, const Obj_Entry *refobj, int *fdp) 1545 { 1546 char *pathname; 1547 char *name; 1548 bool nodeflib, objgiven; 1549 1550 objgiven = refobj != NULL; 1551 if (strchr(xname, '/') != NULL) { /* Hard coded pathname */ 1552 if (xname[0] != '/' && !trust) { 1553 _rtld_error("Absolute pathname required for shared object \"%s\"", 1554 xname); 1555 return NULL; 1556 } 1557 return (origin_subst(__DECONST(Obj_Entry *, refobj), 1558 __DECONST(char *, xname))); 1559 } 1560 1561 if (libmap_disable || !objgiven || 1562 (name = lm_find(refobj->path, xname)) == NULL) 1563 name = (char *)xname; 1564 1565 dbg(" Searching for \"%s\"", name); 1566 1567 /* 1568 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall 1569 * back to pre-conforming behaviour if user requested so with 1570 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z 1571 * nodeflib. 1572 */ 1573 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) { 1574 if ((pathname = search_library_path(name, ld_library_path)) != NULL || 1575 (refobj != NULL && 1576 (pathname = search_library_path(name, refobj->rpath)) != NULL) || 1577 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL || 1578 (pathname = search_library_path(name, gethints(false))) != NULL || 1579 (pathname = search_library_path(name, ld_standard_library_path)) != NULL) 1580 return (pathname); 1581 } else { 1582 nodeflib = objgiven ? refobj->z_nodeflib : false; 1583 if ((objgiven && 1584 (pathname = search_library_path(name, refobj->rpath)) != NULL) || 1585 (objgiven && refobj->runpath == NULL && refobj != obj_main && 1586 (pathname = search_library_path(name, obj_main->rpath)) != NULL) || 1587 (pathname = search_library_path(name, ld_library_path)) != NULL || 1588 (objgiven && 1589 (pathname = search_library_path(name, refobj->runpath)) != NULL) || 1590 (pathname = search_library_pathfds(name, ld_library_dirs, fdp)) != NULL || 1591 (pathname = search_library_path(name, gethints(nodeflib))) != NULL || 1592 (objgiven && !nodeflib && 1593 (pathname = search_library_path(name, ld_standard_library_path)) != NULL)) 1594 return (pathname); 1595 } 1596 1597 if (objgiven && refobj->path != NULL) { 1598 _rtld_error("Shared object \"%s\" not found, required by \"%s\"", 1599 name, basename(refobj->path)); 1600 } else { 1601 _rtld_error("Shared object \"%s\" not found", name); 1602 } 1603 return NULL; 1604 } 1605 1606 /* 1607 * Given a symbol number in a referencing object, find the corresponding 1608 * definition of the symbol. Returns a pointer to the symbol, or NULL if 1609 * no definition was found. Returns a pointer to the Obj_Entry of the 1610 * defining object via the reference parameter DEFOBJ_OUT. 1611 */ 1612 const Elf_Sym * 1613 find_symdef(unsigned long symnum, const Obj_Entry *refobj, 1614 const Obj_Entry **defobj_out, int flags, SymCache *cache, 1615 RtldLockState *lockstate) 1616 { 1617 const Elf_Sym *ref; 1618 const Elf_Sym *def; 1619 const Obj_Entry *defobj; 1620 SymLook req; 1621 const char *name; 1622 int res; 1623 1624 /* 1625 * If we have already found this symbol, get the information from 1626 * the cache. 1627 */ 1628 if (symnum >= refobj->dynsymcount) 1629 return NULL; /* Bad object */ 1630 if (cache != NULL && cache[symnum].sym != NULL) { 1631 *defobj_out = cache[symnum].obj; 1632 return cache[symnum].sym; 1633 } 1634 1635 ref = refobj->symtab + symnum; 1636 name = refobj->strtab + ref->st_name; 1637 def = NULL; 1638 defobj = NULL; 1639 1640 /* 1641 * We don't have to do a full scale lookup if the symbol is local. 1642 * We know it will bind to the instance in this load module; to 1643 * which we already have a pointer (ie ref). By not doing a lookup, 1644 * we not only improve performance, but it also avoids unresolvable 1645 * symbols when local symbols are not in the hash table. This has 1646 * been seen with the ia64 toolchain. 1647 */ 1648 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) { 1649 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) { 1650 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path, 1651 symnum); 1652 } 1653 symlook_init(&req, name); 1654 req.flags = flags; 1655 req.ventry = fetch_ventry(refobj, symnum); 1656 req.lockstate = lockstate; 1657 res = symlook_default(&req, refobj); 1658 if (res == 0) { 1659 def = req.sym_out; 1660 defobj = req.defobj_out; 1661 } 1662 } else { 1663 def = ref; 1664 defobj = refobj; 1665 } 1666 1667 /* 1668 * If we found no definition and the reference is weak, treat the 1669 * symbol as having the value zero. 1670 */ 1671 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) { 1672 def = &sym_zero; 1673 defobj = obj_main; 1674 } 1675 1676 if (def != NULL) { 1677 *defobj_out = defobj; 1678 /* Record the information in the cache to avoid subsequent lookups. */ 1679 if (cache != NULL) { 1680 cache[symnum].sym = def; 1681 cache[symnum].obj = defobj; 1682 } 1683 } else { 1684 if (refobj != &obj_rtld) 1685 _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name); 1686 } 1687 return def; 1688 } 1689 1690 /* 1691 * Return the search path from the ldconfig hints file, reading it if 1692 * necessary. If nostdlib is true, then the default search paths are 1693 * not added to result. 1694 * 1695 * Returns NULL if there are problems with the hints file, 1696 * or if the search path there is empty. 1697 */ 1698 static const char * 1699 gethints(bool nostdlib) 1700 { 1701 static char *hints, *filtered_path; 1702 static struct elfhints_hdr hdr; 1703 struct fill_search_info_args sargs, hargs; 1704 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo; 1705 struct dl_serpath *SLPpath, *hintpath; 1706 char *p; 1707 struct stat hint_stat; 1708 unsigned int SLPndx, hintndx, fndx, fcount; 1709 int fd; 1710 size_t flen; 1711 uint32_t dl; 1712 bool skip; 1713 1714 /* First call, read the hints file */ 1715 if (hints == NULL) { 1716 /* Keep from trying again in case the hints file is bad. */ 1717 hints = ""; 1718 1719 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1) 1720 return (NULL); 1721 1722 /* 1723 * Check of hdr.dirlistlen value against type limit 1724 * intends to pacify static analyzers. Further 1725 * paranoia leads to checks that dirlist is fully 1726 * contained in the file range. 1727 */ 1728 if (read(fd, &hdr, sizeof hdr) != sizeof hdr || 1729 hdr.magic != ELFHINTS_MAGIC || 1730 hdr.version != 1 || hdr.dirlistlen > UINT_MAX / 2 || 1731 fstat(fd, &hint_stat) == -1) { 1732 cleanup1: 1733 close(fd); 1734 hdr.dirlistlen = 0; 1735 return (NULL); 1736 } 1737 dl = hdr.strtab; 1738 if (dl + hdr.dirlist < dl) 1739 goto cleanup1; 1740 dl += hdr.dirlist; 1741 if (dl + hdr.dirlistlen < dl) 1742 goto cleanup1; 1743 dl += hdr.dirlistlen; 1744 if (dl > hint_stat.st_size) 1745 goto cleanup1; 1746 p = xmalloc(hdr.dirlistlen + 1); 1747 1748 if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 || 1749 read(fd, p, hdr.dirlistlen + 1) != 1750 (ssize_t)hdr.dirlistlen + 1 || p[hdr.dirlistlen] != '\0') { 1751 free(p); 1752 goto cleanup1; 1753 } 1754 hints = p; 1755 close(fd); 1756 } 1757 1758 /* 1759 * If caller agreed to receive list which includes the default 1760 * paths, we are done. Otherwise, if we still did not 1761 * calculated filtered result, do it now. 1762 */ 1763 if (!nostdlib) 1764 return (hints[0] != '\0' ? hints : NULL); 1765 if (filtered_path != NULL) 1766 goto filt_ret; 1767 1768 /* 1769 * Obtain the list of all configured search paths, and the 1770 * list of the default paths. 1771 * 1772 * First estimate the size of the results. 1773 */ 1774 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 1775 smeta.dls_cnt = 0; 1776 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 1777 hmeta.dls_cnt = 0; 1778 1779 sargs.request = RTLD_DI_SERINFOSIZE; 1780 sargs.serinfo = &smeta; 1781 hargs.request = RTLD_DI_SERINFOSIZE; 1782 hargs.serinfo = &hmeta; 1783 1784 path_enumerate(ld_standard_library_path, fill_search_info, &sargs); 1785 path_enumerate(hints, fill_search_info, &hargs); 1786 1787 SLPinfo = xmalloc(smeta.dls_size); 1788 hintinfo = xmalloc(hmeta.dls_size); 1789 1790 /* 1791 * Next fetch both sets of paths. 1792 */ 1793 sargs.request = RTLD_DI_SERINFO; 1794 sargs.serinfo = SLPinfo; 1795 sargs.serpath = &SLPinfo->dls_serpath[0]; 1796 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt]; 1797 1798 hargs.request = RTLD_DI_SERINFO; 1799 hargs.serinfo = hintinfo; 1800 hargs.serpath = &hintinfo->dls_serpath[0]; 1801 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt]; 1802 1803 path_enumerate(ld_standard_library_path, fill_search_info, &sargs); 1804 path_enumerate(hints, fill_search_info, &hargs); 1805 1806 /* 1807 * Now calculate the difference between two sets, by excluding 1808 * standard paths from the full set. 1809 */ 1810 fndx = 0; 1811 fcount = 0; 1812 filtered_path = xmalloc(hdr.dirlistlen + 1); 1813 hintpath = &hintinfo->dls_serpath[0]; 1814 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) { 1815 skip = false; 1816 SLPpath = &SLPinfo->dls_serpath[0]; 1817 /* 1818 * Check each standard path against current. 1819 */ 1820 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) { 1821 /* matched, skip the path */ 1822 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) { 1823 skip = true; 1824 break; 1825 } 1826 } 1827 if (skip) 1828 continue; 1829 /* 1830 * Not matched against any standard path, add the path 1831 * to result. Separate consequtive paths with ':'. 1832 */ 1833 if (fcount > 0) { 1834 filtered_path[fndx] = ':'; 1835 fndx++; 1836 } 1837 fcount++; 1838 flen = strlen(hintpath->dls_name); 1839 strncpy((filtered_path + fndx), hintpath->dls_name, flen); 1840 fndx += flen; 1841 } 1842 filtered_path[fndx] = '\0'; 1843 1844 free(SLPinfo); 1845 free(hintinfo); 1846 1847 filt_ret: 1848 return (filtered_path[0] != '\0' ? filtered_path : NULL); 1849 } 1850 1851 static void 1852 init_dag(Obj_Entry *root) 1853 { 1854 const Needed_Entry *needed; 1855 const Objlist_Entry *elm; 1856 DoneList donelist; 1857 1858 if (root->dag_inited) 1859 return; 1860 donelist_init(&donelist); 1861 1862 /* Root object belongs to own DAG. */ 1863 objlist_push_tail(&root->dldags, root); 1864 objlist_push_tail(&root->dagmembers, root); 1865 donelist_check(&donelist, root); 1866 1867 /* 1868 * Add dependencies of root object to DAG in breadth order 1869 * by exploiting the fact that each new object get added 1870 * to the tail of the dagmembers list. 1871 */ 1872 STAILQ_FOREACH(elm, &root->dagmembers, link) { 1873 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) { 1874 if (needed->obj == NULL || donelist_check(&donelist, needed->obj)) 1875 continue; 1876 objlist_push_tail(&needed->obj->dldags, root); 1877 objlist_push_tail(&root->dagmembers, needed->obj); 1878 } 1879 } 1880 root->dag_inited = true; 1881 } 1882 1883 static void 1884 init_marker(Obj_Entry *marker) 1885 { 1886 1887 bzero(marker, sizeof(*marker)); 1888 marker->marker = true; 1889 } 1890 1891 Obj_Entry * 1892 globallist_curr(const Obj_Entry *obj) 1893 { 1894 1895 for (;;) { 1896 if (obj == NULL) 1897 return (NULL); 1898 if (!obj->marker) 1899 return (__DECONST(Obj_Entry *, obj)); 1900 obj = TAILQ_PREV(obj, obj_entry_q, next); 1901 } 1902 } 1903 1904 Obj_Entry * 1905 globallist_next(const Obj_Entry *obj) 1906 { 1907 1908 for (;;) { 1909 obj = TAILQ_NEXT(obj, next); 1910 if (obj == NULL) 1911 return (NULL); 1912 if (!obj->marker) 1913 return (__DECONST(Obj_Entry *, obj)); 1914 } 1915 } 1916 1917 /* Prevent the object from being unmapped while the bind lock is dropped. */ 1918 static void 1919 hold_object(Obj_Entry *obj) 1920 { 1921 1922 obj->holdcount++; 1923 } 1924 1925 static void 1926 unhold_object(Obj_Entry *obj) 1927 { 1928 1929 assert(obj->holdcount > 0); 1930 if (--obj->holdcount == 0 && obj->unholdfree) 1931 release_object(obj); 1932 } 1933 1934 static void 1935 process_z(Obj_Entry *root) 1936 { 1937 const Objlist_Entry *elm; 1938 Obj_Entry *obj; 1939 1940 /* 1941 * Walk over object DAG and process every dependent object 1942 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need 1943 * to grow their own DAG. 1944 * 1945 * For DF_1_GLOBAL, DAG is required for symbol lookups in 1946 * symlook_global() to work. 1947 * 1948 * For DF_1_NODELETE, the DAG should have its reference upped. 1949 */ 1950 STAILQ_FOREACH(elm, &root->dagmembers, link) { 1951 obj = elm->obj; 1952 if (obj == NULL) 1953 continue; 1954 if (obj->z_nodelete && !obj->ref_nodel) { 1955 dbg("obj %s -z nodelete", obj->path); 1956 init_dag(obj); 1957 ref_dag(obj); 1958 obj->ref_nodel = true; 1959 } 1960 if (obj->z_global && objlist_find(&list_global, obj) == NULL) { 1961 dbg("obj %s -z global", obj->path); 1962 objlist_push_tail(&list_global, obj); 1963 init_dag(obj); 1964 } 1965 } 1966 } 1967 /* 1968 * Initialize the dynamic linker. The argument is the address at which 1969 * the dynamic linker has been mapped into memory. The primary task of 1970 * this function is to relocate the dynamic linker. 1971 */ 1972 static void 1973 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info) 1974 { 1975 Obj_Entry objtmp; /* Temporary rtld object */ 1976 const Elf_Ehdr *ehdr; 1977 const Elf_Dyn *dyn_rpath; 1978 const Elf_Dyn *dyn_soname; 1979 const Elf_Dyn *dyn_runpath; 1980 1981 #ifdef RTLD_INIT_PAGESIZES_EARLY 1982 /* The page size is required by the dynamic memory allocator. */ 1983 init_pagesizes(aux_info); 1984 #endif 1985 1986 /* 1987 * Conjure up an Obj_Entry structure for the dynamic linker. 1988 * 1989 * The "path" member can't be initialized yet because string constants 1990 * cannot yet be accessed. Below we will set it correctly. 1991 */ 1992 memset(&objtmp, 0, sizeof(objtmp)); 1993 objtmp.path = NULL; 1994 objtmp.rtld = true; 1995 objtmp.mapbase = mapbase; 1996 #ifdef PIC 1997 objtmp.relocbase = mapbase; 1998 #endif 1999 2000 objtmp.dynamic = rtld_dynamic(&objtmp); 2001 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath); 2002 assert(objtmp.needed == NULL); 2003 #if !defined(__mips__) 2004 /* MIPS has a bogus DT_TEXTREL. */ 2005 assert(!objtmp.textrel); 2006 #endif 2007 /* 2008 * Temporarily put the dynamic linker entry into the object list, so 2009 * that symbols can be found. 2010 */ 2011 relocate_objects(&objtmp, true, &objtmp, 0, NULL); 2012 2013 ehdr = (Elf_Ehdr *)mapbase; 2014 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff); 2015 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]); 2016 2017 /* Initialize the object list. */ 2018 TAILQ_INIT(&obj_list); 2019 2020 /* Now that non-local variables can be accesses, copy out obj_rtld. */ 2021 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld)); 2022 2023 #ifndef RTLD_INIT_PAGESIZES_EARLY 2024 /* The page size is required by the dynamic memory allocator. */ 2025 init_pagesizes(aux_info); 2026 #endif 2027 2028 if (aux_info[AT_OSRELDATE] != NULL) 2029 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val; 2030 2031 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath); 2032 2033 /* Replace the path with a dynamically allocated copy. */ 2034 obj_rtld.path = xstrdup(ld_path_rtld); 2035 2036 r_debug.r_brk = r_debug_state; 2037 r_debug.r_state = RT_CONSISTENT; 2038 } 2039 2040 /* 2041 * Retrieve the array of supported page sizes. The kernel provides the page 2042 * sizes in increasing order. 2043 */ 2044 static void 2045 init_pagesizes(Elf_Auxinfo **aux_info) 2046 { 2047 static size_t psa[MAXPAGESIZES]; 2048 int mib[2]; 2049 size_t len, size; 2050 2051 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] != 2052 NULL) { 2053 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val; 2054 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr; 2055 } else { 2056 len = 2; 2057 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0) 2058 size = sizeof(psa); 2059 else { 2060 /* As a fallback, retrieve the base page size. */ 2061 size = sizeof(psa[0]); 2062 if (aux_info[AT_PAGESZ] != NULL) { 2063 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val; 2064 goto psa_filled; 2065 } else { 2066 mib[0] = CTL_HW; 2067 mib[1] = HW_PAGESIZE; 2068 len = 2; 2069 } 2070 } 2071 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) { 2072 _rtld_error("sysctl for hw.pagesize(s) failed"); 2073 rtld_die(); 2074 } 2075 psa_filled: 2076 pagesizes = psa; 2077 } 2078 npagesizes = size / sizeof(pagesizes[0]); 2079 /* Discard any invalid entries at the end of the array. */ 2080 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0) 2081 npagesizes--; 2082 } 2083 2084 /* 2085 * Add the init functions from a needed object list (and its recursive 2086 * needed objects) to "list". This is not used directly; it is a helper 2087 * function for initlist_add_objects(). The write lock must be held 2088 * when this function is called. 2089 */ 2090 static void 2091 initlist_add_neededs(Needed_Entry *needed, Objlist *list) 2092 { 2093 /* Recursively process the successor needed objects. */ 2094 if (needed->next != NULL) 2095 initlist_add_neededs(needed->next, list); 2096 2097 /* Process the current needed object. */ 2098 if (needed->obj != NULL) 2099 initlist_add_objects(needed->obj, needed->obj, list); 2100 } 2101 2102 /* 2103 * Scan all of the DAGs rooted in the range of objects from "obj" to 2104 * "tail" and add their init functions to "list". This recurses over 2105 * the DAGs and ensure the proper init ordering such that each object's 2106 * needed libraries are initialized before the object itself. At the 2107 * same time, this function adds the objects to the global finalization 2108 * list "list_fini" in the opposite order. The write lock must be 2109 * held when this function is called. 2110 */ 2111 static void 2112 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list) 2113 { 2114 Obj_Entry *nobj; 2115 2116 if (obj->init_scanned || obj->init_done) 2117 return; 2118 obj->init_scanned = true; 2119 2120 /* Recursively process the successor objects. */ 2121 nobj = globallist_next(obj); 2122 if (nobj != NULL && obj != tail) 2123 initlist_add_objects(nobj, tail, list); 2124 2125 /* Recursively process the needed objects. */ 2126 if (obj->needed != NULL) 2127 initlist_add_neededs(obj->needed, list); 2128 if (obj->needed_filtees != NULL) 2129 initlist_add_neededs(obj->needed_filtees, list); 2130 if (obj->needed_aux_filtees != NULL) 2131 initlist_add_neededs(obj->needed_aux_filtees, list); 2132 2133 /* Add the object to the init list. */ 2134 if (obj->preinit_array != (Elf_Addr)NULL || obj->init != (Elf_Addr)NULL || 2135 obj->init_array != (Elf_Addr)NULL) 2136 objlist_push_tail(list, obj); 2137 2138 /* Add the object to the global fini list in the reverse order. */ 2139 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL) 2140 && !obj->on_fini_list) { 2141 objlist_push_head(&list_fini, obj); 2142 obj->on_fini_list = true; 2143 } 2144 } 2145 2146 #ifndef FPTR_TARGET 2147 #define FPTR_TARGET(f) ((Elf_Addr) (f)) 2148 #endif 2149 2150 static void 2151 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate) 2152 { 2153 Needed_Entry *needed, *needed1; 2154 2155 for (needed = n; needed != NULL; needed = needed->next) { 2156 if (needed->obj != NULL) { 2157 dlclose_locked(needed->obj, lockstate); 2158 needed->obj = NULL; 2159 } 2160 } 2161 for (needed = n; needed != NULL; needed = needed1) { 2162 needed1 = needed->next; 2163 free(needed); 2164 } 2165 } 2166 2167 static void 2168 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate) 2169 { 2170 2171 free_needed_filtees(obj->needed_filtees, lockstate); 2172 obj->needed_filtees = NULL; 2173 free_needed_filtees(obj->needed_aux_filtees, lockstate); 2174 obj->needed_aux_filtees = NULL; 2175 obj->filtees_loaded = false; 2176 } 2177 2178 static void 2179 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags, 2180 RtldLockState *lockstate) 2181 { 2182 2183 for (; needed != NULL; needed = needed->next) { 2184 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj, 2185 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) | 2186 RTLD_LOCAL, lockstate); 2187 } 2188 } 2189 2190 static void 2191 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate) 2192 { 2193 2194 lock_restart_for_upgrade(lockstate); 2195 if (!obj->filtees_loaded) { 2196 load_filtee1(obj, obj->needed_filtees, flags, lockstate); 2197 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate); 2198 obj->filtees_loaded = true; 2199 } 2200 } 2201 2202 static int 2203 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags) 2204 { 2205 Obj_Entry *obj1; 2206 2207 for (; needed != NULL; needed = needed->next) { 2208 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj, 2209 flags & ~RTLD_LO_NOLOAD); 2210 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0) 2211 return (-1); 2212 } 2213 return (0); 2214 } 2215 2216 /* 2217 * Given a shared object, traverse its list of needed objects, and load 2218 * each of them. Returns 0 on success. Generates an error message and 2219 * returns -1 on failure. 2220 */ 2221 static int 2222 load_needed_objects(Obj_Entry *first, int flags) 2223 { 2224 Obj_Entry *obj; 2225 2226 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 2227 if (obj->marker) 2228 continue; 2229 if (process_needed(obj, obj->needed, flags) == -1) 2230 return (-1); 2231 } 2232 return (0); 2233 } 2234 2235 static int 2236 load_preload_objects(void) 2237 { 2238 char *p = ld_preload; 2239 Obj_Entry *obj; 2240 static const char delim[] = " \t:;"; 2241 2242 if (p == NULL) 2243 return 0; 2244 2245 p += strspn(p, delim); 2246 while (*p != '\0') { 2247 size_t len = strcspn(p, delim); 2248 char savech; 2249 2250 savech = p[len]; 2251 p[len] = '\0'; 2252 obj = load_object(p, -1, NULL, 0); 2253 if (obj == NULL) 2254 return -1; /* XXX - cleanup */ 2255 obj->z_interpose = true; 2256 p[len] = savech; 2257 p += len; 2258 p += strspn(p, delim); 2259 } 2260 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL); 2261 return 0; 2262 } 2263 2264 static const char * 2265 printable_path(const char *path) 2266 { 2267 2268 return (path == NULL ? "<unknown>" : path); 2269 } 2270 2271 /* 2272 * Load a shared object into memory, if it is not already loaded. The 2273 * object may be specified by name or by user-supplied file descriptor 2274 * fd_u. In the later case, the fd_u descriptor is not closed, but its 2275 * duplicate is. 2276 * 2277 * Returns a pointer to the Obj_Entry for the object. Returns NULL 2278 * on failure. 2279 */ 2280 static Obj_Entry * 2281 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags) 2282 { 2283 Obj_Entry *obj; 2284 int fd; 2285 struct stat sb; 2286 char *path; 2287 2288 fd = -1; 2289 if (name != NULL) { 2290 TAILQ_FOREACH(obj, &obj_list, next) { 2291 if (obj->marker || obj->doomed) 2292 continue; 2293 if (object_match_name(obj, name)) 2294 return (obj); 2295 } 2296 2297 path = find_library(name, refobj, &fd); 2298 if (path == NULL) 2299 return (NULL); 2300 } else 2301 path = NULL; 2302 2303 if (fd >= 0) { 2304 /* 2305 * search_library_pathfds() opens a fresh file descriptor for the 2306 * library, so there is no need to dup(). 2307 */ 2308 } else if (fd_u == -1) { 2309 /* 2310 * If we didn't find a match by pathname, or the name is not 2311 * supplied, open the file and check again by device and inode. 2312 * This avoids false mismatches caused by multiple links or ".." 2313 * in pathnames. 2314 * 2315 * To avoid a race, we open the file and use fstat() rather than 2316 * using stat(). 2317 */ 2318 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) { 2319 _rtld_error("Cannot open \"%s\"", path); 2320 free(path); 2321 return (NULL); 2322 } 2323 } else { 2324 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0); 2325 if (fd == -1) { 2326 _rtld_error("Cannot dup fd"); 2327 free(path); 2328 return (NULL); 2329 } 2330 } 2331 if (fstat(fd, &sb) == -1) { 2332 _rtld_error("Cannot fstat \"%s\"", printable_path(path)); 2333 close(fd); 2334 free(path); 2335 return NULL; 2336 } 2337 TAILQ_FOREACH(obj, &obj_list, next) { 2338 if (obj->marker || obj->doomed) 2339 continue; 2340 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) 2341 break; 2342 } 2343 if (obj != NULL && name != NULL) { 2344 object_add_name(obj, name); 2345 free(path); 2346 close(fd); 2347 return obj; 2348 } 2349 if (flags & RTLD_LO_NOLOAD) { 2350 free(path); 2351 close(fd); 2352 return (NULL); 2353 } 2354 2355 /* First use of this object, so we must map it in */ 2356 obj = do_load_object(fd, name, path, &sb, flags); 2357 if (obj == NULL) 2358 free(path); 2359 close(fd); 2360 2361 return obj; 2362 } 2363 2364 static Obj_Entry * 2365 do_load_object(int fd, const char *name, char *path, struct stat *sbp, 2366 int flags) 2367 { 2368 Obj_Entry *obj; 2369 struct statfs fs; 2370 2371 /* 2372 * but first, make sure that environment variables haven't been 2373 * used to circumvent the noexec flag on a filesystem. 2374 */ 2375 if (dangerous_ld_env) { 2376 if (fstatfs(fd, &fs) != 0) { 2377 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path)); 2378 return NULL; 2379 } 2380 if (fs.f_flags & MNT_NOEXEC) { 2381 _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname); 2382 return NULL; 2383 } 2384 } 2385 dbg("loading \"%s\"", printable_path(path)); 2386 obj = map_object(fd, printable_path(path), sbp); 2387 if (obj == NULL) 2388 return NULL; 2389 2390 /* 2391 * If DT_SONAME is present in the object, digest_dynamic2 already 2392 * added it to the object names. 2393 */ 2394 if (name != NULL) 2395 object_add_name(obj, name); 2396 obj->path = path; 2397 digest_dynamic(obj, 0); 2398 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path, 2399 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount); 2400 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) == 2401 RTLD_LO_DLOPEN) { 2402 dbg("refusing to load non-loadable \"%s\"", obj->path); 2403 _rtld_error("Cannot dlopen non-loadable %s", obj->path); 2404 munmap(obj->mapbase, obj->mapsize); 2405 obj_free(obj); 2406 return (NULL); 2407 } 2408 2409 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0; 2410 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2411 obj_count++; 2412 obj_loads++; 2413 linkmap_add(obj); /* for GDB & dlinfo() */ 2414 max_stack_flags |= obj->stack_flags; 2415 2416 dbg(" %p .. %p: %s", obj->mapbase, 2417 obj->mapbase + obj->mapsize - 1, obj->path); 2418 if (obj->textrel) 2419 dbg(" WARNING: %s has impure text", obj->path); 2420 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 2421 obj->path); 2422 2423 return obj; 2424 } 2425 2426 static Obj_Entry * 2427 obj_from_addr(const void *addr) 2428 { 2429 Obj_Entry *obj; 2430 2431 TAILQ_FOREACH(obj, &obj_list, next) { 2432 if (obj->marker) 2433 continue; 2434 if (addr < (void *) obj->mapbase) 2435 continue; 2436 if (addr < (void *) (obj->mapbase + obj->mapsize)) 2437 return obj; 2438 } 2439 return NULL; 2440 } 2441 2442 static void 2443 preinit_main(void) 2444 { 2445 Elf_Addr *preinit_addr; 2446 int index; 2447 2448 preinit_addr = (Elf_Addr *)obj_main->preinit_array; 2449 if (preinit_addr == NULL) 2450 return; 2451 2452 for (index = 0; index < obj_main->preinit_array_num; index++) { 2453 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) { 2454 dbg("calling preinit function for %s at %p", obj_main->path, 2455 (void *)preinit_addr[index]); 2456 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index], 2457 0, 0, obj_main->path); 2458 call_init_pointer(obj_main, preinit_addr[index]); 2459 } 2460 } 2461 } 2462 2463 /* 2464 * Call the finalization functions for each of the objects in "list" 2465 * belonging to the DAG of "root" and referenced once. If NULL "root" 2466 * is specified, every finalization function will be called regardless 2467 * of the reference count and the list elements won't be freed. All of 2468 * the objects are expected to have non-NULL fini functions. 2469 */ 2470 static void 2471 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate) 2472 { 2473 Objlist_Entry *elm; 2474 char *saved_msg; 2475 Elf_Addr *fini_addr; 2476 int index; 2477 2478 assert(root == NULL || root->refcount == 1); 2479 2480 if (root != NULL) 2481 root->doomed = true; 2482 2483 /* 2484 * Preserve the current error message since a fini function might 2485 * call into the dynamic linker and overwrite it. 2486 */ 2487 saved_msg = errmsg_save(); 2488 do { 2489 STAILQ_FOREACH(elm, list, link) { 2490 if (root != NULL && (elm->obj->refcount != 1 || 2491 objlist_find(&root->dagmembers, elm->obj) == NULL)) 2492 continue; 2493 /* Remove object from fini list to prevent recursive invocation. */ 2494 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 2495 /* Ensure that new references cannot be acquired. */ 2496 elm->obj->doomed = true; 2497 2498 hold_object(elm->obj); 2499 lock_release(rtld_bind_lock, lockstate); 2500 /* 2501 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined. 2502 * When this happens, DT_FINI_ARRAY is processed first. 2503 */ 2504 fini_addr = (Elf_Addr *)elm->obj->fini_array; 2505 if (fini_addr != NULL && elm->obj->fini_array_num > 0) { 2506 for (index = elm->obj->fini_array_num - 1; index >= 0; 2507 index--) { 2508 if (fini_addr[index] != 0 && fini_addr[index] != 1) { 2509 dbg("calling fini function for %s at %p", 2510 elm->obj->path, (void *)fini_addr[index]); 2511 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, 2512 (void *)fini_addr[index], 0, 0, elm->obj->path); 2513 call_initfini_pointer(elm->obj, fini_addr[index]); 2514 } 2515 } 2516 } 2517 if (elm->obj->fini != (Elf_Addr)NULL) { 2518 dbg("calling fini function for %s at %p", elm->obj->path, 2519 (void *)elm->obj->fini); 2520 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 2521 0, 0, elm->obj->path); 2522 call_initfini_pointer(elm->obj, elm->obj->fini); 2523 } 2524 wlock_acquire(rtld_bind_lock, lockstate); 2525 unhold_object(elm->obj); 2526 /* No need to free anything if process is going down. */ 2527 if (root != NULL) 2528 free(elm); 2529 /* 2530 * We must restart the list traversal after every fini call 2531 * because a dlclose() call from the fini function or from 2532 * another thread might have modified the reference counts. 2533 */ 2534 break; 2535 } 2536 } while (elm != NULL); 2537 errmsg_restore(saved_msg); 2538 } 2539 2540 /* 2541 * Call the initialization functions for each of the objects in 2542 * "list". All of the objects are expected to have non-NULL init 2543 * functions. 2544 */ 2545 static void 2546 objlist_call_init(Objlist *list, RtldLockState *lockstate) 2547 { 2548 Objlist_Entry *elm; 2549 Obj_Entry *obj; 2550 char *saved_msg; 2551 Elf_Addr *init_addr; 2552 int index; 2553 2554 /* 2555 * Clean init_scanned flag so that objects can be rechecked and 2556 * possibly initialized earlier if any of vectors called below 2557 * cause the change by using dlopen. 2558 */ 2559 TAILQ_FOREACH(obj, &obj_list, next) { 2560 if (obj->marker) 2561 continue; 2562 obj->init_scanned = false; 2563 } 2564 2565 /* 2566 * Preserve the current error message since an init function might 2567 * call into the dynamic linker and overwrite it. 2568 */ 2569 saved_msg = errmsg_save(); 2570 STAILQ_FOREACH(elm, list, link) { 2571 if (elm->obj->init_done) /* Initialized early. */ 2572 continue; 2573 /* 2574 * Race: other thread might try to use this object before current 2575 * one completes the initialization. Not much can be done here 2576 * without better locking. 2577 */ 2578 elm->obj->init_done = true; 2579 hold_object(elm->obj); 2580 lock_release(rtld_bind_lock, lockstate); 2581 2582 /* 2583 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. 2584 * When this happens, DT_INIT is processed first. 2585 */ 2586 if (elm->obj->init != (Elf_Addr)NULL) { 2587 dbg("calling init function for %s at %p", elm->obj->path, 2588 (void *)elm->obj->init); 2589 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 2590 0, 0, elm->obj->path); 2591 call_initfini_pointer(elm->obj, elm->obj->init); 2592 } 2593 init_addr = (Elf_Addr *)elm->obj->init_array; 2594 if (init_addr != NULL) { 2595 for (index = 0; index < elm->obj->init_array_num; index++) { 2596 if (init_addr[index] != 0 && init_addr[index] != 1) { 2597 dbg("calling init function for %s at %p", elm->obj->path, 2598 (void *)init_addr[index]); 2599 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, 2600 (void *)init_addr[index], 0, 0, elm->obj->path); 2601 call_init_pointer(elm->obj, init_addr[index]); 2602 } 2603 } 2604 } 2605 wlock_acquire(rtld_bind_lock, lockstate); 2606 unhold_object(elm->obj); 2607 } 2608 errmsg_restore(saved_msg); 2609 } 2610 2611 static void 2612 objlist_clear(Objlist *list) 2613 { 2614 Objlist_Entry *elm; 2615 2616 while (!STAILQ_EMPTY(list)) { 2617 elm = STAILQ_FIRST(list); 2618 STAILQ_REMOVE_HEAD(list, link); 2619 free(elm); 2620 } 2621 } 2622 2623 static Objlist_Entry * 2624 objlist_find(Objlist *list, const Obj_Entry *obj) 2625 { 2626 Objlist_Entry *elm; 2627 2628 STAILQ_FOREACH(elm, list, link) 2629 if (elm->obj == obj) 2630 return elm; 2631 return NULL; 2632 } 2633 2634 static void 2635 objlist_init(Objlist *list) 2636 { 2637 STAILQ_INIT(list); 2638 } 2639 2640 static void 2641 objlist_push_head(Objlist *list, Obj_Entry *obj) 2642 { 2643 Objlist_Entry *elm; 2644 2645 elm = NEW(Objlist_Entry); 2646 elm->obj = obj; 2647 STAILQ_INSERT_HEAD(list, elm, link); 2648 } 2649 2650 static void 2651 objlist_push_tail(Objlist *list, Obj_Entry *obj) 2652 { 2653 Objlist_Entry *elm; 2654 2655 elm = NEW(Objlist_Entry); 2656 elm->obj = obj; 2657 STAILQ_INSERT_TAIL(list, elm, link); 2658 } 2659 2660 static void 2661 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj) 2662 { 2663 Objlist_Entry *elm, *listelm; 2664 2665 STAILQ_FOREACH(listelm, list, link) { 2666 if (listelm->obj == listobj) 2667 break; 2668 } 2669 elm = NEW(Objlist_Entry); 2670 elm->obj = obj; 2671 if (listelm != NULL) 2672 STAILQ_INSERT_AFTER(list, listelm, elm, link); 2673 else 2674 STAILQ_INSERT_TAIL(list, elm, link); 2675 } 2676 2677 static void 2678 objlist_remove(Objlist *list, Obj_Entry *obj) 2679 { 2680 Objlist_Entry *elm; 2681 2682 if ((elm = objlist_find(list, obj)) != NULL) { 2683 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 2684 free(elm); 2685 } 2686 } 2687 2688 /* 2689 * Relocate dag rooted in the specified object. 2690 * Returns 0 on success, or -1 on failure. 2691 */ 2692 2693 static int 2694 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj, 2695 int flags, RtldLockState *lockstate) 2696 { 2697 Objlist_Entry *elm; 2698 int error; 2699 2700 error = 0; 2701 STAILQ_FOREACH(elm, &root->dagmembers, link) { 2702 error = relocate_object(elm->obj, bind_now, rtldobj, flags, 2703 lockstate); 2704 if (error == -1) 2705 break; 2706 } 2707 return (error); 2708 } 2709 2710 /* 2711 * Prepare for, or clean after, relocating an object marked with 2712 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only 2713 * segments are remapped read-write. After relocations are done, the 2714 * segment's permissions are returned back to the modes specified in 2715 * the phdrs. If any relocation happened, or always for wired 2716 * program, COW is triggered. 2717 */ 2718 static int 2719 reloc_textrel_prot(Obj_Entry *obj, bool before) 2720 { 2721 const Elf_Phdr *ph; 2722 void *base; 2723 size_t l, sz; 2724 int prot; 2725 2726 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0; 2727 l--, ph++) { 2728 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0) 2729 continue; 2730 base = obj->relocbase + trunc_page(ph->p_vaddr); 2731 sz = round_page(ph->p_vaddr + ph->p_filesz) - 2732 trunc_page(ph->p_vaddr); 2733 prot = convert_prot(ph->p_flags) | (before ? PROT_WRITE : 0); 2734 if (mprotect(base, sz, prot) == -1) { 2735 _rtld_error("%s: Cannot write-%sable text segment: %s", 2736 obj->path, before ? "en" : "dis", 2737 rtld_strerror(errno)); 2738 return (-1); 2739 } 2740 } 2741 return (0); 2742 } 2743 2744 /* 2745 * Relocate single object. 2746 * Returns 0 on success, or -1 on failure. 2747 */ 2748 static int 2749 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, 2750 int flags, RtldLockState *lockstate) 2751 { 2752 2753 if (obj->relocated) 2754 return (0); 2755 obj->relocated = true; 2756 if (obj != rtldobj) 2757 dbg("relocating \"%s\"", obj->path); 2758 2759 if (obj->symtab == NULL || obj->strtab == NULL || 2760 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) { 2761 _rtld_error("%s: Shared object has no run-time symbol table", 2762 obj->path); 2763 return (-1); 2764 } 2765 2766 /* There are relocations to the write-protected text segment. */ 2767 if (obj->textrel && reloc_textrel_prot(obj, true) != 0) 2768 return (-1); 2769 2770 /* Process the non-PLT non-IFUNC relocations. */ 2771 if (reloc_non_plt(obj, rtldobj, flags, lockstate)) 2772 return (-1); 2773 2774 /* Re-protected the text segment. */ 2775 if (obj->textrel && reloc_textrel_prot(obj, false) != 0) 2776 return (-1); 2777 2778 /* Set the special PLT or GOT entries. */ 2779 init_pltgot(obj); 2780 2781 /* Process the PLT relocations. */ 2782 if (reloc_plt(obj) == -1) 2783 return (-1); 2784 /* Relocate the jump slots if we are doing immediate binding. */ 2785 if (obj->bind_now || bind_now) 2786 if (reloc_jmpslots(obj, flags, lockstate) == -1) 2787 return (-1); 2788 2789 /* 2790 * Process the non-PLT IFUNC relocations. The relocations are 2791 * processed in two phases, because IFUNC resolvers may 2792 * reference other symbols, which must be readily processed 2793 * before resolvers are called. 2794 */ 2795 if (obj->non_plt_gnu_ifunc && 2796 reloc_non_plt(obj, rtldobj, flags | SYMLOOK_IFUNC, lockstate)) 2797 return (-1); 2798 2799 if (!obj->mainprog && obj_enforce_relro(obj) == -1) 2800 return (-1); 2801 2802 /* 2803 * Set up the magic number and version in the Obj_Entry. These 2804 * were checked in the crt1.o from the original ElfKit, so we 2805 * set them for backward compatibility. 2806 */ 2807 obj->magic = RTLD_MAGIC; 2808 obj->version = RTLD_VERSION; 2809 2810 return (0); 2811 } 2812 2813 /* 2814 * Relocate newly-loaded shared objects. The argument is a pointer to 2815 * the Obj_Entry for the first such object. All objects from the first 2816 * to the end of the list of objects are relocated. Returns 0 on success, 2817 * or -1 on failure. 2818 */ 2819 static int 2820 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj, 2821 int flags, RtldLockState *lockstate) 2822 { 2823 Obj_Entry *obj; 2824 int error; 2825 2826 for (error = 0, obj = first; obj != NULL; 2827 obj = TAILQ_NEXT(obj, next)) { 2828 if (obj->marker) 2829 continue; 2830 error = relocate_object(obj, bind_now, rtldobj, flags, 2831 lockstate); 2832 if (error == -1) 2833 break; 2834 } 2835 return (error); 2836 } 2837 2838 /* 2839 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots 2840 * referencing STT_GNU_IFUNC symbols is postponed till the other 2841 * relocations are done. The indirect functions specified as 2842 * ifunc are allowed to call other symbols, so we need to have 2843 * objects relocated before asking for resolution from indirects. 2844 * 2845 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion, 2846 * instead of the usual lazy handling of PLT slots. It is 2847 * consistent with how GNU does it. 2848 */ 2849 static int 2850 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags, 2851 RtldLockState *lockstate) 2852 { 2853 if (obj->irelative && reloc_iresolve(obj, lockstate) == -1) 2854 return (-1); 2855 if ((obj->bind_now || bind_now) && obj->gnu_ifunc && 2856 reloc_gnu_ifunc(obj, flags, lockstate) == -1) 2857 return (-1); 2858 return (0); 2859 } 2860 2861 static int 2862 resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags, 2863 RtldLockState *lockstate) 2864 { 2865 Obj_Entry *obj; 2866 2867 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 2868 if (obj->marker) 2869 continue; 2870 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1) 2871 return (-1); 2872 } 2873 return (0); 2874 } 2875 2876 static int 2877 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags, 2878 RtldLockState *lockstate) 2879 { 2880 Objlist_Entry *elm; 2881 2882 STAILQ_FOREACH(elm, list, link) { 2883 if (resolve_object_ifunc(elm->obj, bind_now, flags, 2884 lockstate) == -1) 2885 return (-1); 2886 } 2887 return (0); 2888 } 2889 2890 /* 2891 * Cleanup procedure. It will be called (by the atexit mechanism) just 2892 * before the process exits. 2893 */ 2894 static void 2895 rtld_exit(void) 2896 { 2897 RtldLockState lockstate; 2898 2899 wlock_acquire(rtld_bind_lock, &lockstate); 2900 dbg("rtld_exit()"); 2901 objlist_call_fini(&list_fini, NULL, &lockstate); 2902 /* No need to remove the items from the list, since we are exiting. */ 2903 if (!libmap_disable) 2904 lm_fini(); 2905 lock_release(rtld_bind_lock, &lockstate); 2906 } 2907 2908 /* 2909 * Iterate over a search path, translate each element, and invoke the 2910 * callback on the result. 2911 */ 2912 static void * 2913 path_enumerate(const char *path, path_enum_proc callback, void *arg) 2914 { 2915 const char *trans; 2916 if (path == NULL) 2917 return (NULL); 2918 2919 path += strspn(path, ":;"); 2920 while (*path != '\0') { 2921 size_t len; 2922 char *res; 2923 2924 len = strcspn(path, ":;"); 2925 trans = lm_findn(NULL, path, len); 2926 if (trans) 2927 res = callback(trans, strlen(trans), arg); 2928 else 2929 res = callback(path, len, arg); 2930 2931 if (res != NULL) 2932 return (res); 2933 2934 path += len; 2935 path += strspn(path, ":;"); 2936 } 2937 2938 return (NULL); 2939 } 2940 2941 struct try_library_args { 2942 const char *name; 2943 size_t namelen; 2944 char *buffer; 2945 size_t buflen; 2946 }; 2947 2948 static void * 2949 try_library_path(const char *dir, size_t dirlen, void *param) 2950 { 2951 struct try_library_args *arg; 2952 2953 arg = param; 2954 if (*dir == '/' || trust) { 2955 char *pathname; 2956 2957 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 2958 return (NULL); 2959 2960 pathname = arg->buffer; 2961 strncpy(pathname, dir, dirlen); 2962 pathname[dirlen] = '/'; 2963 strcpy(pathname + dirlen + 1, arg->name); 2964 2965 dbg(" Trying \"%s\"", pathname); 2966 if (access(pathname, F_OK) == 0) { /* We found it */ 2967 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 2968 strcpy(pathname, arg->buffer); 2969 return (pathname); 2970 } 2971 } 2972 return (NULL); 2973 } 2974 2975 static char * 2976 search_library_path(const char *name, const char *path) 2977 { 2978 char *p; 2979 struct try_library_args arg; 2980 2981 if (path == NULL) 2982 return NULL; 2983 2984 arg.name = name; 2985 arg.namelen = strlen(name); 2986 arg.buffer = xmalloc(PATH_MAX); 2987 arg.buflen = PATH_MAX; 2988 2989 p = path_enumerate(path, try_library_path, &arg); 2990 2991 free(arg.buffer); 2992 2993 return (p); 2994 } 2995 2996 2997 /* 2998 * Finds the library with the given name using the directory descriptors 2999 * listed in the LD_LIBRARY_PATH_FDS environment variable. 3000 * 3001 * Returns a freshly-opened close-on-exec file descriptor for the library, 3002 * or -1 if the library cannot be found. 3003 */ 3004 static char * 3005 search_library_pathfds(const char *name, const char *path, int *fdp) 3006 { 3007 char *envcopy, *fdstr, *found, *last_token; 3008 size_t len; 3009 int dirfd, fd; 3010 3011 dbg("%s('%s', '%s', fdp)", __func__, name, path); 3012 3013 /* Don't load from user-specified libdirs into setuid binaries. */ 3014 if (!trust) 3015 return (NULL); 3016 3017 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */ 3018 if (path == NULL) 3019 return (NULL); 3020 3021 /* LD_LIBRARY_PATH_FDS only works with relative paths. */ 3022 if (name[0] == '/') { 3023 dbg("Absolute path (%s) passed to %s", name, __func__); 3024 return (NULL); 3025 } 3026 3027 /* 3028 * Use strtok_r() to walk the FD:FD:FD list. This requires a local 3029 * copy of the path, as strtok_r rewrites separator tokens 3030 * with '\0'. 3031 */ 3032 found = NULL; 3033 envcopy = xstrdup(path); 3034 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL; 3035 fdstr = strtok_r(NULL, ":", &last_token)) { 3036 dirfd = parse_libdir(fdstr); 3037 if (dirfd < 0) 3038 break; 3039 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY); 3040 if (fd >= 0) { 3041 *fdp = fd; 3042 len = strlen(fdstr) + strlen(name) + 3; 3043 found = xmalloc(len); 3044 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) { 3045 _rtld_error("error generating '%d/%s'", 3046 dirfd, name); 3047 rtld_die(); 3048 } 3049 dbg("open('%s') => %d", found, fd); 3050 break; 3051 } 3052 } 3053 free(envcopy); 3054 3055 return (found); 3056 } 3057 3058 3059 int 3060 dlclose(void *handle) 3061 { 3062 RtldLockState lockstate; 3063 int error; 3064 3065 wlock_acquire(rtld_bind_lock, &lockstate); 3066 error = dlclose_locked(handle, &lockstate); 3067 lock_release(rtld_bind_lock, &lockstate); 3068 return (error); 3069 } 3070 3071 static int 3072 dlclose_locked(void *handle, RtldLockState *lockstate) 3073 { 3074 Obj_Entry *root; 3075 3076 root = dlcheck(handle); 3077 if (root == NULL) 3078 return -1; 3079 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount, 3080 root->path); 3081 3082 /* Unreference the object and its dependencies. */ 3083 root->dl_refcount--; 3084 3085 if (root->refcount == 1) { 3086 /* 3087 * The object will be no longer referenced, so we must unload it. 3088 * First, call the fini functions. 3089 */ 3090 objlist_call_fini(&list_fini, root, lockstate); 3091 3092 unref_dag(root); 3093 3094 /* Finish cleaning up the newly-unreferenced objects. */ 3095 GDB_STATE(RT_DELETE,&root->linkmap); 3096 unload_object(root, lockstate); 3097 GDB_STATE(RT_CONSISTENT,NULL); 3098 } else 3099 unref_dag(root); 3100 3101 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL); 3102 return 0; 3103 } 3104 3105 char * 3106 dlerror(void) 3107 { 3108 char *msg = error_message; 3109 error_message = NULL; 3110 return msg; 3111 } 3112 3113 /* 3114 * This function is deprecated and has no effect. 3115 */ 3116 void 3117 dllockinit(void *context, 3118 void *(*lock_create)(void *context), 3119 void (*rlock_acquire)(void *lock), 3120 void (*wlock_acquire)(void *lock), 3121 void (*lock_release)(void *lock), 3122 void (*lock_destroy)(void *lock), 3123 void (*context_destroy)(void *context)) 3124 { 3125 static void *cur_context; 3126 static void (*cur_context_destroy)(void *); 3127 3128 /* Just destroy the context from the previous call, if necessary. */ 3129 if (cur_context_destroy != NULL) 3130 cur_context_destroy(cur_context); 3131 cur_context = context; 3132 cur_context_destroy = context_destroy; 3133 } 3134 3135 void * 3136 dlopen(const char *name, int mode) 3137 { 3138 3139 return (rtld_dlopen(name, -1, mode)); 3140 } 3141 3142 void * 3143 fdlopen(int fd, int mode) 3144 { 3145 3146 return (rtld_dlopen(NULL, fd, mode)); 3147 } 3148 3149 static void * 3150 rtld_dlopen(const char *name, int fd, int mode) 3151 { 3152 RtldLockState lockstate; 3153 int lo_flags; 3154 3155 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name); 3156 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 3157 if (ld_tracing != NULL) { 3158 rlock_acquire(rtld_bind_lock, &lockstate); 3159 if (sigsetjmp(lockstate.env, 0) != 0) 3160 lock_upgrade(rtld_bind_lock, &lockstate); 3161 environ = (char **)*get_program_var_addr("environ", &lockstate); 3162 lock_release(rtld_bind_lock, &lockstate); 3163 } 3164 lo_flags = RTLD_LO_DLOPEN; 3165 if (mode & RTLD_NODELETE) 3166 lo_flags |= RTLD_LO_NODELETE; 3167 if (mode & RTLD_NOLOAD) 3168 lo_flags |= RTLD_LO_NOLOAD; 3169 if (ld_tracing != NULL) 3170 lo_flags |= RTLD_LO_TRACE; 3171 3172 return (dlopen_object(name, fd, obj_main, lo_flags, 3173 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL)); 3174 } 3175 3176 static void 3177 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate) 3178 { 3179 3180 obj->dl_refcount--; 3181 unref_dag(obj); 3182 if (obj->refcount == 0) 3183 unload_object(obj, lockstate); 3184 } 3185 3186 static Obj_Entry * 3187 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags, 3188 int mode, RtldLockState *lockstate) 3189 { 3190 Obj_Entry *old_obj_tail; 3191 Obj_Entry *obj; 3192 Objlist initlist; 3193 RtldLockState mlockstate; 3194 int result; 3195 3196 objlist_init(&initlist); 3197 3198 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) { 3199 wlock_acquire(rtld_bind_lock, &mlockstate); 3200 lockstate = &mlockstate; 3201 } 3202 GDB_STATE(RT_ADD,NULL); 3203 3204 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q)); 3205 obj = NULL; 3206 if (name == NULL && fd == -1) { 3207 obj = obj_main; 3208 obj->refcount++; 3209 } else { 3210 obj = load_object(name, fd, refobj, lo_flags); 3211 } 3212 3213 if (obj) { 3214 obj->dl_refcount++; 3215 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) 3216 objlist_push_tail(&list_global, obj); 3217 if (globallist_next(old_obj_tail) != NULL) { 3218 /* We loaded something new. */ 3219 assert(globallist_next(old_obj_tail) == obj); 3220 result = load_needed_objects(obj, 3221 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY)); 3222 init_dag(obj); 3223 ref_dag(obj); 3224 if (result != -1) 3225 result = rtld_verify_versions(&obj->dagmembers); 3226 if (result != -1 && ld_tracing) 3227 goto trace; 3228 if (result == -1 || relocate_object_dag(obj, 3229 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld, 3230 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3231 lockstate) == -1) { 3232 dlopen_cleanup(obj, lockstate); 3233 obj = NULL; 3234 } else if (lo_flags & RTLD_LO_EARLY) { 3235 /* 3236 * Do not call the init functions for early loaded 3237 * filtees. The image is still not initialized enough 3238 * for them to work. 3239 * 3240 * Our object is found by the global object list and 3241 * will be ordered among all init calls done right 3242 * before transferring control to main. 3243 */ 3244 } else { 3245 /* Make list of init functions to call. */ 3246 initlist_add_objects(obj, obj, &initlist); 3247 } 3248 /* 3249 * Process all no_delete or global objects here, given 3250 * them own DAGs to prevent their dependencies from being 3251 * unloaded. This has to be done after we have loaded all 3252 * of the dependencies, so that we do not miss any. 3253 */ 3254 if (obj != NULL) 3255 process_z(obj); 3256 } else { 3257 /* 3258 * Bump the reference counts for objects on this DAG. If 3259 * this is the first dlopen() call for the object that was 3260 * already loaded as a dependency, initialize the dag 3261 * starting at it. 3262 */ 3263 init_dag(obj); 3264 ref_dag(obj); 3265 3266 if ((lo_flags & RTLD_LO_TRACE) != 0) 3267 goto trace; 3268 } 3269 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 || 3270 obj->z_nodelete) && !obj->ref_nodel) { 3271 dbg("obj %s nodelete", obj->path); 3272 ref_dag(obj); 3273 obj->z_nodelete = obj->ref_nodel = true; 3274 } 3275 } 3276 3277 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0, 3278 name); 3279 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); 3280 3281 if (!(lo_flags & RTLD_LO_EARLY)) { 3282 map_stacks_exec(lockstate); 3283 } 3284 3285 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW, 3286 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3287 lockstate) == -1) { 3288 objlist_clear(&initlist); 3289 dlopen_cleanup(obj, lockstate); 3290 if (lockstate == &mlockstate) 3291 lock_release(rtld_bind_lock, lockstate); 3292 return (NULL); 3293 } 3294 3295 if (!(lo_flags & RTLD_LO_EARLY)) { 3296 /* Call the init functions. */ 3297 objlist_call_init(&initlist, lockstate); 3298 } 3299 objlist_clear(&initlist); 3300 if (lockstate == &mlockstate) 3301 lock_release(rtld_bind_lock, lockstate); 3302 return obj; 3303 trace: 3304 trace_loaded_objects(obj); 3305 if (lockstate == &mlockstate) 3306 lock_release(rtld_bind_lock, lockstate); 3307 exit(0); 3308 } 3309 3310 static void * 3311 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve, 3312 int flags) 3313 { 3314 DoneList donelist; 3315 const Obj_Entry *obj, *defobj; 3316 const Elf_Sym *def; 3317 SymLook req; 3318 RtldLockState lockstate; 3319 tls_index ti; 3320 void *sym; 3321 int res; 3322 3323 def = NULL; 3324 defobj = NULL; 3325 symlook_init(&req, name); 3326 req.ventry = ve; 3327 req.flags = flags | SYMLOOK_IN_PLT; 3328 req.lockstate = &lockstate; 3329 3330 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name); 3331 rlock_acquire(rtld_bind_lock, &lockstate); 3332 if (sigsetjmp(lockstate.env, 0) != 0) 3333 lock_upgrade(rtld_bind_lock, &lockstate); 3334 if (handle == NULL || handle == RTLD_NEXT || 3335 handle == RTLD_DEFAULT || handle == RTLD_SELF) { 3336 3337 if ((obj = obj_from_addr(retaddr)) == NULL) { 3338 _rtld_error("Cannot determine caller's shared object"); 3339 lock_release(rtld_bind_lock, &lockstate); 3340 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3341 return NULL; 3342 } 3343 if (handle == NULL) { /* Just the caller's shared object. */ 3344 res = symlook_obj(&req, obj); 3345 if (res == 0) { 3346 def = req.sym_out; 3347 defobj = req.defobj_out; 3348 } 3349 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 3350 handle == RTLD_SELF) { /* ... caller included */ 3351 if (handle == RTLD_NEXT) 3352 obj = globallist_next(obj); 3353 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 3354 if (obj->marker) 3355 continue; 3356 res = symlook_obj(&req, obj); 3357 if (res == 0) { 3358 if (def == NULL || 3359 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) { 3360 def = req.sym_out; 3361 defobj = req.defobj_out; 3362 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 3363 break; 3364 } 3365 } 3366 } 3367 /* 3368 * Search the dynamic linker itself, and possibly resolve the 3369 * symbol from there. This is how the application links to 3370 * dynamic linker services such as dlopen. 3371 */ 3372 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3373 res = symlook_obj(&req, &obj_rtld); 3374 if (res == 0) { 3375 def = req.sym_out; 3376 defobj = req.defobj_out; 3377 } 3378 } 3379 } else { 3380 assert(handle == RTLD_DEFAULT); 3381 res = symlook_default(&req, obj); 3382 if (res == 0) { 3383 defobj = req.defobj_out; 3384 def = req.sym_out; 3385 } 3386 } 3387 } else { 3388 if ((obj = dlcheck(handle)) == NULL) { 3389 lock_release(rtld_bind_lock, &lockstate); 3390 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3391 return NULL; 3392 } 3393 3394 donelist_init(&donelist); 3395 if (obj->mainprog) { 3396 /* Handle obtained by dlopen(NULL, ...) implies global scope. */ 3397 res = symlook_global(&req, &donelist); 3398 if (res == 0) { 3399 def = req.sym_out; 3400 defobj = req.defobj_out; 3401 } 3402 /* 3403 * Search the dynamic linker itself, and possibly resolve the 3404 * symbol from there. This is how the application links to 3405 * dynamic linker services such as dlopen. 3406 */ 3407 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3408 res = symlook_obj(&req, &obj_rtld); 3409 if (res == 0) { 3410 def = req.sym_out; 3411 defobj = req.defobj_out; 3412 } 3413 } 3414 } 3415 else { 3416 /* Search the whole DAG rooted at the given object. */ 3417 res = symlook_list(&req, &obj->dagmembers, &donelist); 3418 if (res == 0) { 3419 def = req.sym_out; 3420 defobj = req.defobj_out; 3421 } 3422 } 3423 } 3424 3425 if (def != NULL) { 3426 lock_release(rtld_bind_lock, &lockstate); 3427 3428 /* 3429 * The value required by the caller is derived from the value 3430 * of the symbol. this is simply the relocated value of the 3431 * symbol. 3432 */ 3433 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 3434 sym = make_function_pointer(def, defobj); 3435 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 3436 sym = rtld_resolve_ifunc(defobj, def); 3437 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) { 3438 ti.ti_module = defobj->tlsindex; 3439 ti.ti_offset = def->st_value; 3440 sym = __tls_get_addr(&ti); 3441 } else 3442 sym = defobj->relocbase + def->st_value; 3443 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name); 3444 return (sym); 3445 } 3446 3447 _rtld_error("Undefined symbol \"%s\"", name); 3448 lock_release(rtld_bind_lock, &lockstate); 3449 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3450 return NULL; 3451 } 3452 3453 void * 3454 dlsym(void *handle, const char *name) 3455 { 3456 return do_dlsym(handle, name, __builtin_return_address(0), NULL, 3457 SYMLOOK_DLSYM); 3458 } 3459 3460 dlfunc_t 3461 dlfunc(void *handle, const char *name) 3462 { 3463 union { 3464 void *d; 3465 dlfunc_t f; 3466 } rv; 3467 3468 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL, 3469 SYMLOOK_DLSYM); 3470 return (rv.f); 3471 } 3472 3473 void * 3474 dlvsym(void *handle, const char *name, const char *version) 3475 { 3476 Ver_Entry ventry; 3477 3478 ventry.name = version; 3479 ventry.file = NULL; 3480 ventry.hash = elf_hash(version); 3481 ventry.flags= 0; 3482 return do_dlsym(handle, name, __builtin_return_address(0), &ventry, 3483 SYMLOOK_DLSYM); 3484 } 3485 3486 int 3487 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info) 3488 { 3489 const Obj_Entry *obj; 3490 RtldLockState lockstate; 3491 3492 rlock_acquire(rtld_bind_lock, &lockstate); 3493 obj = obj_from_addr(addr); 3494 if (obj == NULL) { 3495 _rtld_error("No shared object contains address"); 3496 lock_release(rtld_bind_lock, &lockstate); 3497 return (0); 3498 } 3499 rtld_fill_dl_phdr_info(obj, phdr_info); 3500 lock_release(rtld_bind_lock, &lockstate); 3501 return (1); 3502 } 3503 3504 int 3505 dladdr(const void *addr, Dl_info *info) 3506 { 3507 const Obj_Entry *obj; 3508 const Elf_Sym *def; 3509 void *symbol_addr; 3510 unsigned long symoffset; 3511 RtldLockState lockstate; 3512 3513 rlock_acquire(rtld_bind_lock, &lockstate); 3514 obj = obj_from_addr(addr); 3515 if (obj == NULL) { 3516 _rtld_error("No shared object contains address"); 3517 lock_release(rtld_bind_lock, &lockstate); 3518 return 0; 3519 } 3520 info->dli_fname = obj->path; 3521 info->dli_fbase = obj->mapbase; 3522 info->dli_saddr = (void *)0; 3523 info->dli_sname = NULL; 3524 3525 /* 3526 * Walk the symbol list looking for the symbol whose address is 3527 * closest to the address sent in. 3528 */ 3529 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) { 3530 def = obj->symtab + symoffset; 3531 3532 /* 3533 * For skip the symbol if st_shndx is either SHN_UNDEF or 3534 * SHN_COMMON. 3535 */ 3536 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 3537 continue; 3538 3539 /* 3540 * If the symbol is greater than the specified address, or if it 3541 * is further away from addr than the current nearest symbol, 3542 * then reject it. 3543 */ 3544 symbol_addr = obj->relocbase + def->st_value; 3545 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 3546 continue; 3547 3548 /* Update our idea of the nearest symbol. */ 3549 info->dli_sname = obj->strtab + def->st_name; 3550 info->dli_saddr = symbol_addr; 3551 3552 /* Exact match? */ 3553 if (info->dli_saddr == addr) 3554 break; 3555 } 3556 lock_release(rtld_bind_lock, &lockstate); 3557 return 1; 3558 } 3559 3560 int 3561 dlinfo(void *handle, int request, void *p) 3562 { 3563 const Obj_Entry *obj; 3564 RtldLockState lockstate; 3565 int error; 3566 3567 rlock_acquire(rtld_bind_lock, &lockstate); 3568 3569 if (handle == NULL || handle == RTLD_SELF) { 3570 void *retaddr; 3571 3572 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 3573 if ((obj = obj_from_addr(retaddr)) == NULL) 3574 _rtld_error("Cannot determine caller's shared object"); 3575 } else 3576 obj = dlcheck(handle); 3577 3578 if (obj == NULL) { 3579 lock_release(rtld_bind_lock, &lockstate); 3580 return (-1); 3581 } 3582 3583 error = 0; 3584 switch (request) { 3585 case RTLD_DI_LINKMAP: 3586 *((struct link_map const **)p) = &obj->linkmap; 3587 break; 3588 case RTLD_DI_ORIGIN: 3589 error = rtld_dirname(obj->path, p); 3590 break; 3591 3592 case RTLD_DI_SERINFOSIZE: 3593 case RTLD_DI_SERINFO: 3594 error = do_search_info(obj, request, (struct dl_serinfo *)p); 3595 break; 3596 3597 default: 3598 _rtld_error("Invalid request %d passed to dlinfo()", request); 3599 error = -1; 3600 } 3601 3602 lock_release(rtld_bind_lock, &lockstate); 3603 3604 return (error); 3605 } 3606 3607 static void 3608 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info) 3609 { 3610 3611 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase; 3612 phdr_info->dlpi_name = obj->path; 3613 phdr_info->dlpi_phdr = obj->phdr; 3614 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]); 3615 phdr_info->dlpi_tls_modid = obj->tlsindex; 3616 phdr_info->dlpi_tls_data = obj->tlsinit; 3617 phdr_info->dlpi_adds = obj_loads; 3618 phdr_info->dlpi_subs = obj_loads - obj_count; 3619 } 3620 3621 int 3622 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param) 3623 { 3624 struct dl_phdr_info phdr_info; 3625 Obj_Entry *obj, marker; 3626 RtldLockState bind_lockstate, phdr_lockstate; 3627 int error; 3628 3629 init_marker(&marker); 3630 error = 0; 3631 3632 wlock_acquire(rtld_phdr_lock, &phdr_lockstate); 3633 wlock_acquire(rtld_bind_lock, &bind_lockstate); 3634 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) { 3635 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next); 3636 rtld_fill_dl_phdr_info(obj, &phdr_info); 3637 hold_object(obj); 3638 lock_release(rtld_bind_lock, &bind_lockstate); 3639 3640 error = callback(&phdr_info, sizeof phdr_info, param); 3641 3642 wlock_acquire(rtld_bind_lock, &bind_lockstate); 3643 unhold_object(obj); 3644 obj = globallist_next(&marker); 3645 TAILQ_REMOVE(&obj_list, &marker, next); 3646 if (error != 0) { 3647 lock_release(rtld_bind_lock, &bind_lockstate); 3648 lock_release(rtld_phdr_lock, &phdr_lockstate); 3649 return (error); 3650 } 3651 } 3652 3653 if (error == 0) { 3654 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info); 3655 lock_release(rtld_bind_lock, &bind_lockstate); 3656 error = callback(&phdr_info, sizeof(phdr_info), param); 3657 } 3658 lock_release(rtld_phdr_lock, &phdr_lockstate); 3659 return (error); 3660 } 3661 3662 static void * 3663 fill_search_info(const char *dir, size_t dirlen, void *param) 3664 { 3665 struct fill_search_info_args *arg; 3666 3667 arg = param; 3668 3669 if (arg->request == RTLD_DI_SERINFOSIZE) { 3670 arg->serinfo->dls_cnt ++; 3671 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1; 3672 } else { 3673 struct dl_serpath *s_entry; 3674 3675 s_entry = arg->serpath; 3676 s_entry->dls_name = arg->strspace; 3677 s_entry->dls_flags = arg->flags; 3678 3679 strncpy(arg->strspace, dir, dirlen); 3680 arg->strspace[dirlen] = '\0'; 3681 3682 arg->strspace += dirlen + 1; 3683 arg->serpath++; 3684 } 3685 3686 return (NULL); 3687 } 3688 3689 static int 3690 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 3691 { 3692 struct dl_serinfo _info; 3693 struct fill_search_info_args args; 3694 3695 args.request = RTLD_DI_SERINFOSIZE; 3696 args.serinfo = &_info; 3697 3698 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 3699 _info.dls_cnt = 0; 3700 3701 path_enumerate(obj->rpath, fill_search_info, &args); 3702 path_enumerate(ld_library_path, fill_search_info, &args); 3703 path_enumerate(obj->runpath, fill_search_info, &args); 3704 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args); 3705 if (!obj->z_nodeflib) 3706 path_enumerate(ld_standard_library_path, fill_search_info, &args); 3707 3708 3709 if (request == RTLD_DI_SERINFOSIZE) { 3710 info->dls_size = _info.dls_size; 3711 info->dls_cnt = _info.dls_cnt; 3712 return (0); 3713 } 3714 3715 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { 3716 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); 3717 return (-1); 3718 } 3719 3720 args.request = RTLD_DI_SERINFO; 3721 args.serinfo = info; 3722 args.serpath = &info->dls_serpath[0]; 3723 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 3724 3725 args.flags = LA_SER_RUNPATH; 3726 if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL) 3727 return (-1); 3728 3729 args.flags = LA_SER_LIBPATH; 3730 if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL) 3731 return (-1); 3732 3733 args.flags = LA_SER_RUNPATH; 3734 if (path_enumerate(obj->runpath, fill_search_info, &args) != NULL) 3735 return (-1); 3736 3737 args.flags = LA_SER_CONFIG; 3738 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, &args) 3739 != NULL) 3740 return (-1); 3741 3742 args.flags = LA_SER_DEFAULT; 3743 if (!obj->z_nodeflib && 3744 path_enumerate(ld_standard_library_path, fill_search_info, &args) != NULL) 3745 return (-1); 3746 return (0); 3747 } 3748 3749 static int 3750 rtld_dirname(const char *path, char *bname) 3751 { 3752 const char *endp; 3753 3754 /* Empty or NULL string gets treated as "." */ 3755 if (path == NULL || *path == '\0') { 3756 bname[0] = '.'; 3757 bname[1] = '\0'; 3758 return (0); 3759 } 3760 3761 /* Strip trailing slashes */ 3762 endp = path + strlen(path) - 1; 3763 while (endp > path && *endp == '/') 3764 endp--; 3765 3766 /* Find the start of the dir */ 3767 while (endp > path && *endp != '/') 3768 endp--; 3769 3770 /* Either the dir is "/" or there are no slashes */ 3771 if (endp == path) { 3772 bname[0] = *endp == '/' ? '/' : '.'; 3773 bname[1] = '\0'; 3774 return (0); 3775 } else { 3776 do { 3777 endp--; 3778 } while (endp > path && *endp == '/'); 3779 } 3780 3781 if (endp - path + 2 > PATH_MAX) 3782 { 3783 _rtld_error("Filename is too long: %s", path); 3784 return(-1); 3785 } 3786 3787 strncpy(bname, path, endp - path + 1); 3788 bname[endp - path + 1] = '\0'; 3789 return (0); 3790 } 3791 3792 static int 3793 rtld_dirname_abs(const char *path, char *base) 3794 { 3795 char *last; 3796 3797 if (realpath(path, base) == NULL) 3798 return (-1); 3799 dbg("%s -> %s", path, base); 3800 last = strrchr(base, '/'); 3801 if (last == NULL) 3802 return (-1); 3803 if (last != base) 3804 *last = '\0'; 3805 return (0); 3806 } 3807 3808 static void 3809 linkmap_add(Obj_Entry *obj) 3810 { 3811 struct link_map *l = &obj->linkmap; 3812 struct link_map *prev; 3813 3814 obj->linkmap.l_name = obj->path; 3815 obj->linkmap.l_addr = obj->mapbase; 3816 obj->linkmap.l_ld = obj->dynamic; 3817 #ifdef __mips__ 3818 /* GDB needs load offset on MIPS to use the symbols */ 3819 obj->linkmap.l_offs = obj->relocbase; 3820 #endif 3821 3822 if (r_debug.r_map == NULL) { 3823 r_debug.r_map = l; 3824 return; 3825 } 3826 3827 /* 3828 * Scan to the end of the list, but not past the entry for the 3829 * dynamic linker, which we want to keep at the very end. 3830 */ 3831 for (prev = r_debug.r_map; 3832 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 3833 prev = prev->l_next) 3834 ; 3835 3836 /* Link in the new entry. */ 3837 l->l_prev = prev; 3838 l->l_next = prev->l_next; 3839 if (l->l_next != NULL) 3840 l->l_next->l_prev = l; 3841 prev->l_next = l; 3842 } 3843 3844 static void 3845 linkmap_delete(Obj_Entry *obj) 3846 { 3847 struct link_map *l = &obj->linkmap; 3848 3849 if (l->l_prev == NULL) { 3850 if ((r_debug.r_map = l->l_next) != NULL) 3851 l->l_next->l_prev = NULL; 3852 return; 3853 } 3854 3855 if ((l->l_prev->l_next = l->l_next) != NULL) 3856 l->l_next->l_prev = l->l_prev; 3857 } 3858 3859 /* 3860 * Function for the debugger to set a breakpoint on to gain control. 3861 * 3862 * The two parameters allow the debugger to easily find and determine 3863 * what the runtime loader is doing and to whom it is doing it. 3864 * 3865 * When the loadhook trap is hit (r_debug_state, set at program 3866 * initialization), the arguments can be found on the stack: 3867 * 3868 * +8 struct link_map *m 3869 * +4 struct r_debug *rd 3870 * +0 RetAddr 3871 */ 3872 void 3873 r_debug_state(struct r_debug* rd, struct link_map *m) 3874 { 3875 /* 3876 * The following is a hack to force the compiler to emit calls to 3877 * this function, even when optimizing. If the function is empty, 3878 * the compiler is not obliged to emit any code for calls to it, 3879 * even when marked __noinline. However, gdb depends on those 3880 * calls being made. 3881 */ 3882 __compiler_membar(); 3883 } 3884 3885 /* 3886 * A function called after init routines have completed. This can be used to 3887 * break before a program's entry routine is called, and can be used when 3888 * main is not available in the symbol table. 3889 */ 3890 void 3891 _r_debug_postinit(struct link_map *m) 3892 { 3893 3894 /* See r_debug_state(). */ 3895 __compiler_membar(); 3896 } 3897 3898 static void 3899 release_object(Obj_Entry *obj) 3900 { 3901 3902 if (obj->holdcount > 0) { 3903 obj->unholdfree = true; 3904 return; 3905 } 3906 munmap(obj->mapbase, obj->mapsize); 3907 linkmap_delete(obj); 3908 obj_free(obj); 3909 } 3910 3911 /* 3912 * Get address of the pointer variable in the main program. 3913 * Prefer non-weak symbol over the weak one. 3914 */ 3915 static const void ** 3916 get_program_var_addr(const char *name, RtldLockState *lockstate) 3917 { 3918 SymLook req; 3919 DoneList donelist; 3920 3921 symlook_init(&req, name); 3922 req.lockstate = lockstate; 3923 donelist_init(&donelist); 3924 if (symlook_global(&req, &donelist) != 0) 3925 return (NULL); 3926 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC) 3927 return ((const void **)make_function_pointer(req.sym_out, 3928 req.defobj_out)); 3929 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC) 3930 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out)); 3931 else 3932 return ((const void **)(req.defobj_out->relocbase + 3933 req.sym_out->st_value)); 3934 } 3935 3936 /* 3937 * Set a pointer variable in the main program to the given value. This 3938 * is used to set key variables such as "environ" before any of the 3939 * init functions are called. 3940 */ 3941 static void 3942 set_program_var(const char *name, const void *value) 3943 { 3944 const void **addr; 3945 3946 if ((addr = get_program_var_addr(name, NULL)) != NULL) { 3947 dbg("\"%s\": *%p <-- %p", name, addr, value); 3948 *addr = value; 3949 } 3950 } 3951 3952 /* 3953 * Search the global objects, including dependencies and main object, 3954 * for the given symbol. 3955 */ 3956 static int 3957 symlook_global(SymLook *req, DoneList *donelist) 3958 { 3959 SymLook req1; 3960 const Objlist_Entry *elm; 3961 int res; 3962 3963 symlook_init_from_req(&req1, req); 3964 3965 /* Search all objects loaded at program start up. */ 3966 if (req->defobj_out == NULL || 3967 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 3968 res = symlook_list(&req1, &list_main, donelist); 3969 if (res == 0 && (req->defobj_out == NULL || 3970 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 3971 req->sym_out = req1.sym_out; 3972 req->defobj_out = req1.defobj_out; 3973 assert(req->defobj_out != NULL); 3974 } 3975 } 3976 3977 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 3978 STAILQ_FOREACH(elm, &list_global, link) { 3979 if (req->defobj_out != NULL && 3980 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK) 3981 break; 3982 res = symlook_list(&req1, &elm->obj->dagmembers, donelist); 3983 if (res == 0 && (req->defobj_out == NULL || 3984 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 3985 req->sym_out = req1.sym_out; 3986 req->defobj_out = req1.defobj_out; 3987 assert(req->defobj_out != NULL); 3988 } 3989 } 3990 3991 return (req->sym_out != NULL ? 0 : ESRCH); 3992 } 3993 3994 /* 3995 * Given a symbol name in a referencing object, find the corresponding 3996 * definition of the symbol. Returns a pointer to the symbol, or NULL if 3997 * no definition was found. Returns a pointer to the Obj_Entry of the 3998 * defining object via the reference parameter DEFOBJ_OUT. 3999 */ 4000 static int 4001 symlook_default(SymLook *req, const Obj_Entry *refobj) 4002 { 4003 DoneList donelist; 4004 const Objlist_Entry *elm; 4005 SymLook req1; 4006 int res; 4007 4008 donelist_init(&donelist); 4009 symlook_init_from_req(&req1, req); 4010 4011 /* 4012 * Look first in the referencing object if linked symbolically, 4013 * and similarly handle protected symbols. 4014 */ 4015 res = symlook_obj(&req1, refobj); 4016 if (res == 0 && (refobj->symbolic || 4017 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) { 4018 req->sym_out = req1.sym_out; 4019 req->defobj_out = req1.defobj_out; 4020 assert(req->defobj_out != NULL); 4021 } 4022 if (refobj->symbolic || req->defobj_out != NULL) 4023 donelist_check(&donelist, refobj); 4024 4025 symlook_global(req, &donelist); 4026 4027 /* Search all dlopened DAGs containing the referencing object. */ 4028 STAILQ_FOREACH(elm, &refobj->dldags, link) { 4029 if (req->sym_out != NULL && 4030 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK) 4031 break; 4032 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist); 4033 if (res == 0 && (req->sym_out == NULL || 4034 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4035 req->sym_out = req1.sym_out; 4036 req->defobj_out = req1.defobj_out; 4037 assert(req->defobj_out != NULL); 4038 } 4039 } 4040 4041 /* 4042 * Search the dynamic linker itself, and possibly resolve the 4043 * symbol from there. This is how the application links to 4044 * dynamic linker services such as dlopen. 4045 */ 4046 if (req->sym_out == NULL || 4047 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 4048 res = symlook_obj(&req1, &obj_rtld); 4049 if (res == 0) { 4050 req->sym_out = req1.sym_out; 4051 req->defobj_out = req1.defobj_out; 4052 assert(req->defobj_out != NULL); 4053 } 4054 } 4055 4056 return (req->sym_out != NULL ? 0 : ESRCH); 4057 } 4058 4059 static int 4060 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp) 4061 { 4062 const Elf_Sym *def; 4063 const Obj_Entry *defobj; 4064 const Objlist_Entry *elm; 4065 SymLook req1; 4066 int res; 4067 4068 def = NULL; 4069 defobj = NULL; 4070 STAILQ_FOREACH(elm, objlist, link) { 4071 if (donelist_check(dlp, elm->obj)) 4072 continue; 4073 symlook_init_from_req(&req1, req); 4074 if ((res = symlook_obj(&req1, elm->obj)) == 0) { 4075 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) { 4076 def = req1.sym_out; 4077 defobj = req1.defobj_out; 4078 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 4079 break; 4080 } 4081 } 4082 } 4083 if (def != NULL) { 4084 req->sym_out = def; 4085 req->defobj_out = defobj; 4086 return (0); 4087 } 4088 return (ESRCH); 4089 } 4090 4091 /* 4092 * Search the chain of DAGS cointed to by the given Needed_Entry 4093 * for a symbol of the given name. Each DAG is scanned completely 4094 * before advancing to the next one. Returns a pointer to the symbol, 4095 * or NULL if no definition was found. 4096 */ 4097 static int 4098 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp) 4099 { 4100 const Elf_Sym *def; 4101 const Needed_Entry *n; 4102 const Obj_Entry *defobj; 4103 SymLook req1; 4104 int res; 4105 4106 def = NULL; 4107 defobj = NULL; 4108 symlook_init_from_req(&req1, req); 4109 for (n = needed; n != NULL; n = n->next) { 4110 if (n->obj == NULL || 4111 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0) 4112 continue; 4113 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) { 4114 def = req1.sym_out; 4115 defobj = req1.defobj_out; 4116 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 4117 break; 4118 } 4119 } 4120 if (def != NULL) { 4121 req->sym_out = def; 4122 req->defobj_out = defobj; 4123 return (0); 4124 } 4125 return (ESRCH); 4126 } 4127 4128 /* 4129 * Search the symbol table of a single shared object for a symbol of 4130 * the given name and version, if requested. Returns a pointer to the 4131 * symbol, or NULL if no definition was found. If the object is 4132 * filter, return filtered symbol from filtee. 4133 * 4134 * The symbol's hash value is passed in for efficiency reasons; that 4135 * eliminates many recomputations of the hash value. 4136 */ 4137 int 4138 symlook_obj(SymLook *req, const Obj_Entry *obj) 4139 { 4140 DoneList donelist; 4141 SymLook req1; 4142 int flags, res, mres; 4143 4144 /* 4145 * If there is at least one valid hash at this point, we prefer to 4146 * use the faster GNU version if available. 4147 */ 4148 if (obj->valid_hash_gnu) 4149 mres = symlook_obj1_gnu(req, obj); 4150 else if (obj->valid_hash_sysv) 4151 mres = symlook_obj1_sysv(req, obj); 4152 else 4153 return (EINVAL); 4154 4155 if (mres == 0) { 4156 if (obj->needed_filtees != NULL) { 4157 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0; 4158 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4159 donelist_init(&donelist); 4160 symlook_init_from_req(&req1, req); 4161 res = symlook_needed(&req1, obj->needed_filtees, &donelist); 4162 if (res == 0) { 4163 req->sym_out = req1.sym_out; 4164 req->defobj_out = req1.defobj_out; 4165 } 4166 return (res); 4167 } 4168 if (obj->needed_aux_filtees != NULL) { 4169 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0; 4170 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4171 donelist_init(&donelist); 4172 symlook_init_from_req(&req1, req); 4173 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist); 4174 if (res == 0) { 4175 req->sym_out = req1.sym_out; 4176 req->defobj_out = req1.defobj_out; 4177 return (res); 4178 } 4179 } 4180 } 4181 return (mres); 4182 } 4183 4184 /* Symbol match routine common to both hash functions */ 4185 static bool 4186 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result, 4187 const unsigned long symnum) 4188 { 4189 Elf_Versym verndx; 4190 const Elf_Sym *symp; 4191 const char *strp; 4192 4193 symp = obj->symtab + symnum; 4194 strp = obj->strtab + symp->st_name; 4195 4196 switch (ELF_ST_TYPE(symp->st_info)) { 4197 case STT_FUNC: 4198 case STT_NOTYPE: 4199 case STT_OBJECT: 4200 case STT_COMMON: 4201 case STT_GNU_IFUNC: 4202 if (symp->st_value == 0) 4203 return (false); 4204 /* fallthrough */ 4205 case STT_TLS: 4206 if (symp->st_shndx != SHN_UNDEF) 4207 break; 4208 #ifndef __mips__ 4209 else if (((req->flags & SYMLOOK_IN_PLT) == 0) && 4210 (ELF_ST_TYPE(symp->st_info) == STT_FUNC)) 4211 break; 4212 /* fallthrough */ 4213 #endif 4214 default: 4215 return (false); 4216 } 4217 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0) 4218 return (false); 4219 4220 if (req->ventry == NULL) { 4221 if (obj->versyms != NULL) { 4222 verndx = VER_NDX(obj->versyms[symnum]); 4223 if (verndx > obj->vernum) { 4224 _rtld_error( 4225 "%s: symbol %s references wrong version %d", 4226 obj->path, obj->strtab + symnum, verndx); 4227 return (false); 4228 } 4229 /* 4230 * If we are not called from dlsym (i.e. this 4231 * is a normal relocation from unversioned 4232 * binary), accept the symbol immediately if 4233 * it happens to have first version after this 4234 * shared object became versioned. Otherwise, 4235 * if symbol is versioned and not hidden, 4236 * remember it. If it is the only symbol with 4237 * this name exported by the shared object, it 4238 * will be returned as a match by the calling 4239 * function. If symbol is global (verndx < 2) 4240 * accept it unconditionally. 4241 */ 4242 if ((req->flags & SYMLOOK_DLSYM) == 0 && 4243 verndx == VER_NDX_GIVEN) { 4244 result->sym_out = symp; 4245 return (true); 4246 } 4247 else if (verndx >= VER_NDX_GIVEN) { 4248 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) 4249 == 0) { 4250 if (result->vsymp == NULL) 4251 result->vsymp = symp; 4252 result->vcount++; 4253 } 4254 return (false); 4255 } 4256 } 4257 result->sym_out = symp; 4258 return (true); 4259 } 4260 if (obj->versyms == NULL) { 4261 if (object_match_name(obj, req->ventry->name)) { 4262 _rtld_error("%s: object %s should provide version %s " 4263 "for symbol %s", obj_rtld.path, obj->path, 4264 req->ventry->name, obj->strtab + symnum); 4265 return (false); 4266 } 4267 } else { 4268 verndx = VER_NDX(obj->versyms[symnum]); 4269 if (verndx > obj->vernum) { 4270 _rtld_error("%s: symbol %s references wrong version %d", 4271 obj->path, obj->strtab + symnum, verndx); 4272 return (false); 4273 } 4274 if (obj->vertab[verndx].hash != req->ventry->hash || 4275 strcmp(obj->vertab[verndx].name, req->ventry->name)) { 4276 /* 4277 * Version does not match. Look if this is a 4278 * global symbol and if it is not hidden. If 4279 * global symbol (verndx < 2) is available, 4280 * use it. Do not return symbol if we are 4281 * called by dlvsym, because dlvsym looks for 4282 * a specific version and default one is not 4283 * what dlvsym wants. 4284 */ 4285 if ((req->flags & SYMLOOK_DLSYM) || 4286 (verndx >= VER_NDX_GIVEN) || 4287 (obj->versyms[symnum] & VER_NDX_HIDDEN)) 4288 return (false); 4289 } 4290 } 4291 result->sym_out = symp; 4292 return (true); 4293 } 4294 4295 /* 4296 * Search for symbol using SysV hash function. 4297 * obj->buckets is known not to be NULL at this point; the test for this was 4298 * performed with the obj->valid_hash_sysv assignment. 4299 */ 4300 static int 4301 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj) 4302 { 4303 unsigned long symnum; 4304 Sym_Match_Result matchres; 4305 4306 matchres.sym_out = NULL; 4307 matchres.vsymp = NULL; 4308 matchres.vcount = 0; 4309 4310 for (symnum = obj->buckets[req->hash % obj->nbuckets]; 4311 symnum != STN_UNDEF; symnum = obj->chains[symnum]) { 4312 if (symnum >= obj->nchains) 4313 return (ESRCH); /* Bad object */ 4314 4315 if (matched_symbol(req, obj, &matchres, symnum)) { 4316 req->sym_out = matchres.sym_out; 4317 req->defobj_out = obj; 4318 return (0); 4319 } 4320 } 4321 if (matchres.vcount == 1) { 4322 req->sym_out = matchres.vsymp; 4323 req->defobj_out = obj; 4324 return (0); 4325 } 4326 return (ESRCH); 4327 } 4328 4329 /* Search for symbol using GNU hash function */ 4330 static int 4331 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj) 4332 { 4333 Elf_Addr bloom_word; 4334 const Elf32_Word *hashval; 4335 Elf32_Word bucket; 4336 Sym_Match_Result matchres; 4337 unsigned int h1, h2; 4338 unsigned long symnum; 4339 4340 matchres.sym_out = NULL; 4341 matchres.vsymp = NULL; 4342 matchres.vcount = 0; 4343 4344 /* Pick right bitmask word from Bloom filter array */ 4345 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) & 4346 obj->maskwords_bm_gnu]; 4347 4348 /* Calculate modulus word size of gnu hash and its derivative */ 4349 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1); 4350 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1)); 4351 4352 /* Filter out the "definitely not in set" queries */ 4353 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0) 4354 return (ESRCH); 4355 4356 /* Locate hash chain and corresponding value element*/ 4357 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu]; 4358 if (bucket == 0) 4359 return (ESRCH); 4360 hashval = &obj->chain_zero_gnu[bucket]; 4361 do { 4362 if (((*hashval ^ req->hash_gnu) >> 1) == 0) { 4363 symnum = hashval - obj->chain_zero_gnu; 4364 if (matched_symbol(req, obj, &matchres, symnum)) { 4365 req->sym_out = matchres.sym_out; 4366 req->defobj_out = obj; 4367 return (0); 4368 } 4369 } 4370 } while ((*hashval++ & 1) == 0); 4371 if (matchres.vcount == 1) { 4372 req->sym_out = matchres.vsymp; 4373 req->defobj_out = obj; 4374 return (0); 4375 } 4376 return (ESRCH); 4377 } 4378 4379 static void 4380 trace_loaded_objects(Obj_Entry *obj) 4381 { 4382 char *fmt1, *fmt2, *fmt, *main_local, *list_containers; 4383 int c; 4384 4385 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL) 4386 main_local = ""; 4387 4388 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL) 4389 fmt1 = "\t%o => %p (%x)\n"; 4390 4391 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL) 4392 fmt2 = "\t%o (%x)\n"; 4393 4394 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL")); 4395 4396 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 4397 Needed_Entry *needed; 4398 char *name, *path; 4399 bool is_lib; 4400 4401 if (obj->marker) 4402 continue; 4403 if (list_containers && obj->needed != NULL) 4404 rtld_printf("%s:\n", obj->path); 4405 for (needed = obj->needed; needed; needed = needed->next) { 4406 if (needed->obj != NULL) { 4407 if (needed->obj->traced && !list_containers) 4408 continue; 4409 needed->obj->traced = true; 4410 path = needed->obj->path; 4411 } else 4412 path = "not found"; 4413 4414 name = (char *)obj->strtab + needed->name; 4415 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */ 4416 4417 fmt = is_lib ? fmt1 : fmt2; 4418 while ((c = *fmt++) != '\0') { 4419 switch (c) { 4420 default: 4421 rtld_putchar(c); 4422 continue; 4423 case '\\': 4424 switch (c = *fmt) { 4425 case '\0': 4426 continue; 4427 case 'n': 4428 rtld_putchar('\n'); 4429 break; 4430 case 't': 4431 rtld_putchar('\t'); 4432 break; 4433 } 4434 break; 4435 case '%': 4436 switch (c = *fmt) { 4437 case '\0': 4438 continue; 4439 case '%': 4440 default: 4441 rtld_putchar(c); 4442 break; 4443 case 'A': 4444 rtld_putstr(main_local); 4445 break; 4446 case 'a': 4447 rtld_putstr(obj_main->path); 4448 break; 4449 case 'o': 4450 rtld_putstr(name); 4451 break; 4452 #if 0 4453 case 'm': 4454 rtld_printf("%d", sodp->sod_major); 4455 break; 4456 case 'n': 4457 rtld_printf("%d", sodp->sod_minor); 4458 break; 4459 #endif 4460 case 'p': 4461 rtld_putstr(path); 4462 break; 4463 case 'x': 4464 rtld_printf("%p", needed->obj ? needed->obj->mapbase : 4465 0); 4466 break; 4467 } 4468 break; 4469 } 4470 ++fmt; 4471 } 4472 } 4473 } 4474 } 4475 4476 /* 4477 * Unload a dlopened object and its dependencies from memory and from 4478 * our data structures. It is assumed that the DAG rooted in the 4479 * object has already been unreferenced, and that the object has a 4480 * reference count of 0. 4481 */ 4482 static void 4483 unload_object(Obj_Entry *root, RtldLockState *lockstate) 4484 { 4485 Obj_Entry marker, *obj, *next; 4486 4487 assert(root->refcount == 0); 4488 4489 /* 4490 * Pass over the DAG removing unreferenced objects from 4491 * appropriate lists. 4492 */ 4493 unlink_object(root); 4494 4495 /* Unmap all objects that are no longer referenced. */ 4496 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) { 4497 next = TAILQ_NEXT(obj, next); 4498 if (obj->marker || obj->refcount != 0) 4499 continue; 4500 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, 4501 obj->mapsize, 0, obj->path); 4502 dbg("unloading \"%s\"", obj->path); 4503 /* 4504 * Unlink the object now to prevent new references from 4505 * being acquired while the bind lock is dropped in 4506 * recursive dlclose() invocations. 4507 */ 4508 TAILQ_REMOVE(&obj_list, obj, next); 4509 obj_count--; 4510 4511 if (obj->filtees_loaded) { 4512 if (next != NULL) { 4513 init_marker(&marker); 4514 TAILQ_INSERT_BEFORE(next, &marker, next); 4515 unload_filtees(obj, lockstate); 4516 next = TAILQ_NEXT(&marker, next); 4517 TAILQ_REMOVE(&obj_list, &marker, next); 4518 } else 4519 unload_filtees(obj, lockstate); 4520 } 4521 release_object(obj); 4522 } 4523 } 4524 4525 static void 4526 unlink_object(Obj_Entry *root) 4527 { 4528 Objlist_Entry *elm; 4529 4530 if (root->refcount == 0) { 4531 /* Remove the object from the RTLD_GLOBAL list. */ 4532 objlist_remove(&list_global, root); 4533 4534 /* Remove the object from all objects' DAG lists. */ 4535 STAILQ_FOREACH(elm, &root->dagmembers, link) { 4536 objlist_remove(&elm->obj->dldags, root); 4537 if (elm->obj != root) 4538 unlink_object(elm->obj); 4539 } 4540 } 4541 } 4542 4543 static void 4544 ref_dag(Obj_Entry *root) 4545 { 4546 Objlist_Entry *elm; 4547 4548 assert(root->dag_inited); 4549 STAILQ_FOREACH(elm, &root->dagmembers, link) 4550 elm->obj->refcount++; 4551 } 4552 4553 static void 4554 unref_dag(Obj_Entry *root) 4555 { 4556 Objlist_Entry *elm; 4557 4558 assert(root->dag_inited); 4559 STAILQ_FOREACH(elm, &root->dagmembers, link) 4560 elm->obj->refcount--; 4561 } 4562 4563 /* 4564 * Common code for MD __tls_get_addr(). 4565 */ 4566 static void *tls_get_addr_slow(Elf_Addr **, int, size_t) __noinline; 4567 static void * 4568 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset) 4569 { 4570 Elf_Addr *newdtv, *dtv; 4571 RtldLockState lockstate; 4572 int to_copy; 4573 4574 dtv = *dtvp; 4575 /* Check dtv generation in case new modules have arrived */ 4576 if (dtv[0] != tls_dtv_generation) { 4577 wlock_acquire(rtld_bind_lock, &lockstate); 4578 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 4579 to_copy = dtv[1]; 4580 if (to_copy > tls_max_index) 4581 to_copy = tls_max_index; 4582 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); 4583 newdtv[0] = tls_dtv_generation; 4584 newdtv[1] = tls_max_index; 4585 free(dtv); 4586 lock_release(rtld_bind_lock, &lockstate); 4587 dtv = *dtvp = newdtv; 4588 } 4589 4590 /* Dynamically allocate module TLS if necessary */ 4591 if (dtv[index + 1] == 0) { 4592 /* Signal safe, wlock will block out signals. */ 4593 wlock_acquire(rtld_bind_lock, &lockstate); 4594 if (!dtv[index + 1]) 4595 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); 4596 lock_release(rtld_bind_lock, &lockstate); 4597 } 4598 return ((void *)(dtv[index + 1] + offset)); 4599 } 4600 4601 void * 4602 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset) 4603 { 4604 Elf_Addr *dtv; 4605 4606 dtv = *dtvp; 4607 /* Check dtv generation in case new modules have arrived */ 4608 if (__predict_true(dtv[0] == tls_dtv_generation && 4609 dtv[index + 1] != 0)) 4610 return ((void *)(dtv[index + 1] + offset)); 4611 return (tls_get_addr_slow(dtvp, index, offset)); 4612 } 4613 4614 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \ 4615 defined(__powerpc__) || defined(__riscv__) 4616 4617 /* 4618 * Allocate Static TLS using the Variant I method. 4619 */ 4620 void * 4621 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 4622 { 4623 Obj_Entry *obj; 4624 char *tcb; 4625 Elf_Addr **tls; 4626 Elf_Addr *dtv; 4627 Elf_Addr addr; 4628 int i; 4629 4630 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) 4631 return (oldtcb); 4632 4633 assert(tcbsize >= TLS_TCB_SIZE); 4634 tcb = xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize); 4635 tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE); 4636 4637 if (oldtcb != NULL) { 4638 memcpy(tls, oldtcb, tls_static_space); 4639 free(oldtcb); 4640 4641 /* Adjust the DTV. */ 4642 dtv = tls[0]; 4643 for (i = 0; i < dtv[1]; i++) { 4644 if (dtv[i+2] >= (Elf_Addr)oldtcb && 4645 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) { 4646 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls; 4647 } 4648 } 4649 } else { 4650 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 4651 tls[0] = dtv; 4652 dtv[0] = tls_dtv_generation; 4653 dtv[1] = tls_max_index; 4654 4655 for (obj = globallist_curr(objs); obj != NULL; 4656 obj = globallist_next(obj)) { 4657 if (obj->tlsoffset > 0) { 4658 addr = (Elf_Addr)tls + obj->tlsoffset; 4659 if (obj->tlsinitsize > 0) 4660 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize); 4661 if (obj->tlssize > obj->tlsinitsize) 4662 memset((void*) (addr + obj->tlsinitsize), 0, 4663 obj->tlssize - obj->tlsinitsize); 4664 dtv[obj->tlsindex + 1] = addr; 4665 } 4666 } 4667 } 4668 4669 return (tcb); 4670 } 4671 4672 void 4673 free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 4674 { 4675 Elf_Addr *dtv; 4676 Elf_Addr tlsstart, tlsend; 4677 int dtvsize, i; 4678 4679 assert(tcbsize >= TLS_TCB_SIZE); 4680 4681 tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE; 4682 tlsend = tlsstart + tls_static_space; 4683 4684 dtv = *(Elf_Addr **)tlsstart; 4685 dtvsize = dtv[1]; 4686 for (i = 0; i < dtvsize; i++) { 4687 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) { 4688 free((void*)dtv[i+2]); 4689 } 4690 } 4691 free(dtv); 4692 free(tcb); 4693 } 4694 4695 #endif 4696 4697 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) 4698 4699 /* 4700 * Allocate Static TLS using the Variant II method. 4701 */ 4702 void * 4703 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 4704 { 4705 Obj_Entry *obj; 4706 size_t size, ralign; 4707 char *tls; 4708 Elf_Addr *dtv, *olddtv; 4709 Elf_Addr segbase, oldsegbase, addr; 4710 int i; 4711 4712 ralign = tcbalign; 4713 if (tls_static_max_align > ralign) 4714 ralign = tls_static_max_align; 4715 size = round(tls_static_space, ralign) + round(tcbsize, ralign); 4716 4717 assert(tcbsize >= 2*sizeof(Elf_Addr)); 4718 tls = malloc_aligned(size, ralign); 4719 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 4720 4721 segbase = (Elf_Addr)(tls + round(tls_static_space, ralign)); 4722 ((Elf_Addr*)segbase)[0] = segbase; 4723 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv; 4724 4725 dtv[0] = tls_dtv_generation; 4726 dtv[1] = tls_max_index; 4727 4728 if (oldtls) { 4729 /* 4730 * Copy the static TLS block over whole. 4731 */ 4732 oldsegbase = (Elf_Addr) oldtls; 4733 memcpy((void *)(segbase - tls_static_space), 4734 (const void *)(oldsegbase - tls_static_space), 4735 tls_static_space); 4736 4737 /* 4738 * If any dynamic TLS blocks have been created tls_get_addr(), 4739 * move them over. 4740 */ 4741 olddtv = ((Elf_Addr**)oldsegbase)[1]; 4742 for (i = 0; i < olddtv[1]; i++) { 4743 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) { 4744 dtv[i+2] = olddtv[i+2]; 4745 olddtv[i+2] = 0; 4746 } 4747 } 4748 4749 /* 4750 * We assume that this block was the one we created with 4751 * allocate_initial_tls(). 4752 */ 4753 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); 4754 } else { 4755 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 4756 if (obj->marker || obj->tlsoffset == 0) 4757 continue; 4758 addr = segbase - obj->tlsoffset; 4759 memset((void*) (addr + obj->tlsinitsize), 4760 0, obj->tlssize - obj->tlsinitsize); 4761 if (obj->tlsinit) 4762 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize); 4763 dtv[obj->tlsindex + 1] = addr; 4764 } 4765 } 4766 4767 return (void*) segbase; 4768 } 4769 4770 void 4771 free_tls(void *tls, size_t tcbsize, size_t tcbalign) 4772 { 4773 Elf_Addr* dtv; 4774 size_t size, ralign; 4775 int dtvsize, i; 4776 Elf_Addr tlsstart, tlsend; 4777 4778 /* 4779 * Figure out the size of the initial TLS block so that we can 4780 * find stuff which ___tls_get_addr() allocated dynamically. 4781 */ 4782 ralign = tcbalign; 4783 if (tls_static_max_align > ralign) 4784 ralign = tls_static_max_align; 4785 size = round(tls_static_space, ralign); 4786 4787 dtv = ((Elf_Addr**)tls)[1]; 4788 dtvsize = dtv[1]; 4789 tlsend = (Elf_Addr) tls; 4790 tlsstart = tlsend - size; 4791 for (i = 0; i < dtvsize; i++) { 4792 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) { 4793 free_aligned((void *)dtv[i + 2]); 4794 } 4795 } 4796 4797 free_aligned((void *)tlsstart); 4798 free((void*) dtv); 4799 } 4800 4801 #endif 4802 4803 /* 4804 * Allocate TLS block for module with given index. 4805 */ 4806 void * 4807 allocate_module_tls(int index) 4808 { 4809 Obj_Entry* obj; 4810 char* p; 4811 4812 TAILQ_FOREACH(obj, &obj_list, next) { 4813 if (obj->marker) 4814 continue; 4815 if (obj->tlsindex == index) 4816 break; 4817 } 4818 if (!obj) { 4819 _rtld_error("Can't find module with TLS index %d", index); 4820 rtld_die(); 4821 } 4822 4823 p = malloc_aligned(obj->tlssize, obj->tlsalign); 4824 memcpy(p, obj->tlsinit, obj->tlsinitsize); 4825 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 4826 4827 return p; 4828 } 4829 4830 bool 4831 allocate_tls_offset(Obj_Entry *obj) 4832 { 4833 size_t off; 4834 4835 if (obj->tls_done) 4836 return true; 4837 4838 if (obj->tlssize == 0) { 4839 obj->tls_done = true; 4840 return true; 4841 } 4842 4843 if (tls_last_offset == 0) 4844 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign); 4845 else 4846 off = calculate_tls_offset(tls_last_offset, tls_last_size, 4847 obj->tlssize, obj->tlsalign); 4848 4849 /* 4850 * If we have already fixed the size of the static TLS block, we 4851 * must stay within that size. When allocating the static TLS, we 4852 * leave a small amount of space spare to be used for dynamically 4853 * loading modules which use static TLS. 4854 */ 4855 if (tls_static_space != 0) { 4856 if (calculate_tls_end(off, obj->tlssize) > tls_static_space) 4857 return false; 4858 } else if (obj->tlsalign > tls_static_max_align) { 4859 tls_static_max_align = obj->tlsalign; 4860 } 4861 4862 tls_last_offset = obj->tlsoffset = off; 4863 tls_last_size = obj->tlssize; 4864 obj->tls_done = true; 4865 4866 return true; 4867 } 4868 4869 void 4870 free_tls_offset(Obj_Entry *obj) 4871 { 4872 4873 /* 4874 * If we were the last thing to allocate out of the static TLS 4875 * block, we give our space back to the 'allocator'. This is a 4876 * simplistic workaround to allow libGL.so.1 to be loaded and 4877 * unloaded multiple times. 4878 */ 4879 if (calculate_tls_end(obj->tlsoffset, obj->tlssize) 4880 == calculate_tls_end(tls_last_offset, tls_last_size)) { 4881 tls_last_offset -= obj->tlssize; 4882 tls_last_size = 0; 4883 } 4884 } 4885 4886 void * 4887 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) 4888 { 4889 void *ret; 4890 RtldLockState lockstate; 4891 4892 wlock_acquire(rtld_bind_lock, &lockstate); 4893 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls, 4894 tcbsize, tcbalign); 4895 lock_release(rtld_bind_lock, &lockstate); 4896 return (ret); 4897 } 4898 4899 void 4900 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 4901 { 4902 RtldLockState lockstate; 4903 4904 wlock_acquire(rtld_bind_lock, &lockstate); 4905 free_tls(tcb, tcbsize, tcbalign); 4906 lock_release(rtld_bind_lock, &lockstate); 4907 } 4908 4909 static void 4910 object_add_name(Obj_Entry *obj, const char *name) 4911 { 4912 Name_Entry *entry; 4913 size_t len; 4914 4915 len = strlen(name); 4916 entry = malloc(sizeof(Name_Entry) + len); 4917 4918 if (entry != NULL) { 4919 strcpy(entry->name, name); 4920 STAILQ_INSERT_TAIL(&obj->names, entry, link); 4921 } 4922 } 4923 4924 static int 4925 object_match_name(const Obj_Entry *obj, const char *name) 4926 { 4927 Name_Entry *entry; 4928 4929 STAILQ_FOREACH(entry, &obj->names, link) { 4930 if (strcmp(name, entry->name) == 0) 4931 return (1); 4932 } 4933 return (0); 4934 } 4935 4936 static Obj_Entry * 4937 locate_dependency(const Obj_Entry *obj, const char *name) 4938 { 4939 const Objlist_Entry *entry; 4940 const Needed_Entry *needed; 4941 4942 STAILQ_FOREACH(entry, &list_main, link) { 4943 if (object_match_name(entry->obj, name)) 4944 return entry->obj; 4945 } 4946 4947 for (needed = obj->needed; needed != NULL; needed = needed->next) { 4948 if (strcmp(obj->strtab + needed->name, name) == 0 || 4949 (needed->obj != NULL && object_match_name(needed->obj, name))) { 4950 /* 4951 * If there is DT_NEEDED for the name we are looking for, 4952 * we are all set. Note that object might not be found if 4953 * dependency was not loaded yet, so the function can 4954 * return NULL here. This is expected and handled 4955 * properly by the caller. 4956 */ 4957 return (needed->obj); 4958 } 4959 } 4960 _rtld_error("%s: Unexpected inconsistency: dependency %s not found", 4961 obj->path, name); 4962 rtld_die(); 4963 } 4964 4965 static int 4966 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj, 4967 const Elf_Vernaux *vna) 4968 { 4969 const Elf_Verdef *vd; 4970 const char *vername; 4971 4972 vername = refobj->strtab + vna->vna_name; 4973 vd = depobj->verdef; 4974 if (vd == NULL) { 4975 _rtld_error("%s: version %s required by %s not defined", 4976 depobj->path, vername, refobj->path); 4977 return (-1); 4978 } 4979 for (;;) { 4980 if (vd->vd_version != VER_DEF_CURRENT) { 4981 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 4982 depobj->path, vd->vd_version); 4983 return (-1); 4984 } 4985 if (vna->vna_hash == vd->vd_hash) { 4986 const Elf_Verdaux *aux = (const Elf_Verdaux *) 4987 ((char *)vd + vd->vd_aux); 4988 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0) 4989 return (0); 4990 } 4991 if (vd->vd_next == 0) 4992 break; 4993 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next); 4994 } 4995 if (vna->vna_flags & VER_FLG_WEAK) 4996 return (0); 4997 _rtld_error("%s: version %s required by %s not found", 4998 depobj->path, vername, refobj->path); 4999 return (-1); 5000 } 5001 5002 static int 5003 rtld_verify_object_versions(Obj_Entry *obj) 5004 { 5005 const Elf_Verneed *vn; 5006 const Elf_Verdef *vd; 5007 const Elf_Verdaux *vda; 5008 const Elf_Vernaux *vna; 5009 const Obj_Entry *depobj; 5010 int maxvernum, vernum; 5011 5012 if (obj->ver_checked) 5013 return (0); 5014 obj->ver_checked = true; 5015 5016 maxvernum = 0; 5017 /* 5018 * Walk over defined and required version records and figure out 5019 * max index used by any of them. Do very basic sanity checking 5020 * while there. 5021 */ 5022 vn = obj->verneed; 5023 while (vn != NULL) { 5024 if (vn->vn_version != VER_NEED_CURRENT) { 5025 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry", 5026 obj->path, vn->vn_version); 5027 return (-1); 5028 } 5029 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux); 5030 for (;;) { 5031 vernum = VER_NEED_IDX(vna->vna_other); 5032 if (vernum > maxvernum) 5033 maxvernum = vernum; 5034 if (vna->vna_next == 0) 5035 break; 5036 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next); 5037 } 5038 if (vn->vn_next == 0) 5039 break; 5040 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next); 5041 } 5042 5043 vd = obj->verdef; 5044 while (vd != NULL) { 5045 if (vd->vd_version != VER_DEF_CURRENT) { 5046 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5047 obj->path, vd->vd_version); 5048 return (-1); 5049 } 5050 vernum = VER_DEF_IDX(vd->vd_ndx); 5051 if (vernum > maxvernum) 5052 maxvernum = vernum; 5053 if (vd->vd_next == 0) 5054 break; 5055 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next); 5056 } 5057 5058 if (maxvernum == 0) 5059 return (0); 5060 5061 /* 5062 * Store version information in array indexable by version index. 5063 * Verify that object version requirements are satisfied along the 5064 * way. 5065 */ 5066 obj->vernum = maxvernum + 1; 5067 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry)); 5068 5069 vd = obj->verdef; 5070 while (vd != NULL) { 5071 if ((vd->vd_flags & VER_FLG_BASE) == 0) { 5072 vernum = VER_DEF_IDX(vd->vd_ndx); 5073 assert(vernum <= maxvernum); 5074 vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux); 5075 obj->vertab[vernum].hash = vd->vd_hash; 5076 obj->vertab[vernum].name = obj->strtab + vda->vda_name; 5077 obj->vertab[vernum].file = NULL; 5078 obj->vertab[vernum].flags = 0; 5079 } 5080 if (vd->vd_next == 0) 5081 break; 5082 vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next); 5083 } 5084 5085 vn = obj->verneed; 5086 while (vn != NULL) { 5087 depobj = locate_dependency(obj, obj->strtab + vn->vn_file); 5088 if (depobj == NULL) 5089 return (-1); 5090 vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux); 5091 for (;;) { 5092 if (check_object_provided_version(obj, depobj, vna)) 5093 return (-1); 5094 vernum = VER_NEED_IDX(vna->vna_other); 5095 assert(vernum <= maxvernum); 5096 obj->vertab[vernum].hash = vna->vna_hash; 5097 obj->vertab[vernum].name = obj->strtab + vna->vna_name; 5098 obj->vertab[vernum].file = obj->strtab + vn->vn_file; 5099 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ? 5100 VER_INFO_HIDDEN : 0; 5101 if (vna->vna_next == 0) 5102 break; 5103 vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next); 5104 } 5105 if (vn->vn_next == 0) 5106 break; 5107 vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next); 5108 } 5109 return 0; 5110 } 5111 5112 static int 5113 rtld_verify_versions(const Objlist *objlist) 5114 { 5115 Objlist_Entry *entry; 5116 int rc; 5117 5118 rc = 0; 5119 STAILQ_FOREACH(entry, objlist, link) { 5120 /* 5121 * Skip dummy objects or objects that have their version requirements 5122 * already checked. 5123 */ 5124 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL) 5125 continue; 5126 if (rtld_verify_object_versions(entry->obj) == -1) { 5127 rc = -1; 5128 if (ld_tracing == NULL) 5129 break; 5130 } 5131 } 5132 if (rc == 0 || ld_tracing != NULL) 5133 rc = rtld_verify_object_versions(&obj_rtld); 5134 return rc; 5135 } 5136 5137 const Ver_Entry * 5138 fetch_ventry(const Obj_Entry *obj, unsigned long symnum) 5139 { 5140 Elf_Versym vernum; 5141 5142 if (obj->vertab) { 5143 vernum = VER_NDX(obj->versyms[symnum]); 5144 if (vernum >= obj->vernum) { 5145 _rtld_error("%s: symbol %s has wrong verneed value %d", 5146 obj->path, obj->strtab + symnum, vernum); 5147 } else if (obj->vertab[vernum].hash != 0) { 5148 return &obj->vertab[vernum]; 5149 } 5150 } 5151 return NULL; 5152 } 5153 5154 int 5155 _rtld_get_stack_prot(void) 5156 { 5157 5158 return (stack_prot); 5159 } 5160 5161 int 5162 _rtld_is_dlopened(void *arg) 5163 { 5164 Obj_Entry *obj; 5165 RtldLockState lockstate; 5166 int res; 5167 5168 rlock_acquire(rtld_bind_lock, &lockstate); 5169 obj = dlcheck(arg); 5170 if (obj == NULL) 5171 obj = obj_from_addr(arg); 5172 if (obj == NULL) { 5173 _rtld_error("No shared object contains address"); 5174 lock_release(rtld_bind_lock, &lockstate); 5175 return (-1); 5176 } 5177 res = obj->dlopened ? 1 : 0; 5178 lock_release(rtld_bind_lock, &lockstate); 5179 return (res); 5180 } 5181 5182 int 5183 obj_enforce_relro(Obj_Entry *obj) 5184 { 5185 5186 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size, 5187 PROT_READ) == -1) { 5188 _rtld_error("%s: Cannot enforce relro protection: %s", 5189 obj->path, rtld_strerror(errno)); 5190 return (-1); 5191 } 5192 return (0); 5193 } 5194 5195 static void 5196 map_stacks_exec(RtldLockState *lockstate) 5197 { 5198 void (*thr_map_stacks_exec)(void); 5199 5200 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0) 5201 return; 5202 thr_map_stacks_exec = (void (*)(void))(uintptr_t) 5203 get_program_var_addr("__pthread_map_stacks_exec", lockstate); 5204 if (thr_map_stacks_exec != NULL) { 5205 stack_prot |= PROT_EXEC; 5206 thr_map_stacks_exec(); 5207 } 5208 } 5209 5210 void 5211 symlook_init(SymLook *dst, const char *name) 5212 { 5213 5214 bzero(dst, sizeof(*dst)); 5215 dst->name = name; 5216 dst->hash = elf_hash(name); 5217 dst->hash_gnu = gnu_hash(name); 5218 } 5219 5220 static void 5221 symlook_init_from_req(SymLook *dst, const SymLook *src) 5222 { 5223 5224 dst->name = src->name; 5225 dst->hash = src->hash; 5226 dst->hash_gnu = src->hash_gnu; 5227 dst->ventry = src->ventry; 5228 dst->flags = src->flags; 5229 dst->defobj_out = NULL; 5230 dst->sym_out = NULL; 5231 dst->lockstate = src->lockstate; 5232 } 5233 5234 5235 /* 5236 * Parse a file descriptor number without pulling in more of libc (e.g. atoi). 5237 */ 5238 static int 5239 parse_libdir(const char *str) 5240 { 5241 static const int RADIX = 10; /* XXXJA: possibly support hex? */ 5242 const char *orig; 5243 int fd; 5244 char c; 5245 5246 orig = str; 5247 fd = 0; 5248 for (c = *str; c != '\0'; c = *++str) { 5249 if (c < '0' || c > '9') 5250 return (-1); 5251 5252 fd *= RADIX; 5253 fd += c - '0'; 5254 } 5255 5256 /* Make sure we actually parsed something. */ 5257 if (str == orig) { 5258 _rtld_error("failed to parse directory FD from '%s'", str); 5259 return (-1); 5260 } 5261 return (fd); 5262 } 5263 5264 /* 5265 * Overrides for libc_pic-provided functions. 5266 */ 5267 5268 int 5269 __getosreldate(void) 5270 { 5271 size_t len; 5272 int oid[2]; 5273 int error, osrel; 5274 5275 if (osreldate != 0) 5276 return (osreldate); 5277 5278 oid[0] = CTL_KERN; 5279 oid[1] = KERN_OSRELDATE; 5280 osrel = 0; 5281 len = sizeof(osrel); 5282 error = sysctl(oid, 2, &osrel, &len, NULL, 0); 5283 if (error == 0 && osrel > 0 && len == sizeof(osrel)) 5284 osreldate = osrel; 5285 return (osreldate); 5286 } 5287 5288 void 5289 exit(int status) 5290 { 5291 5292 _exit(status); 5293 } 5294 5295 void (*__cleanup)(void); 5296 int __isthreaded = 0; 5297 int _thread_autoinit_dummy_decl = 1; 5298 5299 /* 5300 * No unresolved symbols for rtld. 5301 */ 5302 void 5303 __pthread_cxa_finalize(struct dl_phdr_info *a) 5304 { 5305 } 5306 5307 void 5308 __stack_chk_fail(void) 5309 { 5310 5311 _rtld_error("stack overflow detected; terminated"); 5312 rtld_die(); 5313 } 5314 __weak_reference(__stack_chk_fail, __stack_chk_fail_local); 5315 5316 void 5317 __chk_fail(void) 5318 { 5319 5320 _rtld_error("buffer overflow detected; terminated"); 5321 rtld_die(); 5322 } 5323 5324 const char * 5325 rtld_strerror(int errnum) 5326 { 5327 5328 if (errnum < 0 || errnum >= sys_nerr) 5329 return ("Unknown error"); 5330 return (sys_errlist[errnum]); 5331 } 5332