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