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