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 2512 return (0); 2513 } 2514 2515 static const char * 2516 printable_path(const char *path) 2517 { 2518 2519 return (path == NULL ? "<unknown>" : path); 2520 } 2521 2522 /* 2523 * Load a shared object into memory, if it is not already loaded. The 2524 * object may be specified by name or by user-supplied file descriptor 2525 * fd_u. In the later case, the fd_u descriptor is not closed, but its 2526 * duplicate is. 2527 * 2528 * Returns a pointer to the Obj_Entry for the object. Returns NULL 2529 * on failure. 2530 */ 2531 static Obj_Entry * 2532 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags) 2533 { 2534 Obj_Entry *obj; 2535 int fd; 2536 struct stat sb; 2537 char *path; 2538 2539 fd = -1; 2540 if (name != NULL) { 2541 TAILQ_FOREACH(obj, &obj_list, next) { 2542 if (obj->marker || obj->doomed) 2543 continue; 2544 if (object_match_name(obj, name)) 2545 return (obj); 2546 } 2547 2548 path = find_library(name, refobj, &fd); 2549 if (path == NULL) 2550 return (NULL); 2551 } else 2552 path = NULL; 2553 2554 if (fd >= 0) { 2555 /* 2556 * search_library_pathfds() opens a fresh file descriptor for the 2557 * library, so there is no need to dup(). 2558 */ 2559 } else if (fd_u == -1) { 2560 /* 2561 * If we didn't find a match by pathname, or the name is not 2562 * supplied, open the file and check again by device and inode. 2563 * This avoids false mismatches caused by multiple links or ".." 2564 * in pathnames. 2565 * 2566 * To avoid a race, we open the file and use fstat() rather than 2567 * using stat(). 2568 */ 2569 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) { 2570 _rtld_error("Cannot open \"%s\"", path); 2571 free(path); 2572 return (NULL); 2573 } 2574 } else { 2575 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0); 2576 if (fd == -1) { 2577 _rtld_error("Cannot dup fd"); 2578 free(path); 2579 return (NULL); 2580 } 2581 } 2582 if (fstat(fd, &sb) == -1) { 2583 _rtld_error("Cannot fstat \"%s\"", printable_path(path)); 2584 close(fd); 2585 free(path); 2586 return NULL; 2587 } 2588 TAILQ_FOREACH(obj, &obj_list, next) { 2589 if (obj->marker || obj->doomed) 2590 continue; 2591 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) 2592 break; 2593 } 2594 if (obj != NULL && name != NULL) { 2595 object_add_name(obj, name); 2596 free(path); 2597 close(fd); 2598 return obj; 2599 } 2600 if (flags & RTLD_LO_NOLOAD) { 2601 free(path); 2602 close(fd); 2603 return (NULL); 2604 } 2605 2606 /* First use of this object, so we must map it in */ 2607 obj = do_load_object(fd, name, path, &sb, flags); 2608 if (obj == NULL) 2609 free(path); 2610 close(fd); 2611 2612 return obj; 2613 } 2614 2615 static Obj_Entry * 2616 do_load_object(int fd, const char *name, char *path, struct stat *sbp, 2617 int flags) 2618 { 2619 Obj_Entry *obj; 2620 struct statfs fs; 2621 2622 /* 2623 * but first, make sure that environment variables haven't been 2624 * used to circumvent the noexec flag on a filesystem. 2625 */ 2626 if (dangerous_ld_env) { 2627 if (fstatfs(fd, &fs) != 0) { 2628 _rtld_error("Cannot fstatfs \"%s\"", printable_path(path)); 2629 return NULL; 2630 } 2631 if (fs.f_flags & MNT_NOEXEC) { 2632 _rtld_error("Cannot execute objects on %s", fs.f_mntonname); 2633 return NULL; 2634 } 2635 } 2636 dbg("loading \"%s\"", printable_path(path)); 2637 obj = map_object(fd, printable_path(path), sbp); 2638 if (obj == NULL) 2639 return NULL; 2640 2641 /* 2642 * If DT_SONAME is present in the object, digest_dynamic2 already 2643 * added it to the object names. 2644 */ 2645 if (name != NULL) 2646 object_add_name(obj, name); 2647 obj->path = path; 2648 if (!digest_dynamic(obj, 0)) 2649 goto errp; 2650 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path, 2651 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount); 2652 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) { 2653 dbg("refusing to load PIE executable \"%s\"", obj->path); 2654 _rtld_error("Cannot load PIE binary %s as DSO", obj->path); 2655 goto errp; 2656 } 2657 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) == 2658 RTLD_LO_DLOPEN) { 2659 dbg("refusing to load non-loadable \"%s\"", obj->path); 2660 _rtld_error("Cannot dlopen non-loadable %s", obj->path); 2661 goto errp; 2662 } 2663 2664 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0; 2665 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2666 obj_count++; 2667 obj_loads++; 2668 linkmap_add(obj); /* for GDB & dlinfo() */ 2669 max_stack_flags |= obj->stack_flags; 2670 2671 dbg(" %p .. %p: %s", obj->mapbase, 2672 obj->mapbase + obj->mapsize - 1, obj->path); 2673 if (obj->textrel) 2674 dbg(" WARNING: %s has impure text", obj->path); 2675 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 2676 obj->path); 2677 2678 return (obj); 2679 2680 errp: 2681 munmap(obj->mapbase, obj->mapsize); 2682 obj_free(obj); 2683 return (NULL); 2684 } 2685 2686 Obj_Entry * 2687 obj_from_addr(const void *addr) 2688 { 2689 Obj_Entry *obj; 2690 2691 TAILQ_FOREACH(obj, &obj_list, next) { 2692 if (obj->marker) 2693 continue; 2694 if (addr < (void *) obj->mapbase) 2695 continue; 2696 if (addr < (void *)(obj->mapbase + obj->mapsize)) 2697 return obj; 2698 } 2699 return NULL; 2700 } 2701 2702 static void 2703 preinit_main(void) 2704 { 2705 Elf_Addr *preinit_addr; 2706 int index; 2707 2708 preinit_addr = (Elf_Addr *)obj_main->preinit_array; 2709 if (preinit_addr == NULL) 2710 return; 2711 2712 for (index = 0; index < obj_main->preinit_array_num; index++) { 2713 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) { 2714 dbg("calling preinit function for %s at %p", obj_main->path, 2715 (void *)preinit_addr[index]); 2716 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index], 2717 0, 0, obj_main->path); 2718 call_init_pointer(obj_main, preinit_addr[index]); 2719 } 2720 } 2721 } 2722 2723 /* 2724 * Call the finalization functions for each of the objects in "list" 2725 * belonging to the DAG of "root" and referenced once. If NULL "root" 2726 * is specified, every finalization function will be called regardless 2727 * of the reference count and the list elements won't be freed. All of 2728 * the objects are expected to have non-NULL fini functions. 2729 */ 2730 static void 2731 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate) 2732 { 2733 Objlist_Entry *elm; 2734 struct dlerror_save *saved_msg; 2735 Elf_Addr *fini_addr; 2736 int index; 2737 2738 assert(root == NULL || root->refcount == 1); 2739 2740 if (root != NULL) 2741 root->doomed = true; 2742 2743 /* 2744 * Preserve the current error message since a fini function might 2745 * call into the dynamic linker and overwrite it. 2746 */ 2747 saved_msg = errmsg_save(); 2748 do { 2749 STAILQ_FOREACH(elm, list, link) { 2750 if (root != NULL && (elm->obj->refcount != 1 || 2751 objlist_find(&root->dagmembers, elm->obj) == NULL)) 2752 continue; 2753 /* Remove object from fini list to prevent recursive invocation. */ 2754 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 2755 /* Ensure that new references cannot be acquired. */ 2756 elm->obj->doomed = true; 2757 2758 hold_object(elm->obj); 2759 lock_release(rtld_bind_lock, lockstate); 2760 /* 2761 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined. 2762 * When this happens, DT_FINI_ARRAY is processed first. 2763 */ 2764 fini_addr = (Elf_Addr *)elm->obj->fini_array; 2765 if (fini_addr != NULL && elm->obj->fini_array_num > 0) { 2766 for (index = elm->obj->fini_array_num - 1; index >= 0; 2767 index--) { 2768 if (fini_addr[index] != 0 && fini_addr[index] != 1) { 2769 dbg("calling fini function for %s at %p", 2770 elm->obj->path, (void *)fini_addr[index]); 2771 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, 2772 (void *)fini_addr[index], 0, 0, elm->obj->path); 2773 call_initfini_pointer(elm->obj, fini_addr[index]); 2774 } 2775 } 2776 } 2777 if (elm->obj->fini != (Elf_Addr)NULL) { 2778 dbg("calling fini function for %s at %p", elm->obj->path, 2779 (void *)elm->obj->fini); 2780 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 2781 0, 0, elm->obj->path); 2782 call_initfini_pointer(elm->obj, elm->obj->fini); 2783 } 2784 wlock_acquire(rtld_bind_lock, lockstate); 2785 unhold_object(elm->obj); 2786 /* No need to free anything if process is going down. */ 2787 if (root != NULL) 2788 free(elm); 2789 /* 2790 * We must restart the list traversal after every fini call 2791 * because a dlclose() call from the fini function or from 2792 * another thread might have modified the reference counts. 2793 */ 2794 break; 2795 } 2796 } while (elm != NULL); 2797 errmsg_restore(saved_msg); 2798 } 2799 2800 /* 2801 * Call the initialization functions for each of the objects in 2802 * "list". All of the objects are expected to have non-NULL init 2803 * functions. 2804 */ 2805 static void 2806 objlist_call_init(Objlist *list, RtldLockState *lockstate) 2807 { 2808 Objlist_Entry *elm; 2809 Obj_Entry *obj; 2810 struct dlerror_save *saved_msg; 2811 Elf_Addr *init_addr; 2812 void (*reg)(void (*)(void)); 2813 int index; 2814 2815 /* 2816 * Clean init_scanned flag so that objects can be rechecked and 2817 * possibly initialized earlier if any of vectors called below 2818 * cause the change by using dlopen. 2819 */ 2820 TAILQ_FOREACH(obj, &obj_list, next) { 2821 if (obj->marker) 2822 continue; 2823 obj->init_scanned = false; 2824 } 2825 2826 /* 2827 * Preserve the current error message since an init function might 2828 * call into the dynamic linker and overwrite it. 2829 */ 2830 saved_msg = errmsg_save(); 2831 STAILQ_FOREACH(elm, list, link) { 2832 if (elm->obj->init_done) /* Initialized early. */ 2833 continue; 2834 /* 2835 * Race: other thread might try to use this object before current 2836 * one completes the initialization. Not much can be done here 2837 * without better locking. 2838 */ 2839 elm->obj->init_done = true; 2840 hold_object(elm->obj); 2841 reg = NULL; 2842 if (elm->obj == obj_main && obj_main->crt_no_init) { 2843 reg = (void (*)(void (*)(void)))get_program_var_addr( 2844 "__libc_atexit", lockstate); 2845 } 2846 lock_release(rtld_bind_lock, lockstate); 2847 if (reg != NULL) { 2848 reg(rtld_exit); 2849 rtld_exit_ptr = rtld_nop_exit; 2850 } 2851 2852 /* 2853 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. 2854 * When this happens, DT_INIT is processed first. 2855 */ 2856 if (elm->obj->init != (Elf_Addr)NULL) { 2857 dbg("calling init function for %s at %p", elm->obj->path, 2858 (void *)elm->obj->init); 2859 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 2860 0, 0, elm->obj->path); 2861 call_init_pointer(elm->obj, elm->obj->init); 2862 } 2863 init_addr = (Elf_Addr *)elm->obj->init_array; 2864 if (init_addr != NULL) { 2865 for (index = 0; index < elm->obj->init_array_num; index++) { 2866 if (init_addr[index] != 0 && init_addr[index] != 1) { 2867 dbg("calling init function for %s at %p", elm->obj->path, 2868 (void *)init_addr[index]); 2869 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, 2870 (void *)init_addr[index], 0, 0, elm->obj->path); 2871 call_init_pointer(elm->obj, init_addr[index]); 2872 } 2873 } 2874 } 2875 wlock_acquire(rtld_bind_lock, lockstate); 2876 unhold_object(elm->obj); 2877 } 2878 errmsg_restore(saved_msg); 2879 } 2880 2881 static void 2882 objlist_clear(Objlist *list) 2883 { 2884 Objlist_Entry *elm; 2885 2886 while (!STAILQ_EMPTY(list)) { 2887 elm = STAILQ_FIRST(list); 2888 STAILQ_REMOVE_HEAD(list, link); 2889 free(elm); 2890 } 2891 } 2892 2893 static Objlist_Entry * 2894 objlist_find(Objlist *list, const Obj_Entry *obj) 2895 { 2896 Objlist_Entry *elm; 2897 2898 STAILQ_FOREACH(elm, list, link) 2899 if (elm->obj == obj) 2900 return elm; 2901 return NULL; 2902 } 2903 2904 static void 2905 objlist_init(Objlist *list) 2906 { 2907 STAILQ_INIT(list); 2908 } 2909 2910 static void 2911 objlist_push_head(Objlist *list, Obj_Entry *obj) 2912 { 2913 Objlist_Entry *elm; 2914 2915 elm = NEW(Objlist_Entry); 2916 elm->obj = obj; 2917 STAILQ_INSERT_HEAD(list, elm, link); 2918 } 2919 2920 static void 2921 objlist_push_tail(Objlist *list, Obj_Entry *obj) 2922 { 2923 Objlist_Entry *elm; 2924 2925 elm = NEW(Objlist_Entry); 2926 elm->obj = obj; 2927 STAILQ_INSERT_TAIL(list, elm, link); 2928 } 2929 2930 static void 2931 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj) 2932 { 2933 Objlist_Entry *elm, *listelm; 2934 2935 STAILQ_FOREACH(listelm, list, link) { 2936 if (listelm->obj == listobj) 2937 break; 2938 } 2939 elm = NEW(Objlist_Entry); 2940 elm->obj = obj; 2941 if (listelm != NULL) 2942 STAILQ_INSERT_AFTER(list, listelm, elm, link); 2943 else 2944 STAILQ_INSERT_TAIL(list, elm, link); 2945 } 2946 2947 static void 2948 objlist_remove(Objlist *list, Obj_Entry *obj) 2949 { 2950 Objlist_Entry *elm; 2951 2952 if ((elm = objlist_find(list, obj)) != NULL) { 2953 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 2954 free(elm); 2955 } 2956 } 2957 2958 /* 2959 * Relocate dag rooted in the specified object. 2960 * Returns 0 on success, or -1 on failure. 2961 */ 2962 2963 static int 2964 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj, 2965 int flags, RtldLockState *lockstate) 2966 { 2967 Objlist_Entry *elm; 2968 int error; 2969 2970 error = 0; 2971 STAILQ_FOREACH(elm, &root->dagmembers, link) { 2972 error = relocate_object(elm->obj, bind_now, rtldobj, flags, 2973 lockstate); 2974 if (error == -1) 2975 break; 2976 } 2977 return (error); 2978 } 2979 2980 /* 2981 * Prepare for, or clean after, relocating an object marked with 2982 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only 2983 * segments are remapped read-write. After relocations are done, the 2984 * segment's permissions are returned back to the modes specified in 2985 * the phdrs. If any relocation happened, or always for wired 2986 * program, COW is triggered. 2987 */ 2988 static int 2989 reloc_textrel_prot(Obj_Entry *obj, bool before) 2990 { 2991 const Elf_Phdr *ph; 2992 void *base; 2993 size_t l, sz; 2994 int prot; 2995 2996 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0; 2997 l--, ph++) { 2998 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0) 2999 continue; 3000 base = obj->relocbase + trunc_page(ph->p_vaddr); 3001 sz = round_page(ph->p_vaddr + ph->p_filesz) - 3002 trunc_page(ph->p_vaddr); 3003 prot = before ? (PROT_READ | PROT_WRITE) : 3004 convert_prot(ph->p_flags); 3005 if (mprotect(base, sz, prot) == -1) { 3006 _rtld_error("%s: Cannot write-%sable text segment: %s", 3007 obj->path, before ? "en" : "dis", 3008 rtld_strerror(errno)); 3009 return (-1); 3010 } 3011 } 3012 return (0); 3013 } 3014 3015 /* 3016 * Relocate single object. 3017 * Returns 0 on success, or -1 on failure. 3018 */ 3019 static int 3020 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, 3021 int flags, RtldLockState *lockstate) 3022 { 3023 3024 if (obj->relocated) 3025 return (0); 3026 obj->relocated = true; 3027 if (obj != rtldobj) 3028 dbg("relocating \"%s\"", obj->path); 3029 3030 if (obj->symtab == NULL || obj->strtab == NULL || 3031 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) 3032 dbg("object %s has no run-time symbol table", obj->path); 3033 3034 /* There are relocations to the write-protected text segment. */ 3035 if (obj->textrel && reloc_textrel_prot(obj, true) != 0) 3036 return (-1); 3037 3038 /* Process the non-PLT non-IFUNC relocations. */ 3039 if (reloc_non_plt(obj, rtldobj, flags, lockstate)) 3040 return (-1); 3041 3042 /* Re-protected the text segment. */ 3043 if (obj->textrel && reloc_textrel_prot(obj, false) != 0) 3044 return (-1); 3045 3046 /* Set the special PLT or GOT entries. */ 3047 init_pltgot(obj); 3048 3049 /* Process the PLT relocations. */ 3050 if (reloc_plt(obj, flags, lockstate) == -1) 3051 return (-1); 3052 /* Relocate the jump slots if we are doing immediate binding. */ 3053 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags, 3054 lockstate) == -1) 3055 return (-1); 3056 3057 if (!obj->mainprog && obj_enforce_relro(obj) == -1) 3058 return (-1); 3059 3060 /* 3061 * Set up the magic number and version in the Obj_Entry. These 3062 * were checked in the crt1.o from the original ElfKit, so we 3063 * set them for backward compatibility. 3064 */ 3065 obj->magic = RTLD_MAGIC; 3066 obj->version = RTLD_VERSION; 3067 3068 return (0); 3069 } 3070 3071 /* 3072 * Relocate newly-loaded shared objects. The argument is a pointer to 3073 * the Obj_Entry for the first such object. All objects from the first 3074 * to the end of the list of objects are relocated. Returns 0 on success, 3075 * or -1 on failure. 3076 */ 3077 static int 3078 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj, 3079 int flags, RtldLockState *lockstate) 3080 { 3081 Obj_Entry *obj; 3082 int error; 3083 3084 for (error = 0, obj = first; obj != NULL; 3085 obj = TAILQ_NEXT(obj, next)) { 3086 if (obj->marker) 3087 continue; 3088 error = relocate_object(obj, bind_now, rtldobj, flags, 3089 lockstate); 3090 if (error == -1) 3091 break; 3092 } 3093 return (error); 3094 } 3095 3096 /* 3097 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots 3098 * referencing STT_GNU_IFUNC symbols is postponed till the other 3099 * relocations are done. The indirect functions specified as 3100 * ifunc are allowed to call other symbols, so we need to have 3101 * objects relocated before asking for resolution from indirects. 3102 * 3103 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion, 3104 * instead of the usual lazy handling of PLT slots. It is 3105 * consistent with how GNU does it. 3106 */ 3107 static int 3108 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags, 3109 RtldLockState *lockstate) 3110 { 3111 3112 if (obj->ifuncs_resolved) 3113 return (0); 3114 obj->ifuncs_resolved = true; 3115 if (!obj->irelative && !obj->irelative_nonplt && 3116 !((obj->bind_now || bind_now) && obj->gnu_ifunc) && 3117 !obj->non_plt_gnu_ifunc) 3118 return (0); 3119 if (obj_disable_relro(obj) == -1 || 3120 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) || 3121 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj, 3122 lockstate) == -1) || 3123 ((obj->bind_now || bind_now) && obj->gnu_ifunc && 3124 reloc_gnu_ifunc(obj, flags, lockstate) == -1) || 3125 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld, 3126 flags | SYMLOOK_IFUNC, lockstate) == -1) || 3127 obj_enforce_relro(obj) == -1) 3128 return (-1); 3129 return (0); 3130 } 3131 3132 static int 3133 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags, 3134 RtldLockState *lockstate) 3135 { 3136 Objlist_Entry *elm; 3137 Obj_Entry *obj; 3138 3139 STAILQ_FOREACH(elm, list, link) { 3140 obj = elm->obj; 3141 if (obj->marker) 3142 continue; 3143 if (resolve_object_ifunc(obj, bind_now, flags, 3144 lockstate) == -1) 3145 return (-1); 3146 } 3147 return (0); 3148 } 3149 3150 /* 3151 * Cleanup procedure. It will be called (by the atexit mechanism) just 3152 * before the process exits. 3153 */ 3154 static void 3155 rtld_exit(void) 3156 { 3157 RtldLockState lockstate; 3158 3159 wlock_acquire(rtld_bind_lock, &lockstate); 3160 dbg("rtld_exit()"); 3161 objlist_call_fini(&list_fini, NULL, &lockstate); 3162 /* No need to remove the items from the list, since we are exiting. */ 3163 if (!libmap_disable) 3164 lm_fini(); 3165 lock_release(rtld_bind_lock, &lockstate); 3166 } 3167 3168 static void 3169 rtld_nop_exit(void) 3170 { 3171 } 3172 3173 /* 3174 * Iterate over a search path, translate each element, and invoke the 3175 * callback on the result. 3176 */ 3177 static void * 3178 path_enumerate(const char *path, path_enum_proc callback, 3179 const char *refobj_path, void *arg) 3180 { 3181 const char *trans; 3182 if (path == NULL) 3183 return (NULL); 3184 3185 path += strspn(path, ":;"); 3186 while (*path != '\0') { 3187 size_t len; 3188 char *res; 3189 3190 len = strcspn(path, ":;"); 3191 trans = lm_findn(refobj_path, path, len); 3192 if (trans) 3193 res = callback(trans, strlen(trans), arg); 3194 else 3195 res = callback(path, len, arg); 3196 3197 if (res != NULL) 3198 return (res); 3199 3200 path += len; 3201 path += strspn(path, ":;"); 3202 } 3203 3204 return (NULL); 3205 } 3206 3207 struct try_library_args { 3208 const char *name; 3209 size_t namelen; 3210 char *buffer; 3211 size_t buflen; 3212 int fd; 3213 }; 3214 3215 static void * 3216 try_library_path(const char *dir, size_t dirlen, void *param) 3217 { 3218 struct try_library_args *arg; 3219 int fd; 3220 3221 arg = param; 3222 if (*dir == '/' || trust) { 3223 char *pathname; 3224 3225 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 3226 return (NULL); 3227 3228 pathname = arg->buffer; 3229 strncpy(pathname, dir, dirlen); 3230 pathname[dirlen] = '/'; 3231 strcpy(pathname + dirlen + 1, arg->name); 3232 3233 dbg(" Trying \"%s\"", pathname); 3234 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY); 3235 if (fd >= 0) { 3236 dbg(" Opened \"%s\", fd %d", pathname, fd); 3237 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 3238 strcpy(pathname, arg->buffer); 3239 arg->fd = fd; 3240 return (pathname); 3241 } else { 3242 dbg(" Failed to open \"%s\": %s", 3243 pathname, rtld_strerror(errno)); 3244 } 3245 } 3246 return (NULL); 3247 } 3248 3249 static char * 3250 search_library_path(const char *name, const char *path, 3251 const char *refobj_path, int *fdp) 3252 { 3253 char *p; 3254 struct try_library_args arg; 3255 3256 if (path == NULL) 3257 return NULL; 3258 3259 arg.name = name; 3260 arg.namelen = strlen(name); 3261 arg.buffer = xmalloc(PATH_MAX); 3262 arg.buflen = PATH_MAX; 3263 arg.fd = -1; 3264 3265 p = path_enumerate(path, try_library_path, refobj_path, &arg); 3266 *fdp = arg.fd; 3267 3268 free(arg.buffer); 3269 3270 return (p); 3271 } 3272 3273 3274 /* 3275 * Finds the library with the given name using the directory descriptors 3276 * listed in the LD_LIBRARY_PATH_FDS environment variable. 3277 * 3278 * Returns a freshly-opened close-on-exec file descriptor for the library, 3279 * or -1 if the library cannot be found. 3280 */ 3281 static char * 3282 search_library_pathfds(const char *name, const char *path, int *fdp) 3283 { 3284 char *envcopy, *fdstr, *found, *last_token; 3285 size_t len; 3286 int dirfd, fd; 3287 3288 dbg("%s('%s', '%s', fdp)", __func__, name, path); 3289 3290 /* Don't load from user-specified libdirs into setuid binaries. */ 3291 if (!trust) 3292 return (NULL); 3293 3294 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */ 3295 if (path == NULL) 3296 return (NULL); 3297 3298 /* LD_LIBRARY_PATH_FDS only works with relative paths. */ 3299 if (name[0] == '/') { 3300 dbg("Absolute path (%s) passed to %s", name, __func__); 3301 return (NULL); 3302 } 3303 3304 /* 3305 * Use strtok_r() to walk the FD:FD:FD list. This requires a local 3306 * copy of the path, as strtok_r rewrites separator tokens 3307 * with '\0'. 3308 */ 3309 found = NULL; 3310 envcopy = xstrdup(path); 3311 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL; 3312 fdstr = strtok_r(NULL, ":", &last_token)) { 3313 dirfd = parse_integer(fdstr); 3314 if (dirfd < 0) { 3315 _rtld_error("failed to parse directory FD: '%s'", 3316 fdstr); 3317 break; 3318 } 3319 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY); 3320 if (fd >= 0) { 3321 *fdp = fd; 3322 len = strlen(fdstr) + strlen(name) + 3; 3323 found = xmalloc(len); 3324 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) { 3325 _rtld_error("error generating '%d/%s'", 3326 dirfd, name); 3327 rtld_die(); 3328 } 3329 dbg("open('%s') => %d", found, fd); 3330 break; 3331 } 3332 } 3333 free(envcopy); 3334 3335 return (found); 3336 } 3337 3338 3339 int 3340 dlclose(void *handle) 3341 { 3342 RtldLockState lockstate; 3343 int error; 3344 3345 wlock_acquire(rtld_bind_lock, &lockstate); 3346 error = dlclose_locked(handle, &lockstate); 3347 lock_release(rtld_bind_lock, &lockstate); 3348 return (error); 3349 } 3350 3351 static int 3352 dlclose_locked(void *handle, RtldLockState *lockstate) 3353 { 3354 Obj_Entry *root; 3355 3356 root = dlcheck(handle); 3357 if (root == NULL) 3358 return -1; 3359 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount, 3360 root->path); 3361 3362 /* Unreference the object and its dependencies. */ 3363 root->dl_refcount--; 3364 3365 if (root->refcount == 1) { 3366 /* 3367 * The object will be no longer referenced, so we must unload it. 3368 * First, call the fini functions. 3369 */ 3370 objlist_call_fini(&list_fini, root, lockstate); 3371 3372 unref_dag(root); 3373 3374 /* Finish cleaning up the newly-unreferenced objects. */ 3375 GDB_STATE(RT_DELETE,&root->linkmap); 3376 unload_object(root, lockstate); 3377 GDB_STATE(RT_CONSISTENT,NULL); 3378 } else 3379 unref_dag(root); 3380 3381 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL); 3382 return 0; 3383 } 3384 3385 char * 3386 dlerror(void) 3387 { 3388 if (*(lockinfo.dlerror_seen()) != 0) 3389 return (NULL); 3390 *lockinfo.dlerror_seen() = 1; 3391 return (lockinfo.dlerror_loc()); 3392 } 3393 3394 /* 3395 * This function is deprecated and has no effect. 3396 */ 3397 void 3398 dllockinit(void *context, 3399 void *(*_lock_create)(void *context) __unused, 3400 void (*_rlock_acquire)(void *lock) __unused, 3401 void (*_wlock_acquire)(void *lock) __unused, 3402 void (*_lock_release)(void *lock) __unused, 3403 void (*_lock_destroy)(void *lock) __unused, 3404 void (*context_destroy)(void *context)) 3405 { 3406 static void *cur_context; 3407 static void (*cur_context_destroy)(void *); 3408 3409 /* Just destroy the context from the previous call, if necessary. */ 3410 if (cur_context_destroy != NULL) 3411 cur_context_destroy(cur_context); 3412 cur_context = context; 3413 cur_context_destroy = context_destroy; 3414 } 3415 3416 void * 3417 dlopen(const char *name, int mode) 3418 { 3419 3420 return (rtld_dlopen(name, -1, mode)); 3421 } 3422 3423 void * 3424 fdlopen(int fd, int mode) 3425 { 3426 3427 return (rtld_dlopen(NULL, fd, mode)); 3428 } 3429 3430 static void * 3431 rtld_dlopen(const char *name, int fd, int mode) 3432 { 3433 RtldLockState lockstate; 3434 int lo_flags; 3435 3436 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name); 3437 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 3438 if (ld_tracing != NULL) { 3439 rlock_acquire(rtld_bind_lock, &lockstate); 3440 if (sigsetjmp(lockstate.env, 0) != 0) 3441 lock_upgrade(rtld_bind_lock, &lockstate); 3442 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate)); 3443 lock_release(rtld_bind_lock, &lockstate); 3444 } 3445 lo_flags = RTLD_LO_DLOPEN; 3446 if (mode & RTLD_NODELETE) 3447 lo_flags |= RTLD_LO_NODELETE; 3448 if (mode & RTLD_NOLOAD) 3449 lo_flags |= RTLD_LO_NOLOAD; 3450 if (mode & RTLD_DEEPBIND) 3451 lo_flags |= RTLD_LO_DEEPBIND; 3452 if (ld_tracing != NULL) 3453 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS; 3454 3455 return (dlopen_object(name, fd, obj_main, lo_flags, 3456 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL)); 3457 } 3458 3459 static void 3460 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate) 3461 { 3462 3463 obj->dl_refcount--; 3464 unref_dag(obj); 3465 if (obj->refcount == 0) 3466 unload_object(obj, lockstate); 3467 } 3468 3469 static Obj_Entry * 3470 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags, 3471 int mode, RtldLockState *lockstate) 3472 { 3473 Obj_Entry *old_obj_tail; 3474 Obj_Entry *obj; 3475 Objlist initlist; 3476 RtldLockState mlockstate; 3477 int result; 3478 3479 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x", 3480 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" : 3481 refobj->path, lo_flags, mode); 3482 objlist_init(&initlist); 3483 3484 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) { 3485 wlock_acquire(rtld_bind_lock, &mlockstate); 3486 lockstate = &mlockstate; 3487 } 3488 GDB_STATE(RT_ADD,NULL); 3489 3490 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q)); 3491 obj = NULL; 3492 if (name == NULL && fd == -1) { 3493 obj = obj_main; 3494 obj->refcount++; 3495 } else { 3496 obj = load_object(name, fd, refobj, lo_flags); 3497 } 3498 3499 if (obj) { 3500 obj->dl_refcount++; 3501 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) 3502 objlist_push_tail(&list_global, obj); 3503 if (globallist_next(old_obj_tail) != NULL) { 3504 /* We loaded something new. */ 3505 assert(globallist_next(old_obj_tail) == obj); 3506 if ((lo_flags & RTLD_LO_DEEPBIND) != 0) 3507 obj->symbolic = true; 3508 result = 0; 3509 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 && 3510 obj->static_tls && !allocate_tls_offset(obj)) { 3511 _rtld_error("%s: No space available " 3512 "for static Thread Local Storage", obj->path); 3513 result = -1; 3514 } 3515 if (result != -1) 3516 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN | 3517 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE)); 3518 init_dag(obj); 3519 ref_dag(obj); 3520 if (result != -1) 3521 result = rtld_verify_versions(&obj->dagmembers); 3522 if (result != -1 && ld_tracing) 3523 goto trace; 3524 if (result == -1 || relocate_object_dag(obj, 3525 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld, 3526 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3527 lockstate) == -1) { 3528 dlopen_cleanup(obj, lockstate); 3529 obj = NULL; 3530 } else if (lo_flags & RTLD_LO_EARLY) { 3531 /* 3532 * Do not call the init functions for early loaded 3533 * filtees. The image is still not initialized enough 3534 * for them to work. 3535 * 3536 * Our object is found by the global object list and 3537 * will be ordered among all init calls done right 3538 * before transferring control to main. 3539 */ 3540 } else { 3541 /* Make list of init functions to call. */ 3542 initlist_add_objects(obj, obj, &initlist); 3543 } 3544 /* 3545 * Process all no_delete or global objects here, given 3546 * them own DAGs to prevent their dependencies from being 3547 * unloaded. This has to be done after we have loaded all 3548 * of the dependencies, so that we do not miss any. 3549 */ 3550 if (obj != NULL) 3551 process_z(obj); 3552 } else { 3553 /* 3554 * Bump the reference counts for objects on this DAG. If 3555 * this is the first dlopen() call for the object that was 3556 * already loaded as a dependency, initialize the dag 3557 * starting at it. 3558 */ 3559 init_dag(obj); 3560 ref_dag(obj); 3561 3562 if ((lo_flags & RTLD_LO_TRACE) != 0) 3563 goto trace; 3564 } 3565 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 || 3566 obj->z_nodelete) && !obj->ref_nodel) { 3567 dbg("obj %s nodelete", obj->path); 3568 ref_dag(obj); 3569 obj->z_nodelete = obj->ref_nodel = true; 3570 } 3571 } 3572 3573 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0, 3574 name); 3575 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); 3576 3577 if ((lo_flags & RTLD_LO_EARLY) == 0) { 3578 map_stacks_exec(lockstate); 3579 if (obj != NULL) 3580 distribute_static_tls(&initlist, lockstate); 3581 } 3582 3583 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW, 3584 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3585 lockstate) == -1) { 3586 objlist_clear(&initlist); 3587 dlopen_cleanup(obj, lockstate); 3588 if (lockstate == &mlockstate) 3589 lock_release(rtld_bind_lock, lockstate); 3590 return (NULL); 3591 } 3592 3593 if (!(lo_flags & RTLD_LO_EARLY)) { 3594 /* Call the init functions. */ 3595 objlist_call_init(&initlist, lockstate); 3596 } 3597 objlist_clear(&initlist); 3598 if (lockstate == &mlockstate) 3599 lock_release(rtld_bind_lock, lockstate); 3600 return obj; 3601 trace: 3602 trace_loaded_objects(obj); 3603 if (lockstate == &mlockstate) 3604 lock_release(rtld_bind_lock, lockstate); 3605 exit(0); 3606 } 3607 3608 static void * 3609 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve, 3610 int flags) 3611 { 3612 DoneList donelist; 3613 const Obj_Entry *obj, *defobj; 3614 const Elf_Sym *def; 3615 SymLook req; 3616 RtldLockState lockstate; 3617 tls_index ti; 3618 void *sym; 3619 int res; 3620 3621 def = NULL; 3622 defobj = NULL; 3623 symlook_init(&req, name); 3624 req.ventry = ve; 3625 req.flags = flags | SYMLOOK_IN_PLT; 3626 req.lockstate = &lockstate; 3627 3628 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name); 3629 rlock_acquire(rtld_bind_lock, &lockstate); 3630 if (sigsetjmp(lockstate.env, 0) != 0) 3631 lock_upgrade(rtld_bind_lock, &lockstate); 3632 if (handle == NULL || handle == RTLD_NEXT || 3633 handle == RTLD_DEFAULT || handle == RTLD_SELF) { 3634 3635 if ((obj = obj_from_addr(retaddr)) == NULL) { 3636 _rtld_error("Cannot determine caller's shared object"); 3637 lock_release(rtld_bind_lock, &lockstate); 3638 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3639 return NULL; 3640 } 3641 if (handle == NULL) { /* Just the caller's shared object. */ 3642 res = symlook_obj(&req, obj); 3643 if (res == 0) { 3644 def = req.sym_out; 3645 defobj = req.defobj_out; 3646 } 3647 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 3648 handle == RTLD_SELF) { /* ... caller included */ 3649 if (handle == RTLD_NEXT) 3650 obj = globallist_next(obj); 3651 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 3652 if (obj->marker) 3653 continue; 3654 res = symlook_obj(&req, obj); 3655 if (res == 0) { 3656 if (def == NULL || 3657 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK) { 3658 def = req.sym_out; 3659 defobj = req.defobj_out; 3660 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 3661 break; 3662 } 3663 } 3664 } 3665 /* 3666 * Search the dynamic linker itself, and possibly resolve the 3667 * symbol from there. This is how the application links to 3668 * dynamic linker services such as dlopen. 3669 */ 3670 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3671 res = symlook_obj(&req, &obj_rtld); 3672 if (res == 0) { 3673 def = req.sym_out; 3674 defobj = req.defobj_out; 3675 } 3676 } 3677 } else { 3678 assert(handle == RTLD_DEFAULT); 3679 res = symlook_default(&req, obj); 3680 if (res == 0) { 3681 defobj = req.defobj_out; 3682 def = req.sym_out; 3683 } 3684 } 3685 } else { 3686 if ((obj = dlcheck(handle)) == NULL) { 3687 lock_release(rtld_bind_lock, &lockstate); 3688 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3689 return NULL; 3690 } 3691 3692 donelist_init(&donelist); 3693 if (obj->mainprog) { 3694 /* Handle obtained by dlopen(NULL, ...) implies global scope. */ 3695 res = symlook_global(&req, &donelist); 3696 if (res == 0) { 3697 def = req.sym_out; 3698 defobj = req.defobj_out; 3699 } 3700 /* 3701 * Search the dynamic linker itself, and possibly resolve the 3702 * symbol from there. This is how the application links to 3703 * dynamic linker services such as dlopen. 3704 */ 3705 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3706 res = symlook_obj(&req, &obj_rtld); 3707 if (res == 0) { 3708 def = req.sym_out; 3709 defobj = req.defobj_out; 3710 } 3711 } 3712 } 3713 else { 3714 /* Search the whole DAG rooted at the given object. */ 3715 res = symlook_list(&req, &obj->dagmembers, &donelist); 3716 if (res == 0) { 3717 def = req.sym_out; 3718 defobj = req.defobj_out; 3719 } 3720 } 3721 } 3722 3723 if (def != NULL) { 3724 lock_release(rtld_bind_lock, &lockstate); 3725 3726 /* 3727 * The value required by the caller is derived from the value 3728 * of the symbol. this is simply the relocated value of the 3729 * symbol. 3730 */ 3731 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 3732 sym = make_function_pointer(def, defobj); 3733 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 3734 sym = rtld_resolve_ifunc(defobj, def); 3735 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) { 3736 ti.ti_module = defobj->tlsindex; 3737 ti.ti_offset = def->st_value; 3738 sym = __tls_get_addr(&ti); 3739 } else 3740 sym = defobj->relocbase + def->st_value; 3741 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name); 3742 return (sym); 3743 } 3744 3745 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "", 3746 ve != NULL ? ve->name : ""); 3747 lock_release(rtld_bind_lock, &lockstate); 3748 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3749 return NULL; 3750 } 3751 3752 void * 3753 dlsym(void *handle, const char *name) 3754 { 3755 return do_dlsym(handle, name, __builtin_return_address(0), NULL, 3756 SYMLOOK_DLSYM); 3757 } 3758 3759 dlfunc_t 3760 dlfunc(void *handle, const char *name) 3761 { 3762 union { 3763 void *d; 3764 dlfunc_t f; 3765 } rv; 3766 3767 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL, 3768 SYMLOOK_DLSYM); 3769 return (rv.f); 3770 } 3771 3772 void * 3773 dlvsym(void *handle, const char *name, const char *version) 3774 { 3775 Ver_Entry ventry; 3776 3777 ventry.name = version; 3778 ventry.file = NULL; 3779 ventry.hash = elf_hash(version); 3780 ventry.flags= 0; 3781 return do_dlsym(handle, name, __builtin_return_address(0), &ventry, 3782 SYMLOOK_DLSYM); 3783 } 3784 3785 int 3786 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info) 3787 { 3788 const Obj_Entry *obj; 3789 RtldLockState lockstate; 3790 3791 rlock_acquire(rtld_bind_lock, &lockstate); 3792 obj = obj_from_addr(addr); 3793 if (obj == NULL) { 3794 _rtld_error("No shared object contains address"); 3795 lock_release(rtld_bind_lock, &lockstate); 3796 return (0); 3797 } 3798 rtld_fill_dl_phdr_info(obj, phdr_info); 3799 lock_release(rtld_bind_lock, &lockstate); 3800 return (1); 3801 } 3802 3803 int 3804 dladdr(const void *addr, Dl_info *info) 3805 { 3806 const Obj_Entry *obj; 3807 const Elf_Sym *def; 3808 void *symbol_addr; 3809 unsigned long symoffset; 3810 RtldLockState lockstate; 3811 3812 rlock_acquire(rtld_bind_lock, &lockstate); 3813 obj = obj_from_addr(addr); 3814 if (obj == NULL) { 3815 _rtld_error("No shared object contains address"); 3816 lock_release(rtld_bind_lock, &lockstate); 3817 return 0; 3818 } 3819 info->dli_fname = obj->path; 3820 info->dli_fbase = obj->mapbase; 3821 info->dli_saddr = (void *)0; 3822 info->dli_sname = NULL; 3823 3824 /* 3825 * Walk the symbol list looking for the symbol whose address is 3826 * closest to the address sent in. 3827 */ 3828 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) { 3829 def = obj->symtab + symoffset; 3830 3831 /* 3832 * For skip the symbol if st_shndx is either SHN_UNDEF or 3833 * SHN_COMMON. 3834 */ 3835 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 3836 continue; 3837 3838 /* 3839 * If the symbol is greater than the specified address, or if it 3840 * is further away from addr than the current nearest symbol, 3841 * then reject it. 3842 */ 3843 symbol_addr = obj->relocbase + def->st_value; 3844 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 3845 continue; 3846 3847 /* Update our idea of the nearest symbol. */ 3848 info->dli_sname = obj->strtab + def->st_name; 3849 info->dli_saddr = symbol_addr; 3850 3851 /* Exact match? */ 3852 if (info->dli_saddr == addr) 3853 break; 3854 } 3855 lock_release(rtld_bind_lock, &lockstate); 3856 return 1; 3857 } 3858 3859 int 3860 dlinfo(void *handle, int request, void *p) 3861 { 3862 const Obj_Entry *obj; 3863 RtldLockState lockstate; 3864 int error; 3865 3866 rlock_acquire(rtld_bind_lock, &lockstate); 3867 3868 if (handle == NULL || handle == RTLD_SELF) { 3869 void *retaddr; 3870 3871 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 3872 if ((obj = obj_from_addr(retaddr)) == NULL) 3873 _rtld_error("Cannot determine caller's shared object"); 3874 } else 3875 obj = dlcheck(handle); 3876 3877 if (obj == NULL) { 3878 lock_release(rtld_bind_lock, &lockstate); 3879 return (-1); 3880 } 3881 3882 error = 0; 3883 switch (request) { 3884 case RTLD_DI_LINKMAP: 3885 *((struct link_map const **)p) = &obj->linkmap; 3886 break; 3887 case RTLD_DI_ORIGIN: 3888 error = rtld_dirname(obj->path, p); 3889 break; 3890 3891 case RTLD_DI_SERINFOSIZE: 3892 case RTLD_DI_SERINFO: 3893 error = do_search_info(obj, request, (struct dl_serinfo *)p); 3894 break; 3895 3896 default: 3897 _rtld_error("Invalid request %d passed to dlinfo()", request); 3898 error = -1; 3899 } 3900 3901 lock_release(rtld_bind_lock, &lockstate); 3902 3903 return (error); 3904 } 3905 3906 static void 3907 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info) 3908 { 3909 Elf_Addr **dtvp; 3910 3911 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase; 3912 phdr_info->dlpi_name = obj->path; 3913 phdr_info->dlpi_phdr = obj->phdr; 3914 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]); 3915 phdr_info->dlpi_tls_modid = obj->tlsindex; 3916 dtvp = _get_tp(); 3917 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp, 3918 obj->tlsindex, 0, true) + TLS_DTV_OFFSET; 3919 phdr_info->dlpi_adds = obj_loads; 3920 phdr_info->dlpi_subs = obj_loads - obj_count; 3921 } 3922 3923 int 3924 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param) 3925 { 3926 struct dl_phdr_info phdr_info; 3927 Obj_Entry *obj, marker; 3928 RtldLockState bind_lockstate, phdr_lockstate; 3929 int error; 3930 3931 init_marker(&marker); 3932 error = 0; 3933 3934 wlock_acquire(rtld_phdr_lock, &phdr_lockstate); 3935 wlock_acquire(rtld_bind_lock, &bind_lockstate); 3936 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) { 3937 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next); 3938 rtld_fill_dl_phdr_info(obj, &phdr_info); 3939 hold_object(obj); 3940 lock_release(rtld_bind_lock, &bind_lockstate); 3941 3942 error = callback(&phdr_info, sizeof phdr_info, param); 3943 3944 wlock_acquire(rtld_bind_lock, &bind_lockstate); 3945 unhold_object(obj); 3946 obj = globallist_next(&marker); 3947 TAILQ_REMOVE(&obj_list, &marker, next); 3948 if (error != 0) { 3949 lock_release(rtld_bind_lock, &bind_lockstate); 3950 lock_release(rtld_phdr_lock, &phdr_lockstate); 3951 return (error); 3952 } 3953 } 3954 3955 if (error == 0) { 3956 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info); 3957 lock_release(rtld_bind_lock, &bind_lockstate); 3958 error = callback(&phdr_info, sizeof(phdr_info), param); 3959 } 3960 lock_release(rtld_phdr_lock, &phdr_lockstate); 3961 return (error); 3962 } 3963 3964 static void * 3965 fill_search_info(const char *dir, size_t dirlen, void *param) 3966 { 3967 struct fill_search_info_args *arg; 3968 3969 arg = param; 3970 3971 if (arg->request == RTLD_DI_SERINFOSIZE) { 3972 arg->serinfo->dls_cnt ++; 3973 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1; 3974 } else { 3975 struct dl_serpath *s_entry; 3976 3977 s_entry = arg->serpath; 3978 s_entry->dls_name = arg->strspace; 3979 s_entry->dls_flags = arg->flags; 3980 3981 strncpy(arg->strspace, dir, dirlen); 3982 arg->strspace[dirlen] = '\0'; 3983 3984 arg->strspace += dirlen + 1; 3985 arg->serpath++; 3986 } 3987 3988 return (NULL); 3989 } 3990 3991 static int 3992 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 3993 { 3994 struct dl_serinfo _info; 3995 struct fill_search_info_args args; 3996 3997 args.request = RTLD_DI_SERINFOSIZE; 3998 args.serinfo = &_info; 3999 4000 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 4001 _info.dls_cnt = 0; 4002 4003 path_enumerate(obj->rpath, fill_search_info, NULL, &args); 4004 path_enumerate(ld_library_path, fill_search_info, NULL, &args); 4005 path_enumerate(obj->runpath, fill_search_info, NULL, &args); 4006 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args); 4007 if (!obj->z_nodeflib) 4008 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args); 4009 4010 4011 if (request == RTLD_DI_SERINFOSIZE) { 4012 info->dls_size = _info.dls_size; 4013 info->dls_cnt = _info.dls_cnt; 4014 return (0); 4015 } 4016 4017 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { 4018 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); 4019 return (-1); 4020 } 4021 4022 args.request = RTLD_DI_SERINFO; 4023 args.serinfo = info; 4024 args.serpath = &info->dls_serpath[0]; 4025 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 4026 4027 args.flags = LA_SER_RUNPATH; 4028 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL) 4029 return (-1); 4030 4031 args.flags = LA_SER_LIBPATH; 4032 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL) 4033 return (-1); 4034 4035 args.flags = LA_SER_RUNPATH; 4036 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL) 4037 return (-1); 4038 4039 args.flags = LA_SER_CONFIG; 4040 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args) 4041 != NULL) 4042 return (-1); 4043 4044 args.flags = LA_SER_DEFAULT; 4045 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path, 4046 fill_search_info, NULL, &args) != NULL) 4047 return (-1); 4048 return (0); 4049 } 4050 4051 static int 4052 rtld_dirname(const char *path, char *bname) 4053 { 4054 const char *endp; 4055 4056 /* Empty or NULL string gets treated as "." */ 4057 if (path == NULL || *path == '\0') { 4058 bname[0] = '.'; 4059 bname[1] = '\0'; 4060 return (0); 4061 } 4062 4063 /* Strip trailing slashes */ 4064 endp = path + strlen(path) - 1; 4065 while (endp > path && *endp == '/') 4066 endp--; 4067 4068 /* Find the start of the dir */ 4069 while (endp > path && *endp != '/') 4070 endp--; 4071 4072 /* Either the dir is "/" or there are no slashes */ 4073 if (endp == path) { 4074 bname[0] = *endp == '/' ? '/' : '.'; 4075 bname[1] = '\0'; 4076 return (0); 4077 } else { 4078 do { 4079 endp--; 4080 } while (endp > path && *endp == '/'); 4081 } 4082 4083 if (endp - path + 2 > PATH_MAX) 4084 { 4085 _rtld_error("Filename is too long: %s", path); 4086 return(-1); 4087 } 4088 4089 strncpy(bname, path, endp - path + 1); 4090 bname[endp - path + 1] = '\0'; 4091 return (0); 4092 } 4093 4094 static int 4095 rtld_dirname_abs(const char *path, char *base) 4096 { 4097 char *last; 4098 4099 if (realpath(path, base) == NULL) { 4100 _rtld_error("realpath \"%s\" failed (%s)", path, 4101 rtld_strerror(errno)); 4102 return (-1); 4103 } 4104 dbg("%s -> %s", path, base); 4105 last = strrchr(base, '/'); 4106 if (last == NULL) { 4107 _rtld_error("non-abs result from realpath \"%s\"", path); 4108 return (-1); 4109 } 4110 if (last != base) 4111 *last = '\0'; 4112 return (0); 4113 } 4114 4115 static void 4116 linkmap_add(Obj_Entry *obj) 4117 { 4118 struct link_map *l, *prev; 4119 4120 l = &obj->linkmap; 4121 l->l_name = obj->path; 4122 l->l_base = obj->mapbase; 4123 l->l_ld = obj->dynamic; 4124 l->l_addr = obj->relocbase; 4125 4126 if (r_debug.r_map == NULL) { 4127 r_debug.r_map = l; 4128 return; 4129 } 4130 4131 /* 4132 * Scan to the end of the list, but not past the entry for the 4133 * dynamic linker, which we want to keep at the very end. 4134 */ 4135 for (prev = r_debug.r_map; 4136 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 4137 prev = prev->l_next) 4138 ; 4139 4140 /* Link in the new entry. */ 4141 l->l_prev = prev; 4142 l->l_next = prev->l_next; 4143 if (l->l_next != NULL) 4144 l->l_next->l_prev = l; 4145 prev->l_next = l; 4146 } 4147 4148 static void 4149 linkmap_delete(Obj_Entry *obj) 4150 { 4151 struct link_map *l; 4152 4153 l = &obj->linkmap; 4154 if (l->l_prev == NULL) { 4155 if ((r_debug.r_map = l->l_next) != NULL) 4156 l->l_next->l_prev = NULL; 4157 return; 4158 } 4159 4160 if ((l->l_prev->l_next = l->l_next) != NULL) 4161 l->l_next->l_prev = l->l_prev; 4162 } 4163 4164 /* 4165 * Function for the debugger to set a breakpoint on to gain control. 4166 * 4167 * The two parameters allow the debugger to easily find and determine 4168 * what the runtime loader is doing and to whom it is doing it. 4169 * 4170 * When the loadhook trap is hit (r_debug_state, set at program 4171 * initialization), the arguments can be found on the stack: 4172 * 4173 * +8 struct link_map *m 4174 * +4 struct r_debug *rd 4175 * +0 RetAddr 4176 */ 4177 void 4178 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused) 4179 { 4180 /* 4181 * The following is a hack to force the compiler to emit calls to 4182 * this function, even when optimizing. If the function is empty, 4183 * the compiler is not obliged to emit any code for calls to it, 4184 * even when marked __noinline. However, gdb depends on those 4185 * calls being made. 4186 */ 4187 __compiler_membar(); 4188 } 4189 4190 /* 4191 * A function called after init routines have completed. This can be used to 4192 * break before a program's entry routine is called, and can be used when 4193 * main is not available in the symbol table. 4194 */ 4195 void 4196 _r_debug_postinit(struct link_map *m __unused) 4197 { 4198 4199 /* See r_debug_state(). */ 4200 __compiler_membar(); 4201 } 4202 4203 static void 4204 release_object(Obj_Entry *obj) 4205 { 4206 4207 if (obj->holdcount > 0) { 4208 obj->unholdfree = true; 4209 return; 4210 } 4211 munmap(obj->mapbase, obj->mapsize); 4212 linkmap_delete(obj); 4213 obj_free(obj); 4214 } 4215 4216 /* 4217 * Get address of the pointer variable in the main program. 4218 * Prefer non-weak symbol over the weak one. 4219 */ 4220 static const void ** 4221 get_program_var_addr(const char *name, RtldLockState *lockstate) 4222 { 4223 SymLook req; 4224 DoneList donelist; 4225 4226 symlook_init(&req, name); 4227 req.lockstate = lockstate; 4228 donelist_init(&donelist); 4229 if (symlook_global(&req, &donelist) != 0) 4230 return (NULL); 4231 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC) 4232 return ((const void **)make_function_pointer(req.sym_out, 4233 req.defobj_out)); 4234 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC) 4235 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out)); 4236 else 4237 return ((const void **)(req.defobj_out->relocbase + 4238 req.sym_out->st_value)); 4239 } 4240 4241 /* 4242 * Set a pointer variable in the main program to the given value. This 4243 * is used to set key variables such as "environ" before any of the 4244 * init functions are called. 4245 */ 4246 static void 4247 set_program_var(const char *name, const void *value) 4248 { 4249 const void **addr; 4250 4251 if ((addr = get_program_var_addr(name, NULL)) != NULL) { 4252 dbg("\"%s\": *%p <-- %p", name, addr, value); 4253 *addr = value; 4254 } 4255 } 4256 4257 /* 4258 * Search the global objects, including dependencies and main object, 4259 * for the given symbol. 4260 */ 4261 static int 4262 symlook_global(SymLook *req, DoneList *donelist) 4263 { 4264 SymLook req1; 4265 const Objlist_Entry *elm; 4266 int res; 4267 4268 symlook_init_from_req(&req1, req); 4269 4270 /* Search all objects loaded at program start up. */ 4271 if (req->defobj_out == NULL || 4272 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 4273 res = symlook_list(&req1, &list_main, donelist); 4274 if (res == 0 && (req->defobj_out == NULL || 4275 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4276 req->sym_out = req1.sym_out; 4277 req->defobj_out = req1.defobj_out; 4278 assert(req->defobj_out != NULL); 4279 } 4280 } 4281 4282 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 4283 STAILQ_FOREACH(elm, &list_global, link) { 4284 if (req->defobj_out != NULL && 4285 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK) 4286 break; 4287 res = symlook_list(&req1, &elm->obj->dagmembers, donelist); 4288 if (res == 0 && (req->defobj_out == NULL || 4289 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4290 req->sym_out = req1.sym_out; 4291 req->defobj_out = req1.defobj_out; 4292 assert(req->defobj_out != NULL); 4293 } 4294 } 4295 4296 return (req->sym_out != NULL ? 0 : ESRCH); 4297 } 4298 4299 /* 4300 * Given a symbol name in a referencing object, find the corresponding 4301 * definition of the symbol. Returns a pointer to the symbol, or NULL if 4302 * no definition was found. Returns a pointer to the Obj_Entry of the 4303 * defining object via the reference parameter DEFOBJ_OUT. 4304 */ 4305 static int 4306 symlook_default(SymLook *req, const Obj_Entry *refobj) 4307 { 4308 DoneList donelist; 4309 const Objlist_Entry *elm; 4310 SymLook req1; 4311 int res; 4312 4313 donelist_init(&donelist); 4314 symlook_init_from_req(&req1, req); 4315 4316 /* 4317 * Look first in the referencing object if linked symbolically, 4318 * and similarly handle protected symbols. 4319 */ 4320 res = symlook_obj(&req1, refobj); 4321 if (res == 0 && (refobj->symbolic || 4322 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) { 4323 req->sym_out = req1.sym_out; 4324 req->defobj_out = req1.defobj_out; 4325 assert(req->defobj_out != NULL); 4326 } 4327 if (refobj->symbolic || req->defobj_out != NULL) 4328 donelist_check(&donelist, refobj); 4329 4330 symlook_global(req, &donelist); 4331 4332 /* Search all dlopened DAGs containing the referencing object. */ 4333 STAILQ_FOREACH(elm, &refobj->dldags, link) { 4334 if (req->sym_out != NULL && 4335 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK) 4336 break; 4337 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist); 4338 if (res == 0 && (req->sym_out == NULL || 4339 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4340 req->sym_out = req1.sym_out; 4341 req->defobj_out = req1.defobj_out; 4342 assert(req->defobj_out != NULL); 4343 } 4344 } 4345 4346 /* 4347 * Search the dynamic linker itself, and possibly resolve the 4348 * symbol from there. This is how the application links to 4349 * dynamic linker services such as dlopen. 4350 */ 4351 if (req->sym_out == NULL || 4352 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 4353 res = symlook_obj(&req1, &obj_rtld); 4354 if (res == 0) { 4355 req->sym_out = req1.sym_out; 4356 req->defobj_out = req1.defobj_out; 4357 assert(req->defobj_out != NULL); 4358 } 4359 } 4360 4361 return (req->sym_out != NULL ? 0 : ESRCH); 4362 } 4363 4364 static int 4365 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp) 4366 { 4367 const Elf_Sym *def; 4368 const Obj_Entry *defobj; 4369 const Objlist_Entry *elm; 4370 SymLook req1; 4371 int res; 4372 4373 def = NULL; 4374 defobj = NULL; 4375 STAILQ_FOREACH(elm, objlist, link) { 4376 if (donelist_check(dlp, elm->obj)) 4377 continue; 4378 symlook_init_from_req(&req1, req); 4379 if ((res = symlook_obj(&req1, elm->obj)) == 0) { 4380 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) { 4381 def = req1.sym_out; 4382 defobj = req1.defobj_out; 4383 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 4384 break; 4385 } 4386 } 4387 } 4388 if (def != NULL) { 4389 req->sym_out = def; 4390 req->defobj_out = defobj; 4391 return (0); 4392 } 4393 return (ESRCH); 4394 } 4395 4396 /* 4397 * Search the chain of DAGS cointed to by the given Needed_Entry 4398 * for a symbol of the given name. Each DAG is scanned completely 4399 * before advancing to the next one. Returns a pointer to the symbol, 4400 * or NULL if no definition was found. 4401 */ 4402 static int 4403 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp) 4404 { 4405 const Elf_Sym *def; 4406 const Needed_Entry *n; 4407 const Obj_Entry *defobj; 4408 SymLook req1; 4409 int res; 4410 4411 def = NULL; 4412 defobj = NULL; 4413 symlook_init_from_req(&req1, req); 4414 for (n = needed; n != NULL; n = n->next) { 4415 if (n->obj == NULL || 4416 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0) 4417 continue; 4418 if (def == NULL || ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK) { 4419 def = req1.sym_out; 4420 defobj = req1.defobj_out; 4421 if (ELF_ST_BIND(def->st_info) != STB_WEAK) 4422 break; 4423 } 4424 } 4425 if (def != NULL) { 4426 req->sym_out = def; 4427 req->defobj_out = defobj; 4428 return (0); 4429 } 4430 return (ESRCH); 4431 } 4432 4433 /* 4434 * Search the symbol table of a single shared object for a symbol of 4435 * the given name and version, if requested. Returns a pointer to the 4436 * symbol, or NULL if no definition was found. If the object is 4437 * filter, return filtered symbol from filtee. 4438 * 4439 * The symbol's hash value is passed in for efficiency reasons; that 4440 * eliminates many recomputations of the hash value. 4441 */ 4442 int 4443 symlook_obj(SymLook *req, const Obj_Entry *obj) 4444 { 4445 DoneList donelist; 4446 SymLook req1; 4447 int flags, res, mres; 4448 4449 /* 4450 * If there is at least one valid hash at this point, we prefer to 4451 * use the faster GNU version if available. 4452 */ 4453 if (obj->valid_hash_gnu) 4454 mres = symlook_obj1_gnu(req, obj); 4455 else if (obj->valid_hash_sysv) 4456 mres = symlook_obj1_sysv(req, obj); 4457 else 4458 return (EINVAL); 4459 4460 if (mres == 0) { 4461 if (obj->needed_filtees != NULL) { 4462 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0; 4463 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4464 donelist_init(&donelist); 4465 symlook_init_from_req(&req1, req); 4466 res = symlook_needed(&req1, obj->needed_filtees, &donelist); 4467 if (res == 0) { 4468 req->sym_out = req1.sym_out; 4469 req->defobj_out = req1.defobj_out; 4470 } 4471 return (res); 4472 } 4473 if (obj->needed_aux_filtees != NULL) { 4474 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0; 4475 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4476 donelist_init(&donelist); 4477 symlook_init_from_req(&req1, req); 4478 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist); 4479 if (res == 0) { 4480 req->sym_out = req1.sym_out; 4481 req->defobj_out = req1.defobj_out; 4482 return (res); 4483 } 4484 } 4485 } 4486 return (mres); 4487 } 4488 4489 /* Symbol match routine common to both hash functions */ 4490 static bool 4491 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result, 4492 const unsigned long symnum) 4493 { 4494 Elf_Versym verndx; 4495 const Elf_Sym *symp; 4496 const char *strp; 4497 4498 symp = obj->symtab + symnum; 4499 strp = obj->strtab + symp->st_name; 4500 4501 switch (ELF_ST_TYPE(symp->st_info)) { 4502 case STT_FUNC: 4503 case STT_NOTYPE: 4504 case STT_OBJECT: 4505 case STT_COMMON: 4506 case STT_GNU_IFUNC: 4507 if (symp->st_value == 0) 4508 return (false); 4509 /* fallthrough */ 4510 case STT_TLS: 4511 if (symp->st_shndx != SHN_UNDEF) 4512 break; 4513 #ifndef __mips__ 4514 else if (((req->flags & SYMLOOK_IN_PLT) == 0) && 4515 (ELF_ST_TYPE(symp->st_info) == STT_FUNC)) 4516 break; 4517 #endif 4518 /* fallthrough */ 4519 default: 4520 return (false); 4521 } 4522 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0) 4523 return (false); 4524 4525 if (req->ventry == NULL) { 4526 if (obj->versyms != NULL) { 4527 verndx = VER_NDX(obj->versyms[symnum]); 4528 if (verndx > obj->vernum) { 4529 _rtld_error( 4530 "%s: symbol %s references wrong version %d", 4531 obj->path, obj->strtab + symnum, verndx); 4532 return (false); 4533 } 4534 /* 4535 * If we are not called from dlsym (i.e. this 4536 * is a normal relocation from unversioned 4537 * binary), accept the symbol immediately if 4538 * it happens to have first version after this 4539 * shared object became versioned. Otherwise, 4540 * if symbol is versioned and not hidden, 4541 * remember it. If it is the only symbol with 4542 * this name exported by the shared object, it 4543 * will be returned as a match by the calling 4544 * function. If symbol is global (verndx < 2) 4545 * accept it unconditionally. 4546 */ 4547 if ((req->flags & SYMLOOK_DLSYM) == 0 && 4548 verndx == VER_NDX_GIVEN) { 4549 result->sym_out = symp; 4550 return (true); 4551 } 4552 else if (verndx >= VER_NDX_GIVEN) { 4553 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) 4554 == 0) { 4555 if (result->vsymp == NULL) 4556 result->vsymp = symp; 4557 result->vcount++; 4558 } 4559 return (false); 4560 } 4561 } 4562 result->sym_out = symp; 4563 return (true); 4564 } 4565 if (obj->versyms == NULL) { 4566 if (object_match_name(obj, req->ventry->name)) { 4567 _rtld_error("%s: object %s should provide version %s " 4568 "for symbol %s", obj_rtld.path, obj->path, 4569 req->ventry->name, obj->strtab + symnum); 4570 return (false); 4571 } 4572 } else { 4573 verndx = VER_NDX(obj->versyms[symnum]); 4574 if (verndx > obj->vernum) { 4575 _rtld_error("%s: symbol %s references wrong version %d", 4576 obj->path, obj->strtab + symnum, verndx); 4577 return (false); 4578 } 4579 if (obj->vertab[verndx].hash != req->ventry->hash || 4580 strcmp(obj->vertab[verndx].name, req->ventry->name)) { 4581 /* 4582 * Version does not match. Look if this is a 4583 * global symbol and if it is not hidden. If 4584 * global symbol (verndx < 2) is available, 4585 * use it. Do not return symbol if we are 4586 * called by dlvsym, because dlvsym looks for 4587 * a specific version and default one is not 4588 * what dlvsym wants. 4589 */ 4590 if ((req->flags & SYMLOOK_DLSYM) || 4591 (verndx >= VER_NDX_GIVEN) || 4592 (obj->versyms[symnum] & VER_NDX_HIDDEN)) 4593 return (false); 4594 } 4595 } 4596 result->sym_out = symp; 4597 return (true); 4598 } 4599 4600 /* 4601 * Search for symbol using SysV hash function. 4602 * obj->buckets is known not to be NULL at this point; the test for this was 4603 * performed with the obj->valid_hash_sysv assignment. 4604 */ 4605 static int 4606 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj) 4607 { 4608 unsigned long symnum; 4609 Sym_Match_Result matchres; 4610 4611 matchres.sym_out = NULL; 4612 matchres.vsymp = NULL; 4613 matchres.vcount = 0; 4614 4615 for (symnum = obj->buckets[req->hash % obj->nbuckets]; 4616 symnum != STN_UNDEF; symnum = obj->chains[symnum]) { 4617 if (symnum >= obj->nchains) 4618 return (ESRCH); /* Bad object */ 4619 4620 if (matched_symbol(req, obj, &matchres, symnum)) { 4621 req->sym_out = matchres.sym_out; 4622 req->defobj_out = obj; 4623 return (0); 4624 } 4625 } 4626 if (matchres.vcount == 1) { 4627 req->sym_out = matchres.vsymp; 4628 req->defobj_out = obj; 4629 return (0); 4630 } 4631 return (ESRCH); 4632 } 4633 4634 /* Search for symbol using GNU hash function */ 4635 static int 4636 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj) 4637 { 4638 Elf_Addr bloom_word; 4639 const Elf32_Word *hashval; 4640 Elf32_Word bucket; 4641 Sym_Match_Result matchres; 4642 unsigned int h1, h2; 4643 unsigned long symnum; 4644 4645 matchres.sym_out = NULL; 4646 matchres.vsymp = NULL; 4647 matchres.vcount = 0; 4648 4649 /* Pick right bitmask word from Bloom filter array */ 4650 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) & 4651 obj->maskwords_bm_gnu]; 4652 4653 /* Calculate modulus word size of gnu hash and its derivative */ 4654 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1); 4655 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1)); 4656 4657 /* Filter out the "definitely not in set" queries */ 4658 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0) 4659 return (ESRCH); 4660 4661 /* Locate hash chain and corresponding value element*/ 4662 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu]; 4663 if (bucket == 0) 4664 return (ESRCH); 4665 hashval = &obj->chain_zero_gnu[bucket]; 4666 do { 4667 if (((*hashval ^ req->hash_gnu) >> 1) == 0) { 4668 symnum = hashval - obj->chain_zero_gnu; 4669 if (matched_symbol(req, obj, &matchres, symnum)) { 4670 req->sym_out = matchres.sym_out; 4671 req->defobj_out = obj; 4672 return (0); 4673 } 4674 } 4675 } while ((*hashval++ & 1) == 0); 4676 if (matchres.vcount == 1) { 4677 req->sym_out = matchres.vsymp; 4678 req->defobj_out = obj; 4679 return (0); 4680 } 4681 return (ESRCH); 4682 } 4683 4684 static void 4685 trace_loaded_objects(Obj_Entry *obj) 4686 { 4687 const char *fmt1, *fmt2, *fmt, *main_local, *list_containers; 4688 int c; 4689 4690 if ((main_local = getenv(_LD("TRACE_LOADED_OBJECTS_PROGNAME"))) == NULL) 4691 main_local = ""; 4692 4693 if ((fmt1 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT1"))) == NULL) 4694 fmt1 = "\t%o => %p (%x)\n"; 4695 4696 if ((fmt2 = getenv(_LD("TRACE_LOADED_OBJECTS_FMT2"))) == NULL) 4697 fmt2 = "\t%o (%x)\n"; 4698 4699 list_containers = getenv(_LD("TRACE_LOADED_OBJECTS_ALL")); 4700 4701 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 4702 Needed_Entry *needed; 4703 const char *name, *path; 4704 bool is_lib; 4705 4706 if (obj->marker) 4707 continue; 4708 if (list_containers && obj->needed != NULL) 4709 rtld_printf("%s:\n", obj->path); 4710 for (needed = obj->needed; needed; needed = needed->next) { 4711 if (needed->obj != NULL) { 4712 if (needed->obj->traced && !list_containers) 4713 continue; 4714 needed->obj->traced = true; 4715 path = needed->obj->path; 4716 } else 4717 path = "not found"; 4718 4719 name = obj->strtab + needed->name; 4720 is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */ 4721 4722 fmt = is_lib ? fmt1 : fmt2; 4723 while ((c = *fmt++) != '\0') { 4724 switch (c) { 4725 default: 4726 rtld_putchar(c); 4727 continue; 4728 case '\\': 4729 switch (c = *fmt) { 4730 case '\0': 4731 continue; 4732 case 'n': 4733 rtld_putchar('\n'); 4734 break; 4735 case 't': 4736 rtld_putchar('\t'); 4737 break; 4738 } 4739 break; 4740 case '%': 4741 switch (c = *fmt) { 4742 case '\0': 4743 continue; 4744 case '%': 4745 default: 4746 rtld_putchar(c); 4747 break; 4748 case 'A': 4749 rtld_putstr(main_local); 4750 break; 4751 case 'a': 4752 rtld_putstr(obj_main->path); 4753 break; 4754 case 'o': 4755 rtld_putstr(name); 4756 break; 4757 #if 0 4758 case 'm': 4759 rtld_printf("%d", sodp->sod_major); 4760 break; 4761 case 'n': 4762 rtld_printf("%d", sodp->sod_minor); 4763 break; 4764 #endif 4765 case 'p': 4766 rtld_putstr(path); 4767 break; 4768 case 'x': 4769 rtld_printf("%p", needed->obj ? needed->obj->mapbase : 4770 0); 4771 break; 4772 } 4773 break; 4774 } 4775 ++fmt; 4776 } 4777 } 4778 } 4779 } 4780 4781 /* 4782 * Unload a dlopened object and its dependencies from memory and from 4783 * our data structures. It is assumed that the DAG rooted in the 4784 * object has already been unreferenced, and that the object has a 4785 * reference count of 0. 4786 */ 4787 static void 4788 unload_object(Obj_Entry *root, RtldLockState *lockstate) 4789 { 4790 Obj_Entry marker, *obj, *next; 4791 4792 assert(root->refcount == 0); 4793 4794 /* 4795 * Pass over the DAG removing unreferenced objects from 4796 * appropriate lists. 4797 */ 4798 unlink_object(root); 4799 4800 /* Unmap all objects that are no longer referenced. */ 4801 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) { 4802 next = TAILQ_NEXT(obj, next); 4803 if (obj->marker || obj->refcount != 0) 4804 continue; 4805 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, 4806 obj->mapsize, 0, obj->path); 4807 dbg("unloading \"%s\"", obj->path); 4808 /* 4809 * Unlink the object now to prevent new references from 4810 * being acquired while the bind lock is dropped in 4811 * recursive dlclose() invocations. 4812 */ 4813 TAILQ_REMOVE(&obj_list, obj, next); 4814 obj_count--; 4815 4816 if (obj->filtees_loaded) { 4817 if (next != NULL) { 4818 init_marker(&marker); 4819 TAILQ_INSERT_BEFORE(next, &marker, next); 4820 unload_filtees(obj, lockstate); 4821 next = TAILQ_NEXT(&marker, next); 4822 TAILQ_REMOVE(&obj_list, &marker, next); 4823 } else 4824 unload_filtees(obj, lockstate); 4825 } 4826 release_object(obj); 4827 } 4828 } 4829 4830 static void 4831 unlink_object(Obj_Entry *root) 4832 { 4833 Objlist_Entry *elm; 4834 4835 if (root->refcount == 0) { 4836 /* Remove the object from the RTLD_GLOBAL list. */ 4837 objlist_remove(&list_global, root); 4838 4839 /* Remove the object from all objects' DAG lists. */ 4840 STAILQ_FOREACH(elm, &root->dagmembers, link) { 4841 objlist_remove(&elm->obj->dldags, root); 4842 if (elm->obj != root) 4843 unlink_object(elm->obj); 4844 } 4845 } 4846 } 4847 4848 static void 4849 ref_dag(Obj_Entry *root) 4850 { 4851 Objlist_Entry *elm; 4852 4853 assert(root->dag_inited); 4854 STAILQ_FOREACH(elm, &root->dagmembers, link) 4855 elm->obj->refcount++; 4856 } 4857 4858 static void 4859 unref_dag(Obj_Entry *root) 4860 { 4861 Objlist_Entry *elm; 4862 4863 assert(root->dag_inited); 4864 STAILQ_FOREACH(elm, &root->dagmembers, link) 4865 elm->obj->refcount--; 4866 } 4867 4868 /* 4869 * Common code for MD __tls_get_addr(). 4870 */ 4871 static void * 4872 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked) 4873 { 4874 Elf_Addr *newdtv, *dtv; 4875 RtldLockState lockstate; 4876 int to_copy; 4877 4878 dtv = *dtvp; 4879 /* Check dtv generation in case new modules have arrived */ 4880 if (dtv[0] != tls_dtv_generation) { 4881 if (!locked) 4882 wlock_acquire(rtld_bind_lock, &lockstate); 4883 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 4884 to_copy = dtv[1]; 4885 if (to_copy > tls_max_index) 4886 to_copy = tls_max_index; 4887 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); 4888 newdtv[0] = tls_dtv_generation; 4889 newdtv[1] = tls_max_index; 4890 free(dtv); 4891 if (!locked) 4892 lock_release(rtld_bind_lock, &lockstate); 4893 dtv = *dtvp = newdtv; 4894 } 4895 4896 /* Dynamically allocate module TLS if necessary */ 4897 if (dtv[index + 1] == 0) { 4898 /* Signal safe, wlock will block out signals. */ 4899 if (!locked) 4900 wlock_acquire(rtld_bind_lock, &lockstate); 4901 if (!dtv[index + 1]) 4902 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); 4903 if (!locked) 4904 lock_release(rtld_bind_lock, &lockstate); 4905 } 4906 return ((void *)(dtv[index + 1] + offset)); 4907 } 4908 4909 void * 4910 tls_get_addr_common(Elf_Addr **dtvp, int index, size_t offset) 4911 { 4912 Elf_Addr *dtv; 4913 4914 dtv = *dtvp; 4915 /* Check dtv generation in case new modules have arrived */ 4916 if (__predict_true(dtv[0] == tls_dtv_generation && 4917 dtv[index + 1] != 0)) 4918 return ((void *)(dtv[index + 1] + offset)); 4919 return (tls_get_addr_slow(dtvp, index, offset, false)); 4920 } 4921 4922 #if defined(__aarch64__) || defined(__arm__) || defined(__mips__) || \ 4923 defined(__powerpc__) || defined(__riscv) 4924 4925 /* 4926 * Return pointer to allocated TLS block 4927 */ 4928 static void * 4929 get_tls_block_ptr(void *tcb, size_t tcbsize) 4930 { 4931 size_t extra_size, post_size, pre_size, tls_block_size; 4932 size_t tls_init_align; 4933 4934 tls_init_align = MAX(obj_main->tlsalign, 1); 4935 4936 /* Compute fragments sizes. */ 4937 extra_size = tcbsize - TLS_TCB_SIZE; 4938 post_size = calculate_tls_post_size(tls_init_align); 4939 tls_block_size = tcbsize + post_size; 4940 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 4941 4942 return ((char *)tcb - pre_size - extra_size); 4943 } 4944 4945 /* 4946 * Allocate Static TLS using the Variant I method. 4947 * 4948 * For details on the layout, see lib/libc/gen/tls.c. 4949 * 4950 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as 4951 * it is based on tls_last_offset, and TLS offsets here are really TCB 4952 * offsets, whereas libc's tls_static_space is just the executable's static 4953 * TLS segment. 4954 */ 4955 void * 4956 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 4957 { 4958 Obj_Entry *obj; 4959 char *tls_block; 4960 Elf_Addr *dtv, **tcb; 4961 Elf_Addr addr; 4962 Elf_Addr i; 4963 size_t extra_size, maxalign, post_size, pre_size, tls_block_size; 4964 size_t tls_init_align, tls_init_offset; 4965 4966 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) 4967 return (oldtcb); 4968 4969 assert(tcbsize >= TLS_TCB_SIZE); 4970 maxalign = MAX(tcbalign, tls_static_max_align); 4971 tls_init_align = MAX(obj_main->tlsalign, 1); 4972 4973 /* Compute fragmets sizes. */ 4974 extra_size = tcbsize - TLS_TCB_SIZE; 4975 post_size = calculate_tls_post_size(tls_init_align); 4976 tls_block_size = tcbsize + post_size; 4977 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 4978 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size; 4979 4980 /* Allocate whole TLS block */ 4981 tls_block = malloc_aligned(tls_block_size, maxalign, 0); 4982 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size); 4983 4984 if (oldtcb != NULL) { 4985 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize), 4986 tls_static_space); 4987 free_aligned(get_tls_block_ptr(oldtcb, tcbsize)); 4988 4989 /* Adjust the DTV. */ 4990 dtv = tcb[0]; 4991 for (i = 0; i < dtv[1]; i++) { 4992 if (dtv[i+2] >= (Elf_Addr)oldtcb && 4993 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) { 4994 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb; 4995 } 4996 } 4997 } else { 4998 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 4999 tcb[0] = dtv; 5000 dtv[0] = tls_dtv_generation; 5001 dtv[1] = tls_max_index; 5002 5003 for (obj = globallist_curr(objs); obj != NULL; 5004 obj = globallist_next(obj)) { 5005 if (obj->tlsoffset == 0) 5006 continue; 5007 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1); 5008 addr = (Elf_Addr)tcb + obj->tlsoffset; 5009 if (tls_init_offset > 0) 5010 memset((void *)addr, 0, tls_init_offset); 5011 if (obj->tlsinitsize > 0) { 5012 memcpy((void *)(addr + tls_init_offset), obj->tlsinit, 5013 obj->tlsinitsize); 5014 } 5015 if (obj->tlssize > obj->tlsinitsize) { 5016 memset((void *)(addr + tls_init_offset + obj->tlsinitsize), 5017 0, obj->tlssize - obj->tlsinitsize - tls_init_offset); 5018 } 5019 dtv[obj->tlsindex + 1] = addr; 5020 } 5021 } 5022 5023 return (tcb); 5024 } 5025 5026 void 5027 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused) 5028 { 5029 Elf_Addr *dtv; 5030 Elf_Addr tlsstart, tlsend; 5031 size_t post_size; 5032 size_t dtvsize, i, tls_init_align; 5033 5034 assert(tcbsize >= TLS_TCB_SIZE); 5035 tls_init_align = MAX(obj_main->tlsalign, 1); 5036 5037 /* Compute fragments sizes. */ 5038 post_size = calculate_tls_post_size(tls_init_align); 5039 5040 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size; 5041 tlsend = (Elf_Addr)tcb + tls_static_space; 5042 5043 dtv = *(Elf_Addr **)tcb; 5044 dtvsize = dtv[1]; 5045 for (i = 0; i < dtvsize; i++) { 5046 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) { 5047 free((void*)dtv[i+2]); 5048 } 5049 } 5050 free(dtv); 5051 free_aligned(get_tls_block_ptr(tcb, tcbsize)); 5052 } 5053 5054 #endif 5055 5056 #if defined(__i386__) || defined(__amd64__) 5057 5058 /* 5059 * Allocate Static TLS using the Variant II method. 5060 */ 5061 void * 5062 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 5063 { 5064 Obj_Entry *obj; 5065 size_t size, ralign; 5066 char *tls; 5067 Elf_Addr *dtv, *olddtv; 5068 Elf_Addr segbase, oldsegbase, addr; 5069 size_t i; 5070 5071 ralign = tcbalign; 5072 if (tls_static_max_align > ralign) 5073 ralign = tls_static_max_align; 5074 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign); 5075 5076 assert(tcbsize >= 2*sizeof(Elf_Addr)); 5077 tls = malloc_aligned(size, ralign, 0 /* XXX */); 5078 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5079 5080 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign)); 5081 ((Elf_Addr*)segbase)[0] = segbase; 5082 ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv; 5083 5084 dtv[0] = tls_dtv_generation; 5085 dtv[1] = tls_max_index; 5086 5087 if (oldtls) { 5088 /* 5089 * Copy the static TLS block over whole. 5090 */ 5091 oldsegbase = (Elf_Addr) oldtls; 5092 memcpy((void *)(segbase - tls_static_space), 5093 (const void *)(oldsegbase - tls_static_space), 5094 tls_static_space); 5095 5096 /* 5097 * If any dynamic TLS blocks have been created tls_get_addr(), 5098 * move them over. 5099 */ 5100 olddtv = ((Elf_Addr**)oldsegbase)[1]; 5101 for (i = 0; i < olddtv[1]; i++) { 5102 if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) { 5103 dtv[i+2] = olddtv[i+2]; 5104 olddtv[i+2] = 0; 5105 } 5106 } 5107 5108 /* 5109 * We assume that this block was the one we created with 5110 * allocate_initial_tls(). 5111 */ 5112 free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); 5113 } else { 5114 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5115 if (obj->marker || obj->tlsoffset == 0) 5116 continue; 5117 addr = segbase - obj->tlsoffset; 5118 memset((void*)(addr + obj->tlsinitsize), 5119 0, obj->tlssize - obj->tlsinitsize); 5120 if (obj->tlsinit) { 5121 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize); 5122 obj->static_tls_copied = true; 5123 } 5124 dtv[obj->tlsindex + 1] = addr; 5125 } 5126 } 5127 5128 return (void*) segbase; 5129 } 5130 5131 void 5132 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign) 5133 { 5134 Elf_Addr* dtv; 5135 size_t size, ralign; 5136 int dtvsize, i; 5137 Elf_Addr tlsstart, tlsend; 5138 5139 /* 5140 * Figure out the size of the initial TLS block so that we can 5141 * find stuff which ___tls_get_addr() allocated dynamically. 5142 */ 5143 ralign = tcbalign; 5144 if (tls_static_max_align > ralign) 5145 ralign = tls_static_max_align; 5146 size = roundup(tls_static_space, ralign); 5147 5148 dtv = ((Elf_Addr**)tls)[1]; 5149 dtvsize = dtv[1]; 5150 tlsend = (Elf_Addr) tls; 5151 tlsstart = tlsend - size; 5152 for (i = 0; i < dtvsize; i++) { 5153 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || dtv[i + 2] > tlsend)) { 5154 free_aligned((void *)dtv[i + 2]); 5155 } 5156 } 5157 5158 free_aligned((void *)tlsstart); 5159 free((void*) dtv); 5160 } 5161 5162 #endif 5163 5164 /* 5165 * Allocate TLS block for module with given index. 5166 */ 5167 void * 5168 allocate_module_tls(int index) 5169 { 5170 Obj_Entry *obj; 5171 char *p; 5172 5173 TAILQ_FOREACH(obj, &obj_list, next) { 5174 if (obj->marker) 5175 continue; 5176 if (obj->tlsindex == index) 5177 break; 5178 } 5179 if (obj == NULL) { 5180 _rtld_error("Can't find module with TLS index %d", index); 5181 rtld_die(); 5182 } 5183 5184 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset); 5185 memcpy(p, obj->tlsinit, obj->tlsinitsize); 5186 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 5187 return (p); 5188 } 5189 5190 bool 5191 allocate_tls_offset(Obj_Entry *obj) 5192 { 5193 size_t off; 5194 5195 if (obj->tls_done) 5196 return true; 5197 5198 if (obj->tlssize == 0) { 5199 obj->tls_done = true; 5200 return true; 5201 } 5202 5203 if (tls_last_offset == 0) 5204 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign, 5205 obj->tlspoffset); 5206 else 5207 off = calculate_tls_offset(tls_last_offset, tls_last_size, 5208 obj->tlssize, obj->tlsalign, obj->tlspoffset); 5209 5210 /* 5211 * If we have already fixed the size of the static TLS block, we 5212 * must stay within that size. When allocating the static TLS, we 5213 * leave a small amount of space spare to be used for dynamically 5214 * loading modules which use static TLS. 5215 */ 5216 if (tls_static_space != 0) { 5217 if (calculate_tls_end(off, obj->tlssize) > tls_static_space) 5218 return false; 5219 } else if (obj->tlsalign > tls_static_max_align) { 5220 tls_static_max_align = obj->tlsalign; 5221 } 5222 5223 tls_last_offset = obj->tlsoffset = off; 5224 tls_last_size = obj->tlssize; 5225 obj->tls_done = true; 5226 5227 return true; 5228 } 5229 5230 void 5231 free_tls_offset(Obj_Entry *obj) 5232 { 5233 5234 /* 5235 * If we were the last thing to allocate out of the static TLS 5236 * block, we give our space back to the 'allocator'. This is a 5237 * simplistic workaround to allow libGL.so.1 to be loaded and 5238 * unloaded multiple times. 5239 */ 5240 if (calculate_tls_end(obj->tlsoffset, obj->tlssize) 5241 == calculate_tls_end(tls_last_offset, tls_last_size)) { 5242 tls_last_offset -= obj->tlssize; 5243 tls_last_size = 0; 5244 } 5245 } 5246 5247 void * 5248 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) 5249 { 5250 void *ret; 5251 RtldLockState lockstate; 5252 5253 wlock_acquire(rtld_bind_lock, &lockstate); 5254 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls, 5255 tcbsize, tcbalign); 5256 lock_release(rtld_bind_lock, &lockstate); 5257 return (ret); 5258 } 5259 5260 void 5261 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 5262 { 5263 RtldLockState lockstate; 5264 5265 wlock_acquire(rtld_bind_lock, &lockstate); 5266 free_tls(tcb, tcbsize, tcbalign); 5267 lock_release(rtld_bind_lock, &lockstate); 5268 } 5269 5270 static void 5271 object_add_name(Obj_Entry *obj, const char *name) 5272 { 5273 Name_Entry *entry; 5274 size_t len; 5275 5276 len = strlen(name); 5277 entry = malloc(sizeof(Name_Entry) + len); 5278 5279 if (entry != NULL) { 5280 strcpy(entry->name, name); 5281 STAILQ_INSERT_TAIL(&obj->names, entry, link); 5282 } 5283 } 5284 5285 static int 5286 object_match_name(const Obj_Entry *obj, const char *name) 5287 { 5288 Name_Entry *entry; 5289 5290 STAILQ_FOREACH(entry, &obj->names, link) { 5291 if (strcmp(name, entry->name) == 0) 5292 return (1); 5293 } 5294 return (0); 5295 } 5296 5297 static Obj_Entry * 5298 locate_dependency(const Obj_Entry *obj, const char *name) 5299 { 5300 const Objlist_Entry *entry; 5301 const Needed_Entry *needed; 5302 5303 STAILQ_FOREACH(entry, &list_main, link) { 5304 if (object_match_name(entry->obj, name)) 5305 return entry->obj; 5306 } 5307 5308 for (needed = obj->needed; needed != NULL; needed = needed->next) { 5309 if (strcmp(obj->strtab + needed->name, name) == 0 || 5310 (needed->obj != NULL && object_match_name(needed->obj, name))) { 5311 /* 5312 * If there is DT_NEEDED for the name we are looking for, 5313 * we are all set. Note that object might not be found if 5314 * dependency was not loaded yet, so the function can 5315 * return NULL here. This is expected and handled 5316 * properly by the caller. 5317 */ 5318 return (needed->obj); 5319 } 5320 } 5321 _rtld_error("%s: Unexpected inconsistency: dependency %s not found", 5322 obj->path, name); 5323 rtld_die(); 5324 } 5325 5326 static int 5327 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj, 5328 const Elf_Vernaux *vna) 5329 { 5330 const Elf_Verdef *vd; 5331 const char *vername; 5332 5333 vername = refobj->strtab + vna->vna_name; 5334 vd = depobj->verdef; 5335 if (vd == NULL) { 5336 _rtld_error("%s: version %s required by %s not defined", 5337 depobj->path, vername, refobj->path); 5338 return (-1); 5339 } 5340 for (;;) { 5341 if (vd->vd_version != VER_DEF_CURRENT) { 5342 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5343 depobj->path, vd->vd_version); 5344 return (-1); 5345 } 5346 if (vna->vna_hash == vd->vd_hash) { 5347 const Elf_Verdaux *aux = (const Elf_Verdaux *) 5348 ((const char *)vd + vd->vd_aux); 5349 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0) 5350 return (0); 5351 } 5352 if (vd->vd_next == 0) 5353 break; 5354 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5355 } 5356 if (vna->vna_flags & VER_FLG_WEAK) 5357 return (0); 5358 _rtld_error("%s: version %s required by %s not found", 5359 depobj->path, vername, refobj->path); 5360 return (-1); 5361 } 5362 5363 static int 5364 rtld_verify_object_versions(Obj_Entry *obj) 5365 { 5366 const Elf_Verneed *vn; 5367 const Elf_Verdef *vd; 5368 const Elf_Verdaux *vda; 5369 const Elf_Vernaux *vna; 5370 const Obj_Entry *depobj; 5371 int maxvernum, vernum; 5372 5373 if (obj->ver_checked) 5374 return (0); 5375 obj->ver_checked = true; 5376 5377 maxvernum = 0; 5378 /* 5379 * Walk over defined and required version records and figure out 5380 * max index used by any of them. Do very basic sanity checking 5381 * while there. 5382 */ 5383 vn = obj->verneed; 5384 while (vn != NULL) { 5385 if (vn->vn_version != VER_NEED_CURRENT) { 5386 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry", 5387 obj->path, vn->vn_version); 5388 return (-1); 5389 } 5390 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 5391 for (;;) { 5392 vernum = VER_NEED_IDX(vna->vna_other); 5393 if (vernum > maxvernum) 5394 maxvernum = vernum; 5395 if (vna->vna_next == 0) 5396 break; 5397 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next); 5398 } 5399 if (vn->vn_next == 0) 5400 break; 5401 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 5402 } 5403 5404 vd = obj->verdef; 5405 while (vd != NULL) { 5406 if (vd->vd_version != VER_DEF_CURRENT) { 5407 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5408 obj->path, vd->vd_version); 5409 return (-1); 5410 } 5411 vernum = VER_DEF_IDX(vd->vd_ndx); 5412 if (vernum > maxvernum) 5413 maxvernum = vernum; 5414 if (vd->vd_next == 0) 5415 break; 5416 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5417 } 5418 5419 if (maxvernum == 0) 5420 return (0); 5421 5422 /* 5423 * Store version information in array indexable by version index. 5424 * Verify that object version requirements are satisfied along the 5425 * way. 5426 */ 5427 obj->vernum = maxvernum + 1; 5428 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry)); 5429 5430 vd = obj->verdef; 5431 while (vd != NULL) { 5432 if ((vd->vd_flags & VER_FLG_BASE) == 0) { 5433 vernum = VER_DEF_IDX(vd->vd_ndx); 5434 assert(vernum <= maxvernum); 5435 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux); 5436 obj->vertab[vernum].hash = vd->vd_hash; 5437 obj->vertab[vernum].name = obj->strtab + vda->vda_name; 5438 obj->vertab[vernum].file = NULL; 5439 obj->vertab[vernum].flags = 0; 5440 } 5441 if (vd->vd_next == 0) 5442 break; 5443 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5444 } 5445 5446 vn = obj->verneed; 5447 while (vn != NULL) { 5448 depobj = locate_dependency(obj, obj->strtab + vn->vn_file); 5449 if (depobj == NULL) 5450 return (-1); 5451 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 5452 for (;;) { 5453 if (check_object_provided_version(obj, depobj, vna)) 5454 return (-1); 5455 vernum = VER_NEED_IDX(vna->vna_other); 5456 assert(vernum <= maxvernum); 5457 obj->vertab[vernum].hash = vna->vna_hash; 5458 obj->vertab[vernum].name = obj->strtab + vna->vna_name; 5459 obj->vertab[vernum].file = obj->strtab + vn->vn_file; 5460 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ? 5461 VER_INFO_HIDDEN : 0; 5462 if (vna->vna_next == 0) 5463 break; 5464 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next); 5465 } 5466 if (vn->vn_next == 0) 5467 break; 5468 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 5469 } 5470 return 0; 5471 } 5472 5473 static int 5474 rtld_verify_versions(const Objlist *objlist) 5475 { 5476 Objlist_Entry *entry; 5477 int rc; 5478 5479 rc = 0; 5480 STAILQ_FOREACH(entry, objlist, link) { 5481 /* 5482 * Skip dummy objects or objects that have their version requirements 5483 * already checked. 5484 */ 5485 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL) 5486 continue; 5487 if (rtld_verify_object_versions(entry->obj) == -1) { 5488 rc = -1; 5489 if (ld_tracing == NULL) 5490 break; 5491 } 5492 } 5493 if (rc == 0 || ld_tracing != NULL) 5494 rc = rtld_verify_object_versions(&obj_rtld); 5495 return rc; 5496 } 5497 5498 const Ver_Entry * 5499 fetch_ventry(const Obj_Entry *obj, unsigned long symnum) 5500 { 5501 Elf_Versym vernum; 5502 5503 if (obj->vertab) { 5504 vernum = VER_NDX(obj->versyms[symnum]); 5505 if (vernum >= obj->vernum) { 5506 _rtld_error("%s: symbol %s has wrong verneed value %d", 5507 obj->path, obj->strtab + symnum, vernum); 5508 } else if (obj->vertab[vernum].hash != 0) { 5509 return &obj->vertab[vernum]; 5510 } 5511 } 5512 return NULL; 5513 } 5514 5515 int 5516 _rtld_get_stack_prot(void) 5517 { 5518 5519 return (stack_prot); 5520 } 5521 5522 int 5523 _rtld_is_dlopened(void *arg) 5524 { 5525 Obj_Entry *obj; 5526 RtldLockState lockstate; 5527 int res; 5528 5529 rlock_acquire(rtld_bind_lock, &lockstate); 5530 obj = dlcheck(arg); 5531 if (obj == NULL) 5532 obj = obj_from_addr(arg); 5533 if (obj == NULL) { 5534 _rtld_error("No shared object contains address"); 5535 lock_release(rtld_bind_lock, &lockstate); 5536 return (-1); 5537 } 5538 res = obj->dlopened ? 1 : 0; 5539 lock_release(rtld_bind_lock, &lockstate); 5540 return (res); 5541 } 5542 5543 static int 5544 obj_remap_relro(Obj_Entry *obj, int prot) 5545 { 5546 5547 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size, 5548 prot) == -1) { 5549 _rtld_error("%s: Cannot set relro protection to %#x: %s", 5550 obj->path, prot, rtld_strerror(errno)); 5551 return (-1); 5552 } 5553 return (0); 5554 } 5555 5556 static int 5557 obj_disable_relro(Obj_Entry *obj) 5558 { 5559 5560 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE)); 5561 } 5562 5563 static int 5564 obj_enforce_relro(Obj_Entry *obj) 5565 { 5566 5567 return (obj_remap_relro(obj, PROT_READ)); 5568 } 5569 5570 static void 5571 map_stacks_exec(RtldLockState *lockstate) 5572 { 5573 void (*thr_map_stacks_exec)(void); 5574 5575 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0) 5576 return; 5577 thr_map_stacks_exec = (void (*)(void))(uintptr_t) 5578 get_program_var_addr("__pthread_map_stacks_exec", lockstate); 5579 if (thr_map_stacks_exec != NULL) { 5580 stack_prot |= PROT_EXEC; 5581 thr_map_stacks_exec(); 5582 } 5583 } 5584 5585 static void 5586 distribute_static_tls(Objlist *list, RtldLockState *lockstate) 5587 { 5588 Objlist_Entry *elm; 5589 Obj_Entry *obj; 5590 void (*distrib)(size_t, void *, size_t, size_t); 5591 5592 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t) 5593 get_program_var_addr("__pthread_distribute_static_tls", lockstate); 5594 if (distrib == NULL) 5595 return; 5596 STAILQ_FOREACH(elm, list, link) { 5597 obj = elm->obj; 5598 if (obj->marker || !obj->tls_done || obj->static_tls_copied) 5599 continue; 5600 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize, 5601 obj->tlssize); 5602 obj->static_tls_copied = true; 5603 } 5604 } 5605 5606 void 5607 symlook_init(SymLook *dst, const char *name) 5608 { 5609 5610 bzero(dst, sizeof(*dst)); 5611 dst->name = name; 5612 dst->hash = elf_hash(name); 5613 dst->hash_gnu = gnu_hash(name); 5614 } 5615 5616 static void 5617 symlook_init_from_req(SymLook *dst, const SymLook *src) 5618 { 5619 5620 dst->name = src->name; 5621 dst->hash = src->hash; 5622 dst->hash_gnu = src->hash_gnu; 5623 dst->ventry = src->ventry; 5624 dst->flags = src->flags; 5625 dst->defobj_out = NULL; 5626 dst->sym_out = NULL; 5627 dst->lockstate = src->lockstate; 5628 } 5629 5630 static int 5631 open_binary_fd(const char *argv0, bool search_in_path, 5632 const char **binpath_res) 5633 { 5634 char *binpath, *pathenv, *pe, *res1; 5635 const char *res; 5636 int fd; 5637 5638 binpath = NULL; 5639 res = NULL; 5640 if (search_in_path && strchr(argv0, '/') == NULL) { 5641 binpath = xmalloc(PATH_MAX); 5642 pathenv = getenv("PATH"); 5643 if (pathenv == NULL) { 5644 _rtld_error("-p and no PATH environment variable"); 5645 rtld_die(); 5646 } 5647 pathenv = strdup(pathenv); 5648 if (pathenv == NULL) { 5649 _rtld_error("Cannot allocate memory"); 5650 rtld_die(); 5651 } 5652 fd = -1; 5653 errno = ENOENT; 5654 while ((pe = strsep(&pathenv, ":")) != NULL) { 5655 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX) 5656 continue; 5657 if (binpath[0] != '\0' && 5658 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX) 5659 continue; 5660 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX) 5661 continue; 5662 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY); 5663 if (fd != -1 || errno != ENOENT) { 5664 res = binpath; 5665 break; 5666 } 5667 } 5668 free(pathenv); 5669 } else { 5670 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY); 5671 res = argv0; 5672 } 5673 5674 if (fd == -1) { 5675 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno)); 5676 rtld_die(); 5677 } 5678 if (res != NULL && res[0] != '/') { 5679 res1 = xmalloc(PATH_MAX); 5680 if (realpath(res, res1) != NULL) { 5681 if (res != argv0) 5682 free(__DECONST(char *, res)); 5683 res = res1; 5684 } else { 5685 free(res1); 5686 } 5687 } 5688 *binpath_res = res; 5689 return (fd); 5690 } 5691 5692 /* 5693 * Parse a set of command-line arguments. 5694 */ 5695 static int 5696 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp, 5697 const char **argv0) 5698 { 5699 const char *arg; 5700 char machine[64]; 5701 size_t sz; 5702 int arglen, fd, i, j, mib[2]; 5703 char opt; 5704 bool seen_b, seen_f; 5705 5706 dbg("Parsing command-line arguments"); 5707 *use_pathp = false; 5708 *fdp = -1; 5709 seen_b = seen_f = false; 5710 5711 for (i = 1; i < argc; i++ ) { 5712 arg = argv[i]; 5713 dbg("argv[%d]: '%s'", i, arg); 5714 5715 /* 5716 * rtld arguments end with an explicit "--" or with the first 5717 * non-prefixed argument. 5718 */ 5719 if (strcmp(arg, "--") == 0) { 5720 i++; 5721 break; 5722 } 5723 if (arg[0] != '-') 5724 break; 5725 5726 /* 5727 * All other arguments are single-character options that can 5728 * be combined, so we need to search through `arg` for them. 5729 */ 5730 arglen = strlen(arg); 5731 for (j = 1; j < arglen; j++) { 5732 opt = arg[j]; 5733 if (opt == 'h') { 5734 print_usage(argv[0]); 5735 _exit(0); 5736 } else if (opt == 'b') { 5737 if (seen_f) { 5738 _rtld_error("Both -b and -f specified"); 5739 rtld_die(); 5740 } 5741 i++; 5742 *argv0 = argv[i]; 5743 seen_b = true; 5744 break; 5745 } else if (opt == 'f') { 5746 if (seen_b) { 5747 _rtld_error("Both -b and -f specified"); 5748 rtld_die(); 5749 } 5750 5751 /* 5752 * -f XX can be used to specify a 5753 * descriptor for the binary named at 5754 * the command line (i.e., the later 5755 * argument will specify the process 5756 * name but the descriptor is what 5757 * will actually be executed). 5758 * 5759 * -f must be the last option in, e.g., -abcf. 5760 */ 5761 if (j != arglen - 1) { 5762 _rtld_error("Invalid options: %s", arg); 5763 rtld_die(); 5764 } 5765 i++; 5766 fd = parse_integer(argv[i]); 5767 if (fd == -1) { 5768 _rtld_error( 5769 "Invalid file descriptor: '%s'", 5770 argv[i]); 5771 rtld_die(); 5772 } 5773 *fdp = fd; 5774 seen_f = true; 5775 break; 5776 } else if (opt == 'p') { 5777 *use_pathp = true; 5778 } else if (opt == 'u') { 5779 trust = false; 5780 } else if (opt == 'v') { 5781 machine[0] = '\0'; 5782 mib[0] = CTL_HW; 5783 mib[1] = HW_MACHINE; 5784 sz = sizeof(machine); 5785 sysctl(mib, nitems(mib), machine, &sz, NULL, 0); 5786 rtld_printf( 5787 "FreeBSD ld-elf.so.1 %s\n" 5788 "FreeBSD_version %d\n" 5789 "Default lib path %s\n" 5790 "Env prefix %s\n" 5791 "Hint file %s\n" 5792 "libmap file %s\n", 5793 machine, 5794 __FreeBSD_version, ld_standard_library_path, 5795 ld_env_prefix, ld_elf_hints_default, 5796 ld_path_libmap_conf); 5797 _exit(0); 5798 } else { 5799 _rtld_error("Invalid argument: '%s'", arg); 5800 print_usage(argv[0]); 5801 rtld_die(); 5802 } 5803 } 5804 } 5805 5806 if (!seen_b) 5807 *argv0 = argv[i]; 5808 return (i); 5809 } 5810 5811 /* 5812 * Parse a file descriptor number without pulling in more of libc (e.g. atoi). 5813 */ 5814 static int 5815 parse_integer(const char *str) 5816 { 5817 static const int RADIX = 10; /* XXXJA: possibly support hex? */ 5818 const char *orig; 5819 int n; 5820 char c; 5821 5822 orig = str; 5823 n = 0; 5824 for (c = *str; c != '\0'; c = *++str) { 5825 if (c < '0' || c > '9') 5826 return (-1); 5827 5828 n *= RADIX; 5829 n += c - '0'; 5830 } 5831 5832 /* Make sure we actually parsed something. */ 5833 if (str == orig) 5834 return (-1); 5835 return (n); 5836 } 5837 5838 static void 5839 print_usage(const char *argv0) 5840 { 5841 5842 rtld_printf( 5843 "Usage: %s [-h] [-b <exe>] [-f <FD>] [-p] [--] <binary> [<args>]\n" 5844 "\n" 5845 "Options:\n" 5846 " -h Display this help message\n" 5847 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n" 5848 " -f <FD> Execute <FD> instead of searching for <binary>\n" 5849 " -p Search in PATH for named binary\n" 5850 " -u Ignore LD_ environment variables\n" 5851 " -v Display identification information\n" 5852 " -- End of RTLD options\n" 5853 " <binary> Name of process to execute\n" 5854 " <args> Arguments to the executed process\n", argv0); 5855 } 5856 5857 /* 5858 * Overrides for libc_pic-provided functions. 5859 */ 5860 5861 int 5862 __getosreldate(void) 5863 { 5864 size_t len; 5865 int oid[2]; 5866 int error, osrel; 5867 5868 if (osreldate != 0) 5869 return (osreldate); 5870 5871 oid[0] = CTL_KERN; 5872 oid[1] = KERN_OSRELDATE; 5873 osrel = 0; 5874 len = sizeof(osrel); 5875 error = sysctl(oid, 2, &osrel, &len, NULL, 0); 5876 if (error == 0 && osrel > 0 && len == sizeof(osrel)) 5877 osreldate = osrel; 5878 return (osreldate); 5879 } 5880 const char * 5881 rtld_strerror(int errnum) 5882 { 5883 5884 if (errnum < 0 || errnum >= sys_nerr) 5885 return ("Unknown error"); 5886 return (sys_errlist[errnum]); 5887 } 5888 5889 /* malloc */ 5890 void * 5891 malloc(size_t nbytes) 5892 { 5893 5894 return (__crt_malloc(nbytes)); 5895 } 5896 5897 void * 5898 calloc(size_t num, size_t size) 5899 { 5900 5901 return (__crt_calloc(num, size)); 5902 } 5903 5904 void 5905 free(void *cp) 5906 { 5907 5908 __crt_free(cp); 5909 } 5910 5911 void * 5912 realloc(void *cp, size_t nbytes) 5913 { 5914 5915 return (__crt_realloc(cp, nbytes)); 5916 } 5917 5918 extern int _rtld_version__FreeBSD_version __exported; 5919 int _rtld_version__FreeBSD_version = __FreeBSD_version; 5920 5921 extern char _rtld_version_laddr_offset __exported; 5922 char _rtld_version_laddr_offset; 5923 5924 extern char _rtld_version_dlpi_tls_data __exported; 5925 char _rtld_version_dlpi_tls_data; 5926