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