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