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