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