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