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