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