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