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 static void 2535 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate) 2536 { 2537 Needed_Entry *needed, *needed1; 2538 2539 for (needed = n; needed != NULL; needed = needed->next) { 2540 if (needed->obj != NULL) { 2541 dlclose_locked(needed->obj, lockstate); 2542 needed->obj = NULL; 2543 } 2544 } 2545 for (needed = n; needed != NULL; needed = needed1) { 2546 needed1 = needed->next; 2547 free(needed); 2548 } 2549 } 2550 2551 static void 2552 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate) 2553 { 2554 2555 free_needed_filtees(obj->needed_filtees, lockstate); 2556 obj->needed_filtees = NULL; 2557 free_needed_filtees(obj->needed_aux_filtees, lockstate); 2558 obj->needed_aux_filtees = NULL; 2559 obj->filtees_loaded = false; 2560 } 2561 2562 static void 2563 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags, 2564 RtldLockState *lockstate) 2565 { 2566 2567 for (; needed != NULL; needed = needed->next) { 2568 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj, 2569 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) | 2570 RTLD_LOCAL, lockstate); 2571 } 2572 } 2573 2574 static void 2575 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate) 2576 { 2577 2578 lock_restart_for_upgrade(lockstate); 2579 if (!obj->filtees_loaded) { 2580 load_filtee1(obj, obj->needed_filtees, flags, lockstate); 2581 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate); 2582 obj->filtees_loaded = true; 2583 } 2584 } 2585 2586 static int 2587 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags) 2588 { 2589 Obj_Entry *obj1; 2590 2591 for (; needed != NULL; needed = needed->next) { 2592 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj, 2593 flags & ~RTLD_LO_NOLOAD); 2594 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0) 2595 return (-1); 2596 } 2597 return (0); 2598 } 2599 2600 /* 2601 * Given a shared object, traverse its list of needed objects, and load 2602 * each of them. Returns 0 on success. Generates an error message and 2603 * returns -1 on failure. 2604 */ 2605 static int 2606 load_needed_objects(Obj_Entry *first, int flags) 2607 { 2608 Obj_Entry *obj; 2609 2610 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 2611 if (obj->marker) 2612 continue; 2613 if (process_needed(obj, obj->needed, flags) == -1) 2614 return (-1); 2615 } 2616 return (0); 2617 } 2618 2619 static int 2620 load_preload_objects(const char *penv, bool isfd) 2621 { 2622 Obj_Entry *obj; 2623 const char *name; 2624 size_t len; 2625 char savech, *p, *psave; 2626 int fd; 2627 static const char delim[] = " \t:;"; 2628 2629 if (penv == NULL) 2630 return (0); 2631 2632 p = psave = xstrdup(penv); 2633 p += strspn(p, delim); 2634 while (*p != '\0') { 2635 len = strcspn(p, delim); 2636 2637 savech = p[len]; 2638 p[len] = '\0'; 2639 if (isfd) { 2640 name = NULL; 2641 fd = parse_integer(p); 2642 if (fd == -1) { 2643 free(psave); 2644 return (-1); 2645 } 2646 } else { 2647 name = p; 2648 fd = -1; 2649 } 2650 2651 obj = load_object(name, fd, NULL, 0); 2652 if (obj == NULL) { 2653 free(psave); 2654 return (-1); /* XXX - cleanup */ 2655 } 2656 obj->z_interpose = true; 2657 p[len] = savech; 2658 p += len; 2659 p += strspn(p, delim); 2660 } 2661 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL); 2662 2663 free(psave); 2664 return (0); 2665 } 2666 2667 static const char * 2668 printable_path(const char *path) 2669 { 2670 2671 return (path == NULL ? "<unknown>" : path); 2672 } 2673 2674 /* 2675 * Load a shared object into memory, if it is not already loaded. The 2676 * object may be specified by name or by user-supplied file descriptor 2677 * fd_u. In the later case, the fd_u descriptor is not closed, but its 2678 * duplicate is. 2679 * 2680 * Returns a pointer to the Obj_Entry for the object. Returns NULL 2681 * on failure. 2682 */ 2683 static Obj_Entry * 2684 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags) 2685 { 2686 Obj_Entry *obj; 2687 int fd; 2688 struct stat sb; 2689 char *path; 2690 2691 fd = -1; 2692 if (name != NULL) { 2693 TAILQ_FOREACH(obj, &obj_list, next) { 2694 if (obj->marker || obj->doomed) 2695 continue; 2696 if (object_match_name(obj, name)) 2697 return (obj); 2698 } 2699 2700 path = find_library(name, refobj, &fd); 2701 if (path == NULL) 2702 return (NULL); 2703 } else 2704 path = NULL; 2705 2706 if (fd >= 0) { 2707 /* 2708 * search_library_pathfds() opens a fresh file descriptor for the 2709 * library, so there is no need to dup(). 2710 */ 2711 } else if (fd_u == -1) { 2712 /* 2713 * If we didn't find a match by pathname, or the name is not 2714 * supplied, open the file and check again by device and inode. 2715 * This avoids false mismatches caused by multiple links or ".." 2716 * in pathnames. 2717 * 2718 * To avoid a race, we open the file and use fstat() rather than 2719 * using stat(). 2720 */ 2721 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) { 2722 _rtld_error("Cannot open \"%s\"", path); 2723 free(path); 2724 return (NULL); 2725 } 2726 } else { 2727 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0); 2728 if (fd == -1) { 2729 _rtld_error("Cannot dup fd"); 2730 free(path); 2731 return (NULL); 2732 } 2733 } 2734 if (fstat(fd, &sb) == -1) { 2735 _rtld_error("Cannot fstat \"%s\"", printable_path(path)); 2736 close(fd); 2737 free(path); 2738 return (NULL); 2739 } 2740 TAILQ_FOREACH(obj, &obj_list, next) { 2741 if (obj->marker || obj->doomed) 2742 continue; 2743 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) 2744 break; 2745 } 2746 if (obj != NULL && name != NULL) { 2747 object_add_name(obj, name); 2748 free(path); 2749 close(fd); 2750 return (obj); 2751 } 2752 if (flags & RTLD_LO_NOLOAD) { 2753 free(path); 2754 close(fd); 2755 return (NULL); 2756 } 2757 2758 /* First use of this object, so we must map it in */ 2759 obj = do_load_object(fd, name, path, &sb, flags); 2760 if (obj == NULL) 2761 free(path); 2762 close(fd); 2763 2764 return (obj); 2765 } 2766 2767 static Obj_Entry * 2768 do_load_object(int fd, const char *name, char *path, struct stat *sbp, 2769 int flags) 2770 { 2771 Obj_Entry *obj; 2772 struct statfs fs; 2773 2774 /* 2775 * First, make sure that environment variables haven't been 2776 * used to circumvent the noexec flag on a filesystem. 2777 * We ignore fstatfs(2) failures, since fd might reference 2778 * not a file, e.g. shmfd. 2779 */ 2780 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 && 2781 (fs.f_flags & MNT_NOEXEC) != 0) { 2782 _rtld_error("Cannot execute objects on %s", fs.f_mntonname); 2783 return (NULL); 2784 } 2785 2786 dbg("loading \"%s\"", printable_path(path)); 2787 obj = map_object(fd, printable_path(path), sbp); 2788 if (obj == NULL) 2789 return (NULL); 2790 2791 /* 2792 * If DT_SONAME is present in the object, digest_dynamic2 already 2793 * added it to the object names. 2794 */ 2795 if (name != NULL) 2796 object_add_name(obj, name); 2797 obj->path = path; 2798 if (!digest_dynamic(obj, 0)) 2799 goto errp; 2800 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path, 2801 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount); 2802 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) { 2803 dbg("refusing to load PIE executable \"%s\"", obj->path); 2804 _rtld_error("Cannot load PIE binary %s as DSO", obj->path); 2805 goto errp; 2806 } 2807 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) == 2808 RTLD_LO_DLOPEN) { 2809 dbg("refusing to load non-loadable \"%s\"", obj->path); 2810 _rtld_error("Cannot dlopen non-loadable %s", obj->path); 2811 goto errp; 2812 } 2813 2814 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0; 2815 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2816 obj_count++; 2817 obj_loads++; 2818 linkmap_add(obj); /* for GDB & dlinfo() */ 2819 max_stack_flags |= obj->stack_flags; 2820 2821 dbg(" %p .. %p: %s", obj->mapbase, 2822 obj->mapbase + obj->mapsize - 1, obj->path); 2823 if (obj->textrel) 2824 dbg(" WARNING: %s has impure text", obj->path); 2825 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 2826 obj->path); 2827 2828 return (obj); 2829 2830 errp: 2831 munmap(obj->mapbase, obj->mapsize); 2832 obj_free(obj); 2833 return (NULL); 2834 } 2835 2836 static int 2837 load_kpreload(const void *addr) 2838 { 2839 Obj_Entry *obj; 2840 const Elf_Ehdr *ehdr; 2841 const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn; 2842 static const char kname[] = "[vdso]"; 2843 2844 ehdr = addr; 2845 if (!check_elf_headers(ehdr, "kpreload")) 2846 return (-1); 2847 obj = obj_new(); 2848 phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff); 2849 obj->phdr = phdr; 2850 obj->phsize = ehdr->e_phnum * sizeof(*phdr); 2851 phlimit = phdr + ehdr->e_phnum; 2852 seg0 = segn = NULL; 2853 2854 for (; phdr < phlimit; phdr++) { 2855 switch (phdr->p_type) { 2856 case PT_DYNAMIC: 2857 phdyn = phdr; 2858 break; 2859 case PT_GNU_STACK: 2860 /* Absense of PT_GNU_STACK implies stack_flags == 0. */ 2861 obj->stack_flags = phdr->p_flags; 2862 break; 2863 case PT_LOAD: 2864 if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr) 2865 seg0 = phdr; 2866 if (segn == NULL || segn->p_vaddr + segn->p_memsz < 2867 phdr->p_vaddr + phdr->p_memsz) 2868 segn = phdr; 2869 break; 2870 } 2871 } 2872 2873 obj->mapbase = __DECONST(caddr_t, addr); 2874 obj->mapsize = segn->p_vaddr + segn->p_memsz - (Elf_Addr)addr; 2875 obj->vaddrbase = 0; 2876 obj->relocbase = obj->mapbase; 2877 2878 object_add_name(obj, kname); 2879 obj->path = xstrdup(kname); 2880 obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr); 2881 2882 if (!digest_dynamic(obj, 0)) { 2883 obj_free(obj); 2884 return (-1); 2885 } 2886 2887 /* 2888 * We assume that kernel-preloaded object does not need 2889 * relocation. It is currently written into read-only page, 2890 * handling relocations would mean we need to allocate at 2891 * least one additional page per AS. 2892 */ 2893 dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p", 2894 obj->path, obj->mapbase, obj->phdr, seg0, 2895 obj->relocbase + seg0->p_vaddr, obj->dynamic); 2896 2897 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2898 obj_count++; 2899 obj_loads++; 2900 linkmap_add(obj); /* for GDB & dlinfo() */ 2901 max_stack_flags |= obj->stack_flags; 2902 2903 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, 0, 0, obj->path); 2904 return (0); 2905 } 2906 2907 Obj_Entry * 2908 obj_from_addr(const void *addr) 2909 { 2910 Obj_Entry *obj; 2911 2912 TAILQ_FOREACH(obj, &obj_list, next) { 2913 if (obj->marker) 2914 continue; 2915 if (addr < (void *) obj->mapbase) 2916 continue; 2917 if (addr < (void *)(obj->mapbase + obj->mapsize)) 2918 return obj; 2919 } 2920 return (NULL); 2921 } 2922 2923 static void 2924 preinit_main(void) 2925 { 2926 Elf_Addr *preinit_addr; 2927 int index; 2928 2929 preinit_addr = (Elf_Addr *)obj_main->preinit_array; 2930 if (preinit_addr == NULL) 2931 return; 2932 2933 for (index = 0; index < obj_main->preinit_array_num; index++) { 2934 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) { 2935 dbg("calling preinit function for %s at %p", obj_main->path, 2936 (void *)preinit_addr[index]); 2937 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index], 2938 0, 0, obj_main->path); 2939 call_init_pointer(obj_main, preinit_addr[index]); 2940 } 2941 } 2942 } 2943 2944 /* 2945 * Call the finalization functions for each of the objects in "list" 2946 * belonging to the DAG of "root" and referenced once. If NULL "root" 2947 * is specified, every finalization function will be called regardless 2948 * of the reference count and the list elements won't be freed. All of 2949 * the objects are expected to have non-NULL fini functions. 2950 */ 2951 static void 2952 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate) 2953 { 2954 Objlist_Entry *elm; 2955 struct dlerror_save *saved_msg; 2956 Elf_Addr *fini_addr; 2957 int index; 2958 2959 assert(root == NULL || root->refcount == 1); 2960 2961 if (root != NULL) 2962 root->doomed = true; 2963 2964 /* 2965 * Preserve the current error message since a fini function might 2966 * call into the dynamic linker and overwrite it. 2967 */ 2968 saved_msg = errmsg_save(); 2969 do { 2970 STAILQ_FOREACH(elm, list, link) { 2971 if (root != NULL && (elm->obj->refcount != 1 || 2972 objlist_find(&root->dagmembers, elm->obj) == NULL)) 2973 continue; 2974 /* Remove object from fini list to prevent recursive invocation. */ 2975 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 2976 /* Ensure that new references cannot be acquired. */ 2977 elm->obj->doomed = true; 2978 2979 hold_object(elm->obj); 2980 lock_release(rtld_bind_lock, lockstate); 2981 /* 2982 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined. 2983 * When this happens, DT_FINI_ARRAY is processed first. 2984 */ 2985 fini_addr = (Elf_Addr *)elm->obj->fini_array; 2986 if (fini_addr != NULL && elm->obj->fini_array_num > 0) { 2987 for (index = elm->obj->fini_array_num - 1; index >= 0; 2988 index--) { 2989 if (fini_addr[index] != 0 && fini_addr[index] != 1) { 2990 dbg("calling fini function for %s at %p", 2991 elm->obj->path, (void *)fini_addr[index]); 2992 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, 2993 (void *)fini_addr[index], 0, 0, elm->obj->path); 2994 call_initfini_pointer(elm->obj, fini_addr[index]); 2995 } 2996 } 2997 } 2998 if (elm->obj->fini != (Elf_Addr)NULL) { 2999 dbg("calling fini function for %s at %p", elm->obj->path, 3000 (void *)elm->obj->fini); 3001 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 3002 0, 0, elm->obj->path); 3003 call_initfini_pointer(elm->obj, elm->obj->fini); 3004 } 3005 wlock_acquire(rtld_bind_lock, lockstate); 3006 unhold_object(elm->obj); 3007 /* No need to free anything if process is going down. */ 3008 if (root != NULL) 3009 free(elm); 3010 /* 3011 * We must restart the list traversal after every fini call 3012 * because a dlclose() call from the fini function or from 3013 * another thread might have modified the reference counts. 3014 */ 3015 break; 3016 } 3017 } while (elm != NULL); 3018 errmsg_restore(saved_msg); 3019 } 3020 3021 /* 3022 * Call the initialization functions for each of the objects in 3023 * "list". All of the objects are expected to have non-NULL init 3024 * functions. 3025 */ 3026 static void 3027 objlist_call_init(Objlist *list, RtldLockState *lockstate) 3028 { 3029 Objlist_Entry *elm; 3030 Obj_Entry *obj; 3031 struct dlerror_save *saved_msg; 3032 Elf_Addr *init_addr; 3033 void (*reg)(void (*)(void)); 3034 int index; 3035 3036 /* 3037 * Clean init_scanned flag so that objects can be rechecked and 3038 * possibly initialized earlier if any of vectors called below 3039 * cause the change by using dlopen. 3040 */ 3041 TAILQ_FOREACH(obj, &obj_list, next) { 3042 if (obj->marker) 3043 continue; 3044 obj->init_scanned = false; 3045 } 3046 3047 /* 3048 * Preserve the current error message since an init function might 3049 * call into the dynamic linker and overwrite it. 3050 */ 3051 saved_msg = errmsg_save(); 3052 STAILQ_FOREACH(elm, list, link) { 3053 if (elm->obj->init_done) /* Initialized early. */ 3054 continue; 3055 /* 3056 * Race: other thread might try to use this object before current 3057 * one completes the initialization. Not much can be done here 3058 * without better locking. 3059 */ 3060 elm->obj->init_done = true; 3061 hold_object(elm->obj); 3062 reg = NULL; 3063 if (elm->obj == obj_main && obj_main->crt_no_init) { 3064 reg = (void (*)(void (*)(void)))get_program_var_addr( 3065 "__libc_atexit", lockstate); 3066 } 3067 lock_release(rtld_bind_lock, lockstate); 3068 if (reg != NULL) { 3069 reg(rtld_exit); 3070 rtld_exit_ptr = rtld_nop_exit; 3071 } 3072 3073 /* 3074 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. 3075 * When this happens, DT_INIT is processed first. 3076 */ 3077 if (elm->obj->init != (Elf_Addr)NULL) { 3078 dbg("calling init function for %s at %p", elm->obj->path, 3079 (void *)elm->obj->init); 3080 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 3081 0, 0, elm->obj->path); 3082 call_init_pointer(elm->obj, elm->obj->init); 3083 } 3084 init_addr = (Elf_Addr *)elm->obj->init_array; 3085 if (init_addr != NULL) { 3086 for (index = 0; index < elm->obj->init_array_num; index++) { 3087 if (init_addr[index] != 0 && init_addr[index] != 1) { 3088 dbg("calling init function for %s at %p", elm->obj->path, 3089 (void *)init_addr[index]); 3090 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, 3091 (void *)init_addr[index], 0, 0, elm->obj->path); 3092 call_init_pointer(elm->obj, init_addr[index]); 3093 } 3094 } 3095 } 3096 wlock_acquire(rtld_bind_lock, lockstate); 3097 unhold_object(elm->obj); 3098 } 3099 errmsg_restore(saved_msg); 3100 } 3101 3102 static void 3103 objlist_clear(Objlist *list) 3104 { 3105 Objlist_Entry *elm; 3106 3107 while (!STAILQ_EMPTY(list)) { 3108 elm = STAILQ_FIRST(list); 3109 STAILQ_REMOVE_HEAD(list, link); 3110 free(elm); 3111 } 3112 } 3113 3114 static Objlist_Entry * 3115 objlist_find(Objlist *list, const Obj_Entry *obj) 3116 { 3117 Objlist_Entry *elm; 3118 3119 STAILQ_FOREACH(elm, list, link) 3120 if (elm->obj == obj) 3121 return elm; 3122 return (NULL); 3123 } 3124 3125 static void 3126 objlist_init(Objlist *list) 3127 { 3128 STAILQ_INIT(list); 3129 } 3130 3131 static void 3132 objlist_push_head(Objlist *list, Obj_Entry *obj) 3133 { 3134 Objlist_Entry *elm; 3135 3136 elm = NEW(Objlist_Entry); 3137 elm->obj = obj; 3138 STAILQ_INSERT_HEAD(list, elm, link); 3139 } 3140 3141 static void 3142 objlist_push_tail(Objlist *list, Obj_Entry *obj) 3143 { 3144 Objlist_Entry *elm; 3145 3146 elm = NEW(Objlist_Entry); 3147 elm->obj = obj; 3148 STAILQ_INSERT_TAIL(list, elm, link); 3149 } 3150 3151 static void 3152 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj) 3153 { 3154 Objlist_Entry *elm, *listelm; 3155 3156 STAILQ_FOREACH(listelm, list, link) { 3157 if (listelm->obj == listobj) 3158 break; 3159 } 3160 elm = NEW(Objlist_Entry); 3161 elm->obj = obj; 3162 if (listelm != NULL) 3163 STAILQ_INSERT_AFTER(list, listelm, elm, link); 3164 else 3165 STAILQ_INSERT_TAIL(list, elm, link); 3166 } 3167 3168 static void 3169 objlist_remove(Objlist *list, Obj_Entry *obj) 3170 { 3171 Objlist_Entry *elm; 3172 3173 if ((elm = objlist_find(list, obj)) != NULL) { 3174 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 3175 free(elm); 3176 } 3177 } 3178 3179 /* 3180 * Relocate dag rooted in the specified object. 3181 * Returns 0 on success, or -1 on failure. 3182 */ 3183 3184 static int 3185 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj, 3186 int flags, RtldLockState *lockstate) 3187 { 3188 Objlist_Entry *elm; 3189 int error; 3190 3191 error = 0; 3192 STAILQ_FOREACH(elm, &root->dagmembers, link) { 3193 error = relocate_object(elm->obj, bind_now, rtldobj, flags, 3194 lockstate); 3195 if (error == -1) 3196 break; 3197 } 3198 return (error); 3199 } 3200 3201 /* 3202 * Prepare for, or clean after, relocating an object marked with 3203 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only 3204 * segments are remapped read-write. After relocations are done, the 3205 * segment's permissions are returned back to the modes specified in 3206 * the phdrs. If any relocation happened, or always for wired 3207 * program, COW is triggered. 3208 */ 3209 static int 3210 reloc_textrel_prot(Obj_Entry *obj, bool before) 3211 { 3212 const Elf_Phdr *ph; 3213 void *base; 3214 size_t l, sz; 3215 int prot; 3216 3217 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0; 3218 l--, ph++) { 3219 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0) 3220 continue; 3221 base = obj->relocbase + rtld_trunc_page(ph->p_vaddr); 3222 sz = rtld_round_page(ph->p_vaddr + ph->p_filesz) - 3223 rtld_trunc_page(ph->p_vaddr); 3224 prot = before ? (PROT_READ | PROT_WRITE) : 3225 convert_prot(ph->p_flags); 3226 if (mprotect(base, sz, prot) == -1) { 3227 _rtld_error("%s: Cannot write-%sable text segment: %s", 3228 obj->path, before ? "en" : "dis", 3229 rtld_strerror(errno)); 3230 return (-1); 3231 } 3232 } 3233 return (0); 3234 } 3235 3236 /* Process RELR relative relocations. */ 3237 static void 3238 reloc_relr(Obj_Entry *obj) 3239 { 3240 const Elf_Relr *relr, *relrlim; 3241 Elf_Addr *where; 3242 3243 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize); 3244 for (relr = obj->relr; relr < relrlim; relr++) { 3245 Elf_Relr entry = *relr; 3246 3247 if ((entry & 1) == 0) { 3248 where = (Elf_Addr *)(obj->relocbase + entry); 3249 *where++ += (Elf_Addr)obj->relocbase; 3250 } else { 3251 for (long i = 0; (entry >>= 1) != 0; i++) 3252 if ((entry & 1) != 0) 3253 where[i] += (Elf_Addr)obj->relocbase; 3254 where += CHAR_BIT * sizeof(Elf_Relr) - 1; 3255 } 3256 } 3257 } 3258 3259 /* 3260 * Relocate single object. 3261 * Returns 0 on success, or -1 on failure. 3262 */ 3263 static int 3264 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, 3265 int flags, RtldLockState *lockstate) 3266 { 3267 3268 if (obj->relocated) 3269 return (0); 3270 obj->relocated = true; 3271 if (obj != rtldobj) 3272 dbg("relocating \"%s\"", obj->path); 3273 3274 if (obj->symtab == NULL || obj->strtab == NULL || 3275 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) 3276 dbg("object %s has no run-time symbol table", obj->path); 3277 3278 /* There are relocations to the write-protected text segment. */ 3279 if (obj->textrel && reloc_textrel_prot(obj, true) != 0) 3280 return (-1); 3281 3282 /* Process the non-PLT non-IFUNC relocations. */ 3283 if (reloc_non_plt(obj, rtldobj, flags, lockstate)) 3284 return (-1); 3285 reloc_relr(obj); 3286 3287 /* Re-protected the text segment. */ 3288 if (obj->textrel && reloc_textrel_prot(obj, false) != 0) 3289 return (-1); 3290 3291 /* Set the special PLT or GOT entries. */ 3292 init_pltgot(obj); 3293 3294 /* Process the PLT relocations. */ 3295 if (reloc_plt(obj, flags, lockstate) == -1) 3296 return (-1); 3297 /* Relocate the jump slots if we are doing immediate binding. */ 3298 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags, 3299 lockstate) == -1) 3300 return (-1); 3301 3302 if (!obj->mainprog && obj_enforce_relro(obj) == -1) 3303 return (-1); 3304 3305 /* 3306 * Set up the magic number and version in the Obj_Entry. These 3307 * were checked in the crt1.o from the original ElfKit, so we 3308 * set them for backward compatibility. 3309 */ 3310 obj->magic = RTLD_MAGIC; 3311 obj->version = RTLD_VERSION; 3312 3313 return (0); 3314 } 3315 3316 /* 3317 * Relocate newly-loaded shared objects. The argument is a pointer to 3318 * the Obj_Entry for the first such object. All objects from the first 3319 * to the end of the list of objects are relocated. Returns 0 on success, 3320 * or -1 on failure. 3321 */ 3322 static int 3323 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj, 3324 int flags, RtldLockState *lockstate) 3325 { 3326 Obj_Entry *obj; 3327 int error; 3328 3329 for (error = 0, obj = first; obj != NULL; 3330 obj = TAILQ_NEXT(obj, next)) { 3331 if (obj->marker) 3332 continue; 3333 error = relocate_object(obj, bind_now, rtldobj, flags, 3334 lockstate); 3335 if (error == -1) 3336 break; 3337 } 3338 return (error); 3339 } 3340 3341 /* 3342 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots 3343 * referencing STT_GNU_IFUNC symbols is postponed till the other 3344 * relocations are done. The indirect functions specified as 3345 * ifunc are allowed to call other symbols, so we need to have 3346 * objects relocated before asking for resolution from indirects. 3347 * 3348 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion, 3349 * instead of the usual lazy handling of PLT slots. It is 3350 * consistent with how GNU does it. 3351 */ 3352 static int 3353 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags, 3354 RtldLockState *lockstate) 3355 { 3356 3357 if (obj->ifuncs_resolved) 3358 return (0); 3359 obj->ifuncs_resolved = true; 3360 if (!obj->irelative && !obj->irelative_nonplt && 3361 !((obj->bind_now || bind_now) && obj->gnu_ifunc) && 3362 !obj->non_plt_gnu_ifunc) 3363 return (0); 3364 if (obj_disable_relro(obj) == -1 || 3365 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) || 3366 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj, 3367 lockstate) == -1) || 3368 ((obj->bind_now || bind_now) && obj->gnu_ifunc && 3369 reloc_gnu_ifunc(obj, flags, lockstate) == -1) || 3370 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld, 3371 flags | SYMLOOK_IFUNC, lockstate) == -1) || 3372 obj_enforce_relro(obj) == -1) 3373 return (-1); 3374 return (0); 3375 } 3376 3377 static int 3378 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags, 3379 RtldLockState *lockstate) 3380 { 3381 Objlist_Entry *elm; 3382 Obj_Entry *obj; 3383 3384 STAILQ_FOREACH(elm, list, link) { 3385 obj = elm->obj; 3386 if (obj->marker) 3387 continue; 3388 if (resolve_object_ifunc(obj, bind_now, flags, 3389 lockstate) == -1) 3390 return (-1); 3391 } 3392 return (0); 3393 } 3394 3395 /* 3396 * Cleanup procedure. It will be called (by the atexit mechanism) just 3397 * before the process exits. 3398 */ 3399 static void 3400 rtld_exit(void) 3401 { 3402 RtldLockState lockstate; 3403 3404 wlock_acquire(rtld_bind_lock, &lockstate); 3405 dbg("rtld_exit()"); 3406 objlist_call_fini(&list_fini, NULL, &lockstate); 3407 /* No need to remove the items from the list, since we are exiting. */ 3408 if (!libmap_disable) 3409 lm_fini(); 3410 lock_release(rtld_bind_lock, &lockstate); 3411 } 3412 3413 static void 3414 rtld_nop_exit(void) 3415 { 3416 } 3417 3418 /* 3419 * Iterate over a search path, translate each element, and invoke the 3420 * callback on the result. 3421 */ 3422 static void * 3423 path_enumerate(const char *path, path_enum_proc callback, 3424 const char *refobj_path, void *arg) 3425 { 3426 const char *trans; 3427 if (path == NULL) 3428 return (NULL); 3429 3430 path += strspn(path, ":;"); 3431 while (*path != '\0') { 3432 size_t len; 3433 char *res; 3434 3435 len = strcspn(path, ":;"); 3436 trans = lm_findn(refobj_path, path, len); 3437 if (trans) 3438 res = callback(trans, strlen(trans), arg); 3439 else 3440 res = callback(path, len, arg); 3441 3442 if (res != NULL) 3443 return (res); 3444 3445 path += len; 3446 path += strspn(path, ":;"); 3447 } 3448 3449 return (NULL); 3450 } 3451 3452 struct try_library_args { 3453 const char *name; 3454 size_t namelen; 3455 char *buffer; 3456 size_t buflen; 3457 int fd; 3458 }; 3459 3460 static void * 3461 try_library_path(const char *dir, size_t dirlen, void *param) 3462 { 3463 struct try_library_args *arg; 3464 int fd; 3465 3466 arg = param; 3467 if (*dir == '/' || trust) { 3468 char *pathname; 3469 3470 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 3471 return (NULL); 3472 3473 pathname = arg->buffer; 3474 strncpy(pathname, dir, dirlen); 3475 pathname[dirlen] = '/'; 3476 strcpy(pathname + dirlen + 1, arg->name); 3477 3478 dbg(" Trying \"%s\"", pathname); 3479 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY); 3480 if (fd >= 0) { 3481 dbg(" Opened \"%s\", fd %d", pathname, fd); 3482 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 3483 strcpy(pathname, arg->buffer); 3484 arg->fd = fd; 3485 return (pathname); 3486 } else { 3487 dbg(" Failed to open \"%s\": %s", 3488 pathname, rtld_strerror(errno)); 3489 } 3490 } 3491 return (NULL); 3492 } 3493 3494 static char * 3495 search_library_path(const char *name, const char *path, 3496 const char *refobj_path, int *fdp) 3497 { 3498 char *p; 3499 struct try_library_args arg; 3500 3501 if (path == NULL) 3502 return (NULL); 3503 3504 arg.name = name; 3505 arg.namelen = strlen(name); 3506 arg.buffer = xmalloc(PATH_MAX); 3507 arg.buflen = PATH_MAX; 3508 arg.fd = -1; 3509 3510 p = path_enumerate(path, try_library_path, refobj_path, &arg); 3511 *fdp = arg.fd; 3512 3513 free(arg.buffer); 3514 3515 return (p); 3516 } 3517 3518 3519 /* 3520 * Finds the library with the given name using the directory descriptors 3521 * listed in the LD_LIBRARY_PATH_FDS environment variable. 3522 * 3523 * Returns a freshly-opened close-on-exec file descriptor for the library, 3524 * or -1 if the library cannot be found. 3525 */ 3526 static char * 3527 search_library_pathfds(const char *name, const char *path, int *fdp) 3528 { 3529 char *envcopy, *fdstr, *found, *last_token; 3530 size_t len; 3531 int dirfd, fd; 3532 3533 dbg("%s('%s', '%s', fdp)", __func__, name, path); 3534 3535 /* Don't load from user-specified libdirs into setuid binaries. */ 3536 if (!trust) 3537 return (NULL); 3538 3539 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */ 3540 if (path == NULL) 3541 return (NULL); 3542 3543 /* LD_LIBRARY_PATH_FDS only works with relative paths. */ 3544 if (name[0] == '/') { 3545 dbg("Absolute path (%s) passed to %s", name, __func__); 3546 return (NULL); 3547 } 3548 3549 /* 3550 * Use strtok_r() to walk the FD:FD:FD list. This requires a local 3551 * copy of the path, as strtok_r rewrites separator tokens 3552 * with '\0'. 3553 */ 3554 found = NULL; 3555 envcopy = xstrdup(path); 3556 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL; 3557 fdstr = strtok_r(NULL, ":", &last_token)) { 3558 dirfd = parse_integer(fdstr); 3559 if (dirfd < 0) { 3560 _rtld_error("failed to parse directory FD: '%s'", 3561 fdstr); 3562 break; 3563 } 3564 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY); 3565 if (fd >= 0) { 3566 *fdp = fd; 3567 len = strlen(fdstr) + strlen(name) + 3; 3568 found = xmalloc(len); 3569 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) { 3570 _rtld_error("error generating '%d/%s'", 3571 dirfd, name); 3572 rtld_die(); 3573 } 3574 dbg("open('%s') => %d", found, fd); 3575 break; 3576 } 3577 } 3578 free(envcopy); 3579 3580 return (found); 3581 } 3582 3583 3584 int 3585 dlclose(void *handle) 3586 { 3587 RtldLockState lockstate; 3588 int error; 3589 3590 wlock_acquire(rtld_bind_lock, &lockstate); 3591 error = dlclose_locked(handle, &lockstate); 3592 lock_release(rtld_bind_lock, &lockstate); 3593 return (error); 3594 } 3595 3596 static int 3597 dlclose_locked(void *handle, RtldLockState *lockstate) 3598 { 3599 Obj_Entry *root; 3600 3601 root = dlcheck(handle); 3602 if (root == NULL) 3603 return (-1); 3604 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount, 3605 root->path); 3606 3607 /* Unreference the object and its dependencies. */ 3608 root->dl_refcount--; 3609 3610 if (root->refcount == 1) { 3611 /* 3612 * The object will be no longer referenced, so we must unload it. 3613 * First, call the fini functions. 3614 */ 3615 objlist_call_fini(&list_fini, root, lockstate); 3616 3617 unref_dag(root); 3618 3619 /* Finish cleaning up the newly-unreferenced objects. */ 3620 GDB_STATE(RT_DELETE,&root->linkmap); 3621 unload_object(root, lockstate); 3622 GDB_STATE(RT_CONSISTENT,NULL); 3623 } else 3624 unref_dag(root); 3625 3626 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL); 3627 return (0); 3628 } 3629 3630 char * 3631 dlerror(void) 3632 { 3633 if (*(lockinfo.dlerror_seen()) != 0) 3634 return (NULL); 3635 *lockinfo.dlerror_seen() = 1; 3636 return (lockinfo.dlerror_loc()); 3637 } 3638 3639 /* 3640 * This function is deprecated and has no effect. 3641 */ 3642 void 3643 dllockinit(void *context, 3644 void *(*_lock_create)(void *context) __unused, 3645 void (*_rlock_acquire)(void *lock) __unused, 3646 void (*_wlock_acquire)(void *lock) __unused, 3647 void (*_lock_release)(void *lock) __unused, 3648 void (*_lock_destroy)(void *lock) __unused, 3649 void (*context_destroy)(void *context)) 3650 { 3651 static void *cur_context; 3652 static void (*cur_context_destroy)(void *); 3653 3654 /* Just destroy the context from the previous call, if necessary. */ 3655 if (cur_context_destroy != NULL) 3656 cur_context_destroy(cur_context); 3657 cur_context = context; 3658 cur_context_destroy = context_destroy; 3659 } 3660 3661 void * 3662 dlopen(const char *name, int mode) 3663 { 3664 3665 return (rtld_dlopen(name, -1, mode)); 3666 } 3667 3668 void * 3669 fdlopen(int fd, int mode) 3670 { 3671 3672 return (rtld_dlopen(NULL, fd, mode)); 3673 } 3674 3675 static void * 3676 rtld_dlopen(const char *name, int fd, int mode) 3677 { 3678 RtldLockState lockstate; 3679 int lo_flags; 3680 3681 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name); 3682 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 3683 if (ld_tracing != NULL) { 3684 rlock_acquire(rtld_bind_lock, &lockstate); 3685 if (sigsetjmp(lockstate.env, 0) != 0) 3686 lock_upgrade(rtld_bind_lock, &lockstate); 3687 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate)); 3688 lock_release(rtld_bind_lock, &lockstate); 3689 } 3690 lo_flags = RTLD_LO_DLOPEN; 3691 if (mode & RTLD_NODELETE) 3692 lo_flags |= RTLD_LO_NODELETE; 3693 if (mode & RTLD_NOLOAD) 3694 lo_flags |= RTLD_LO_NOLOAD; 3695 if (mode & RTLD_DEEPBIND) 3696 lo_flags |= RTLD_LO_DEEPBIND; 3697 if (ld_tracing != NULL) 3698 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS; 3699 3700 return (dlopen_object(name, fd, obj_main, lo_flags, 3701 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL)); 3702 } 3703 3704 static void 3705 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate) 3706 { 3707 3708 obj->dl_refcount--; 3709 unref_dag(obj); 3710 if (obj->refcount == 0) 3711 unload_object(obj, lockstate); 3712 } 3713 3714 static Obj_Entry * 3715 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags, 3716 int mode, RtldLockState *lockstate) 3717 { 3718 Obj_Entry *old_obj_tail; 3719 Obj_Entry *obj; 3720 Objlist initlist; 3721 RtldLockState mlockstate; 3722 int result; 3723 3724 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x", 3725 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" : 3726 refobj->path, lo_flags, mode); 3727 objlist_init(&initlist); 3728 3729 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) { 3730 wlock_acquire(rtld_bind_lock, &mlockstate); 3731 lockstate = &mlockstate; 3732 } 3733 GDB_STATE(RT_ADD,NULL); 3734 3735 old_obj_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q)); 3736 obj = NULL; 3737 if (name == NULL && fd == -1) { 3738 obj = obj_main; 3739 obj->refcount++; 3740 } else { 3741 obj = load_object(name, fd, refobj, lo_flags); 3742 } 3743 3744 if (obj) { 3745 obj->dl_refcount++; 3746 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) 3747 objlist_push_tail(&list_global, obj); 3748 if (globallist_next(old_obj_tail) != NULL) { 3749 /* We loaded something new. */ 3750 assert(globallist_next(old_obj_tail) == obj); 3751 if ((lo_flags & RTLD_LO_DEEPBIND) != 0) 3752 obj->symbolic = true; 3753 result = 0; 3754 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 && 3755 obj->static_tls && !allocate_tls_offset(obj)) { 3756 _rtld_error("%s: No space available " 3757 "for static Thread Local Storage", obj->path); 3758 result = -1; 3759 } 3760 if (result != -1) 3761 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN | 3762 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE)); 3763 init_dag(obj); 3764 ref_dag(obj); 3765 if (result != -1) 3766 result = rtld_verify_versions(&obj->dagmembers); 3767 if (result != -1 && ld_tracing) 3768 goto trace; 3769 if (result == -1 || relocate_object_dag(obj, 3770 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld, 3771 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3772 lockstate) == -1) { 3773 dlopen_cleanup(obj, lockstate); 3774 obj = NULL; 3775 } else if (lo_flags & RTLD_LO_EARLY) { 3776 /* 3777 * Do not call the init functions for early loaded 3778 * filtees. The image is still not initialized enough 3779 * for them to work. 3780 * 3781 * Our object is found by the global object list and 3782 * will be ordered among all init calls done right 3783 * before transferring control to main. 3784 */ 3785 } else { 3786 /* Make list of init functions to call. */ 3787 initlist_add_objects(obj, obj, &initlist); 3788 } 3789 /* 3790 * Process all no_delete or global objects here, given 3791 * them own DAGs to prevent their dependencies from being 3792 * unloaded. This has to be done after we have loaded all 3793 * of the dependencies, so that we do not miss any. 3794 */ 3795 if (obj != NULL) 3796 process_z(obj); 3797 } else { 3798 /* 3799 * Bump the reference counts for objects on this DAG. If 3800 * this is the first dlopen() call for the object that was 3801 * already loaded as a dependency, initialize the dag 3802 * starting at it. 3803 */ 3804 init_dag(obj); 3805 ref_dag(obj); 3806 3807 if ((lo_flags & RTLD_LO_TRACE) != 0) 3808 goto trace; 3809 } 3810 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 || 3811 obj->z_nodelete) && !obj->ref_nodel) { 3812 dbg("obj %s nodelete", obj->path); 3813 ref_dag(obj); 3814 obj->z_nodelete = obj->ref_nodel = true; 3815 } 3816 } 3817 3818 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0, 3819 name); 3820 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); 3821 3822 if ((lo_flags & RTLD_LO_EARLY) == 0) { 3823 map_stacks_exec(lockstate); 3824 if (obj != NULL) 3825 distribute_static_tls(&initlist, lockstate); 3826 } 3827 3828 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW, 3829 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3830 lockstate) == -1) { 3831 objlist_clear(&initlist); 3832 dlopen_cleanup(obj, lockstate); 3833 if (lockstate == &mlockstate) 3834 lock_release(rtld_bind_lock, lockstate); 3835 return (NULL); 3836 } 3837 3838 if (!(lo_flags & RTLD_LO_EARLY)) { 3839 /* Call the init functions. */ 3840 objlist_call_init(&initlist, lockstate); 3841 } 3842 objlist_clear(&initlist); 3843 if (lockstate == &mlockstate) 3844 lock_release(rtld_bind_lock, lockstate); 3845 return (obj); 3846 trace: 3847 trace_loaded_objects(obj, false); 3848 if (lockstate == &mlockstate) 3849 lock_release(rtld_bind_lock, lockstate); 3850 exit(0); 3851 } 3852 3853 static void * 3854 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve, 3855 int flags) 3856 { 3857 DoneList donelist; 3858 const Obj_Entry *obj, *defobj; 3859 const Elf_Sym *def; 3860 SymLook req; 3861 RtldLockState lockstate; 3862 tls_index ti; 3863 void *sym; 3864 int res; 3865 3866 def = NULL; 3867 defobj = NULL; 3868 symlook_init(&req, name); 3869 req.ventry = ve; 3870 req.flags = flags | SYMLOOK_IN_PLT; 3871 req.lockstate = &lockstate; 3872 3873 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name); 3874 rlock_acquire(rtld_bind_lock, &lockstate); 3875 if (sigsetjmp(lockstate.env, 0) != 0) 3876 lock_upgrade(rtld_bind_lock, &lockstate); 3877 if (handle == NULL || handle == RTLD_NEXT || 3878 handle == RTLD_DEFAULT || handle == RTLD_SELF) { 3879 3880 if ((obj = obj_from_addr(retaddr)) == NULL) { 3881 _rtld_error("Cannot determine caller's shared object"); 3882 lock_release(rtld_bind_lock, &lockstate); 3883 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3884 return (NULL); 3885 } 3886 if (handle == NULL) { /* Just the caller's shared object. */ 3887 res = symlook_obj(&req, obj); 3888 if (res == 0) { 3889 def = req.sym_out; 3890 defobj = req.defobj_out; 3891 } 3892 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 3893 handle == RTLD_SELF) { /* ... caller included */ 3894 if (handle == RTLD_NEXT) 3895 obj = globallist_next(obj); 3896 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 3897 if (obj->marker) 3898 continue; 3899 res = symlook_obj(&req, obj); 3900 if (res == 0) { 3901 if (def == NULL || (ld_dynamic_weak && 3902 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) { 3903 def = req.sym_out; 3904 defobj = req.defobj_out; 3905 if (!ld_dynamic_weak || 3906 ELF_ST_BIND(def->st_info) != STB_WEAK) 3907 break; 3908 } 3909 } 3910 } 3911 /* 3912 * Search the dynamic linker itself, and possibly resolve the 3913 * symbol from there. This is how the application links to 3914 * dynamic linker services such as dlopen. 3915 * Note that we ignore ld_dynamic_weak == false case, 3916 * always overriding weak symbols by rtld definitions. 3917 */ 3918 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3919 res = symlook_obj(&req, &obj_rtld); 3920 if (res == 0) { 3921 def = req.sym_out; 3922 defobj = req.defobj_out; 3923 } 3924 } 3925 } else { 3926 assert(handle == RTLD_DEFAULT); 3927 res = symlook_default(&req, obj); 3928 if (res == 0) { 3929 defobj = req.defobj_out; 3930 def = req.sym_out; 3931 } 3932 } 3933 } else { 3934 if ((obj = dlcheck(handle)) == NULL) { 3935 lock_release(rtld_bind_lock, &lockstate); 3936 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3937 return (NULL); 3938 } 3939 3940 donelist_init(&donelist); 3941 if (obj->mainprog) { 3942 /* Handle obtained by dlopen(NULL, ...) implies global scope. */ 3943 res = symlook_global(&req, &donelist); 3944 if (res == 0) { 3945 def = req.sym_out; 3946 defobj = req.defobj_out; 3947 } 3948 /* 3949 * Search the dynamic linker itself, and possibly resolve the 3950 * symbol from there. This is how the application links to 3951 * dynamic linker services such as dlopen. 3952 */ 3953 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3954 res = symlook_obj(&req, &obj_rtld); 3955 if (res == 0) { 3956 def = req.sym_out; 3957 defobj = req.defobj_out; 3958 } 3959 } 3960 } 3961 else { 3962 /* Search the whole DAG rooted at the given object. */ 3963 res = symlook_list(&req, &obj->dagmembers, &donelist); 3964 if (res == 0) { 3965 def = req.sym_out; 3966 defobj = req.defobj_out; 3967 } 3968 } 3969 } 3970 3971 if (def != NULL) { 3972 lock_release(rtld_bind_lock, &lockstate); 3973 3974 /* 3975 * The value required by the caller is derived from the value 3976 * of the symbol. this is simply the relocated value of the 3977 * symbol. 3978 */ 3979 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 3980 sym = make_function_pointer(def, defobj); 3981 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 3982 sym = rtld_resolve_ifunc(defobj, def); 3983 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) { 3984 ti.ti_module = defobj->tlsindex; 3985 ti.ti_offset = def->st_value; 3986 sym = __tls_get_addr(&ti); 3987 } else 3988 sym = defobj->relocbase + def->st_value; 3989 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name); 3990 return (sym); 3991 } 3992 3993 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "", 3994 ve != NULL ? ve->name : ""); 3995 lock_release(rtld_bind_lock, &lockstate); 3996 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3997 return (NULL); 3998 } 3999 4000 void * 4001 dlsym(void *handle, const char *name) 4002 { 4003 return (do_dlsym(handle, name, __builtin_return_address(0), NULL, 4004 SYMLOOK_DLSYM)); 4005 } 4006 4007 dlfunc_t 4008 dlfunc(void *handle, const char *name) 4009 { 4010 union { 4011 void *d; 4012 dlfunc_t f; 4013 } rv; 4014 4015 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL, 4016 SYMLOOK_DLSYM); 4017 return (rv.f); 4018 } 4019 4020 void * 4021 dlvsym(void *handle, const char *name, const char *version) 4022 { 4023 Ver_Entry ventry; 4024 4025 ventry.name = version; 4026 ventry.file = NULL; 4027 ventry.hash = elf_hash(version); 4028 ventry.flags= 0; 4029 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry, 4030 SYMLOOK_DLSYM)); 4031 } 4032 4033 int 4034 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info) 4035 { 4036 const Obj_Entry *obj; 4037 RtldLockState lockstate; 4038 4039 rlock_acquire(rtld_bind_lock, &lockstate); 4040 obj = obj_from_addr(addr); 4041 if (obj == NULL) { 4042 _rtld_error("No shared object contains address"); 4043 lock_release(rtld_bind_lock, &lockstate); 4044 return (0); 4045 } 4046 rtld_fill_dl_phdr_info(obj, phdr_info); 4047 lock_release(rtld_bind_lock, &lockstate); 4048 return (1); 4049 } 4050 4051 int 4052 dladdr(const void *addr, Dl_info *info) 4053 { 4054 const Obj_Entry *obj; 4055 const Elf_Sym *def; 4056 void *symbol_addr; 4057 unsigned long symoffset; 4058 RtldLockState lockstate; 4059 4060 rlock_acquire(rtld_bind_lock, &lockstate); 4061 obj = obj_from_addr(addr); 4062 if (obj == NULL) { 4063 _rtld_error("No shared object contains address"); 4064 lock_release(rtld_bind_lock, &lockstate); 4065 return (0); 4066 } 4067 info->dli_fname = obj->path; 4068 info->dli_fbase = obj->mapbase; 4069 info->dli_saddr = (void *)0; 4070 info->dli_sname = NULL; 4071 4072 /* 4073 * Walk the symbol list looking for the symbol whose address is 4074 * closest to the address sent in. 4075 */ 4076 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) { 4077 def = obj->symtab + symoffset; 4078 4079 /* 4080 * For skip the symbol if st_shndx is either SHN_UNDEF or 4081 * SHN_COMMON. 4082 */ 4083 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 4084 continue; 4085 4086 /* 4087 * If the symbol is greater than the specified address, or if it 4088 * is further away from addr than the current nearest symbol, 4089 * then reject it. 4090 */ 4091 symbol_addr = obj->relocbase + def->st_value; 4092 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 4093 continue; 4094 4095 /* Update our idea of the nearest symbol. */ 4096 info->dli_sname = obj->strtab + def->st_name; 4097 info->dli_saddr = symbol_addr; 4098 4099 /* Exact match? */ 4100 if (info->dli_saddr == addr) 4101 break; 4102 } 4103 lock_release(rtld_bind_lock, &lockstate); 4104 return (1); 4105 } 4106 4107 int 4108 dlinfo(void *handle, int request, void *p) 4109 { 4110 const Obj_Entry *obj; 4111 RtldLockState lockstate; 4112 int error; 4113 4114 rlock_acquire(rtld_bind_lock, &lockstate); 4115 4116 if (handle == NULL || handle == RTLD_SELF) { 4117 void *retaddr; 4118 4119 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 4120 if ((obj = obj_from_addr(retaddr)) == NULL) 4121 _rtld_error("Cannot determine caller's shared object"); 4122 } else 4123 obj = dlcheck(handle); 4124 4125 if (obj == NULL) { 4126 lock_release(rtld_bind_lock, &lockstate); 4127 return (-1); 4128 } 4129 4130 error = 0; 4131 switch (request) { 4132 case RTLD_DI_LINKMAP: 4133 *((struct link_map const **)p) = &obj->linkmap; 4134 break; 4135 case RTLD_DI_ORIGIN: 4136 error = rtld_dirname(obj->path, p); 4137 break; 4138 4139 case RTLD_DI_SERINFOSIZE: 4140 case RTLD_DI_SERINFO: 4141 error = do_search_info(obj, request, (struct dl_serinfo *)p); 4142 break; 4143 4144 default: 4145 _rtld_error("Invalid request %d passed to dlinfo()", request); 4146 error = -1; 4147 } 4148 4149 lock_release(rtld_bind_lock, &lockstate); 4150 4151 return (error); 4152 } 4153 4154 static void 4155 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info) 4156 { 4157 uintptr_t **dtvp; 4158 4159 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase; 4160 phdr_info->dlpi_name = obj->path; 4161 phdr_info->dlpi_phdr = obj->phdr; 4162 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]); 4163 phdr_info->dlpi_tls_modid = obj->tlsindex; 4164 dtvp = &_tcb_get()->tcb_dtv; 4165 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp, 4166 obj->tlsindex, 0, true) + TLS_DTV_OFFSET; 4167 phdr_info->dlpi_adds = obj_loads; 4168 phdr_info->dlpi_subs = obj_loads - obj_count; 4169 } 4170 4171 int 4172 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param) 4173 { 4174 struct dl_phdr_info phdr_info; 4175 Obj_Entry *obj, marker; 4176 RtldLockState bind_lockstate, phdr_lockstate; 4177 int error; 4178 4179 init_marker(&marker); 4180 error = 0; 4181 4182 wlock_acquire(rtld_phdr_lock, &phdr_lockstate); 4183 wlock_acquire(rtld_bind_lock, &bind_lockstate); 4184 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) { 4185 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next); 4186 rtld_fill_dl_phdr_info(obj, &phdr_info); 4187 hold_object(obj); 4188 lock_release(rtld_bind_lock, &bind_lockstate); 4189 4190 error = callback(&phdr_info, sizeof phdr_info, param); 4191 4192 wlock_acquire(rtld_bind_lock, &bind_lockstate); 4193 unhold_object(obj); 4194 obj = globallist_next(&marker); 4195 TAILQ_REMOVE(&obj_list, &marker, next); 4196 if (error != 0) { 4197 lock_release(rtld_bind_lock, &bind_lockstate); 4198 lock_release(rtld_phdr_lock, &phdr_lockstate); 4199 return (error); 4200 } 4201 } 4202 4203 if (error == 0) { 4204 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info); 4205 lock_release(rtld_bind_lock, &bind_lockstate); 4206 error = callback(&phdr_info, sizeof(phdr_info), param); 4207 } 4208 lock_release(rtld_phdr_lock, &phdr_lockstate); 4209 return (error); 4210 } 4211 4212 static void * 4213 fill_search_info(const char *dir, size_t dirlen, void *param) 4214 { 4215 struct fill_search_info_args *arg; 4216 4217 arg = param; 4218 4219 if (arg->request == RTLD_DI_SERINFOSIZE) { 4220 arg->serinfo->dls_cnt ++; 4221 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1; 4222 } else { 4223 struct dl_serpath *s_entry; 4224 4225 s_entry = arg->serpath; 4226 s_entry->dls_name = arg->strspace; 4227 s_entry->dls_flags = arg->flags; 4228 4229 strncpy(arg->strspace, dir, dirlen); 4230 arg->strspace[dirlen] = '\0'; 4231 4232 arg->strspace += dirlen + 1; 4233 arg->serpath++; 4234 } 4235 4236 return (NULL); 4237 } 4238 4239 static int 4240 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 4241 { 4242 struct dl_serinfo _info; 4243 struct fill_search_info_args args; 4244 4245 args.request = RTLD_DI_SERINFOSIZE; 4246 args.serinfo = &_info; 4247 4248 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 4249 _info.dls_cnt = 0; 4250 4251 path_enumerate(obj->rpath, fill_search_info, NULL, &args); 4252 path_enumerate(ld_library_path, fill_search_info, NULL, &args); 4253 path_enumerate(obj->runpath, fill_search_info, NULL, &args); 4254 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args); 4255 if (!obj->z_nodeflib) 4256 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args); 4257 4258 4259 if (request == RTLD_DI_SERINFOSIZE) { 4260 info->dls_size = _info.dls_size; 4261 info->dls_cnt = _info.dls_cnt; 4262 return (0); 4263 } 4264 4265 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { 4266 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); 4267 return (-1); 4268 } 4269 4270 args.request = RTLD_DI_SERINFO; 4271 args.serinfo = info; 4272 args.serpath = &info->dls_serpath[0]; 4273 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 4274 4275 args.flags = LA_SER_RUNPATH; 4276 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL) 4277 return (-1); 4278 4279 args.flags = LA_SER_LIBPATH; 4280 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL) 4281 return (-1); 4282 4283 args.flags = LA_SER_RUNPATH; 4284 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL) 4285 return (-1); 4286 4287 args.flags = LA_SER_CONFIG; 4288 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args) 4289 != NULL) 4290 return (-1); 4291 4292 args.flags = LA_SER_DEFAULT; 4293 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path, 4294 fill_search_info, NULL, &args) != NULL) 4295 return (-1); 4296 return (0); 4297 } 4298 4299 static int 4300 rtld_dirname(const char *path, char *bname) 4301 { 4302 const char *endp; 4303 4304 /* Empty or NULL string gets treated as "." */ 4305 if (path == NULL || *path == '\0') { 4306 bname[0] = '.'; 4307 bname[1] = '\0'; 4308 return (0); 4309 } 4310 4311 /* Strip trailing slashes */ 4312 endp = path + strlen(path) - 1; 4313 while (endp > path && *endp == '/') 4314 endp--; 4315 4316 /* Find the start of the dir */ 4317 while (endp > path && *endp != '/') 4318 endp--; 4319 4320 /* Either the dir is "/" or there are no slashes */ 4321 if (endp == path) { 4322 bname[0] = *endp == '/' ? '/' : '.'; 4323 bname[1] = '\0'; 4324 return (0); 4325 } else { 4326 do { 4327 endp--; 4328 } while (endp > path && *endp == '/'); 4329 } 4330 4331 if (endp - path + 2 > PATH_MAX) 4332 { 4333 _rtld_error("Filename is too long: %s", path); 4334 return(-1); 4335 } 4336 4337 strncpy(bname, path, endp - path + 1); 4338 bname[endp - path + 1] = '\0'; 4339 return (0); 4340 } 4341 4342 static int 4343 rtld_dirname_abs(const char *path, char *base) 4344 { 4345 char *last; 4346 4347 if (realpath(path, base) == NULL) { 4348 _rtld_error("realpath \"%s\" failed (%s)", path, 4349 rtld_strerror(errno)); 4350 return (-1); 4351 } 4352 dbg("%s -> %s", path, base); 4353 last = strrchr(base, '/'); 4354 if (last == NULL) { 4355 _rtld_error("non-abs result from realpath \"%s\"", path); 4356 return (-1); 4357 } 4358 if (last != base) 4359 *last = '\0'; 4360 return (0); 4361 } 4362 4363 static void 4364 linkmap_add(Obj_Entry *obj) 4365 { 4366 struct link_map *l, *prev; 4367 4368 l = &obj->linkmap; 4369 l->l_name = obj->path; 4370 l->l_base = obj->mapbase; 4371 l->l_ld = obj->dynamic; 4372 l->l_addr = obj->relocbase; 4373 4374 if (r_debug.r_map == NULL) { 4375 r_debug.r_map = l; 4376 return; 4377 } 4378 4379 /* 4380 * Scan to the end of the list, but not past the entry for the 4381 * dynamic linker, which we want to keep at the very end. 4382 */ 4383 for (prev = r_debug.r_map; 4384 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 4385 prev = prev->l_next) 4386 ; 4387 4388 /* Link in the new entry. */ 4389 l->l_prev = prev; 4390 l->l_next = prev->l_next; 4391 if (l->l_next != NULL) 4392 l->l_next->l_prev = l; 4393 prev->l_next = l; 4394 } 4395 4396 static void 4397 linkmap_delete(Obj_Entry *obj) 4398 { 4399 struct link_map *l; 4400 4401 l = &obj->linkmap; 4402 if (l->l_prev == NULL) { 4403 if ((r_debug.r_map = l->l_next) != NULL) 4404 l->l_next->l_prev = NULL; 4405 return; 4406 } 4407 4408 if ((l->l_prev->l_next = l->l_next) != NULL) 4409 l->l_next->l_prev = l->l_prev; 4410 } 4411 4412 /* 4413 * Function for the debugger to set a breakpoint on to gain control. 4414 * 4415 * The two parameters allow the debugger to easily find and determine 4416 * what the runtime loader is doing and to whom it is doing it. 4417 * 4418 * When the loadhook trap is hit (r_debug_state, set at program 4419 * initialization), the arguments can be found on the stack: 4420 * 4421 * +8 struct link_map *m 4422 * +4 struct r_debug *rd 4423 * +0 RetAddr 4424 */ 4425 void 4426 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused) 4427 { 4428 /* 4429 * The following is a hack to force the compiler to emit calls to 4430 * this function, even when optimizing. If the function is empty, 4431 * the compiler is not obliged to emit any code for calls to it, 4432 * even when marked __noinline. However, gdb depends on those 4433 * calls being made. 4434 */ 4435 __compiler_membar(); 4436 } 4437 4438 /* 4439 * A function called after init routines have completed. This can be used to 4440 * break before a program's entry routine is called, and can be used when 4441 * main is not available in the symbol table. 4442 */ 4443 void 4444 _r_debug_postinit(struct link_map *m __unused) 4445 { 4446 4447 /* See r_debug_state(). */ 4448 __compiler_membar(); 4449 } 4450 4451 static void 4452 release_object(Obj_Entry *obj) 4453 { 4454 4455 if (obj->holdcount > 0) { 4456 obj->unholdfree = true; 4457 return; 4458 } 4459 munmap(obj->mapbase, obj->mapsize); 4460 linkmap_delete(obj); 4461 obj_free(obj); 4462 } 4463 4464 /* 4465 * Get address of the pointer variable in the main program. 4466 * Prefer non-weak symbol over the weak one. 4467 */ 4468 static const void ** 4469 get_program_var_addr(const char *name, RtldLockState *lockstate) 4470 { 4471 SymLook req; 4472 DoneList donelist; 4473 4474 symlook_init(&req, name); 4475 req.lockstate = lockstate; 4476 donelist_init(&donelist); 4477 if (symlook_global(&req, &donelist) != 0) 4478 return (NULL); 4479 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC) 4480 return ((const void **)make_function_pointer(req.sym_out, 4481 req.defobj_out)); 4482 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC) 4483 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out)); 4484 else 4485 return ((const void **)(req.defobj_out->relocbase + 4486 req.sym_out->st_value)); 4487 } 4488 4489 /* 4490 * Set a pointer variable in the main program to the given value. This 4491 * is used to set key variables such as "environ" before any of the 4492 * init functions are called. 4493 */ 4494 static void 4495 set_program_var(const char *name, const void *value) 4496 { 4497 const void **addr; 4498 4499 if ((addr = get_program_var_addr(name, NULL)) != NULL) { 4500 dbg("\"%s\": *%p <-- %p", name, addr, value); 4501 *addr = value; 4502 } 4503 } 4504 4505 /* 4506 * Search the global objects, including dependencies and main object, 4507 * for the given symbol. 4508 */ 4509 static int 4510 symlook_global(SymLook *req, DoneList *donelist) 4511 { 4512 SymLook req1; 4513 const Objlist_Entry *elm; 4514 int res; 4515 4516 symlook_init_from_req(&req1, req); 4517 4518 /* Search all objects loaded at program start up. */ 4519 if (req->defobj_out == NULL || (ld_dynamic_weak && 4520 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) { 4521 res = symlook_list(&req1, &list_main, donelist); 4522 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL || 4523 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4524 req->sym_out = req1.sym_out; 4525 req->defobj_out = req1.defobj_out; 4526 assert(req->defobj_out != NULL); 4527 } 4528 } 4529 4530 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 4531 STAILQ_FOREACH(elm, &list_global, link) { 4532 if (req->defobj_out != NULL && (!ld_dynamic_weak || 4533 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)) 4534 break; 4535 res = symlook_list(&req1, &elm->obj->dagmembers, donelist); 4536 if (res == 0 && (req->defobj_out == NULL || 4537 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4538 req->sym_out = req1.sym_out; 4539 req->defobj_out = req1.defobj_out; 4540 assert(req->defobj_out != NULL); 4541 } 4542 } 4543 4544 return (req->sym_out != NULL ? 0 : ESRCH); 4545 } 4546 4547 /* 4548 * Given a symbol name in a referencing object, find the corresponding 4549 * definition of the symbol. Returns a pointer to the symbol, or NULL if 4550 * no definition was found. Returns a pointer to the Obj_Entry of the 4551 * defining object via the reference parameter DEFOBJ_OUT. 4552 */ 4553 static int 4554 symlook_default(SymLook *req, const Obj_Entry *refobj) 4555 { 4556 DoneList donelist; 4557 const Objlist_Entry *elm; 4558 SymLook req1; 4559 int res; 4560 4561 donelist_init(&donelist); 4562 symlook_init_from_req(&req1, req); 4563 4564 /* 4565 * Look first in the referencing object if linked symbolically, 4566 * and similarly handle protected symbols. 4567 */ 4568 res = symlook_obj(&req1, refobj); 4569 if (res == 0 && (refobj->symbolic || 4570 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) { 4571 req->sym_out = req1.sym_out; 4572 req->defobj_out = req1.defobj_out; 4573 assert(req->defobj_out != NULL); 4574 } 4575 if (refobj->symbolic || req->defobj_out != NULL) 4576 donelist_check(&donelist, refobj); 4577 4578 symlook_global(req, &donelist); 4579 4580 /* Search all dlopened DAGs containing the referencing object. */ 4581 STAILQ_FOREACH(elm, &refobj->dldags, link) { 4582 if (req->sym_out != NULL && (!ld_dynamic_weak || 4583 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)) 4584 break; 4585 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist); 4586 if (res == 0 && (req->sym_out == NULL || 4587 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4588 req->sym_out = req1.sym_out; 4589 req->defobj_out = req1.defobj_out; 4590 assert(req->defobj_out != NULL); 4591 } 4592 } 4593 4594 /* 4595 * Search the dynamic linker itself, and possibly resolve the 4596 * symbol from there. This is how the application links to 4597 * dynamic linker services such as dlopen. 4598 */ 4599 if (req->sym_out == NULL || 4600 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 4601 res = symlook_obj(&req1, &obj_rtld); 4602 if (res == 0) { 4603 req->sym_out = req1.sym_out; 4604 req->defobj_out = req1.defobj_out; 4605 assert(req->defobj_out != NULL); 4606 } 4607 } 4608 4609 return (req->sym_out != NULL ? 0 : ESRCH); 4610 } 4611 4612 static int 4613 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp) 4614 { 4615 const Elf_Sym *def; 4616 const Obj_Entry *defobj; 4617 const Objlist_Entry *elm; 4618 SymLook req1; 4619 int res; 4620 4621 def = NULL; 4622 defobj = NULL; 4623 STAILQ_FOREACH(elm, objlist, link) { 4624 if (donelist_check(dlp, elm->obj)) 4625 continue; 4626 symlook_init_from_req(&req1, req); 4627 if ((res = symlook_obj(&req1, elm->obj)) == 0) { 4628 if (def == NULL || (ld_dynamic_weak && 4629 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4630 def = req1.sym_out; 4631 defobj = req1.defobj_out; 4632 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK) 4633 break; 4634 } 4635 } 4636 } 4637 if (def != NULL) { 4638 req->sym_out = def; 4639 req->defobj_out = defobj; 4640 return (0); 4641 } 4642 return (ESRCH); 4643 } 4644 4645 /* 4646 * Search the chain of DAGS cointed to by the given Needed_Entry 4647 * for a symbol of the given name. Each DAG is scanned completely 4648 * before advancing to the next one. Returns a pointer to the symbol, 4649 * or NULL if no definition was found. 4650 */ 4651 static int 4652 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp) 4653 { 4654 const Elf_Sym *def; 4655 const Needed_Entry *n; 4656 const Obj_Entry *defobj; 4657 SymLook req1; 4658 int res; 4659 4660 def = NULL; 4661 defobj = NULL; 4662 symlook_init_from_req(&req1, req); 4663 for (n = needed; n != NULL; n = n->next) { 4664 if (n->obj == NULL || 4665 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0) 4666 continue; 4667 if (def == NULL || (ld_dynamic_weak && 4668 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4669 def = req1.sym_out; 4670 defobj = req1.defobj_out; 4671 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK) 4672 break; 4673 } 4674 } 4675 if (def != NULL) { 4676 req->sym_out = def; 4677 req->defobj_out = defobj; 4678 return (0); 4679 } 4680 return (ESRCH); 4681 } 4682 4683 /* 4684 * Search the symbol table of a single shared object for a symbol of 4685 * the given name and version, if requested. Returns a pointer to the 4686 * symbol, or NULL if no definition was found. If the object is 4687 * filter, return filtered symbol from filtee. 4688 * 4689 * The symbol's hash value is passed in for efficiency reasons; that 4690 * eliminates many recomputations of the hash value. 4691 */ 4692 int 4693 symlook_obj(SymLook *req, const Obj_Entry *obj) 4694 { 4695 DoneList donelist; 4696 SymLook req1; 4697 int flags, res, mres; 4698 4699 /* 4700 * If there is at least one valid hash at this point, we prefer to 4701 * use the faster GNU version if available. 4702 */ 4703 if (obj->valid_hash_gnu) 4704 mres = symlook_obj1_gnu(req, obj); 4705 else if (obj->valid_hash_sysv) 4706 mres = symlook_obj1_sysv(req, obj); 4707 else 4708 return (EINVAL); 4709 4710 if (mres == 0) { 4711 if (obj->needed_filtees != NULL) { 4712 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0; 4713 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4714 donelist_init(&donelist); 4715 symlook_init_from_req(&req1, req); 4716 res = symlook_needed(&req1, obj->needed_filtees, &donelist); 4717 if (res == 0) { 4718 req->sym_out = req1.sym_out; 4719 req->defobj_out = req1.defobj_out; 4720 } 4721 return (res); 4722 } 4723 if (obj->needed_aux_filtees != NULL) { 4724 flags = (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0; 4725 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4726 donelist_init(&donelist); 4727 symlook_init_from_req(&req1, req); 4728 res = symlook_needed(&req1, obj->needed_aux_filtees, &donelist); 4729 if (res == 0) { 4730 req->sym_out = req1.sym_out; 4731 req->defobj_out = req1.defobj_out; 4732 return (res); 4733 } 4734 } 4735 } 4736 return (mres); 4737 } 4738 4739 /* Symbol match routine common to both hash functions */ 4740 static bool 4741 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result, 4742 const unsigned long symnum) 4743 { 4744 Elf_Versym verndx; 4745 const Elf_Sym *symp; 4746 const char *strp; 4747 4748 symp = obj->symtab + symnum; 4749 strp = obj->strtab + symp->st_name; 4750 4751 switch (ELF_ST_TYPE(symp->st_info)) { 4752 case STT_FUNC: 4753 case STT_NOTYPE: 4754 case STT_OBJECT: 4755 case STT_COMMON: 4756 case STT_GNU_IFUNC: 4757 if (symp->st_value == 0) 4758 return (false); 4759 /* fallthrough */ 4760 case STT_TLS: 4761 if (symp->st_shndx != SHN_UNDEF) 4762 break; 4763 else if (((req->flags & SYMLOOK_IN_PLT) == 0) && 4764 (ELF_ST_TYPE(symp->st_info) == STT_FUNC)) 4765 break; 4766 /* fallthrough */ 4767 default: 4768 return (false); 4769 } 4770 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0) 4771 return (false); 4772 4773 if (req->ventry == NULL) { 4774 if (obj->versyms != NULL) { 4775 verndx = VER_NDX(obj->versyms[symnum]); 4776 if (verndx > obj->vernum) { 4777 _rtld_error( 4778 "%s: symbol %s references wrong version %d", 4779 obj->path, obj->strtab + symnum, verndx); 4780 return (false); 4781 } 4782 /* 4783 * If we are not called from dlsym (i.e. this 4784 * is a normal relocation from unversioned 4785 * binary), accept the symbol immediately if 4786 * it happens to have first version after this 4787 * shared object became versioned. Otherwise, 4788 * if symbol is versioned and not hidden, 4789 * remember it. If it is the only symbol with 4790 * this name exported by the shared object, it 4791 * will be returned as a match by the calling 4792 * function. If symbol is global (verndx < 2) 4793 * accept it unconditionally. 4794 */ 4795 if ((req->flags & SYMLOOK_DLSYM) == 0 && 4796 verndx == VER_NDX_GIVEN) { 4797 result->sym_out = symp; 4798 return (true); 4799 } 4800 else if (verndx >= VER_NDX_GIVEN) { 4801 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) 4802 == 0) { 4803 if (result->vsymp == NULL) 4804 result->vsymp = symp; 4805 result->vcount++; 4806 } 4807 return (false); 4808 } 4809 } 4810 result->sym_out = symp; 4811 return (true); 4812 } 4813 if (obj->versyms == NULL) { 4814 if (object_match_name(obj, req->ventry->name)) { 4815 _rtld_error("%s: object %s should provide version %s " 4816 "for symbol %s", obj_rtld.path, obj->path, 4817 req->ventry->name, obj->strtab + symnum); 4818 return (false); 4819 } 4820 } else { 4821 verndx = VER_NDX(obj->versyms[symnum]); 4822 if (verndx > obj->vernum) { 4823 _rtld_error("%s: symbol %s references wrong version %d", 4824 obj->path, obj->strtab + symnum, verndx); 4825 return (false); 4826 } 4827 if (obj->vertab[verndx].hash != req->ventry->hash || 4828 strcmp(obj->vertab[verndx].name, req->ventry->name)) { 4829 /* 4830 * Version does not match. Look if this is a 4831 * global symbol and if it is not hidden. If 4832 * global symbol (verndx < 2) is available, 4833 * use it. Do not return symbol if we are 4834 * called by dlvsym, because dlvsym looks for 4835 * a specific version and default one is not 4836 * what dlvsym wants. 4837 */ 4838 if ((req->flags & SYMLOOK_DLSYM) || 4839 (verndx >= VER_NDX_GIVEN) || 4840 (obj->versyms[symnum] & VER_NDX_HIDDEN)) 4841 return (false); 4842 } 4843 } 4844 result->sym_out = symp; 4845 return (true); 4846 } 4847 4848 /* 4849 * Search for symbol using SysV hash function. 4850 * obj->buckets is known not to be NULL at this point; the test for this was 4851 * performed with the obj->valid_hash_sysv assignment. 4852 */ 4853 static int 4854 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj) 4855 { 4856 unsigned long symnum; 4857 Sym_Match_Result matchres; 4858 4859 matchres.sym_out = NULL; 4860 matchres.vsymp = NULL; 4861 matchres.vcount = 0; 4862 4863 for (symnum = obj->buckets[req->hash % obj->nbuckets]; 4864 symnum != STN_UNDEF; symnum = obj->chains[symnum]) { 4865 if (symnum >= obj->nchains) 4866 return (ESRCH); /* Bad object */ 4867 4868 if (matched_symbol(req, obj, &matchres, symnum)) { 4869 req->sym_out = matchres.sym_out; 4870 req->defobj_out = obj; 4871 return (0); 4872 } 4873 } 4874 if (matchres.vcount == 1) { 4875 req->sym_out = matchres.vsymp; 4876 req->defobj_out = obj; 4877 return (0); 4878 } 4879 return (ESRCH); 4880 } 4881 4882 /* Search for symbol using GNU hash function */ 4883 static int 4884 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj) 4885 { 4886 Elf_Addr bloom_word; 4887 const Elf32_Word *hashval; 4888 Elf32_Word bucket; 4889 Sym_Match_Result matchres; 4890 unsigned int h1, h2; 4891 unsigned long symnum; 4892 4893 matchres.sym_out = NULL; 4894 matchres.vsymp = NULL; 4895 matchres.vcount = 0; 4896 4897 /* Pick right bitmask word from Bloom filter array */ 4898 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) & 4899 obj->maskwords_bm_gnu]; 4900 4901 /* Calculate modulus word size of gnu hash and its derivative */ 4902 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1); 4903 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1)); 4904 4905 /* Filter out the "definitely not in set" queries */ 4906 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0) 4907 return (ESRCH); 4908 4909 /* Locate hash chain and corresponding value element*/ 4910 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu]; 4911 if (bucket == 0) 4912 return (ESRCH); 4913 hashval = &obj->chain_zero_gnu[bucket]; 4914 do { 4915 if (((*hashval ^ req->hash_gnu) >> 1) == 0) { 4916 symnum = hashval - obj->chain_zero_gnu; 4917 if (matched_symbol(req, obj, &matchres, symnum)) { 4918 req->sym_out = matchres.sym_out; 4919 req->defobj_out = obj; 4920 return (0); 4921 } 4922 } 4923 } while ((*hashval++ & 1) == 0); 4924 if (matchres.vcount == 1) { 4925 req->sym_out = matchres.vsymp; 4926 req->defobj_out = obj; 4927 return (0); 4928 } 4929 return (ESRCH); 4930 } 4931 4932 static void 4933 trace_calc_fmts(const char **main_local, const char **fmt1, const char **fmt2) 4934 { 4935 *main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME); 4936 if (*main_local == NULL) 4937 *main_local = ""; 4938 4939 *fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1); 4940 if (*fmt1 == NULL) 4941 *fmt1 = "\t%o => %p (%x)\n"; 4942 4943 *fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2); 4944 if (*fmt2 == NULL) 4945 *fmt2 = "\t%o (%x)\n"; 4946 } 4947 4948 static void 4949 trace_print_obj(Obj_Entry *obj, const char *name, const char *path, 4950 const char *main_local, const char *fmt1, const char *fmt2) 4951 { 4952 const char *fmt; 4953 int c; 4954 4955 if (fmt1 == NULL) 4956 fmt = fmt2; 4957 else 4958 /* XXX bogus */ 4959 fmt = strncmp(name, "lib", 3) == 0 ? fmt1 : fmt2; 4960 4961 while ((c = *fmt++) != '\0') { 4962 switch (c) { 4963 default: 4964 rtld_putchar(c); 4965 continue; 4966 case '\\': 4967 switch (c = *fmt) { 4968 case '\0': 4969 continue; 4970 case 'n': 4971 rtld_putchar('\n'); 4972 break; 4973 case 't': 4974 rtld_putchar('\t'); 4975 break; 4976 } 4977 break; 4978 case '%': 4979 switch (c = *fmt) { 4980 case '\0': 4981 continue; 4982 case '%': 4983 default: 4984 rtld_putchar(c); 4985 break; 4986 case 'A': 4987 rtld_putstr(main_local); 4988 break; 4989 case 'a': 4990 rtld_putstr(obj_main->path); 4991 break; 4992 case 'o': 4993 rtld_putstr(name); 4994 break; 4995 case 'p': 4996 rtld_putstr(path); 4997 break; 4998 case 'x': 4999 rtld_printf("%p", obj != NULL ? 5000 obj->mapbase : NULL); 5001 break; 5002 } 5003 break; 5004 } 5005 ++fmt; 5006 } 5007 } 5008 5009 static void 5010 trace_loaded_objects(Obj_Entry *obj, bool show_preload) 5011 { 5012 const char *fmt1, *fmt2, *main_local; 5013 const char *name, *path; 5014 bool first_spurious, list_containers; 5015 5016 trace_calc_fmts(&main_local, &fmt1, &fmt2); 5017 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL) != NULL; 5018 5019 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5020 Needed_Entry *needed; 5021 5022 if (obj->marker) 5023 continue; 5024 if (list_containers && obj->needed != NULL) 5025 rtld_printf("%s:\n", obj->path); 5026 for (needed = obj->needed; needed; needed = needed->next) { 5027 if (needed->obj != NULL) { 5028 if (needed->obj->traced && !list_containers) 5029 continue; 5030 needed->obj->traced = true; 5031 path = needed->obj->path; 5032 } else 5033 path = "not found"; 5034 5035 name = obj->strtab + needed->name; 5036 trace_print_obj(needed->obj, name, path, main_local, 5037 fmt1, fmt2); 5038 } 5039 } 5040 5041 if (show_preload) { 5042 if (ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2) == NULL) 5043 fmt2 = "\t%p (%x)\n"; 5044 first_spurious = true; 5045 5046 TAILQ_FOREACH(obj, &obj_list, next) { 5047 if (obj->marker || obj == obj_main || obj->traced) 5048 continue; 5049 5050 if (list_containers && first_spurious) { 5051 rtld_printf("[preloaded]\n"); 5052 first_spurious = false; 5053 } 5054 5055 Name_Entry *fname = STAILQ_FIRST(&obj->names); 5056 name = fname == NULL ? "<unknown>" : fname->name; 5057 trace_print_obj(obj, name, obj->path, main_local, 5058 NULL, fmt2); 5059 } 5060 } 5061 } 5062 5063 /* 5064 * Unload a dlopened object and its dependencies from memory and from 5065 * our data structures. It is assumed that the DAG rooted in the 5066 * object has already been unreferenced, and that the object has a 5067 * reference count of 0. 5068 */ 5069 static void 5070 unload_object(Obj_Entry *root, RtldLockState *lockstate) 5071 { 5072 Obj_Entry marker, *obj, *next; 5073 5074 assert(root->refcount == 0); 5075 5076 /* 5077 * Pass over the DAG removing unreferenced objects from 5078 * appropriate lists. 5079 */ 5080 unlink_object(root); 5081 5082 /* Unmap all objects that are no longer referenced. */ 5083 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) { 5084 next = TAILQ_NEXT(obj, next); 5085 if (obj->marker || obj->refcount != 0) 5086 continue; 5087 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, 5088 obj->mapsize, 0, obj->path); 5089 dbg("unloading \"%s\"", obj->path); 5090 /* 5091 * Unlink the object now to prevent new references from 5092 * being acquired while the bind lock is dropped in 5093 * recursive dlclose() invocations. 5094 */ 5095 TAILQ_REMOVE(&obj_list, obj, next); 5096 obj_count--; 5097 5098 if (obj->filtees_loaded) { 5099 if (next != NULL) { 5100 init_marker(&marker); 5101 TAILQ_INSERT_BEFORE(next, &marker, next); 5102 unload_filtees(obj, lockstate); 5103 next = TAILQ_NEXT(&marker, next); 5104 TAILQ_REMOVE(&obj_list, &marker, next); 5105 } else 5106 unload_filtees(obj, lockstate); 5107 } 5108 release_object(obj); 5109 } 5110 } 5111 5112 static void 5113 unlink_object(Obj_Entry *root) 5114 { 5115 Objlist_Entry *elm; 5116 5117 if (root->refcount == 0) { 5118 /* Remove the object from the RTLD_GLOBAL list. */ 5119 objlist_remove(&list_global, root); 5120 5121 /* Remove the object from all objects' DAG lists. */ 5122 STAILQ_FOREACH(elm, &root->dagmembers, link) { 5123 objlist_remove(&elm->obj->dldags, root); 5124 if (elm->obj != root) 5125 unlink_object(elm->obj); 5126 } 5127 } 5128 } 5129 5130 static void 5131 ref_dag(Obj_Entry *root) 5132 { 5133 Objlist_Entry *elm; 5134 5135 assert(root->dag_inited); 5136 STAILQ_FOREACH(elm, &root->dagmembers, link) 5137 elm->obj->refcount++; 5138 } 5139 5140 static void 5141 unref_dag(Obj_Entry *root) 5142 { 5143 Objlist_Entry *elm; 5144 5145 assert(root->dag_inited); 5146 STAILQ_FOREACH(elm, &root->dagmembers, link) 5147 elm->obj->refcount--; 5148 } 5149 5150 /* 5151 * Common code for MD __tls_get_addr(). 5152 */ 5153 static void * 5154 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked) 5155 { 5156 Elf_Addr *newdtv, *dtv; 5157 RtldLockState lockstate; 5158 int to_copy; 5159 5160 dtv = *dtvp; 5161 /* Check dtv generation in case new modules have arrived */ 5162 if (dtv[0] != tls_dtv_generation) { 5163 if (!locked) 5164 wlock_acquire(rtld_bind_lock, &lockstate); 5165 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5166 to_copy = dtv[1]; 5167 if (to_copy > tls_max_index) 5168 to_copy = tls_max_index; 5169 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); 5170 newdtv[0] = tls_dtv_generation; 5171 newdtv[1] = tls_max_index; 5172 free(dtv); 5173 if (!locked) 5174 lock_release(rtld_bind_lock, &lockstate); 5175 dtv = *dtvp = newdtv; 5176 } 5177 5178 /* Dynamically allocate module TLS if necessary */ 5179 if (dtv[index + 1] == 0) { 5180 /* Signal safe, wlock will block out signals. */ 5181 if (!locked) 5182 wlock_acquire(rtld_bind_lock, &lockstate); 5183 if (!dtv[index + 1]) 5184 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); 5185 if (!locked) 5186 lock_release(rtld_bind_lock, &lockstate); 5187 } 5188 return ((void *)(dtv[index + 1] + offset)); 5189 } 5190 5191 void * 5192 tls_get_addr_common(uintptr_t **dtvp, int index, size_t offset) 5193 { 5194 uintptr_t *dtv; 5195 5196 dtv = *dtvp; 5197 /* Check dtv generation in case new modules have arrived */ 5198 if (__predict_true(dtv[0] == tls_dtv_generation && 5199 dtv[index + 1] != 0)) 5200 return ((void *)(dtv[index + 1] + offset)); 5201 return (tls_get_addr_slow(dtvp, index, offset, false)); 5202 } 5203 5204 #ifdef TLS_VARIANT_I 5205 5206 /* 5207 * Return pointer to allocated TLS block 5208 */ 5209 static void * 5210 get_tls_block_ptr(void *tcb, size_t tcbsize) 5211 { 5212 size_t extra_size, post_size, pre_size, tls_block_size; 5213 size_t tls_init_align; 5214 5215 tls_init_align = MAX(obj_main->tlsalign, 1); 5216 5217 /* Compute fragments sizes. */ 5218 extra_size = tcbsize - TLS_TCB_SIZE; 5219 post_size = calculate_tls_post_size(tls_init_align); 5220 tls_block_size = tcbsize + post_size; 5221 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 5222 5223 return ((char *)tcb - pre_size - extra_size); 5224 } 5225 5226 /* 5227 * Allocate Static TLS using the Variant I method. 5228 * 5229 * For details on the layout, see lib/libc/gen/tls.c. 5230 * 5231 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as 5232 * it is based on tls_last_offset, and TLS offsets here are really TCB 5233 * offsets, whereas libc's tls_static_space is just the executable's static 5234 * TLS segment. 5235 */ 5236 void * 5237 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 5238 { 5239 Obj_Entry *obj; 5240 char *tls_block; 5241 Elf_Addr *dtv, **tcb; 5242 Elf_Addr addr; 5243 Elf_Addr i; 5244 size_t extra_size, maxalign, post_size, pre_size, tls_block_size; 5245 size_t tls_init_align, tls_init_offset; 5246 5247 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) 5248 return (oldtcb); 5249 5250 assert(tcbsize >= TLS_TCB_SIZE); 5251 maxalign = MAX(tcbalign, tls_static_max_align); 5252 tls_init_align = MAX(obj_main->tlsalign, 1); 5253 5254 /* Compute fragmets sizes. */ 5255 extra_size = tcbsize - TLS_TCB_SIZE; 5256 post_size = calculate_tls_post_size(tls_init_align); 5257 tls_block_size = tcbsize + post_size; 5258 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 5259 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size; 5260 5261 /* Allocate whole TLS block */ 5262 tls_block = malloc_aligned(tls_block_size, maxalign, 0); 5263 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size); 5264 5265 if (oldtcb != NULL) { 5266 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize), 5267 tls_static_space); 5268 free_aligned(get_tls_block_ptr(oldtcb, tcbsize)); 5269 5270 /* Adjust the DTV. */ 5271 dtv = tcb[0]; 5272 for (i = 0; i < dtv[1]; i++) { 5273 if (dtv[i+2] >= (Elf_Addr)oldtcb && 5274 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) { 5275 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb; 5276 } 5277 } 5278 } else { 5279 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5280 tcb[0] = dtv; 5281 dtv[0] = tls_dtv_generation; 5282 dtv[1] = tls_max_index; 5283 5284 for (obj = globallist_curr(objs); obj != NULL; 5285 obj = globallist_next(obj)) { 5286 if (obj->tlsoffset == 0) 5287 continue; 5288 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1); 5289 addr = (Elf_Addr)tcb + obj->tlsoffset; 5290 if (tls_init_offset > 0) 5291 memset((void *)addr, 0, tls_init_offset); 5292 if (obj->tlsinitsize > 0) { 5293 memcpy((void *)(addr + tls_init_offset), obj->tlsinit, 5294 obj->tlsinitsize); 5295 } 5296 if (obj->tlssize > obj->tlsinitsize) { 5297 memset((void *)(addr + tls_init_offset + obj->tlsinitsize), 5298 0, obj->tlssize - obj->tlsinitsize - tls_init_offset); 5299 } 5300 dtv[obj->tlsindex + 1] = addr; 5301 } 5302 } 5303 5304 return (tcb); 5305 } 5306 5307 void 5308 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused) 5309 { 5310 Elf_Addr *dtv; 5311 Elf_Addr tlsstart, tlsend; 5312 size_t post_size; 5313 size_t dtvsize, i, tls_init_align; 5314 5315 assert(tcbsize >= TLS_TCB_SIZE); 5316 tls_init_align = MAX(obj_main->tlsalign, 1); 5317 5318 /* Compute fragments sizes. */ 5319 post_size = calculate_tls_post_size(tls_init_align); 5320 5321 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size; 5322 tlsend = (Elf_Addr)tcb + tls_static_space; 5323 5324 dtv = *(Elf_Addr **)tcb; 5325 dtvsize = dtv[1]; 5326 for (i = 0; i < dtvsize; i++) { 5327 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) { 5328 free((void*)dtv[i+2]); 5329 } 5330 } 5331 free(dtv); 5332 free_aligned(get_tls_block_ptr(tcb, tcbsize)); 5333 } 5334 5335 #endif /* TLS_VARIANT_I */ 5336 5337 #ifdef TLS_VARIANT_II 5338 5339 /* 5340 * Allocate Static TLS using the Variant II method. 5341 */ 5342 void * 5343 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 5344 { 5345 Obj_Entry *obj; 5346 size_t size, ralign; 5347 char *tls; 5348 Elf_Addr *dtv, *olddtv; 5349 Elf_Addr segbase, oldsegbase, addr; 5350 size_t i; 5351 5352 ralign = tcbalign; 5353 if (tls_static_max_align > ralign) 5354 ralign = tls_static_max_align; 5355 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign); 5356 5357 assert(tcbsize >= 2*sizeof(Elf_Addr)); 5358 tls = malloc_aligned(size, ralign, 0 /* XXX */); 5359 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5360 5361 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign)); 5362 ((Elf_Addr *)segbase)[0] = segbase; 5363 ((Elf_Addr *)segbase)[1] = (Elf_Addr) dtv; 5364 5365 dtv[0] = tls_dtv_generation; 5366 dtv[1] = tls_max_index; 5367 5368 if (oldtls) { 5369 /* 5370 * Copy the static TLS block over whole. 5371 */ 5372 oldsegbase = (Elf_Addr) oldtls; 5373 memcpy((void *)(segbase - tls_static_space), 5374 (const void *)(oldsegbase - tls_static_space), 5375 tls_static_space); 5376 5377 /* 5378 * If any dynamic TLS blocks have been created tls_get_addr(), 5379 * move them over. 5380 */ 5381 olddtv = ((Elf_Addr **)oldsegbase)[1]; 5382 for (i = 0; i < olddtv[1]; i++) { 5383 if (olddtv[i + 2] < oldsegbase - size || 5384 olddtv[i + 2] > oldsegbase) { 5385 dtv[i + 2] = olddtv[i + 2]; 5386 olddtv[i + 2] = 0; 5387 } 5388 } 5389 5390 /* 5391 * We assume that this block was the one we created with 5392 * allocate_initial_tls(). 5393 */ 5394 free_tls(oldtls, 2 * sizeof(Elf_Addr), sizeof(Elf_Addr)); 5395 } else { 5396 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5397 if (obj->marker || obj->tlsoffset == 0) 5398 continue; 5399 addr = segbase - obj->tlsoffset; 5400 memset((void *)(addr + obj->tlsinitsize), 5401 0, obj->tlssize - obj->tlsinitsize); 5402 if (obj->tlsinit) { 5403 memcpy((void *)addr, obj->tlsinit, obj->tlsinitsize); 5404 obj->static_tls_copied = true; 5405 } 5406 dtv[obj->tlsindex + 1] = addr; 5407 } 5408 } 5409 5410 return ((void *)segbase); 5411 } 5412 5413 void 5414 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign) 5415 { 5416 Elf_Addr* dtv; 5417 size_t size, ralign; 5418 int dtvsize, i; 5419 Elf_Addr tlsstart, tlsend; 5420 5421 /* 5422 * Figure out the size of the initial TLS block so that we can 5423 * find stuff which ___tls_get_addr() allocated dynamically. 5424 */ 5425 ralign = tcbalign; 5426 if (tls_static_max_align > ralign) 5427 ralign = tls_static_max_align; 5428 size = roundup(tls_static_space, ralign); 5429 5430 dtv = ((Elf_Addr **)tls)[1]; 5431 dtvsize = dtv[1]; 5432 tlsend = (Elf_Addr)tls; 5433 tlsstart = tlsend - size; 5434 for (i = 0; i < dtvsize; i++) { 5435 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || 5436 dtv[i + 2] > tlsend)) { 5437 free_aligned((void *)dtv[i + 2]); 5438 } 5439 } 5440 5441 free_aligned((void *)tlsstart); 5442 free((void *)dtv); 5443 } 5444 5445 #endif /* TLS_VARIANT_II */ 5446 5447 /* 5448 * Allocate TLS block for module with given index. 5449 */ 5450 void * 5451 allocate_module_tls(int index) 5452 { 5453 Obj_Entry *obj; 5454 char *p; 5455 5456 TAILQ_FOREACH(obj, &obj_list, next) { 5457 if (obj->marker) 5458 continue; 5459 if (obj->tlsindex == index) 5460 break; 5461 } 5462 if (obj == NULL) { 5463 _rtld_error("Can't find module with TLS index %d", index); 5464 rtld_die(); 5465 } 5466 5467 p = malloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset); 5468 memcpy(p, obj->tlsinit, obj->tlsinitsize); 5469 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 5470 return (p); 5471 } 5472 5473 bool 5474 allocate_tls_offset(Obj_Entry *obj) 5475 { 5476 size_t off; 5477 5478 if (obj->tls_done) 5479 return (true); 5480 5481 if (obj->tlssize == 0) { 5482 obj->tls_done = true; 5483 return (true); 5484 } 5485 5486 if (tls_last_offset == 0) 5487 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign, 5488 obj->tlspoffset); 5489 else 5490 off = calculate_tls_offset(tls_last_offset, tls_last_size, 5491 obj->tlssize, obj->tlsalign, obj->tlspoffset); 5492 5493 obj->tlsoffset = off; 5494 #ifdef TLS_VARIANT_I 5495 off += obj->tlssize; 5496 #endif 5497 5498 /* 5499 * If we have already fixed the size of the static TLS block, we 5500 * must stay within that size. When allocating the static TLS, we 5501 * leave a small amount of space spare to be used for dynamically 5502 * loading modules which use static TLS. 5503 */ 5504 if (tls_static_space != 0) { 5505 if (off > tls_static_space) 5506 return (false); 5507 } else if (obj->tlsalign > tls_static_max_align) { 5508 tls_static_max_align = obj->tlsalign; 5509 } 5510 5511 tls_last_offset = off; 5512 tls_last_size = obj->tlssize; 5513 obj->tls_done = true; 5514 5515 return (true); 5516 } 5517 5518 void 5519 free_tls_offset(Obj_Entry *obj) 5520 { 5521 5522 /* 5523 * If we were the last thing to allocate out of the static TLS 5524 * block, we give our space back to the 'allocator'. This is a 5525 * simplistic workaround to allow libGL.so.1 to be loaded and 5526 * unloaded multiple times. 5527 */ 5528 size_t off = obj->tlsoffset; 5529 #ifdef TLS_VARIANT_I 5530 off += obj->tlssize; 5531 #endif 5532 if (off == tls_last_offset) { 5533 tls_last_offset -= obj->tlssize; 5534 tls_last_size = 0; 5535 } 5536 } 5537 5538 void * 5539 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) 5540 { 5541 void *ret; 5542 RtldLockState lockstate; 5543 5544 wlock_acquire(rtld_bind_lock, &lockstate); 5545 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls, 5546 tcbsize, tcbalign); 5547 lock_release(rtld_bind_lock, &lockstate); 5548 return (ret); 5549 } 5550 5551 void 5552 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 5553 { 5554 RtldLockState lockstate; 5555 5556 wlock_acquire(rtld_bind_lock, &lockstate); 5557 free_tls(tcb, tcbsize, tcbalign); 5558 lock_release(rtld_bind_lock, &lockstate); 5559 } 5560 5561 static void 5562 object_add_name(Obj_Entry *obj, const char *name) 5563 { 5564 Name_Entry *entry; 5565 size_t len; 5566 5567 len = strlen(name); 5568 entry = malloc(sizeof(Name_Entry) + len); 5569 5570 if (entry != NULL) { 5571 strcpy(entry->name, name); 5572 STAILQ_INSERT_TAIL(&obj->names, entry, link); 5573 } 5574 } 5575 5576 static int 5577 object_match_name(const Obj_Entry *obj, const char *name) 5578 { 5579 Name_Entry *entry; 5580 5581 STAILQ_FOREACH(entry, &obj->names, link) { 5582 if (strcmp(name, entry->name) == 0) 5583 return (1); 5584 } 5585 return (0); 5586 } 5587 5588 static Obj_Entry * 5589 locate_dependency(const Obj_Entry *obj, const char *name) 5590 { 5591 const Objlist_Entry *entry; 5592 const Needed_Entry *needed; 5593 5594 STAILQ_FOREACH(entry, &list_main, link) { 5595 if (object_match_name(entry->obj, name)) 5596 return (entry->obj); 5597 } 5598 5599 for (needed = obj->needed; needed != NULL; needed = needed->next) { 5600 if (strcmp(obj->strtab + needed->name, name) == 0 || 5601 (needed->obj != NULL && object_match_name(needed->obj, name))) { 5602 /* 5603 * If there is DT_NEEDED for the name we are looking for, 5604 * we are all set. Note that object might not be found if 5605 * dependency was not loaded yet, so the function can 5606 * return NULL here. This is expected and handled 5607 * properly by the caller. 5608 */ 5609 return (needed->obj); 5610 } 5611 } 5612 _rtld_error("%s: Unexpected inconsistency: dependency %s not found", 5613 obj->path, name); 5614 rtld_die(); 5615 } 5616 5617 static int 5618 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj, 5619 const Elf_Vernaux *vna) 5620 { 5621 const Elf_Verdef *vd; 5622 const char *vername; 5623 5624 vername = refobj->strtab + vna->vna_name; 5625 vd = depobj->verdef; 5626 if (vd == NULL) { 5627 _rtld_error("%s: version %s required by %s not defined", 5628 depobj->path, vername, refobj->path); 5629 return (-1); 5630 } 5631 for (;;) { 5632 if (vd->vd_version != VER_DEF_CURRENT) { 5633 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5634 depobj->path, vd->vd_version); 5635 return (-1); 5636 } 5637 if (vna->vna_hash == vd->vd_hash) { 5638 const Elf_Verdaux *aux = (const Elf_Verdaux *) 5639 ((const char *)vd + vd->vd_aux); 5640 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0) 5641 return (0); 5642 } 5643 if (vd->vd_next == 0) 5644 break; 5645 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5646 } 5647 if (vna->vna_flags & VER_FLG_WEAK) 5648 return (0); 5649 _rtld_error("%s: version %s required by %s not found", 5650 depobj->path, vername, refobj->path); 5651 return (-1); 5652 } 5653 5654 static int 5655 rtld_verify_object_versions(Obj_Entry *obj) 5656 { 5657 const Elf_Verneed *vn; 5658 const Elf_Verdef *vd; 5659 const Elf_Verdaux *vda; 5660 const Elf_Vernaux *vna; 5661 const Obj_Entry *depobj; 5662 int maxvernum, vernum; 5663 5664 if (obj->ver_checked) 5665 return (0); 5666 obj->ver_checked = true; 5667 5668 maxvernum = 0; 5669 /* 5670 * Walk over defined and required version records and figure out 5671 * max index used by any of them. Do very basic sanity checking 5672 * while there. 5673 */ 5674 vn = obj->verneed; 5675 while (vn != NULL) { 5676 if (vn->vn_version != VER_NEED_CURRENT) { 5677 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry", 5678 obj->path, vn->vn_version); 5679 return (-1); 5680 } 5681 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 5682 for (;;) { 5683 vernum = VER_NEED_IDX(vna->vna_other); 5684 if (vernum > maxvernum) 5685 maxvernum = vernum; 5686 if (vna->vna_next == 0) 5687 break; 5688 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next); 5689 } 5690 if (vn->vn_next == 0) 5691 break; 5692 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 5693 } 5694 5695 vd = obj->verdef; 5696 while (vd != NULL) { 5697 if (vd->vd_version != VER_DEF_CURRENT) { 5698 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5699 obj->path, vd->vd_version); 5700 return (-1); 5701 } 5702 vernum = VER_DEF_IDX(vd->vd_ndx); 5703 if (vernum > maxvernum) 5704 maxvernum = vernum; 5705 if (vd->vd_next == 0) 5706 break; 5707 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5708 } 5709 5710 if (maxvernum == 0) 5711 return (0); 5712 5713 /* 5714 * Store version information in array indexable by version index. 5715 * Verify that object version requirements are satisfied along the 5716 * way. 5717 */ 5718 obj->vernum = maxvernum + 1; 5719 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry)); 5720 5721 vd = obj->verdef; 5722 while (vd != NULL) { 5723 if ((vd->vd_flags & VER_FLG_BASE) == 0) { 5724 vernum = VER_DEF_IDX(vd->vd_ndx); 5725 assert(vernum <= maxvernum); 5726 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux); 5727 obj->vertab[vernum].hash = vd->vd_hash; 5728 obj->vertab[vernum].name = obj->strtab + vda->vda_name; 5729 obj->vertab[vernum].file = NULL; 5730 obj->vertab[vernum].flags = 0; 5731 } 5732 if (vd->vd_next == 0) 5733 break; 5734 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5735 } 5736 5737 vn = obj->verneed; 5738 while (vn != NULL) { 5739 depobj = locate_dependency(obj, obj->strtab + vn->vn_file); 5740 if (depobj == NULL) 5741 return (-1); 5742 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 5743 for (;;) { 5744 if (check_object_provided_version(obj, depobj, vna)) 5745 return (-1); 5746 vernum = VER_NEED_IDX(vna->vna_other); 5747 assert(vernum <= maxvernum); 5748 obj->vertab[vernum].hash = vna->vna_hash; 5749 obj->vertab[vernum].name = obj->strtab + vna->vna_name; 5750 obj->vertab[vernum].file = obj->strtab + vn->vn_file; 5751 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ? 5752 VER_INFO_HIDDEN : 0; 5753 if (vna->vna_next == 0) 5754 break; 5755 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next); 5756 } 5757 if (vn->vn_next == 0) 5758 break; 5759 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 5760 } 5761 return (0); 5762 } 5763 5764 static int 5765 rtld_verify_versions(const Objlist *objlist) 5766 { 5767 Objlist_Entry *entry; 5768 int rc; 5769 5770 rc = 0; 5771 STAILQ_FOREACH(entry, objlist, link) { 5772 /* 5773 * Skip dummy objects or objects that have their version requirements 5774 * already checked. 5775 */ 5776 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL) 5777 continue; 5778 if (rtld_verify_object_versions(entry->obj) == -1) { 5779 rc = -1; 5780 if (ld_tracing == NULL) 5781 break; 5782 } 5783 } 5784 if (rc == 0 || ld_tracing != NULL) 5785 rc = rtld_verify_object_versions(&obj_rtld); 5786 return (rc); 5787 } 5788 5789 const Ver_Entry * 5790 fetch_ventry(const Obj_Entry *obj, unsigned long symnum) 5791 { 5792 Elf_Versym vernum; 5793 5794 if (obj->vertab) { 5795 vernum = VER_NDX(obj->versyms[symnum]); 5796 if (vernum >= obj->vernum) { 5797 _rtld_error("%s: symbol %s has wrong verneed value %d", 5798 obj->path, obj->strtab + symnum, vernum); 5799 } else if (obj->vertab[vernum].hash != 0) { 5800 return (&obj->vertab[vernum]); 5801 } 5802 } 5803 return (NULL); 5804 } 5805 5806 int 5807 _rtld_get_stack_prot(void) 5808 { 5809 5810 return (stack_prot); 5811 } 5812 5813 int 5814 _rtld_is_dlopened(void *arg) 5815 { 5816 Obj_Entry *obj; 5817 RtldLockState lockstate; 5818 int res; 5819 5820 rlock_acquire(rtld_bind_lock, &lockstate); 5821 obj = dlcheck(arg); 5822 if (obj == NULL) 5823 obj = obj_from_addr(arg); 5824 if (obj == NULL) { 5825 _rtld_error("No shared object contains address"); 5826 lock_release(rtld_bind_lock, &lockstate); 5827 return (-1); 5828 } 5829 res = obj->dlopened ? 1 : 0; 5830 lock_release(rtld_bind_lock, &lockstate); 5831 return (res); 5832 } 5833 5834 static int 5835 obj_remap_relro(Obj_Entry *obj, int prot) 5836 { 5837 5838 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size, 5839 prot) == -1) { 5840 _rtld_error("%s: Cannot set relro protection to %#x: %s", 5841 obj->path, prot, rtld_strerror(errno)); 5842 return (-1); 5843 } 5844 return (0); 5845 } 5846 5847 static int 5848 obj_disable_relro(Obj_Entry *obj) 5849 { 5850 5851 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE)); 5852 } 5853 5854 static int 5855 obj_enforce_relro(Obj_Entry *obj) 5856 { 5857 5858 return (obj_remap_relro(obj, PROT_READ)); 5859 } 5860 5861 static void 5862 map_stacks_exec(RtldLockState *lockstate) 5863 { 5864 void (*thr_map_stacks_exec)(void); 5865 5866 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0) 5867 return; 5868 thr_map_stacks_exec = (void (*)(void))(uintptr_t) 5869 get_program_var_addr("__pthread_map_stacks_exec", lockstate); 5870 if (thr_map_stacks_exec != NULL) { 5871 stack_prot |= PROT_EXEC; 5872 thr_map_stacks_exec(); 5873 } 5874 } 5875 5876 static void 5877 distribute_static_tls(Objlist *list, RtldLockState *lockstate) 5878 { 5879 Objlist_Entry *elm; 5880 Obj_Entry *obj; 5881 void (*distrib)(size_t, void *, size_t, size_t); 5882 5883 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t) 5884 get_program_var_addr("__pthread_distribute_static_tls", lockstate); 5885 if (distrib == NULL) 5886 return; 5887 STAILQ_FOREACH(elm, list, link) { 5888 obj = elm->obj; 5889 if (obj->marker || !obj->tls_done || obj->static_tls_copied) 5890 continue; 5891 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize, 5892 obj->tlssize); 5893 obj->static_tls_copied = true; 5894 } 5895 } 5896 5897 void 5898 symlook_init(SymLook *dst, const char *name) 5899 { 5900 5901 bzero(dst, sizeof(*dst)); 5902 dst->name = name; 5903 dst->hash = elf_hash(name); 5904 dst->hash_gnu = gnu_hash(name); 5905 } 5906 5907 static void 5908 symlook_init_from_req(SymLook *dst, const SymLook *src) 5909 { 5910 5911 dst->name = src->name; 5912 dst->hash = src->hash; 5913 dst->hash_gnu = src->hash_gnu; 5914 dst->ventry = src->ventry; 5915 dst->flags = src->flags; 5916 dst->defobj_out = NULL; 5917 dst->sym_out = NULL; 5918 dst->lockstate = src->lockstate; 5919 } 5920 5921 static int 5922 open_binary_fd(const char *argv0, bool search_in_path, 5923 const char **binpath_res) 5924 { 5925 char *binpath, *pathenv, *pe, *res1; 5926 const char *res; 5927 int fd; 5928 5929 binpath = NULL; 5930 res = NULL; 5931 if (search_in_path && strchr(argv0, '/') == NULL) { 5932 binpath = xmalloc(PATH_MAX); 5933 pathenv = getenv("PATH"); 5934 if (pathenv == NULL) { 5935 _rtld_error("-p and no PATH environment variable"); 5936 rtld_die(); 5937 } 5938 pathenv = strdup(pathenv); 5939 if (pathenv == NULL) { 5940 _rtld_error("Cannot allocate memory"); 5941 rtld_die(); 5942 } 5943 fd = -1; 5944 errno = ENOENT; 5945 while ((pe = strsep(&pathenv, ":")) != NULL) { 5946 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX) 5947 continue; 5948 if (binpath[0] != '\0' && 5949 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX) 5950 continue; 5951 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX) 5952 continue; 5953 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY); 5954 if (fd != -1 || errno != ENOENT) { 5955 res = binpath; 5956 break; 5957 } 5958 } 5959 free(pathenv); 5960 } else { 5961 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY); 5962 res = argv0; 5963 } 5964 5965 if (fd == -1) { 5966 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno)); 5967 rtld_die(); 5968 } 5969 if (res != NULL && res[0] != '/') { 5970 res1 = xmalloc(PATH_MAX); 5971 if (realpath(res, res1) != NULL) { 5972 if (res != argv0) 5973 free(__DECONST(char *, res)); 5974 res = res1; 5975 } else { 5976 free(res1); 5977 } 5978 } 5979 *binpath_res = res; 5980 return (fd); 5981 } 5982 5983 /* 5984 * Parse a set of command-line arguments. 5985 */ 5986 static int 5987 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp, 5988 const char **argv0, bool *dir_ignore) 5989 { 5990 const char *arg; 5991 char machine[64]; 5992 size_t sz; 5993 int arglen, fd, i, j, mib[2]; 5994 char opt; 5995 bool seen_b, seen_f; 5996 5997 dbg("Parsing command-line arguments"); 5998 *use_pathp = false; 5999 *fdp = -1; 6000 *dir_ignore = false; 6001 seen_b = seen_f = false; 6002 6003 for (i = 1; i < argc; i++ ) { 6004 arg = argv[i]; 6005 dbg("argv[%d]: '%s'", i, arg); 6006 6007 /* 6008 * rtld arguments end with an explicit "--" or with the first 6009 * non-prefixed argument. 6010 */ 6011 if (strcmp(arg, "--") == 0) { 6012 i++; 6013 break; 6014 } 6015 if (arg[0] != '-') 6016 break; 6017 6018 /* 6019 * All other arguments are single-character options that can 6020 * be combined, so we need to search through `arg` for them. 6021 */ 6022 arglen = strlen(arg); 6023 for (j = 1; j < arglen; j++) { 6024 opt = arg[j]; 6025 if (opt == 'h') { 6026 print_usage(argv[0]); 6027 _exit(0); 6028 } else if (opt == 'b') { 6029 if (seen_f) { 6030 _rtld_error("Both -b and -f specified"); 6031 rtld_die(); 6032 } 6033 i++; 6034 *argv0 = argv[i]; 6035 seen_b = true; 6036 break; 6037 } else if (opt == 'd') { 6038 *dir_ignore = true; 6039 break; 6040 } else if (opt == 'f') { 6041 if (seen_b) { 6042 _rtld_error("Both -b and -f specified"); 6043 rtld_die(); 6044 } 6045 6046 /* 6047 * -f XX can be used to specify a 6048 * descriptor for the binary named at 6049 * the command line (i.e., the later 6050 * argument will specify the process 6051 * name but the descriptor is what 6052 * will actually be executed). 6053 * 6054 * -f must be the last option in, e.g., -abcf. 6055 */ 6056 if (j != arglen - 1) { 6057 _rtld_error("Invalid options: %s", arg); 6058 rtld_die(); 6059 } 6060 i++; 6061 fd = parse_integer(argv[i]); 6062 if (fd == -1) { 6063 _rtld_error( 6064 "Invalid file descriptor: '%s'", 6065 argv[i]); 6066 rtld_die(); 6067 } 6068 *fdp = fd; 6069 seen_f = true; 6070 break; 6071 } else if (opt == 'p') { 6072 *use_pathp = true; 6073 } else if (opt == 'u') { 6074 trust = false; 6075 } else if (opt == 'v') { 6076 machine[0] = '\0'; 6077 mib[0] = CTL_HW; 6078 mib[1] = HW_MACHINE; 6079 sz = sizeof(machine); 6080 sysctl(mib, nitems(mib), machine, &sz, NULL, 0); 6081 ld_elf_hints_path = ld_get_env_var( 6082 LD_ELF_HINTS_PATH); 6083 set_ld_elf_hints_path(); 6084 rtld_printf( 6085 "FreeBSD ld-elf.so.1 %s\n" 6086 "FreeBSD_version %d\n" 6087 "Default lib path %s\n" 6088 "Hints lib path %s\n" 6089 "Env prefix %s\n" 6090 "Default hint file %s\n" 6091 "Hint file %s\n" 6092 "libmap file %s\n", 6093 machine, 6094 __FreeBSD_version, ld_standard_library_path, 6095 gethints(false), 6096 ld_env_prefix, ld_elf_hints_default, 6097 ld_elf_hints_path, 6098 ld_path_libmap_conf); 6099 _exit(0); 6100 } else { 6101 _rtld_error("Invalid argument: '%s'", arg); 6102 print_usage(argv[0]); 6103 rtld_die(); 6104 } 6105 } 6106 } 6107 6108 if (!seen_b) 6109 *argv0 = argv[i]; 6110 return (i); 6111 } 6112 6113 /* 6114 * Parse a file descriptor number without pulling in more of libc (e.g. atoi). 6115 */ 6116 static int 6117 parse_integer(const char *str) 6118 { 6119 static const int RADIX = 10; /* XXXJA: possibly support hex? */ 6120 const char *orig; 6121 int n; 6122 char c; 6123 6124 orig = str; 6125 n = 0; 6126 for (c = *str; c != '\0'; c = *++str) { 6127 if (c < '0' || c > '9') 6128 return (-1); 6129 6130 n *= RADIX; 6131 n += c - '0'; 6132 } 6133 6134 /* Make sure we actually parsed something. */ 6135 if (str == orig) 6136 return (-1); 6137 return (n); 6138 } 6139 6140 static void 6141 print_usage(const char *argv0) 6142 { 6143 6144 rtld_printf( 6145 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n" 6146 "\n" 6147 "Options:\n" 6148 " -h Display this help message\n" 6149 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n" 6150 " -d Ignore lack of exec permissions for the binary\n" 6151 " -f <FD> Execute <FD> instead of searching for <binary>\n" 6152 " -p Search in PATH for named binary\n" 6153 " -u Ignore LD_ environment variables\n" 6154 " -v Display identification information\n" 6155 " -- End of RTLD options\n" 6156 " <binary> Name of process to execute\n" 6157 " <args> Arguments to the executed process\n", argv0); 6158 } 6159 6160 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt } 6161 static const struct auxfmt { 6162 const char *name; 6163 const char *fmt; 6164 } auxfmts[] = { 6165 AUXFMT(AT_NULL, NULL), 6166 AUXFMT(AT_IGNORE, NULL), 6167 AUXFMT(AT_EXECFD, "%ld"), 6168 AUXFMT(AT_PHDR, "%p"), 6169 AUXFMT(AT_PHENT, "%lu"), 6170 AUXFMT(AT_PHNUM, "%lu"), 6171 AUXFMT(AT_PAGESZ, "%lu"), 6172 AUXFMT(AT_BASE, "%#lx"), 6173 AUXFMT(AT_FLAGS, "%#lx"), 6174 AUXFMT(AT_ENTRY, "%p"), 6175 AUXFMT(AT_NOTELF, NULL), 6176 AUXFMT(AT_UID, "%ld"), 6177 AUXFMT(AT_EUID, "%ld"), 6178 AUXFMT(AT_GID, "%ld"), 6179 AUXFMT(AT_EGID, "%ld"), 6180 AUXFMT(AT_EXECPATH, "%s"), 6181 AUXFMT(AT_CANARY, "%p"), 6182 AUXFMT(AT_CANARYLEN, "%lu"), 6183 AUXFMT(AT_OSRELDATE, "%lu"), 6184 AUXFMT(AT_NCPUS, "%lu"), 6185 AUXFMT(AT_PAGESIZES, "%p"), 6186 AUXFMT(AT_PAGESIZESLEN, "%lu"), 6187 AUXFMT(AT_TIMEKEEP, "%p"), 6188 AUXFMT(AT_STACKPROT, "%#lx"), 6189 AUXFMT(AT_EHDRFLAGS, "%#lx"), 6190 AUXFMT(AT_HWCAP, "%#lx"), 6191 AUXFMT(AT_HWCAP2, "%#lx"), 6192 AUXFMT(AT_BSDFLAGS, "%#lx"), 6193 AUXFMT(AT_ARGC, "%lu"), 6194 AUXFMT(AT_ARGV, "%p"), 6195 AUXFMT(AT_ENVC, "%p"), 6196 AUXFMT(AT_ENVV, "%p"), 6197 AUXFMT(AT_PS_STRINGS, "%p"), 6198 AUXFMT(AT_FXRNG, "%p"), 6199 AUXFMT(AT_KPRELOAD, "%p"), 6200 AUXFMT(AT_USRSTACKBASE, "%#lx"), 6201 AUXFMT(AT_USRSTACKLIM, "%#lx"), 6202 }; 6203 6204 static bool 6205 is_ptr_fmt(const char *fmt) 6206 { 6207 char last; 6208 6209 last = fmt[strlen(fmt) - 1]; 6210 return (last == 'p' || last == 's'); 6211 } 6212 6213 static void 6214 dump_auxv(Elf_Auxinfo **aux_info) 6215 { 6216 Elf_Auxinfo *auxp; 6217 const struct auxfmt *fmt; 6218 int i; 6219 6220 for (i = 0; i < AT_COUNT; i++) { 6221 auxp = aux_info[i]; 6222 if (auxp == NULL) 6223 continue; 6224 fmt = &auxfmts[i]; 6225 if (fmt->fmt == NULL) 6226 continue; 6227 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name); 6228 if (is_ptr_fmt(fmt->fmt)) { 6229 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt, 6230 auxp->a_un.a_ptr); 6231 } else { 6232 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt, 6233 auxp->a_un.a_val); 6234 } 6235 rtld_fdprintf(STDOUT_FILENO, "\n"); 6236 } 6237 } 6238 6239 /* 6240 * Overrides for libc_pic-provided functions. 6241 */ 6242 6243 int 6244 __getosreldate(void) 6245 { 6246 size_t len; 6247 int oid[2]; 6248 int error, osrel; 6249 6250 if (osreldate != 0) 6251 return (osreldate); 6252 6253 oid[0] = CTL_KERN; 6254 oid[1] = KERN_OSRELDATE; 6255 osrel = 0; 6256 len = sizeof(osrel); 6257 error = sysctl(oid, 2, &osrel, &len, NULL, 0); 6258 if (error == 0 && osrel > 0 && len == sizeof(osrel)) 6259 osreldate = osrel; 6260 return (osreldate); 6261 } 6262 const char * 6263 rtld_strerror(int errnum) 6264 { 6265 6266 if (errnum < 0 || errnum >= sys_nerr) 6267 return ("Unknown error"); 6268 return (sys_errlist[errnum]); 6269 } 6270 6271 char * 6272 getenv(const char *name) 6273 { 6274 return (__DECONST(char *, rtld_get_env_val(environ, name, 6275 strlen(name)))); 6276 } 6277 6278 /* malloc */ 6279 void * 6280 malloc(size_t nbytes) 6281 { 6282 6283 return (__crt_malloc(nbytes)); 6284 } 6285 6286 void * 6287 calloc(size_t num, size_t size) 6288 { 6289 6290 return (__crt_calloc(num, size)); 6291 } 6292 6293 void 6294 free(void *cp) 6295 { 6296 6297 __crt_free(cp); 6298 } 6299 6300 void * 6301 realloc(void *cp, size_t nbytes) 6302 { 6303 6304 return (__crt_realloc(cp, nbytes)); 6305 } 6306 6307 extern int _rtld_version__FreeBSD_version __exported; 6308 int _rtld_version__FreeBSD_version = __FreeBSD_version; 6309 6310 extern char _rtld_version_laddr_offset __exported; 6311 char _rtld_version_laddr_offset; 6312 6313 extern char _rtld_version_dlpi_tls_data __exported; 6314 char _rtld_version_dlpi_tls_data; 6315