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