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