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