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