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