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