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