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