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