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