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