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