1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause 3 * 4 * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra. 5 * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>. 6 * Copyright 2009-2013 Konstantin Belousov <kib@FreeBSD.ORG>. 7 * Copyright 2012 John Marino <draco@marino.st>. 8 * Copyright 2014-2017 The FreeBSD Foundation 9 * All rights reserved. 10 * 11 * Portions of this software were developed by Konstantin Belousov 12 * under sponsorship from the FreeBSD Foundation. 13 * 14 * Redistribution and use in source and binary forms, with or without 15 * modification, are permitted provided that the following conditions 16 * are met: 17 * 1. Redistributions of source code must retain the above copyright 18 * notice, this list of conditions and the following disclaimer. 19 * 2. Redistributions in binary form must reproduce the above copyright 20 * notice, this list of conditions and the following disclaimer in the 21 * documentation and/or other materials provided with the distribution. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 */ 34 35 /* 36 * Dynamic linker for ELF. 37 * 38 * John Polstra <jdp@polstra.com>. 39 */ 40 41 #include <sys/param.h> 42 #include <sys/mount.h> 43 #include <sys/mman.h> 44 #include <sys/stat.h> 45 #include <sys/sysctl.h> 46 #include <sys/uio.h> 47 #include <sys/utsname.h> 48 #include <sys/ktrace.h> 49 50 #include <dlfcn.h> 51 #include <err.h> 52 #include <errno.h> 53 #include <fcntl.h> 54 #include <stdarg.h> 55 #include <stdio.h> 56 #include <stdlib.h> 57 #include <string.h> 58 #include <unistd.h> 59 60 #include "debug.h" 61 #include "rtld.h" 62 #include "libmap.h" 63 #include "rtld_paths.h" 64 #include "rtld_tls.h" 65 #include "rtld_printf.h" 66 #include "rtld_malloc.h" 67 #include "rtld_utrace.h" 68 #include "notes.h" 69 #include "rtld_libc.h" 70 71 /* Types. */ 72 typedef void (*func_ptr_type)(void); 73 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg); 74 75 76 /* Variables that cannot be static: */ 77 extern struct r_debug r_debug; /* For GDB */ 78 extern int _thread_autoinit_dummy_decl; 79 extern void (*__cleanup)(void); 80 81 struct dlerror_save { 82 int seen; 83 char *msg; 84 }; 85 86 /* 87 * Function declarations. 88 */ 89 static const char *basename(const char *); 90 static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **, 91 const Elf_Dyn **, const Elf_Dyn **); 92 static bool digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *, 93 const Elf_Dyn *); 94 static bool digest_dynamic(Obj_Entry *, int); 95 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *); 96 static void distribute_static_tls(Objlist *, RtldLockState *); 97 static Obj_Entry *dlcheck(void *); 98 static int dlclose_locked(void *, RtldLockState *); 99 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj, 100 int lo_flags, int mode, RtldLockState *lockstate); 101 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int); 102 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *); 103 static bool donelist_check(DoneList *, const Obj_Entry *); 104 static void dump_auxv(Elf_Auxinfo **aux_info); 105 static void errmsg_restore(struct dlerror_save *); 106 static struct dlerror_save *errmsg_save(void); 107 static void *fill_search_info(const char *, size_t, void *); 108 static char *find_library(const char *, const Obj_Entry *, int *); 109 static const char *gethints(bool); 110 static void hold_object(Obj_Entry *); 111 static void unhold_object(Obj_Entry *); 112 static void init_dag(Obj_Entry *); 113 static void init_marker(Obj_Entry *); 114 static void init_pagesizes(Elf_Auxinfo **aux_info); 115 static void init_rtld(caddr_t, Elf_Auxinfo **); 116 static void initlist_add_neededs(Needed_Entry *, Objlist *); 117 static void initlist_add_objects(Obj_Entry *, Obj_Entry *, Objlist *); 118 static int initlist_objects_ifunc(Objlist *, bool, int, RtldLockState *); 119 static void linkmap_add(Obj_Entry *); 120 static void linkmap_delete(Obj_Entry *); 121 static void load_filtees(Obj_Entry *, int flags, RtldLockState *); 122 static void unload_filtees(Obj_Entry *, RtldLockState *); 123 static int load_needed_objects(Obj_Entry *, int); 124 static int load_preload_objects(const char *, bool); 125 static int load_kpreload(const void *addr); 126 static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int); 127 static void map_stacks_exec(RtldLockState *); 128 static int obj_disable_relro(Obj_Entry *); 129 static int obj_enforce_relro(Obj_Entry *); 130 static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *); 131 static void objlist_call_init(Objlist *, RtldLockState *); 132 static void objlist_clear(Objlist *); 133 static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *); 134 static void objlist_init(Objlist *); 135 static void objlist_push_head(Objlist *, Obj_Entry *); 136 static void objlist_push_tail(Objlist *, Obj_Entry *); 137 static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *); 138 static void objlist_remove(Objlist *, Obj_Entry *); 139 static int open_binary_fd(const char *argv0, bool search_in_path, 140 const char **binpath_res); 141 static int parse_args(char* argv[], int argc, bool *use_pathp, int *fdp, 142 const char **argv0, bool *dir_ignore); 143 static int parse_integer(const char *); 144 static void *path_enumerate(const char *, path_enum_proc, const char *, void *); 145 static void print_usage(const char *argv0); 146 static void release_object(Obj_Entry *); 147 static int relocate_object_dag(Obj_Entry *root, bool bind_now, 148 Obj_Entry *rtldobj, int flags, RtldLockState *lockstate); 149 static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, 150 int flags, RtldLockState *lockstate); 151 static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int, 152 RtldLockState *); 153 static int resolve_object_ifunc(Obj_Entry *, bool, int, RtldLockState *); 154 static int rtld_dirname(const char *, char *); 155 static int rtld_dirname_abs(const char *, char *); 156 static void *rtld_dlopen(const char *name, int fd, int mode); 157 static void rtld_exit(void); 158 static void rtld_nop_exit(void); 159 static char *search_library_path(const char *, const char *, const char *, 160 int *); 161 static char *search_library_pathfds(const char *, const char *, int *); 162 static const void **get_program_var_addr(const char *, RtldLockState *); 163 static void set_program_var(const char *, const void *); 164 static int symlook_default(SymLook *, const Obj_Entry *refobj); 165 static int symlook_global(SymLook *, DoneList *); 166 static void symlook_init_from_req(SymLook *, const SymLook *); 167 static int symlook_list(SymLook *, const Objlist *, DoneList *); 168 static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *); 169 static int symlook_obj1_sysv(SymLook *, const Obj_Entry *); 170 static int symlook_obj1_gnu(SymLook *, const Obj_Entry *); 171 static void *tls_get_addr_slow(Elf_Addr **, int, size_t, bool) __noinline; 172 static void trace_loaded_objects(Obj_Entry *, bool); 173 static void unlink_object(Obj_Entry *); 174 static void unload_object(Obj_Entry *, RtldLockState *lockstate); 175 static void unref_dag(Obj_Entry *); 176 static void ref_dag(Obj_Entry *); 177 static char *origin_subst_one(Obj_Entry *, char *, const char *, 178 const char *, bool); 179 static char *origin_subst(Obj_Entry *, const char *); 180 static bool obj_resolve_origin(Obj_Entry *obj); 181 static void preinit_main(void); 182 static int rtld_verify_versions(const Objlist *); 183 static int rtld_verify_object_versions(Obj_Entry *); 184 static void object_add_name(Obj_Entry *, const char *); 185 static int object_match_name(const Obj_Entry *, const char *); 186 static void ld_utrace_log(int, void *, void *, size_t, int, const char *); 187 static void rtld_fill_dl_phdr_info(const Obj_Entry *obj, 188 struct dl_phdr_info *phdr_info); 189 static uint32_t gnu_hash(const char *); 190 static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *, 191 const unsigned long); 192 193 void r_debug_state(struct r_debug *, struct link_map *) __noinline __exported; 194 void _r_debug_postinit(struct link_map *) __noinline __exported; 195 196 int __sys_openat(int, const char *, int, ...); 197 198 /* 199 * Data declarations. 200 */ 201 struct r_debug r_debug __exported; /* for GDB; */ 202 static bool libmap_disable; /* Disable libmap */ 203 static bool ld_loadfltr; /* Immediate filters processing */ 204 static const char *libmap_override;/* Maps to use in addition to libmap.conf */ 205 static bool trust; /* False for setuid and setgid programs */ 206 static bool dangerous_ld_env; /* True if environment variables have been 207 used to affect the libraries loaded */ 208 bool ld_bind_not; /* Disable PLT update */ 209 static const char *ld_bind_now; /* Environment variable for immediate binding */ 210 static const char *ld_debug; /* Environment variable for debugging */ 211 static bool ld_dynamic_weak = true; /* True if non-weak definition overrides 212 weak definition */ 213 static const char *ld_library_path;/* Environment variable for search path */ 214 static const char *ld_library_dirs;/* Environment variable for library descriptors */ 215 static const char *ld_preload; /* Environment variable for libraries to 216 load first */ 217 static const char *ld_preload_fds;/* Environment variable for libraries represented by 218 descriptors */ 219 static const char *ld_elf_hints_path; /* Environment variable for alternative hints path */ 220 static const char *ld_tracing; /* Called from ldd to print libs */ 221 static const char *ld_utrace; /* Use utrace() to log events. */ 222 static struct obj_entry_q obj_list; /* Queue of all loaded objects */ 223 static Obj_Entry *obj_main; /* The main program shared object */ 224 static Obj_Entry obj_rtld; /* The dynamic linker shared object */ 225 static unsigned int obj_count; /* Number of objects in obj_list */ 226 static unsigned int obj_loads; /* Number of loads of objects (gen count) */ 227 size_t ld_static_tls_extra = /* Static TLS extra space (bytes) */ 228 RTLD_STATIC_TLS_EXTRA; 229 230 static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */ 231 STAILQ_HEAD_INITIALIZER(list_global); 232 static Objlist list_main = /* Objects loaded at program startup */ 233 STAILQ_HEAD_INITIALIZER(list_main); 234 static Objlist list_fini = /* Objects needing fini() calls */ 235 STAILQ_HEAD_INITIALIZER(list_fini); 236 237 Elf_Sym sym_zero; /* For resolving undefined weak refs. */ 238 239 #define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m); 240 241 extern Elf_Dyn _DYNAMIC; 242 #pragma weak _DYNAMIC 243 244 int dlclose(void *) __exported; 245 char *dlerror(void) __exported; 246 void *dlopen(const char *, int) __exported; 247 void *fdlopen(int, int) __exported; 248 void *dlsym(void *, const char *) __exported; 249 dlfunc_t dlfunc(void *, const char *) __exported; 250 void *dlvsym(void *, const char *, const char *) __exported; 251 int dladdr(const void *, Dl_info *) __exported; 252 void dllockinit(void *, void *(*)(void *), void (*)(void *), void (*)(void *), 253 void (*)(void *), void (*)(void *), void (*)(void *)) __exported; 254 int dlinfo(void *, int , void *) __exported; 255 int dl_iterate_phdr(__dl_iterate_hdr_callback, void *) __exported; 256 int _rtld_addr_phdr(const void *, struct dl_phdr_info *) __exported; 257 int _rtld_get_stack_prot(void) __exported; 258 int _rtld_is_dlopened(void *) __exported; 259 void _rtld_error(const char *, ...) __exported; 260 261 /* Only here to fix -Wmissing-prototypes warnings */ 262 int __getosreldate(void); 263 func_ptr_type _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp); 264 Elf_Addr _rtld_bind(Obj_Entry *obj, Elf_Size reloff); 265 266 int npagesizes; 267 static int osreldate; 268 size_t *pagesizes; 269 size_t page_size; 270 271 static int stack_prot = PROT_READ | PROT_WRITE | PROT_EXEC; 272 static int max_stack_flags; 273 274 /* 275 * Global declarations normally provided by crt1. The dynamic linker is 276 * not built with crt1, so we have to provide them ourselves. 277 */ 278 char *__progname; 279 char **environ; 280 281 /* 282 * Used to pass argc, argv to init functions. 283 */ 284 int main_argc; 285 char **main_argv; 286 287 /* 288 * Globals to control TLS allocation. 289 */ 290 size_t tls_last_offset; /* Static TLS offset of last module */ 291 size_t tls_last_size; /* Static TLS size of last module */ 292 size_t tls_static_space; /* Static TLS space allocated */ 293 static size_t tls_static_max_align; 294 Elf_Addr tls_dtv_generation = 1; /* Used to detect when dtv size changes */ 295 int tls_max_index = 1; /* Largest module index allocated */ 296 297 static bool ld_library_path_rpath = false; 298 bool ld_fast_sigblock = false; 299 300 /* 301 * Globals for path names, and such 302 */ 303 const char *ld_elf_hints_default = _PATH_ELF_HINTS; 304 const char *ld_path_libmap_conf = _PATH_LIBMAP_CONF; 305 const char *ld_path_rtld = _PATH_RTLD; 306 const char *ld_standard_library_path = STANDARD_LIBRARY_PATH; 307 const char *ld_env_prefix = LD_; 308 309 static void (*rtld_exit_ptr)(void); 310 311 /* 312 * Fill in a DoneList with an allocation large enough to hold all of 313 * the currently-loaded objects. Keep this as a macro since it calls 314 * alloca and we want that to occur within the scope of the caller. 315 */ 316 #define donelist_init(dlp) \ 317 ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \ 318 assert((dlp)->objs != NULL), \ 319 (dlp)->num_alloc = obj_count, \ 320 (dlp)->num_used = 0) 321 322 #define LD_UTRACE(e, h, mb, ms, r, n) do { \ 323 if (ld_utrace != NULL) \ 324 ld_utrace_log(e, h, mb, ms, r, n); \ 325 } while (0) 326 327 static void 328 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize, 329 int refcnt, const char *name) 330 { 331 struct utrace_rtld ut; 332 static const char rtld_utrace_sig[RTLD_UTRACE_SIG_SZ] = RTLD_UTRACE_SIG; 333 334 memcpy(ut.sig, rtld_utrace_sig, sizeof(ut.sig)); 335 ut.event = event; 336 ut.handle = handle; 337 ut.mapbase = mapbase; 338 ut.mapsize = mapsize; 339 ut.refcnt = refcnt; 340 bzero(ut.name, sizeof(ut.name)); 341 if (name) 342 strlcpy(ut.name, name, sizeof(ut.name)); 343 utrace(&ut, sizeof(ut)); 344 } 345 346 enum { 347 LD_BIND_NOW = 0, 348 LD_PRELOAD, 349 LD_LIBMAP, 350 LD_LIBRARY_PATH, 351 LD_LIBRARY_PATH_FDS, 352 LD_LIBMAP_DISABLE, 353 LD_BIND_NOT, 354 LD_DEBUG, 355 LD_ELF_HINTS_PATH, 356 LD_LOADFLTR, 357 LD_LIBRARY_PATH_RPATH, 358 LD_PRELOAD_FDS, 359 LD_DYNAMIC_WEAK, 360 LD_TRACE_LOADED_OBJECTS, 361 LD_UTRACE, 362 LD_DUMP_REL_PRE, 363 LD_DUMP_REL_POST, 364 LD_TRACE_LOADED_OBJECTS_PROGNAME, 365 LD_TRACE_LOADED_OBJECTS_FMT1, 366 LD_TRACE_LOADED_OBJECTS_FMT2, 367 LD_TRACE_LOADED_OBJECTS_ALL, 368 LD_SHOW_AUXV, 369 LD_STATIC_TLS_EXTRA, 370 }; 371 372 struct ld_env_var_desc { 373 const char * const n; 374 const char *val; 375 const bool unsecure; 376 }; 377 #define LD_ENV_DESC(var, unsec) \ 378 [LD_##var] = { .n = #var, .unsecure = unsec } 379 380 static struct ld_env_var_desc ld_env_vars[] = { 381 LD_ENV_DESC(BIND_NOW, false), 382 LD_ENV_DESC(PRELOAD, true), 383 LD_ENV_DESC(LIBMAP, true), 384 LD_ENV_DESC(LIBRARY_PATH, true), 385 LD_ENV_DESC(LIBRARY_PATH_FDS, true), 386 LD_ENV_DESC(LIBMAP_DISABLE, true), 387 LD_ENV_DESC(BIND_NOT, true), 388 LD_ENV_DESC(DEBUG, true), 389 LD_ENV_DESC(ELF_HINTS_PATH, true), 390 LD_ENV_DESC(LOADFLTR, true), 391 LD_ENV_DESC(LIBRARY_PATH_RPATH, true), 392 LD_ENV_DESC(PRELOAD_FDS, true), 393 LD_ENV_DESC(DYNAMIC_WEAK, true), 394 LD_ENV_DESC(TRACE_LOADED_OBJECTS, false), 395 LD_ENV_DESC(UTRACE, false), 396 LD_ENV_DESC(DUMP_REL_PRE, false), 397 LD_ENV_DESC(DUMP_REL_POST, false), 398 LD_ENV_DESC(TRACE_LOADED_OBJECTS_PROGNAME, false), 399 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT1, false), 400 LD_ENV_DESC(TRACE_LOADED_OBJECTS_FMT2, false), 401 LD_ENV_DESC(TRACE_LOADED_OBJECTS_ALL, false), 402 LD_ENV_DESC(SHOW_AUXV, false), 403 LD_ENV_DESC(STATIC_TLS_EXTRA, false), 404 }; 405 406 static const char * 407 ld_get_env_var(int idx) 408 { 409 return (ld_env_vars[idx].val); 410 } 411 412 static const char * 413 rtld_get_env_val(char **env, const char *name, size_t name_len) 414 { 415 char **m, *n, *v; 416 417 for (m = env; *m != NULL; m++) { 418 n = *m; 419 v = strchr(n, '='); 420 if (v == NULL) { 421 /* corrupt environment? */ 422 continue; 423 } 424 if (v - n == (ptrdiff_t)name_len && 425 strncmp(name, n, name_len) == 0) 426 return (v + 1); 427 } 428 return (NULL); 429 } 430 431 static void 432 rtld_init_env_vars_for_prefix(char **env, const char *env_prefix) 433 { 434 struct ld_env_var_desc *lvd; 435 size_t prefix_len, nlen; 436 char **m, *n, *v; 437 int i; 438 439 prefix_len = strlen(env_prefix); 440 for (m = env; *m != NULL; m++) { 441 n = *m; 442 if (strncmp(env_prefix, n, prefix_len) != 0) { 443 /* Not a rtld environment variable. */ 444 continue; 445 } 446 n += prefix_len; 447 v = strchr(n, '='); 448 if (v == NULL) { 449 /* corrupt environment? */ 450 continue; 451 } 452 for (i = 0; i < (int)nitems(ld_env_vars); i++) { 453 lvd = &ld_env_vars[i]; 454 if (lvd->val != NULL) { 455 /* Saw higher-priority variable name already. */ 456 continue; 457 } 458 nlen = strlen(lvd->n); 459 if (v - n == (ptrdiff_t)nlen && 460 strncmp(lvd->n, n, nlen) == 0) { 461 lvd->val = v + 1; 462 break; 463 } 464 } 465 } 466 } 467 468 static void 469 rtld_init_env_vars(char **env) 470 { 471 rtld_init_env_vars_for_prefix(env, ld_env_prefix); 472 } 473 474 static void 475 set_ld_elf_hints_path(void) 476 { 477 if (ld_elf_hints_path == NULL || strlen(ld_elf_hints_path) == 0) 478 ld_elf_hints_path = ld_elf_hints_default; 479 } 480 481 uintptr_t 482 rtld_round_page(uintptr_t x) 483 { 484 return (roundup2(x, page_size)); 485 } 486 487 uintptr_t 488 rtld_trunc_page(uintptr_t x) 489 { 490 return (rounddown2(x, page_size)); 491 } 492 493 /* 494 * Main entry point for dynamic linking. The first argument is the 495 * stack pointer. The stack is expected to be laid out as described 496 * in the SVR4 ABI specification, Intel 386 Processor Supplement. 497 * Specifically, the stack pointer points to a word containing 498 * ARGC. Following that in the stack is a null-terminated sequence 499 * of pointers to argument strings. Then comes a null-terminated 500 * sequence of pointers to environment strings. Finally, there is a 501 * sequence of "auxiliary vector" entries. 502 * 503 * The second argument points to a place to store the dynamic linker's 504 * exit procedure pointer and the third to a place to store the main 505 * program's object. 506 * 507 * The return value is the main program's entry point. 508 */ 509 func_ptr_type 510 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) 511 { 512 Elf_Auxinfo *aux, *auxp, *auxpf, *aux_info[AT_COUNT]; 513 Objlist_Entry *entry; 514 Obj_Entry *last_interposer, *obj, *preload_tail; 515 const Elf_Phdr *phdr; 516 Objlist initlist; 517 RtldLockState lockstate; 518 struct stat st; 519 Elf_Addr *argcp; 520 char **argv, **env, **envp, *kexecpath; 521 const char *argv0, *binpath, *library_path_rpath, *static_tls_extra; 522 struct ld_env_var_desc *lvd; 523 caddr_t imgentry; 524 char buf[MAXPATHLEN]; 525 int argc, fd, i, mib[4], old_osrel, osrel, phnum, rtld_argc; 526 size_t sz; 527 #ifdef __powerpc__ 528 int old_auxv_format = 1; 529 #endif 530 bool dir_enable, dir_ignore, direct_exec, explicit_fd, search_in_path; 531 532 /* 533 * On entry, the dynamic linker itself has not been relocated yet. 534 * Be very careful not to reference any global data until after 535 * init_rtld has returned. It is OK to reference file-scope statics 536 * and string constants, and to call static and global functions. 537 */ 538 539 /* Find the auxiliary vector on the stack. */ 540 argcp = sp; 541 argc = *sp++; 542 argv = (char **) sp; 543 sp += argc + 1; /* Skip over arguments and NULL terminator */ 544 env = (char **) sp; 545 while (*sp++ != 0) /* Skip over environment, and NULL terminator */ 546 ; 547 aux = (Elf_Auxinfo *) sp; 548 549 /* Digest the auxiliary vector. */ 550 for (i = 0; i < AT_COUNT; i++) 551 aux_info[i] = NULL; 552 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { 553 if (auxp->a_type < AT_COUNT) 554 aux_info[auxp->a_type] = auxp; 555 #ifdef __powerpc__ 556 if (auxp->a_type == 23) /* AT_STACKPROT */ 557 old_auxv_format = 0; 558 #endif 559 } 560 561 #ifdef __powerpc__ 562 if (old_auxv_format) { 563 /* Remap from old-style auxv numbers. */ 564 aux_info[23] = aux_info[21]; /* AT_STACKPROT */ 565 aux_info[21] = aux_info[19]; /* AT_PAGESIZESLEN */ 566 aux_info[19] = aux_info[17]; /* AT_NCPUS */ 567 aux_info[17] = aux_info[15]; /* AT_CANARYLEN */ 568 aux_info[15] = aux_info[13]; /* AT_EXECPATH */ 569 aux_info[13] = NULL; /* AT_GID */ 570 571 aux_info[20] = aux_info[18]; /* AT_PAGESIZES */ 572 aux_info[18] = aux_info[16]; /* AT_OSRELDATE */ 573 aux_info[16] = aux_info[14]; /* AT_CANARY */ 574 aux_info[14] = NULL; /* AT_EGID */ 575 } 576 #endif 577 578 /* Initialize and relocate ourselves. */ 579 assert(aux_info[AT_BASE] != NULL); 580 init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info); 581 582 dlerror_dflt_init(); 583 584 __progname = obj_rtld.path; 585 argv0 = argv[0] != NULL ? argv[0] : "(null)"; 586 environ = env; 587 main_argc = argc; 588 main_argv = argv; 589 590 if (aux_info[AT_BSDFLAGS] != NULL && 591 (aux_info[AT_BSDFLAGS]->a_un.a_val & ELF_BSDF_SIGFASTBLK) != 0) 592 ld_fast_sigblock = true; 593 594 trust = !issetugid(); 595 direct_exec = false; 596 597 md_abi_variant_hook(aux_info); 598 rtld_init_env_vars(env); 599 600 fd = -1; 601 if (aux_info[AT_EXECFD] != NULL) { 602 fd = aux_info[AT_EXECFD]->a_un.a_val; 603 } else { 604 assert(aux_info[AT_PHDR] != NULL); 605 phdr = (const Elf_Phdr *)aux_info[AT_PHDR]->a_un.a_ptr; 606 if (phdr == obj_rtld.phdr) { 607 if (!trust) { 608 _rtld_error("Tainted process refusing to run binary %s", 609 argv0); 610 rtld_die(); 611 } 612 direct_exec = true; 613 614 dbg("opening main program in direct exec mode"); 615 if (argc >= 2) { 616 rtld_argc = parse_args(argv, argc, &search_in_path, &fd, 617 &argv0, &dir_ignore); 618 explicit_fd = (fd != -1); 619 binpath = NULL; 620 if (!explicit_fd) 621 fd = open_binary_fd(argv0, search_in_path, &binpath); 622 if (fstat(fd, &st) == -1) { 623 _rtld_error("Failed to fstat FD %d (%s): %s", fd, 624 explicit_fd ? "user-provided descriptor" : argv0, 625 rtld_strerror(errno)); 626 rtld_die(); 627 } 628 629 /* 630 * Rough emulation of the permission checks done by 631 * execve(2), only Unix DACs are checked, ACLs are 632 * ignored. Preserve the semantic of disabling owner 633 * to execute if owner x bit is cleared, even if 634 * others x bit is enabled. 635 * mmap(2) does not allow to mmap with PROT_EXEC if 636 * binary' file comes from noexec mount. We cannot 637 * set a text reference on the binary. 638 */ 639 dir_enable = false; 640 if (st.st_uid == geteuid()) { 641 if ((st.st_mode & S_IXUSR) != 0) 642 dir_enable = true; 643 } else if (st.st_gid == getegid()) { 644 if ((st.st_mode & S_IXGRP) != 0) 645 dir_enable = true; 646 } else if ((st.st_mode & S_IXOTH) != 0) { 647 dir_enable = true; 648 } 649 if (!dir_enable && !dir_ignore) { 650 _rtld_error("No execute permission for binary %s", 651 argv0); 652 rtld_die(); 653 } 654 655 /* 656 * For direct exec mode, argv[0] is the interpreter 657 * name, we must remove it and shift arguments left 658 * before invoking binary main. Since stack layout 659 * places environment pointers and aux vectors right 660 * after the terminating NULL, we must shift 661 * environment and aux as well. 662 */ 663 main_argc = argc - rtld_argc; 664 for (i = 0; i <= main_argc; i++) 665 argv[i] = argv[i + rtld_argc]; 666 *argcp -= rtld_argc; 667 environ = env = envp = argv + main_argc + 1; 668 dbg("move env from %p to %p", envp + rtld_argc, envp); 669 do { 670 *envp = *(envp + rtld_argc); 671 } while (*envp++ != NULL); 672 aux = auxp = (Elf_Auxinfo *)envp; 673 auxpf = (Elf_Auxinfo *)(envp + rtld_argc); 674 dbg("move aux from %p to %p", auxpf, aux); 675 /* XXXKIB insert place for AT_EXECPATH if not present */ 676 for (;; auxp++, auxpf++) { 677 *auxp = *auxpf; 678 if (auxp->a_type == AT_NULL) 679 break; 680 } 681 /* Since the auxiliary vector has moved, redigest it. */ 682 for (i = 0; i < AT_COUNT; i++) 683 aux_info[i] = NULL; 684 for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { 685 if (auxp->a_type < AT_COUNT) 686 aux_info[auxp->a_type] = auxp; 687 } 688 689 /* Point AT_EXECPATH auxv and aux_info to the binary path. */ 690 if (binpath == NULL) { 691 aux_info[AT_EXECPATH] = NULL; 692 } else { 693 if (aux_info[AT_EXECPATH] == NULL) { 694 aux_info[AT_EXECPATH] = xmalloc(sizeof(Elf_Auxinfo)); 695 aux_info[AT_EXECPATH]->a_type = AT_EXECPATH; 696 } 697 aux_info[AT_EXECPATH]->a_un.a_ptr = __DECONST(void *, 698 binpath); 699 } 700 } else { 701 _rtld_error("No binary"); 702 rtld_die(); 703 } 704 } 705 } 706 707 ld_bind_now = ld_get_env_var(LD_BIND_NOW); 708 709 /* 710 * If the process is tainted, then we un-set the dangerous environment 711 * variables. The process will be marked as tainted until setuid(2) 712 * is called. If any child process calls setuid(2) we do not want any 713 * future processes to honor the potentially un-safe variables. 714 */ 715 if (!trust) { 716 for (i = 0; i < (int)nitems(ld_env_vars); i++) { 717 lvd = &ld_env_vars[i]; 718 if (lvd->unsecure) 719 lvd->val = NULL; 720 } 721 } 722 723 ld_debug = ld_get_env_var(LD_DEBUG); 724 if (ld_bind_now == NULL) 725 ld_bind_not = ld_get_env_var(LD_BIND_NOT) != NULL; 726 ld_dynamic_weak = ld_get_env_var(LD_DYNAMIC_WEAK) == NULL; 727 libmap_disable = ld_get_env_var(LD_LIBMAP_DISABLE) != NULL; 728 libmap_override = ld_get_env_var(LD_LIBMAP); 729 ld_library_path = ld_get_env_var(LD_LIBRARY_PATH); 730 ld_library_dirs = ld_get_env_var(LD_LIBRARY_PATH_FDS); 731 ld_preload = ld_get_env_var(LD_PRELOAD); 732 ld_preload_fds = ld_get_env_var(LD_PRELOAD_FDS); 733 ld_elf_hints_path = ld_get_env_var(LD_ELF_HINTS_PATH); 734 ld_loadfltr = ld_get_env_var(LD_LOADFLTR) != NULL; 735 library_path_rpath = ld_get_env_var(LD_LIBRARY_PATH_RPATH); 736 if (library_path_rpath != NULL) { 737 if (library_path_rpath[0] == 'y' || 738 library_path_rpath[0] == 'Y' || 739 library_path_rpath[0] == '1') 740 ld_library_path_rpath = true; 741 else 742 ld_library_path_rpath = false; 743 } 744 static_tls_extra = ld_get_env_var(LD_STATIC_TLS_EXTRA); 745 if (static_tls_extra != NULL && static_tls_extra[0] != '\0') { 746 sz = parse_integer(static_tls_extra); 747 if (sz >= RTLD_STATIC_TLS_EXTRA && sz <= SIZE_T_MAX) 748 ld_static_tls_extra = sz; 749 } 750 dangerous_ld_env = libmap_disable || libmap_override != NULL || 751 ld_library_path != NULL || ld_preload != NULL || 752 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak || 753 static_tls_extra != NULL; 754 ld_tracing = ld_get_env_var(LD_TRACE_LOADED_OBJECTS); 755 ld_utrace = ld_get_env_var(LD_UTRACE); 756 757 set_ld_elf_hints_path(); 758 if (ld_debug != NULL && *ld_debug != '\0') 759 debug = 1; 760 dbg("%s is initialized, base address = %p", __progname, 761 (caddr_t) aux_info[AT_BASE]->a_un.a_ptr); 762 dbg("RTLD dynamic = %p", obj_rtld.dynamic); 763 dbg("RTLD pltgot = %p", obj_rtld.pltgot); 764 765 dbg("initializing thread locks"); 766 lockdflt_init(); 767 768 /* 769 * Load the main program, or process its program header if it is 770 * already loaded. 771 */ 772 if (fd != -1) { /* Load the main program. */ 773 dbg("loading main program"); 774 obj_main = map_object(fd, argv0, NULL); 775 close(fd); 776 if (obj_main == NULL) 777 rtld_die(); 778 max_stack_flags = obj_main->stack_flags; 779 } else { /* Main program already loaded. */ 780 dbg("processing main program's program header"); 781 assert(aux_info[AT_PHDR] != NULL); 782 phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr; 783 assert(aux_info[AT_PHNUM] != NULL); 784 phnum = aux_info[AT_PHNUM]->a_un.a_val; 785 assert(aux_info[AT_PHENT] != NULL); 786 assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr)); 787 assert(aux_info[AT_ENTRY] != NULL); 788 imgentry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr; 789 if ((obj_main = digest_phdr(phdr, phnum, imgentry, argv0)) == NULL) 790 rtld_die(); 791 } 792 793 if (aux_info[AT_EXECPATH] != NULL && fd == -1) { 794 kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr; 795 dbg("AT_EXECPATH %p %s", kexecpath, kexecpath); 796 if (kexecpath[0] == '/') 797 obj_main->path = kexecpath; 798 else if (getcwd(buf, sizeof(buf)) == NULL || 799 strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) || 800 strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf)) 801 obj_main->path = xstrdup(argv0); 802 else 803 obj_main->path = xstrdup(buf); 804 } else { 805 dbg("No AT_EXECPATH or direct exec"); 806 obj_main->path = xstrdup(argv0); 807 } 808 dbg("obj_main path %s", obj_main->path); 809 obj_main->mainprog = true; 810 811 if (aux_info[AT_STACKPROT] != NULL && 812 aux_info[AT_STACKPROT]->a_un.a_val != 0) 813 stack_prot = aux_info[AT_STACKPROT]->a_un.a_val; 814 815 #ifndef COMPAT_libcompat 816 /* 817 * Get the actual dynamic linker pathname from the executable if 818 * possible. (It should always be possible.) That ensures that 819 * gdb will find the right dynamic linker even if a non-standard 820 * one is being used. 821 */ 822 if (obj_main->interp != NULL && 823 strcmp(obj_main->interp, obj_rtld.path) != 0) { 824 free(obj_rtld.path); 825 obj_rtld.path = xstrdup(obj_main->interp); 826 __progname = obj_rtld.path; 827 } 828 #endif 829 830 if (!digest_dynamic(obj_main, 0)) 831 rtld_die(); 832 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", 833 obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu, 834 obj_main->dynsymcount); 835 836 linkmap_add(obj_main); 837 linkmap_add(&obj_rtld); 838 839 /* Link the main program into the list of objects. */ 840 TAILQ_INSERT_HEAD(&obj_list, obj_main, next); 841 obj_count++; 842 obj_loads++; 843 844 /* Initialize a fake symbol for resolving undefined weak references. */ 845 sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE); 846 sym_zero.st_shndx = SHN_UNDEF; 847 sym_zero.st_value = -(uintptr_t)obj_main->relocbase; 848 849 if (!libmap_disable) 850 libmap_disable = (bool)lm_init(libmap_override); 851 852 if (aux_info[AT_KPRELOAD] != NULL && 853 aux_info[AT_KPRELOAD]->a_un.a_ptr != NULL) { 854 dbg("loading kernel vdso"); 855 if (load_kpreload(aux_info[AT_KPRELOAD]->a_un.a_ptr) == -1) 856 rtld_die(); 857 } 858 859 dbg("loading LD_PRELOAD_FDS libraries"); 860 if (load_preload_objects(ld_preload_fds, true) == -1) 861 rtld_die(); 862 863 dbg("loading LD_PRELOAD libraries"); 864 if (load_preload_objects(ld_preload, false) == -1) 865 rtld_die(); 866 preload_tail = globallist_curr(TAILQ_LAST(&obj_list, obj_entry_q)); 867 868 dbg("loading needed objects"); 869 if (load_needed_objects(obj_main, ld_tracing != NULL ? RTLD_LO_TRACE : 870 0) == -1) 871 rtld_die(); 872 873 /* Make a list of all objects loaded at startup. */ 874 last_interposer = obj_main; 875 TAILQ_FOREACH(obj, &obj_list, next) { 876 if (obj->marker) 877 continue; 878 if (obj->z_interpose && obj != obj_main) { 879 objlist_put_after(&list_main, last_interposer, obj); 880 last_interposer = obj; 881 } else { 882 objlist_push_tail(&list_main, obj); 883 } 884 obj->refcount++; 885 } 886 887 dbg("checking for required versions"); 888 if (rtld_verify_versions(&list_main) == -1 && !ld_tracing) 889 rtld_die(); 890 891 if (ld_get_env_var(LD_SHOW_AUXV) != NULL) 892 dump_auxv(aux_info); 893 894 if (ld_tracing) { /* We're done */ 895 trace_loaded_objects(obj_main, true); 896 exit(0); 897 } 898 899 if (ld_get_env_var(LD_DUMP_REL_PRE) != NULL) { 900 dump_relocations(obj_main); 901 exit (0); 902 } 903 904 /* 905 * Processing tls relocations requires having the tls offsets 906 * initialized. Prepare offsets before starting initial 907 * relocation processing. 908 */ 909 dbg("initializing initial thread local storage offsets"); 910 STAILQ_FOREACH(entry, &list_main, link) { 911 /* 912 * Allocate all the initial objects out of the static TLS 913 * block even if they didn't ask for it. 914 */ 915 allocate_tls_offset(entry->obj); 916 } 917 918 if (relocate_objects(obj_main, 919 ld_bind_now != NULL && *ld_bind_now != '\0', 920 &obj_rtld, SYMLOOK_EARLY, NULL) == -1) 921 rtld_die(); 922 923 dbg("doing copy relocations"); 924 if (do_copy_relocations(obj_main) == -1) 925 rtld_die(); 926 927 if (ld_get_env_var(LD_DUMP_REL_POST) != NULL) { 928 dump_relocations(obj_main); 929 exit (0); 930 } 931 932 ifunc_init(aux); 933 934 /* 935 * Setup TLS for main thread. This must be done after the 936 * relocations are processed, since tls initialization section 937 * might be the subject for relocations. 938 */ 939 dbg("initializing initial thread local storage"); 940 allocate_initial_tls(globallist_curr(TAILQ_FIRST(&obj_list))); 941 942 dbg("initializing key program variables"); 943 set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : ""); 944 set_program_var("environ", env); 945 set_program_var("__elf_aux_vector", aux); 946 947 /* Make a list of init functions to call. */ 948 objlist_init(&initlist); 949 initlist_add_objects(globallist_curr(TAILQ_FIRST(&obj_list)), 950 preload_tail, &initlist); 951 952 r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */ 953 954 map_stacks_exec(NULL); 955 956 if (!obj_main->crt_no_init) { 957 /* 958 * Make sure we don't call the main program's init and fini 959 * functions for binaries linked with old crt1 which calls 960 * _init itself. 961 */ 962 obj_main->init = obj_main->fini = (Elf_Addr)NULL; 963 obj_main->preinit_array = obj_main->init_array = 964 obj_main->fini_array = (Elf_Addr)NULL; 965 } 966 967 if (direct_exec) { 968 /* Set osrel for direct-execed binary */ 969 mib[0] = CTL_KERN; 970 mib[1] = KERN_PROC; 971 mib[2] = KERN_PROC_OSREL; 972 mib[3] = getpid(); 973 osrel = obj_main->osrel; 974 sz = sizeof(old_osrel); 975 dbg("setting osrel to %d", osrel); 976 (void)sysctl(mib, 4, &old_osrel, &sz, &osrel, sizeof(osrel)); 977 } 978 979 wlock_acquire(rtld_bind_lock, &lockstate); 980 981 dbg("resolving ifuncs"); 982 if (initlist_objects_ifunc(&initlist, ld_bind_now != NULL && 983 *ld_bind_now != '\0', SYMLOOK_EARLY, &lockstate) == -1) 984 rtld_die(); 985 986 rtld_exit_ptr = rtld_exit; 987 if (obj_main->crt_no_init) 988 preinit_main(); 989 objlist_call_init(&initlist, &lockstate); 990 _r_debug_postinit(&obj_main->linkmap); 991 objlist_clear(&initlist); 992 dbg("loading filtees"); 993 TAILQ_FOREACH(obj, &obj_list, next) { 994 if (obj->marker) 995 continue; 996 if (ld_loadfltr || obj->z_loadfltr) 997 load_filtees(obj, 0, &lockstate); 998 } 999 1000 dbg("enforcing main obj relro"); 1001 if (obj_enforce_relro(obj_main) == -1) 1002 rtld_die(); 1003 1004 lock_release(rtld_bind_lock, &lockstate); 1005 1006 dbg("transferring control to program entry point = %p", obj_main->entry); 1007 1008 /* Return the exit procedure and the program entry point. */ 1009 *exit_proc = rtld_exit_ptr; 1010 *objp = obj_main; 1011 return ((func_ptr_type)obj_main->entry); 1012 } 1013 1014 void * 1015 rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def) 1016 { 1017 void *ptr; 1018 Elf_Addr target; 1019 1020 ptr = (void *)make_function_pointer(def, obj); 1021 target = call_ifunc_resolver(ptr); 1022 return ((void *)target); 1023 } 1024 1025 Elf_Addr 1026 _rtld_bind(Obj_Entry *obj, Elf_Size reloff) 1027 { 1028 const Elf_Rel *rel; 1029 const Elf_Sym *def; 1030 const Obj_Entry *defobj; 1031 Elf_Addr *where; 1032 Elf_Addr target; 1033 RtldLockState lockstate; 1034 1035 rlock_acquire(rtld_bind_lock, &lockstate); 1036 if (sigsetjmp(lockstate.env, 0) != 0) 1037 lock_upgrade(rtld_bind_lock, &lockstate); 1038 if (obj->pltrel) 1039 rel = (const Elf_Rel *)((const char *)obj->pltrel + reloff); 1040 else 1041 rel = (const Elf_Rel *)((const char *)obj->pltrela + reloff); 1042 1043 where = (Elf_Addr *)(obj->relocbase + rel->r_offset); 1044 def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, SYMLOOK_IN_PLT, 1045 NULL, &lockstate); 1046 if (def == NULL) 1047 rtld_die(); 1048 if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 1049 target = (Elf_Addr)rtld_resolve_ifunc(defobj, def); 1050 else 1051 target = (Elf_Addr)(defobj->relocbase + def->st_value); 1052 1053 dbg("\"%s\" in \"%s\" ==> %p in \"%s\"", 1054 defobj->strtab + def->st_name, 1055 obj->path == NULL ? NULL : basename(obj->path), 1056 (void *)target, 1057 defobj->path == NULL ? NULL : basename(defobj->path)); 1058 1059 /* 1060 * Write the new contents for the jmpslot. Note that depending on 1061 * architecture, the value which we need to return back to the 1062 * lazy binding trampoline may or may not be the target 1063 * address. The value returned from reloc_jmpslot() is the value 1064 * that the trampoline needs. 1065 */ 1066 target = reloc_jmpslot(where, target, defobj, obj, rel); 1067 lock_release(rtld_bind_lock, &lockstate); 1068 return (target); 1069 } 1070 1071 /* 1072 * Error reporting function. Use it like printf. If formats the message 1073 * into a buffer, and sets things up so that the next call to dlerror() 1074 * will return the message. 1075 */ 1076 void 1077 _rtld_error(const char *fmt, ...) 1078 { 1079 va_list ap; 1080 1081 va_start(ap, fmt); 1082 rtld_vsnprintf(lockinfo.dlerror_loc(), lockinfo.dlerror_loc_sz, 1083 fmt, ap); 1084 va_end(ap); 1085 *lockinfo.dlerror_seen() = 0; 1086 dbg("rtld_error: %s", lockinfo.dlerror_loc()); 1087 LD_UTRACE(UTRACE_RTLD_ERROR, NULL, NULL, 0, 0, lockinfo.dlerror_loc()); 1088 } 1089 1090 /* 1091 * Return a dynamically-allocated copy of the current error message, if any. 1092 */ 1093 static struct dlerror_save * 1094 errmsg_save(void) 1095 { 1096 struct dlerror_save *res; 1097 1098 res = xmalloc(sizeof(*res)); 1099 res->seen = *lockinfo.dlerror_seen(); 1100 if (res->seen == 0) 1101 res->msg = xstrdup(lockinfo.dlerror_loc()); 1102 return (res); 1103 } 1104 1105 /* 1106 * Restore the current error message from a copy which was previously saved 1107 * by errmsg_save(). The copy is freed. 1108 */ 1109 static void 1110 errmsg_restore(struct dlerror_save *saved_msg) 1111 { 1112 if (saved_msg == NULL || saved_msg->seen == 1) { 1113 *lockinfo.dlerror_seen() = 1; 1114 } else { 1115 *lockinfo.dlerror_seen() = 0; 1116 strlcpy(lockinfo.dlerror_loc(), saved_msg->msg, 1117 lockinfo.dlerror_loc_sz); 1118 free(saved_msg->msg); 1119 } 1120 free(saved_msg); 1121 } 1122 1123 static const char * 1124 basename(const char *name) 1125 { 1126 const char *p; 1127 1128 p = strrchr(name, '/'); 1129 return (p != NULL ? p + 1 : name); 1130 } 1131 1132 static struct utsname uts; 1133 1134 static char * 1135 origin_subst_one(Obj_Entry *obj, char *real, const char *kw, 1136 const char *subst, bool may_free) 1137 { 1138 char *p, *p1, *res, *resp; 1139 int subst_len, kw_len, subst_count, old_len, new_len; 1140 1141 kw_len = strlen(kw); 1142 1143 /* 1144 * First, count the number of the keyword occurrences, to 1145 * preallocate the final string. 1146 */ 1147 for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) { 1148 p1 = strstr(p, kw); 1149 if (p1 == NULL) 1150 break; 1151 } 1152 1153 /* 1154 * If the keyword is not found, just return. 1155 * 1156 * Return non-substituted string if resolution failed. We 1157 * cannot do anything more reasonable, the failure mode of the 1158 * caller is unresolved library anyway. 1159 */ 1160 if (subst_count == 0 || (obj != NULL && !obj_resolve_origin(obj))) 1161 return (may_free ? real : xstrdup(real)); 1162 if (obj != NULL) 1163 subst = obj->origin_path; 1164 1165 /* 1166 * There is indeed something to substitute. Calculate the 1167 * length of the resulting string, and allocate it. 1168 */ 1169 subst_len = strlen(subst); 1170 old_len = strlen(real); 1171 new_len = old_len + (subst_len - kw_len) * subst_count; 1172 res = xmalloc(new_len + 1); 1173 1174 /* 1175 * Now, execute the substitution loop. 1176 */ 1177 for (p = real, resp = res, *resp = '\0';;) { 1178 p1 = strstr(p, kw); 1179 if (p1 != NULL) { 1180 /* Copy the prefix before keyword. */ 1181 memcpy(resp, p, p1 - p); 1182 resp += p1 - p; 1183 /* Keyword replacement. */ 1184 memcpy(resp, subst, subst_len); 1185 resp += subst_len; 1186 *resp = '\0'; 1187 p = p1 + kw_len; 1188 } else 1189 break; 1190 } 1191 1192 /* Copy to the end of string and finish. */ 1193 strcat(resp, p); 1194 if (may_free) 1195 free(real); 1196 return (res); 1197 } 1198 1199 static const struct { 1200 const char *kw; 1201 bool pass_obj; 1202 const char *subst; 1203 } tokens[] = { 1204 { .kw = "$ORIGIN", .pass_obj = true, .subst = NULL }, 1205 { .kw = "${ORIGIN}", .pass_obj = true, .subst = NULL }, 1206 { .kw = "$OSNAME", .pass_obj = false, .subst = uts.sysname }, 1207 { .kw = "${OSNAME}", .pass_obj = false, .subst = uts.sysname }, 1208 { .kw = "$OSREL", .pass_obj = false, .subst = uts.release }, 1209 { .kw = "${OSREL}", .pass_obj = false, .subst = uts.release }, 1210 { .kw = "$PLATFORM", .pass_obj = false, .subst = uts.machine }, 1211 { .kw = "${PLATFORM}", .pass_obj = false, .subst = uts.machine }, 1212 { .kw = "$LIB", .pass_obj = false, .subst = TOKEN_LIB }, 1213 { .kw = "${LIB}", .pass_obj = false, .subst = TOKEN_LIB }, 1214 }; 1215 1216 static char * 1217 origin_subst(Obj_Entry *obj, const char *real) 1218 { 1219 char *res; 1220 int i; 1221 1222 if (obj == NULL || !trust) 1223 return (xstrdup(real)); 1224 if (uts.sysname[0] == '\0') { 1225 if (uname(&uts) != 0) { 1226 _rtld_error("utsname failed: %d", errno); 1227 return (NULL); 1228 } 1229 } 1230 1231 /* __DECONST is safe here since without may_free real is unchanged */ 1232 res = __DECONST(char *, real); 1233 for (i = 0; i < (int)nitems(tokens); i++) { 1234 res = origin_subst_one(tokens[i].pass_obj ? obj : NULL, 1235 res, tokens[i].kw, tokens[i].subst, i != 0); 1236 } 1237 return (res); 1238 } 1239 1240 void 1241 rtld_die(void) 1242 { 1243 const char *msg = dlerror(); 1244 1245 if (msg == NULL) 1246 msg = "Fatal error"; 1247 rtld_fdputstr(STDERR_FILENO, _BASENAME_RTLD ": "); 1248 rtld_fdputstr(STDERR_FILENO, msg); 1249 rtld_fdputchar(STDERR_FILENO, '\n'); 1250 _exit(1); 1251 } 1252 1253 /* 1254 * Process a shared object's DYNAMIC section, and save the important 1255 * information in its Obj_Entry structure. 1256 */ 1257 static void 1258 digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath, 1259 const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath) 1260 { 1261 const Elf_Dyn *dynp; 1262 Needed_Entry **needed_tail = &obj->needed; 1263 Needed_Entry **needed_filtees_tail = &obj->needed_filtees; 1264 Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees; 1265 const Elf_Hashelt *hashtab; 1266 const Elf32_Word *hashval; 1267 Elf32_Word bkt, nmaskwords; 1268 int bloom_size32; 1269 int plttype = DT_REL; 1270 1271 *dyn_rpath = NULL; 1272 *dyn_soname = NULL; 1273 *dyn_runpath = NULL; 1274 1275 obj->bind_now = false; 1276 dynp = obj->dynamic; 1277 if (dynp == NULL) 1278 return; 1279 for (; dynp->d_tag != DT_NULL; dynp++) { 1280 switch (dynp->d_tag) { 1281 1282 case DT_REL: 1283 obj->rel = (const Elf_Rel *)(obj->relocbase + dynp->d_un.d_ptr); 1284 break; 1285 1286 case DT_RELSZ: 1287 obj->relsize = dynp->d_un.d_val; 1288 break; 1289 1290 case DT_RELENT: 1291 assert(dynp->d_un.d_val == sizeof(Elf_Rel)); 1292 break; 1293 1294 case DT_JMPREL: 1295 obj->pltrel = (const Elf_Rel *) 1296 (obj->relocbase + dynp->d_un.d_ptr); 1297 break; 1298 1299 case DT_PLTRELSZ: 1300 obj->pltrelsize = dynp->d_un.d_val; 1301 break; 1302 1303 case DT_RELA: 1304 obj->rela = (const Elf_Rela *)(obj->relocbase + dynp->d_un.d_ptr); 1305 break; 1306 1307 case DT_RELASZ: 1308 obj->relasize = dynp->d_un.d_val; 1309 break; 1310 1311 case DT_RELAENT: 1312 assert(dynp->d_un.d_val == sizeof(Elf_Rela)); 1313 break; 1314 1315 case DT_RELR: 1316 obj->relr = (const Elf_Relr *)(obj->relocbase + dynp->d_un.d_ptr); 1317 break; 1318 1319 case DT_RELRSZ: 1320 obj->relrsize = dynp->d_un.d_val; 1321 break; 1322 1323 case DT_RELRENT: 1324 assert(dynp->d_un.d_val == sizeof(Elf_Relr)); 1325 break; 1326 1327 case DT_PLTREL: 1328 plttype = dynp->d_un.d_val; 1329 assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA); 1330 break; 1331 1332 case DT_SYMTAB: 1333 obj->symtab = (const Elf_Sym *) 1334 (obj->relocbase + dynp->d_un.d_ptr); 1335 break; 1336 1337 case DT_SYMENT: 1338 assert(dynp->d_un.d_val == sizeof(Elf_Sym)); 1339 break; 1340 1341 case DT_STRTAB: 1342 obj->strtab = (const char *)(obj->relocbase + dynp->d_un.d_ptr); 1343 break; 1344 1345 case DT_STRSZ: 1346 obj->strsize = dynp->d_un.d_val; 1347 break; 1348 1349 case DT_VERNEED: 1350 obj->verneed = (const Elf_Verneed *)(obj->relocbase + 1351 dynp->d_un.d_val); 1352 break; 1353 1354 case DT_VERNEEDNUM: 1355 obj->verneednum = dynp->d_un.d_val; 1356 break; 1357 1358 case DT_VERDEF: 1359 obj->verdef = (const Elf_Verdef *)(obj->relocbase + 1360 dynp->d_un.d_val); 1361 break; 1362 1363 case DT_VERDEFNUM: 1364 obj->verdefnum = dynp->d_un.d_val; 1365 break; 1366 1367 case DT_VERSYM: 1368 obj->versyms = (const Elf_Versym *)(obj->relocbase + 1369 dynp->d_un.d_val); 1370 break; 1371 1372 case DT_HASH: 1373 { 1374 hashtab = (const Elf_Hashelt *)(obj->relocbase + 1375 dynp->d_un.d_ptr); 1376 obj->nbuckets = hashtab[0]; 1377 obj->nchains = hashtab[1]; 1378 obj->buckets = hashtab + 2; 1379 obj->chains = obj->buckets + obj->nbuckets; 1380 obj->valid_hash_sysv = obj->nbuckets > 0 && obj->nchains > 0 && 1381 obj->buckets != NULL; 1382 } 1383 break; 1384 1385 case DT_GNU_HASH: 1386 { 1387 hashtab = (const Elf_Hashelt *)(obj->relocbase + 1388 dynp->d_un.d_ptr); 1389 obj->nbuckets_gnu = hashtab[0]; 1390 obj->symndx_gnu = hashtab[1]; 1391 nmaskwords = hashtab[2]; 1392 bloom_size32 = (__ELF_WORD_SIZE / 32) * nmaskwords; 1393 obj->maskwords_bm_gnu = nmaskwords - 1; 1394 obj->shift2_gnu = hashtab[3]; 1395 obj->bloom_gnu = (const Elf_Addr *)(hashtab + 4); 1396 obj->buckets_gnu = hashtab + 4 + bloom_size32; 1397 obj->chain_zero_gnu = obj->buckets_gnu + obj->nbuckets_gnu - 1398 obj->symndx_gnu; 1399 /* Number of bitmask words is required to be power of 2 */ 1400 obj->valid_hash_gnu = powerof2(nmaskwords) && 1401 obj->nbuckets_gnu > 0 && obj->buckets_gnu != NULL; 1402 } 1403 break; 1404 1405 case DT_NEEDED: 1406 if (!obj->rtld) { 1407 Needed_Entry *nep = NEW(Needed_Entry); 1408 nep->name = dynp->d_un.d_val; 1409 nep->obj = NULL; 1410 nep->next = NULL; 1411 1412 *needed_tail = nep; 1413 needed_tail = &nep->next; 1414 } 1415 break; 1416 1417 case DT_FILTER: 1418 if (!obj->rtld) { 1419 Needed_Entry *nep = NEW(Needed_Entry); 1420 nep->name = dynp->d_un.d_val; 1421 nep->obj = NULL; 1422 nep->next = NULL; 1423 1424 *needed_filtees_tail = nep; 1425 needed_filtees_tail = &nep->next; 1426 1427 if (obj->linkmap.l_refname == NULL) 1428 obj->linkmap.l_refname = (char *)dynp->d_un.d_val; 1429 } 1430 break; 1431 1432 case DT_AUXILIARY: 1433 if (!obj->rtld) { 1434 Needed_Entry *nep = NEW(Needed_Entry); 1435 nep->name = dynp->d_un.d_val; 1436 nep->obj = NULL; 1437 nep->next = NULL; 1438 1439 *needed_aux_filtees_tail = nep; 1440 needed_aux_filtees_tail = &nep->next; 1441 } 1442 break; 1443 1444 case DT_PLTGOT: 1445 obj->pltgot = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr); 1446 break; 1447 1448 case DT_TEXTREL: 1449 obj->textrel = true; 1450 break; 1451 1452 case DT_SYMBOLIC: 1453 obj->symbolic = true; 1454 break; 1455 1456 case DT_RPATH: 1457 /* 1458 * We have to wait until later to process this, because we 1459 * might not have gotten the address of the string table yet. 1460 */ 1461 *dyn_rpath = dynp; 1462 break; 1463 1464 case DT_SONAME: 1465 *dyn_soname = dynp; 1466 break; 1467 1468 case DT_RUNPATH: 1469 *dyn_runpath = dynp; 1470 break; 1471 1472 case DT_INIT: 1473 obj->init = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1474 break; 1475 1476 case DT_PREINIT_ARRAY: 1477 obj->preinit_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1478 break; 1479 1480 case DT_PREINIT_ARRAYSZ: 1481 obj->preinit_array_num = dynp->d_un.d_val / sizeof(Elf_Addr); 1482 break; 1483 1484 case DT_INIT_ARRAY: 1485 obj->init_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1486 break; 1487 1488 case DT_INIT_ARRAYSZ: 1489 obj->init_array_num = dynp->d_un.d_val / sizeof(Elf_Addr); 1490 break; 1491 1492 case DT_FINI: 1493 obj->fini = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1494 break; 1495 1496 case DT_FINI_ARRAY: 1497 obj->fini_array = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1498 break; 1499 1500 case DT_FINI_ARRAYSZ: 1501 obj->fini_array_num = dynp->d_un.d_val / sizeof(Elf_Addr); 1502 break; 1503 1504 case DT_DEBUG: 1505 if (!early) 1506 dbg("Filling in DT_DEBUG entry"); 1507 (__DECONST(Elf_Dyn *, dynp))->d_un.d_ptr = (Elf_Addr)&r_debug; 1508 break; 1509 1510 case DT_FLAGS: 1511 if (dynp->d_un.d_val & DF_ORIGIN) 1512 obj->z_origin = true; 1513 if (dynp->d_un.d_val & DF_SYMBOLIC) 1514 obj->symbolic = true; 1515 if (dynp->d_un.d_val & DF_TEXTREL) 1516 obj->textrel = true; 1517 if (dynp->d_un.d_val & DF_BIND_NOW) 1518 obj->bind_now = true; 1519 if (dynp->d_un.d_val & DF_STATIC_TLS) 1520 obj->static_tls = true; 1521 break; 1522 1523 #ifdef __powerpc__ 1524 #ifdef __powerpc64__ 1525 case DT_PPC64_GLINK: 1526 obj->glink = (Elf_Addr)(obj->relocbase + dynp->d_un.d_ptr); 1527 break; 1528 #else 1529 case DT_PPC_GOT: 1530 obj->gotptr = (Elf_Addr *)(obj->relocbase + dynp->d_un.d_ptr); 1531 break; 1532 #endif 1533 #endif 1534 1535 case DT_FLAGS_1: 1536 if (dynp->d_un.d_val & DF_1_NOOPEN) 1537 obj->z_noopen = true; 1538 if (dynp->d_un.d_val & DF_1_ORIGIN) 1539 obj->z_origin = true; 1540 if (dynp->d_un.d_val & DF_1_GLOBAL) 1541 obj->z_global = true; 1542 if (dynp->d_un.d_val & DF_1_BIND_NOW) 1543 obj->bind_now = true; 1544 if (dynp->d_un.d_val & DF_1_NODELETE) 1545 obj->z_nodelete = true; 1546 if (dynp->d_un.d_val & DF_1_LOADFLTR) 1547 obj->z_loadfltr = true; 1548 if (dynp->d_un.d_val & DF_1_INTERPOSE) 1549 obj->z_interpose = true; 1550 if (dynp->d_un.d_val & DF_1_NODEFLIB) 1551 obj->z_nodeflib = true; 1552 if (dynp->d_un.d_val & DF_1_PIE) 1553 obj->z_pie = true; 1554 break; 1555 1556 default: 1557 if (!early) { 1558 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag, 1559 (long)dynp->d_tag); 1560 } 1561 break; 1562 } 1563 } 1564 1565 obj->traced = false; 1566 1567 if (plttype == DT_RELA) { 1568 obj->pltrela = (const Elf_Rela *) obj->pltrel; 1569 obj->pltrel = NULL; 1570 obj->pltrelasize = obj->pltrelsize; 1571 obj->pltrelsize = 0; 1572 } 1573 1574 /* Determine size of dynsym table (equal to nchains of sysv hash) */ 1575 if (obj->valid_hash_sysv) 1576 obj->dynsymcount = obj->nchains; 1577 else if (obj->valid_hash_gnu) { 1578 obj->dynsymcount = 0; 1579 for (bkt = 0; bkt < obj->nbuckets_gnu; bkt++) { 1580 if (obj->buckets_gnu[bkt] == 0) 1581 continue; 1582 hashval = &obj->chain_zero_gnu[obj->buckets_gnu[bkt]]; 1583 do 1584 obj->dynsymcount++; 1585 while ((*hashval++ & 1u) == 0); 1586 } 1587 obj->dynsymcount += obj->symndx_gnu; 1588 } 1589 1590 if (obj->linkmap.l_refname != NULL) 1591 obj->linkmap.l_refname = obj->strtab + (unsigned long)obj-> 1592 linkmap.l_refname; 1593 } 1594 1595 static bool 1596 obj_resolve_origin(Obj_Entry *obj) 1597 { 1598 1599 if (obj->origin_path != NULL) 1600 return (true); 1601 obj->origin_path = xmalloc(PATH_MAX); 1602 return (rtld_dirname_abs(obj->path, obj->origin_path) != -1); 1603 } 1604 1605 static bool 1606 digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath, 1607 const Elf_Dyn *dyn_soname, const Elf_Dyn *dyn_runpath) 1608 { 1609 1610 if (obj->z_origin && !obj_resolve_origin(obj)) 1611 return (false); 1612 1613 if (dyn_runpath != NULL) { 1614 obj->runpath = (const char *)obj->strtab + dyn_runpath->d_un.d_val; 1615 obj->runpath = origin_subst(obj, obj->runpath); 1616 } else if (dyn_rpath != NULL) { 1617 obj->rpath = (const char *)obj->strtab + dyn_rpath->d_un.d_val; 1618 obj->rpath = origin_subst(obj, obj->rpath); 1619 } 1620 if (dyn_soname != NULL) 1621 object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val); 1622 return (true); 1623 } 1624 1625 static bool 1626 digest_dynamic(Obj_Entry *obj, int early) 1627 { 1628 const Elf_Dyn *dyn_rpath; 1629 const Elf_Dyn *dyn_soname; 1630 const Elf_Dyn *dyn_runpath; 1631 1632 digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname, &dyn_runpath); 1633 return (digest_dynamic2(obj, dyn_rpath, dyn_soname, dyn_runpath)); 1634 } 1635 1636 /* 1637 * Process a shared object's program header. This is used only for the 1638 * main program, when the kernel has already loaded the main program 1639 * into memory before calling the dynamic linker. It creates and 1640 * returns an Obj_Entry structure. 1641 */ 1642 static Obj_Entry * 1643 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path) 1644 { 1645 Obj_Entry *obj; 1646 const Elf_Phdr *phlimit = phdr + phnum; 1647 const Elf_Phdr *ph; 1648 Elf_Addr note_start, note_end; 1649 int nsegs = 0; 1650 1651 obj = obj_new(); 1652 for (ph = phdr; ph < phlimit; ph++) { 1653 if (ph->p_type != PT_PHDR) 1654 continue; 1655 1656 obj->phdr = phdr; 1657 obj->phsize = ph->p_memsz; 1658 obj->relocbase = __DECONST(char *, phdr) - ph->p_vaddr; 1659 break; 1660 } 1661 1662 obj->stack_flags = PF_X | PF_R | PF_W; 1663 1664 for (ph = phdr; ph < phlimit; ph++) { 1665 switch (ph->p_type) { 1666 1667 case PT_INTERP: 1668 obj->interp = (const char *)(ph->p_vaddr + obj->relocbase); 1669 break; 1670 1671 case PT_LOAD: 1672 if (nsegs == 0) { /* First load segment */ 1673 obj->vaddrbase = rtld_trunc_page(ph->p_vaddr); 1674 obj->mapbase = obj->vaddrbase + obj->relocbase; 1675 } else { /* Last load segment */ 1676 obj->mapsize = rtld_round_page(ph->p_vaddr + ph->p_memsz) - 1677 obj->vaddrbase; 1678 } 1679 nsegs++; 1680 break; 1681 1682 case PT_DYNAMIC: 1683 obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase); 1684 break; 1685 1686 case PT_TLS: 1687 obj->tlsindex = 1; 1688 obj->tlssize = ph->p_memsz; 1689 obj->tlsalign = ph->p_align; 1690 obj->tlsinitsize = ph->p_filesz; 1691 obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase); 1692 obj->tlspoffset = ph->p_offset; 1693 break; 1694 1695 case PT_GNU_STACK: 1696 obj->stack_flags = ph->p_flags; 1697 break; 1698 1699 case PT_GNU_RELRO: 1700 obj->relro_page = obj->relocbase + rtld_trunc_page(ph->p_vaddr); 1701 obj->relro_size = rtld_trunc_page(ph->p_vaddr + ph->p_memsz) - 1702 rtld_trunc_page(ph->p_vaddr); 1703 break; 1704 1705 case PT_NOTE: 1706 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr; 1707 note_end = note_start + ph->p_filesz; 1708 digest_notes(obj, note_start, note_end); 1709 break; 1710 } 1711 } 1712 if (nsegs < 1) { 1713 _rtld_error("%s: too few PT_LOAD segments", path); 1714 return (NULL); 1715 } 1716 1717 obj->entry = entry; 1718 return (obj); 1719 } 1720 1721 void 1722 digest_notes(Obj_Entry *obj, Elf_Addr note_start, Elf_Addr note_end) 1723 { 1724 const Elf_Note *note; 1725 const char *note_name; 1726 uintptr_t p; 1727 1728 for (note = (const Elf_Note *)note_start; (Elf_Addr)note < note_end; 1729 note = (const Elf_Note *)((const char *)(note + 1) + 1730 roundup2(note->n_namesz, sizeof(Elf32_Addr)) + 1731 roundup2(note->n_descsz, sizeof(Elf32_Addr)))) { 1732 if (note->n_namesz != sizeof(NOTE_FREEBSD_VENDOR) || 1733 note->n_descsz != sizeof(int32_t)) 1734 continue; 1735 if (note->n_type != NT_FREEBSD_ABI_TAG && 1736 note->n_type != NT_FREEBSD_FEATURE_CTL && 1737 note->n_type != NT_FREEBSD_NOINIT_TAG) 1738 continue; 1739 note_name = (const char *)(note + 1); 1740 if (strncmp(NOTE_FREEBSD_VENDOR, note_name, 1741 sizeof(NOTE_FREEBSD_VENDOR)) != 0) 1742 continue; 1743 switch (note->n_type) { 1744 case NT_FREEBSD_ABI_TAG: 1745 /* FreeBSD osrel note */ 1746 p = (uintptr_t)(note + 1); 1747 p += roundup2(note->n_namesz, sizeof(Elf32_Addr)); 1748 obj->osrel = *(const int32_t *)(p); 1749 dbg("note osrel %d", obj->osrel); 1750 break; 1751 case NT_FREEBSD_FEATURE_CTL: 1752 /* FreeBSD ABI feature control note */ 1753 p = (uintptr_t)(note + 1); 1754 p += roundup2(note->n_namesz, sizeof(Elf32_Addr)); 1755 obj->fctl0 = *(const uint32_t *)(p); 1756 dbg("note fctl0 %#x", obj->fctl0); 1757 break; 1758 case NT_FREEBSD_NOINIT_TAG: 1759 /* FreeBSD 'crt does not call init' note */ 1760 obj->crt_no_init = true; 1761 dbg("note crt_no_init"); 1762 break; 1763 } 1764 } 1765 } 1766 1767 static Obj_Entry * 1768 dlcheck(void *handle) 1769 { 1770 Obj_Entry *obj; 1771 1772 TAILQ_FOREACH(obj, &obj_list, next) { 1773 if (obj == (Obj_Entry *) handle) 1774 break; 1775 } 1776 1777 if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) { 1778 _rtld_error("Invalid shared object handle %p", handle); 1779 return (NULL); 1780 } 1781 return (obj); 1782 } 1783 1784 /* 1785 * If the given object is already in the donelist, return true. Otherwise 1786 * add the object to the list and return false. 1787 */ 1788 static bool 1789 donelist_check(DoneList *dlp, const Obj_Entry *obj) 1790 { 1791 unsigned int i; 1792 1793 for (i = 0; i < dlp->num_used; i++) 1794 if (dlp->objs[i] == obj) 1795 return (true); 1796 /* 1797 * Our donelist allocation should always be sufficient. But if 1798 * our threads locking isn't working properly, more shared objects 1799 * could have been loaded since we allocated the list. That should 1800 * never happen, but we'll handle it properly just in case it does. 1801 */ 1802 if (dlp->num_used < dlp->num_alloc) 1803 dlp->objs[dlp->num_used++] = obj; 1804 return (false); 1805 } 1806 1807 /* 1808 * SysV hash function for symbol table lookup. It is a slightly optimized 1809 * version of the hash specified by the System V ABI. 1810 */ 1811 Elf32_Word 1812 elf_hash(const char *name) 1813 { 1814 const unsigned char *p = (const unsigned char *)name; 1815 Elf32_Word h = 0; 1816 1817 while (*p != '\0') { 1818 h = (h << 4) + *p++; 1819 h ^= (h >> 24) & 0xf0; 1820 } 1821 return (h & 0x0fffffff); 1822 } 1823 1824 /* 1825 * The GNU hash function is the Daniel J. Bernstein hash clipped to 32 bits 1826 * unsigned in case it's implemented with a wider type. 1827 */ 1828 static uint32_t 1829 gnu_hash(const char *s) 1830 { 1831 uint32_t h; 1832 unsigned char c; 1833 1834 h = 5381; 1835 for (c = *s; c != '\0'; c = *++s) 1836 h = h * 33 + c; 1837 return (h & 0xffffffff); 1838 } 1839 1840 1841 /* 1842 * Find the library with the given name, and return its full pathname. 1843 * The returned string is dynamically allocated. Generates an error 1844 * message and returns NULL if the library cannot be found. 1845 * 1846 * If the second argument is non-NULL, then it refers to an already- 1847 * loaded shared object, whose library search path will be searched. 1848 * 1849 * If a library is successfully located via LD_LIBRARY_PATH_FDS, its 1850 * descriptor (which is close-on-exec) will be passed out via the third 1851 * argument. 1852 * 1853 * The search order is: 1854 * DT_RPATH in the referencing file _unless_ DT_RUNPATH is present (1) 1855 * DT_RPATH of the main object if DSO without defined DT_RUNPATH (1) 1856 * LD_LIBRARY_PATH 1857 * DT_RUNPATH in the referencing file 1858 * ldconfig hints (if -z nodefaultlib, filter out default library directories 1859 * from list) 1860 * /lib:/usr/lib _unless_ the referencing file is linked with -z nodefaultlib 1861 * 1862 * (1) Handled in digest_dynamic2 - rpath left NULL if runpath defined. 1863 */ 1864 static char * 1865 find_library(const char *xname, const Obj_Entry *refobj, int *fdp) 1866 { 1867 char *pathname, *refobj_path; 1868 const char *name; 1869 bool nodeflib, objgiven; 1870 1871 objgiven = refobj != NULL; 1872 1873 if (libmap_disable || !objgiven || 1874 (name = lm_find(refobj->path, xname)) == NULL) 1875 name = xname; 1876 1877 if (strchr(name, '/') != NULL) { /* Hard coded pathname */ 1878 if (name[0] != '/' && !trust) { 1879 _rtld_error("Absolute pathname required " 1880 "for shared object \"%s\"", name); 1881 return (NULL); 1882 } 1883 return (origin_subst(__DECONST(Obj_Entry *, refobj), 1884 __DECONST(char *, name))); 1885 } 1886 1887 dbg(" Searching for \"%s\"", name); 1888 refobj_path = objgiven ? refobj->path : NULL; 1889 1890 /* 1891 * If refobj->rpath != NULL, then refobj->runpath is NULL. Fall 1892 * back to pre-conforming behaviour if user requested so with 1893 * LD_LIBRARY_PATH_RPATH environment variable and ignore -z 1894 * nodeflib. 1895 */ 1896 if (objgiven && refobj->rpath != NULL && ld_library_path_rpath) { 1897 pathname = search_library_path(name, ld_library_path, 1898 refobj_path, fdp); 1899 if (pathname != NULL) 1900 return (pathname); 1901 if (refobj != NULL) { 1902 pathname = search_library_path(name, refobj->rpath, 1903 refobj_path, fdp); 1904 if (pathname != NULL) 1905 return (pathname); 1906 } 1907 pathname = search_library_pathfds(name, ld_library_dirs, fdp); 1908 if (pathname != NULL) 1909 return (pathname); 1910 pathname = search_library_path(name, gethints(false), 1911 refobj_path, fdp); 1912 if (pathname != NULL) 1913 return (pathname); 1914 pathname = search_library_path(name, ld_standard_library_path, 1915 refobj_path, fdp); 1916 if (pathname != NULL) 1917 return (pathname); 1918 } else { 1919 nodeflib = objgiven ? refobj->z_nodeflib : false; 1920 if (objgiven) { 1921 pathname = search_library_path(name, refobj->rpath, 1922 refobj->path, fdp); 1923 if (pathname != NULL) 1924 return (pathname); 1925 } 1926 if (objgiven && refobj->runpath == NULL && refobj != obj_main) { 1927 pathname = search_library_path(name, obj_main->rpath, 1928 refobj_path, fdp); 1929 if (pathname != NULL) 1930 return (pathname); 1931 } 1932 pathname = search_library_path(name, ld_library_path, 1933 refobj_path, fdp); 1934 if (pathname != NULL) 1935 return (pathname); 1936 if (objgiven) { 1937 pathname = search_library_path(name, refobj->runpath, 1938 refobj_path, fdp); 1939 if (pathname != NULL) 1940 return (pathname); 1941 } 1942 pathname = search_library_pathfds(name, ld_library_dirs, fdp); 1943 if (pathname != NULL) 1944 return (pathname); 1945 pathname = search_library_path(name, gethints(nodeflib), 1946 refobj_path, fdp); 1947 if (pathname != NULL) 1948 return (pathname); 1949 if (objgiven && !nodeflib) { 1950 pathname = search_library_path(name, 1951 ld_standard_library_path, refobj_path, fdp); 1952 if (pathname != NULL) 1953 return (pathname); 1954 } 1955 } 1956 1957 if (objgiven && refobj->path != NULL) { 1958 _rtld_error("Shared object \"%s\" not found, " 1959 "required by \"%s\"", name, basename(refobj->path)); 1960 } else { 1961 _rtld_error("Shared object \"%s\" not found", name); 1962 } 1963 return (NULL); 1964 } 1965 1966 /* 1967 * Given a symbol number in a referencing object, find the corresponding 1968 * definition of the symbol. Returns a pointer to the symbol, or NULL if 1969 * no definition was found. Returns a pointer to the Obj_Entry of the 1970 * defining object via the reference parameter DEFOBJ_OUT. 1971 */ 1972 const Elf_Sym * 1973 find_symdef(unsigned long symnum, const Obj_Entry *refobj, 1974 const Obj_Entry **defobj_out, int flags, SymCache *cache, 1975 RtldLockState *lockstate) 1976 { 1977 const Elf_Sym *ref; 1978 const Elf_Sym *def; 1979 const Obj_Entry *defobj; 1980 const Ver_Entry *ve; 1981 SymLook req; 1982 const char *name; 1983 int res; 1984 1985 /* 1986 * If we have already found this symbol, get the information from 1987 * the cache. 1988 */ 1989 if (symnum >= refobj->dynsymcount) 1990 return (NULL); /* Bad object */ 1991 if (cache != NULL && cache[symnum].sym != NULL) { 1992 *defobj_out = cache[symnum].obj; 1993 return (cache[symnum].sym); 1994 } 1995 1996 ref = refobj->symtab + symnum; 1997 name = refobj->strtab + ref->st_name; 1998 def = NULL; 1999 defobj = NULL; 2000 ve = NULL; 2001 2002 /* 2003 * We don't have to do a full scale lookup if the symbol is local. 2004 * We know it will bind to the instance in this load module; to 2005 * which we already have a pointer (ie ref). By not doing a lookup, 2006 * we not only improve performance, but it also avoids unresolvable 2007 * symbols when local symbols are not in the hash table. This has 2008 * been seen with the ia64 toolchain. 2009 */ 2010 if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) { 2011 if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) { 2012 _rtld_error("%s: Bogus symbol table entry %lu", refobj->path, 2013 symnum); 2014 } 2015 symlook_init(&req, name); 2016 req.flags = flags; 2017 ve = req.ventry = fetch_ventry(refobj, symnum); 2018 req.lockstate = lockstate; 2019 res = symlook_default(&req, refobj); 2020 if (res == 0) { 2021 def = req.sym_out; 2022 defobj = req.defobj_out; 2023 } 2024 } else { 2025 def = ref; 2026 defobj = refobj; 2027 } 2028 2029 /* 2030 * If we found no definition and the reference is weak, treat the 2031 * symbol as having the value zero. 2032 */ 2033 if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) { 2034 def = &sym_zero; 2035 defobj = obj_main; 2036 } 2037 2038 if (def != NULL) { 2039 *defobj_out = defobj; 2040 /* Record the information in the cache to avoid subsequent lookups. */ 2041 if (cache != NULL) { 2042 cache[symnum].sym = def; 2043 cache[symnum].obj = defobj; 2044 } 2045 } else { 2046 if (refobj != &obj_rtld) 2047 _rtld_error("%s: Undefined symbol \"%s%s%s\"", refobj->path, name, 2048 ve != NULL ? "@" : "", ve != NULL ? ve->name : ""); 2049 } 2050 return (def); 2051 } 2052 2053 /* Convert between native byte order and forced little resp. big endian. */ 2054 #define COND_SWAP(n) (is_le ? le32toh(n) : be32toh(n)) 2055 2056 /* 2057 * Return the search path from the ldconfig hints file, reading it if 2058 * necessary. If nostdlib is true, then the default search paths are 2059 * not added to result. 2060 * 2061 * Returns NULL if there are problems with the hints file, 2062 * or if the search path there is empty. 2063 */ 2064 static const char * 2065 gethints(bool nostdlib) 2066 { 2067 static char *filtered_path; 2068 static const char *hints; 2069 static struct elfhints_hdr hdr; 2070 struct fill_search_info_args sargs, hargs; 2071 struct dl_serinfo smeta, hmeta, *SLPinfo, *hintinfo; 2072 struct dl_serpath *SLPpath, *hintpath; 2073 char *p; 2074 struct stat hint_stat; 2075 unsigned int SLPndx, hintndx, fndx, fcount; 2076 int fd; 2077 size_t flen; 2078 uint32_t dl; 2079 uint32_t magic; /* Magic number */ 2080 uint32_t version; /* File version (1) */ 2081 uint32_t strtab; /* Offset of string table in file */ 2082 uint32_t dirlist; /* Offset of directory list in string table */ 2083 uint32_t dirlistlen; /* strlen(dirlist) */ 2084 bool is_le; /* Does the hints file use little endian */ 2085 bool skip; 2086 2087 /* First call, read the hints file */ 2088 if (hints == NULL) { 2089 /* Keep from trying again in case the hints file is bad. */ 2090 hints = ""; 2091 2092 if ((fd = open(ld_elf_hints_path, O_RDONLY | O_CLOEXEC)) == -1) { 2093 dbg("failed to open hints file \"%s\"", ld_elf_hints_path); 2094 return (NULL); 2095 } 2096 2097 /* 2098 * Check of hdr.dirlistlen value against type limit 2099 * intends to pacify static analyzers. Further 2100 * paranoia leads to checks that dirlist is fully 2101 * contained in the file range. 2102 */ 2103 if (read(fd, &hdr, sizeof hdr) != sizeof hdr) { 2104 dbg("failed to read %lu bytes from hints file \"%s\"", 2105 (u_long)sizeof hdr, ld_elf_hints_path); 2106 cleanup1: 2107 close(fd); 2108 hdr.dirlistlen = 0; 2109 return (NULL); 2110 } 2111 dbg("host byte-order: %s-endian", le32toh(1) == 1 ? "little" : "big"); 2112 dbg("hints file byte-order: %s-endian", 2113 hdr.magic == htole32(ELFHINTS_MAGIC) ? "little" : "big"); 2114 is_le = /*htole32(1) == 1 || */ hdr.magic == htole32(ELFHINTS_MAGIC); 2115 magic = COND_SWAP(hdr.magic); 2116 version = COND_SWAP(hdr.version); 2117 strtab = COND_SWAP(hdr.strtab); 2118 dirlist = COND_SWAP(hdr.dirlist); 2119 dirlistlen = COND_SWAP(hdr.dirlistlen); 2120 if (magic != ELFHINTS_MAGIC) { 2121 dbg("invalid magic number %#08x (expected: %#08x)", 2122 magic, ELFHINTS_MAGIC); 2123 goto cleanup1; 2124 } 2125 if (version != 1) { 2126 dbg("hints file version %d (expected: 1)", version); 2127 goto cleanup1; 2128 } 2129 if (dirlistlen > UINT_MAX / 2) { 2130 dbg("directory list is to long: %d > %d", 2131 dirlistlen, UINT_MAX / 2); 2132 goto cleanup1; 2133 } 2134 if (fstat(fd, &hint_stat) == -1) { 2135 dbg("failed to find length of hints file \"%s\"", 2136 ld_elf_hints_path); 2137 goto cleanup1; 2138 } 2139 dl = strtab; 2140 if (dl + dirlist < dl) { 2141 dbg("invalid string table position %d", dl); 2142 goto cleanup1; 2143 } 2144 dl += dirlist; 2145 if (dl + dirlistlen < dl) { 2146 dbg("invalid directory list offset %d", dirlist); 2147 goto cleanup1; 2148 } 2149 dl += dirlistlen; 2150 if (dl > hint_stat.st_size) { 2151 dbg("hints file \"%s\" is truncated (%d vs. %jd bytes)", 2152 ld_elf_hints_path, dl, (uintmax_t)hint_stat.st_size); 2153 goto cleanup1; 2154 } 2155 p = xmalloc(dirlistlen + 1); 2156 if (pread(fd, p, dirlistlen + 1, 2157 strtab + dirlist) != (ssize_t)dirlistlen + 1 || 2158 p[dirlistlen] != '\0') { 2159 free(p); 2160 dbg("failed to read %d bytes starting at %d from hints file \"%s\"", 2161 dirlistlen + 1, strtab + dirlist, ld_elf_hints_path); 2162 goto cleanup1; 2163 } 2164 hints = p; 2165 close(fd); 2166 } 2167 2168 /* 2169 * If caller agreed to receive list which includes the default 2170 * paths, we are done. Otherwise, if we still did not 2171 * calculated filtered result, do it now. 2172 */ 2173 if (!nostdlib) 2174 return (hints[0] != '\0' ? hints : NULL); 2175 if (filtered_path != NULL) 2176 goto filt_ret; 2177 2178 /* 2179 * Obtain the list of all configured search paths, and the 2180 * list of the default paths. 2181 * 2182 * First estimate the size of the results. 2183 */ 2184 smeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 2185 smeta.dls_cnt = 0; 2186 hmeta.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 2187 hmeta.dls_cnt = 0; 2188 2189 sargs.request = RTLD_DI_SERINFOSIZE; 2190 sargs.serinfo = &smeta; 2191 hargs.request = RTLD_DI_SERINFOSIZE; 2192 hargs.serinfo = &hmeta; 2193 2194 path_enumerate(ld_standard_library_path, fill_search_info, NULL, 2195 &sargs); 2196 path_enumerate(hints, fill_search_info, NULL, &hargs); 2197 2198 SLPinfo = xmalloc(smeta.dls_size); 2199 hintinfo = xmalloc(hmeta.dls_size); 2200 2201 /* 2202 * Next fetch both sets of paths. 2203 */ 2204 sargs.request = RTLD_DI_SERINFO; 2205 sargs.serinfo = SLPinfo; 2206 sargs.serpath = &SLPinfo->dls_serpath[0]; 2207 sargs.strspace = (char *)&SLPinfo->dls_serpath[smeta.dls_cnt]; 2208 2209 hargs.request = RTLD_DI_SERINFO; 2210 hargs.serinfo = hintinfo; 2211 hargs.serpath = &hintinfo->dls_serpath[0]; 2212 hargs.strspace = (char *)&hintinfo->dls_serpath[hmeta.dls_cnt]; 2213 2214 path_enumerate(ld_standard_library_path, fill_search_info, NULL, 2215 &sargs); 2216 path_enumerate(hints, fill_search_info, NULL, &hargs); 2217 2218 /* 2219 * Now calculate the difference between two sets, by excluding 2220 * standard paths from the full set. 2221 */ 2222 fndx = 0; 2223 fcount = 0; 2224 filtered_path = xmalloc(dirlistlen + 1); 2225 hintpath = &hintinfo->dls_serpath[0]; 2226 for (hintndx = 0; hintndx < hmeta.dls_cnt; hintndx++, hintpath++) { 2227 skip = false; 2228 SLPpath = &SLPinfo->dls_serpath[0]; 2229 /* 2230 * Check each standard path against current. 2231 */ 2232 for (SLPndx = 0; SLPndx < smeta.dls_cnt; SLPndx++, SLPpath++) { 2233 /* matched, skip the path */ 2234 if (!strcmp(hintpath->dls_name, SLPpath->dls_name)) { 2235 skip = true; 2236 break; 2237 } 2238 } 2239 if (skip) 2240 continue; 2241 /* 2242 * Not matched against any standard path, add the path 2243 * to result. Separate consequtive paths with ':'. 2244 */ 2245 if (fcount > 0) { 2246 filtered_path[fndx] = ':'; 2247 fndx++; 2248 } 2249 fcount++; 2250 flen = strlen(hintpath->dls_name); 2251 strncpy((filtered_path + fndx), hintpath->dls_name, flen); 2252 fndx += flen; 2253 } 2254 filtered_path[fndx] = '\0'; 2255 2256 free(SLPinfo); 2257 free(hintinfo); 2258 2259 filt_ret: 2260 return (filtered_path[0] != '\0' ? filtered_path : NULL); 2261 } 2262 2263 static void 2264 init_dag(Obj_Entry *root) 2265 { 2266 const Needed_Entry *needed; 2267 const Objlist_Entry *elm; 2268 DoneList donelist; 2269 2270 if (root->dag_inited) 2271 return; 2272 donelist_init(&donelist); 2273 2274 /* Root object belongs to own DAG. */ 2275 objlist_push_tail(&root->dldags, root); 2276 objlist_push_tail(&root->dagmembers, root); 2277 donelist_check(&donelist, root); 2278 2279 /* 2280 * Add dependencies of root object to DAG in breadth order 2281 * by exploiting the fact that each new object get added 2282 * to the tail of the dagmembers list. 2283 */ 2284 STAILQ_FOREACH(elm, &root->dagmembers, link) { 2285 for (needed = elm->obj->needed; needed != NULL; needed = needed->next) { 2286 if (needed->obj == NULL || donelist_check(&donelist, needed->obj)) 2287 continue; 2288 objlist_push_tail(&needed->obj->dldags, root); 2289 objlist_push_tail(&root->dagmembers, needed->obj); 2290 } 2291 } 2292 root->dag_inited = true; 2293 } 2294 2295 static void 2296 init_marker(Obj_Entry *marker) 2297 { 2298 2299 bzero(marker, sizeof(*marker)); 2300 marker->marker = true; 2301 } 2302 2303 Obj_Entry * 2304 globallist_curr(const Obj_Entry *obj) 2305 { 2306 2307 for (;;) { 2308 if (obj == NULL) 2309 return (NULL); 2310 if (!obj->marker) 2311 return (__DECONST(Obj_Entry *, obj)); 2312 obj = TAILQ_PREV(obj, obj_entry_q, next); 2313 } 2314 } 2315 2316 Obj_Entry * 2317 globallist_next(const Obj_Entry *obj) 2318 { 2319 2320 for (;;) { 2321 obj = TAILQ_NEXT(obj, next); 2322 if (obj == NULL) 2323 return (NULL); 2324 if (!obj->marker) 2325 return (__DECONST(Obj_Entry *, obj)); 2326 } 2327 } 2328 2329 /* Prevent the object from being unmapped while the bind lock is dropped. */ 2330 static void 2331 hold_object(Obj_Entry *obj) 2332 { 2333 2334 obj->holdcount++; 2335 } 2336 2337 static void 2338 unhold_object(Obj_Entry *obj) 2339 { 2340 2341 assert(obj->holdcount > 0); 2342 if (--obj->holdcount == 0 && obj->unholdfree) 2343 release_object(obj); 2344 } 2345 2346 static void 2347 process_z(Obj_Entry *root) 2348 { 2349 const Objlist_Entry *elm; 2350 Obj_Entry *obj; 2351 2352 /* 2353 * Walk over object DAG and process every dependent object 2354 * that is marked as DF_1_NODELETE or DF_1_GLOBAL. They need 2355 * to grow their own DAG. 2356 * 2357 * For DF_1_GLOBAL, DAG is required for symbol lookups in 2358 * symlook_global() to work. 2359 * 2360 * For DF_1_NODELETE, the DAG should have its reference upped. 2361 */ 2362 STAILQ_FOREACH(elm, &root->dagmembers, link) { 2363 obj = elm->obj; 2364 if (obj == NULL) 2365 continue; 2366 if (obj->z_nodelete && !obj->ref_nodel) { 2367 dbg("obj %s -z nodelete", obj->path); 2368 init_dag(obj); 2369 ref_dag(obj); 2370 obj->ref_nodel = true; 2371 } 2372 if (obj->z_global && objlist_find(&list_global, obj) == NULL) { 2373 dbg("obj %s -z global", obj->path); 2374 objlist_push_tail(&list_global, obj); 2375 init_dag(obj); 2376 } 2377 } 2378 } 2379 2380 static void 2381 parse_rtld_phdr(Obj_Entry *obj) 2382 { 2383 const Elf_Phdr *ph; 2384 Elf_Addr note_start, note_end; 2385 2386 obj->stack_flags = PF_X | PF_R | PF_W; 2387 for (ph = obj->phdr; (const char *)ph < (const char *)obj->phdr + 2388 obj->phsize; ph++) { 2389 switch (ph->p_type) { 2390 case PT_GNU_STACK: 2391 obj->stack_flags = ph->p_flags; 2392 break; 2393 case PT_GNU_RELRO: 2394 obj->relro_page = obj->relocbase + 2395 rtld_trunc_page(ph->p_vaddr); 2396 obj->relro_size = rtld_round_page(ph->p_memsz); 2397 break; 2398 case PT_NOTE: 2399 note_start = (Elf_Addr)obj->relocbase + ph->p_vaddr; 2400 note_end = note_start + ph->p_filesz; 2401 digest_notes(obj, note_start, note_end); 2402 break; 2403 } 2404 } 2405 } 2406 2407 /* 2408 * Initialize the dynamic linker. The argument is the address at which 2409 * the dynamic linker has been mapped into memory. The primary task of 2410 * this function is to relocate the dynamic linker. 2411 */ 2412 static void 2413 init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info) 2414 { 2415 Obj_Entry objtmp; /* Temporary rtld object */ 2416 const Elf_Ehdr *ehdr; 2417 const Elf_Dyn *dyn_rpath; 2418 const Elf_Dyn *dyn_soname; 2419 const Elf_Dyn *dyn_runpath; 2420 2421 #ifdef RTLD_INIT_PAGESIZES_EARLY 2422 /* The page size is required by the dynamic memory allocator. */ 2423 init_pagesizes(aux_info); 2424 #endif 2425 2426 /* 2427 * Conjure up an Obj_Entry structure for the dynamic linker. 2428 * 2429 * The "path" member can't be initialized yet because string constants 2430 * cannot yet be accessed. Below we will set it correctly. 2431 */ 2432 memset(&objtmp, 0, sizeof(objtmp)); 2433 objtmp.path = NULL; 2434 objtmp.rtld = true; 2435 objtmp.mapbase = mapbase; 2436 #ifdef PIC 2437 objtmp.relocbase = mapbase; 2438 #endif 2439 2440 objtmp.dynamic = rtld_dynamic(&objtmp); 2441 digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname, &dyn_runpath); 2442 assert(objtmp.needed == NULL); 2443 assert(!objtmp.textrel); 2444 /* 2445 * Temporarily put the dynamic linker entry into the object list, so 2446 * that symbols can be found. 2447 */ 2448 relocate_objects(&objtmp, true, &objtmp, 0, NULL); 2449 2450 ehdr = (Elf_Ehdr *)mapbase; 2451 objtmp.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff); 2452 objtmp.phsize = ehdr->e_phnum * sizeof(objtmp.phdr[0]); 2453 2454 /* Initialize the object list. */ 2455 TAILQ_INIT(&obj_list); 2456 2457 /* Now that non-local variables can be accesses, copy out obj_rtld. */ 2458 memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld)); 2459 2460 #ifndef RTLD_INIT_PAGESIZES_EARLY 2461 /* The page size is required by the dynamic memory allocator. */ 2462 init_pagesizes(aux_info); 2463 #endif 2464 2465 if (aux_info[AT_OSRELDATE] != NULL) 2466 osreldate = aux_info[AT_OSRELDATE]->a_un.a_val; 2467 2468 digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname, dyn_runpath); 2469 2470 /* Replace the path with a dynamically allocated copy. */ 2471 obj_rtld.path = xstrdup(ld_path_rtld); 2472 2473 parse_rtld_phdr(&obj_rtld); 2474 if (obj_enforce_relro(&obj_rtld) == -1) 2475 rtld_die(); 2476 2477 r_debug.r_version = R_DEBUG_VERSION; 2478 r_debug.r_brk = r_debug_state; 2479 r_debug.r_state = RT_CONSISTENT; 2480 r_debug.r_ldbase = obj_rtld.relocbase; 2481 } 2482 2483 /* 2484 * Retrieve the array of supported page sizes. The kernel provides the page 2485 * sizes in increasing order. 2486 */ 2487 static void 2488 init_pagesizes(Elf_Auxinfo **aux_info) 2489 { 2490 static size_t psa[MAXPAGESIZES]; 2491 int mib[2]; 2492 size_t len, size; 2493 2494 if (aux_info[AT_PAGESIZES] != NULL && aux_info[AT_PAGESIZESLEN] != 2495 NULL) { 2496 size = aux_info[AT_PAGESIZESLEN]->a_un.a_val; 2497 pagesizes = aux_info[AT_PAGESIZES]->a_un.a_ptr; 2498 } else { 2499 len = 2; 2500 if (sysctlnametomib("hw.pagesizes", mib, &len) == 0) 2501 size = sizeof(psa); 2502 else { 2503 /* As a fallback, retrieve the base page size. */ 2504 size = sizeof(psa[0]); 2505 if (aux_info[AT_PAGESZ] != NULL) { 2506 psa[0] = aux_info[AT_PAGESZ]->a_un.a_val; 2507 goto psa_filled; 2508 } else { 2509 mib[0] = CTL_HW; 2510 mib[1] = HW_PAGESIZE; 2511 len = 2; 2512 } 2513 } 2514 if (sysctl(mib, len, psa, &size, NULL, 0) == -1) { 2515 _rtld_error("sysctl for hw.pagesize(s) failed"); 2516 rtld_die(); 2517 } 2518 psa_filled: 2519 pagesizes = psa; 2520 } 2521 npagesizes = size / sizeof(pagesizes[0]); 2522 /* Discard any invalid entries at the end of the array. */ 2523 while (npagesizes > 0 && pagesizes[npagesizes - 1] == 0) 2524 npagesizes--; 2525 2526 page_size = pagesizes[0]; 2527 } 2528 2529 /* 2530 * Add the init functions from a needed object list (and its recursive 2531 * needed objects) to "list". This is not used directly; it is a helper 2532 * function for initlist_add_objects(). The write lock must be held 2533 * when this function is called. 2534 */ 2535 static void 2536 initlist_add_neededs(Needed_Entry *needed, Objlist *list) 2537 { 2538 /* Recursively process the successor needed objects. */ 2539 if (needed->next != NULL) 2540 initlist_add_neededs(needed->next, list); 2541 2542 /* Process the current needed object. */ 2543 if (needed->obj != NULL) 2544 initlist_add_objects(needed->obj, needed->obj, list); 2545 } 2546 2547 /* 2548 * Scan all of the DAGs rooted in the range of objects from "obj" to 2549 * "tail" and add their init functions to "list". This recurses over 2550 * the DAGs and ensure the proper init ordering such that each object's 2551 * needed libraries are initialized before the object itself. At the 2552 * same time, this function adds the objects to the global finalization 2553 * list "list_fini" in the opposite order. The write lock must be 2554 * held when this function is called. 2555 */ 2556 static void 2557 initlist_add_objects(Obj_Entry *obj, Obj_Entry *tail, Objlist *list) 2558 { 2559 Obj_Entry *nobj; 2560 2561 if (obj->init_scanned || obj->init_done) 2562 return; 2563 obj->init_scanned = true; 2564 2565 /* Recursively process the successor objects. */ 2566 nobj = globallist_next(obj); 2567 if (nobj != NULL && obj != tail) 2568 initlist_add_objects(nobj, tail, list); 2569 2570 /* Recursively process the needed objects. */ 2571 if (obj->needed != NULL) 2572 initlist_add_neededs(obj->needed, list); 2573 if (obj->needed_filtees != NULL) 2574 initlist_add_neededs(obj->needed_filtees, list); 2575 if (obj->needed_aux_filtees != NULL) 2576 initlist_add_neededs(obj->needed_aux_filtees, list); 2577 2578 /* Add the object to the init list. */ 2579 objlist_push_tail(list, obj); 2580 2581 /* Add the object to the global fini list in the reverse order. */ 2582 if ((obj->fini != (Elf_Addr)NULL || obj->fini_array != (Elf_Addr)NULL) 2583 && !obj->on_fini_list) { 2584 objlist_push_head(&list_fini, obj); 2585 obj->on_fini_list = true; 2586 } 2587 } 2588 2589 static void 2590 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate) 2591 { 2592 Needed_Entry *needed, *needed1; 2593 2594 for (needed = n; needed != NULL; needed = needed->next) { 2595 if (needed->obj != NULL) { 2596 dlclose_locked(needed->obj, lockstate); 2597 needed->obj = NULL; 2598 } 2599 } 2600 for (needed = n; needed != NULL; needed = needed1) { 2601 needed1 = needed->next; 2602 free(needed); 2603 } 2604 } 2605 2606 static void 2607 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate) 2608 { 2609 2610 free_needed_filtees(obj->needed_filtees, lockstate); 2611 obj->needed_filtees = NULL; 2612 free_needed_filtees(obj->needed_aux_filtees, lockstate); 2613 obj->needed_aux_filtees = NULL; 2614 obj->filtees_loaded = false; 2615 } 2616 2617 static void 2618 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags, 2619 RtldLockState *lockstate) 2620 { 2621 2622 for (; needed != NULL; needed = needed->next) { 2623 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj, 2624 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) | 2625 RTLD_LOCAL, lockstate); 2626 } 2627 } 2628 2629 static void 2630 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate) 2631 { 2632 if (obj->filtees_loaded || obj->filtees_loading) 2633 return; 2634 lock_restart_for_upgrade(lockstate); 2635 obj->filtees_loading = true; 2636 load_filtee1(obj, obj->needed_filtees, flags, lockstate); 2637 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate); 2638 obj->filtees_loaded = true; 2639 obj->filtees_loading = false; 2640 } 2641 2642 static int 2643 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags) 2644 { 2645 Obj_Entry *obj1; 2646 2647 for (; needed != NULL; needed = needed->next) { 2648 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, obj, 2649 flags & ~RTLD_LO_NOLOAD); 2650 if (obj1 == NULL && !ld_tracing && (flags & RTLD_LO_FILTEES) == 0) 2651 return (-1); 2652 } 2653 return (0); 2654 } 2655 2656 /* 2657 * Given a shared object, traverse its list of needed objects, and load 2658 * each of them. Returns 0 on success. Generates an error message and 2659 * returns -1 on failure. 2660 */ 2661 static int 2662 load_needed_objects(Obj_Entry *first, int flags) 2663 { 2664 Obj_Entry *obj; 2665 2666 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 2667 if (obj->marker) 2668 continue; 2669 if (process_needed(obj, obj->needed, flags) == -1) 2670 return (-1); 2671 } 2672 return (0); 2673 } 2674 2675 static int 2676 load_preload_objects(const char *penv, bool isfd) 2677 { 2678 Obj_Entry *obj; 2679 const char *name; 2680 size_t len; 2681 char savech, *p, *psave; 2682 int fd; 2683 static const char delim[] = " \t:;"; 2684 2685 if (penv == NULL) 2686 return (0); 2687 2688 p = psave = xstrdup(penv); 2689 p += strspn(p, delim); 2690 while (*p != '\0') { 2691 len = strcspn(p, delim); 2692 2693 savech = p[len]; 2694 p[len] = '\0'; 2695 if (isfd) { 2696 name = NULL; 2697 fd = parse_integer(p); 2698 if (fd == -1) { 2699 free(psave); 2700 return (-1); 2701 } 2702 } else { 2703 name = p; 2704 fd = -1; 2705 } 2706 2707 obj = load_object(name, fd, NULL, 0); 2708 if (obj == NULL) { 2709 free(psave); 2710 return (-1); /* XXX - cleanup */ 2711 } 2712 obj->z_interpose = true; 2713 p[len] = savech; 2714 p += len; 2715 p += strspn(p, delim); 2716 } 2717 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL); 2718 2719 free(psave); 2720 return (0); 2721 } 2722 2723 static const char * 2724 printable_path(const char *path) 2725 { 2726 2727 return (path == NULL ? "<unknown>" : path); 2728 } 2729 2730 /* 2731 * Load a shared object into memory, if it is not already loaded. The 2732 * object may be specified by name or by user-supplied file descriptor 2733 * fd_u. In the later case, the fd_u descriptor is not closed, but its 2734 * duplicate is. 2735 * 2736 * Returns a pointer to the Obj_Entry for the object. Returns NULL 2737 * on failure. 2738 */ 2739 static Obj_Entry * 2740 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags) 2741 { 2742 Obj_Entry *obj; 2743 int fd; 2744 struct stat sb; 2745 char *path; 2746 2747 fd = -1; 2748 if (name != NULL) { 2749 TAILQ_FOREACH(obj, &obj_list, next) { 2750 if (obj->marker || obj->doomed) 2751 continue; 2752 if (object_match_name(obj, name)) 2753 return (obj); 2754 } 2755 2756 path = find_library(name, refobj, &fd); 2757 if (path == NULL) 2758 return (NULL); 2759 } else 2760 path = NULL; 2761 2762 if (fd >= 0) { 2763 /* 2764 * search_library_pathfds() opens a fresh file descriptor for the 2765 * library, so there is no need to dup(). 2766 */ 2767 } else if (fd_u == -1) { 2768 /* 2769 * If we didn't find a match by pathname, or the name is not 2770 * supplied, open the file and check again by device and inode. 2771 * This avoids false mismatches caused by multiple links or ".." 2772 * in pathnames. 2773 * 2774 * To avoid a race, we open the file and use fstat() rather than 2775 * using stat(). 2776 */ 2777 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) { 2778 _rtld_error("Cannot open \"%s\"", path); 2779 free(path); 2780 return (NULL); 2781 } 2782 } else { 2783 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0); 2784 if (fd == -1) { 2785 _rtld_error("Cannot dup fd"); 2786 free(path); 2787 return (NULL); 2788 } 2789 } 2790 if (fstat(fd, &sb) == -1) { 2791 _rtld_error("Cannot fstat \"%s\"", printable_path(path)); 2792 close(fd); 2793 free(path); 2794 return (NULL); 2795 } 2796 TAILQ_FOREACH(obj, &obj_list, next) { 2797 if (obj->marker || obj->doomed) 2798 continue; 2799 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) 2800 break; 2801 } 2802 if (obj != NULL) { 2803 if (name != NULL) 2804 object_add_name(obj, name); 2805 free(path); 2806 close(fd); 2807 return (obj); 2808 } 2809 if (flags & RTLD_LO_NOLOAD) { 2810 free(path); 2811 close(fd); 2812 return (NULL); 2813 } 2814 2815 /* First use of this object, so we must map it in */ 2816 obj = do_load_object(fd, name, path, &sb, flags); 2817 if (obj == NULL) 2818 free(path); 2819 close(fd); 2820 2821 return (obj); 2822 } 2823 2824 static Obj_Entry * 2825 do_load_object(int fd, const char *name, char *path, struct stat *sbp, 2826 int flags) 2827 { 2828 Obj_Entry *obj; 2829 struct statfs fs; 2830 2831 /* 2832 * First, make sure that environment variables haven't been 2833 * used to circumvent the noexec flag on a filesystem. 2834 * We ignore fstatfs(2) failures, since fd might reference 2835 * not a file, e.g. shmfd. 2836 */ 2837 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 && 2838 (fs.f_flags & MNT_NOEXEC) != 0) { 2839 _rtld_error("Cannot execute objects on %s", fs.f_mntonname); 2840 return (NULL); 2841 } 2842 2843 dbg("loading \"%s\"", printable_path(path)); 2844 obj = map_object(fd, printable_path(path), sbp); 2845 if (obj == NULL) 2846 return (NULL); 2847 2848 /* 2849 * If DT_SONAME is present in the object, digest_dynamic2 already 2850 * added it to the object names. 2851 */ 2852 if (name != NULL) 2853 object_add_name(obj, name); 2854 obj->path = path; 2855 if (!digest_dynamic(obj, 0)) 2856 goto errp; 2857 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path, 2858 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount); 2859 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) { 2860 dbg("refusing to load PIE executable \"%s\"", obj->path); 2861 _rtld_error("Cannot load PIE binary %s as DSO", obj->path); 2862 goto errp; 2863 } 2864 if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) == 2865 RTLD_LO_DLOPEN) { 2866 dbg("refusing to load non-loadable \"%s\"", obj->path); 2867 _rtld_error("Cannot dlopen non-loadable %s", obj->path); 2868 goto errp; 2869 } 2870 2871 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0; 2872 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2873 obj_count++; 2874 obj_loads++; 2875 linkmap_add(obj); /* for GDB & dlinfo() */ 2876 max_stack_flags |= obj->stack_flags; 2877 2878 dbg(" %p .. %p: %s", obj->mapbase, 2879 obj->mapbase + obj->mapsize - 1, obj->path); 2880 if (obj->textrel) 2881 dbg(" WARNING: %s has impure text", obj->path); 2882 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 2883 obj->path); 2884 2885 return (obj); 2886 2887 errp: 2888 munmap(obj->mapbase, obj->mapsize); 2889 obj_free(obj); 2890 return (NULL); 2891 } 2892 2893 static int 2894 load_kpreload(const void *addr) 2895 { 2896 Obj_Entry *obj; 2897 const Elf_Ehdr *ehdr; 2898 const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn; 2899 static const char kname[] = "[vdso]"; 2900 2901 ehdr = addr; 2902 if (!check_elf_headers(ehdr, "kpreload")) 2903 return (-1); 2904 obj = obj_new(); 2905 phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff); 2906 obj->phdr = phdr; 2907 obj->phsize = ehdr->e_phnum * sizeof(*phdr); 2908 phlimit = phdr + ehdr->e_phnum; 2909 seg0 = segn = NULL; 2910 2911 for (; phdr < phlimit; phdr++) { 2912 switch (phdr->p_type) { 2913 case PT_DYNAMIC: 2914 phdyn = phdr; 2915 break; 2916 case PT_GNU_STACK: 2917 /* Absense of PT_GNU_STACK implies stack_flags == 0. */ 2918 obj->stack_flags = phdr->p_flags; 2919 break; 2920 case PT_LOAD: 2921 if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr) 2922 seg0 = phdr; 2923 if (segn == NULL || segn->p_vaddr + segn->p_memsz < 2924 phdr->p_vaddr + phdr->p_memsz) 2925 segn = phdr; 2926 break; 2927 } 2928 } 2929 2930 obj->mapbase = __DECONST(caddr_t, addr); 2931 obj->mapsize = segn->p_vaddr + segn->p_memsz - (Elf_Addr)addr; 2932 obj->vaddrbase = 0; 2933 obj->relocbase = obj->mapbase; 2934 2935 object_add_name(obj, kname); 2936 obj->path = xstrdup(kname); 2937 obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr); 2938 2939 if (!digest_dynamic(obj, 0)) { 2940 obj_free(obj); 2941 return (-1); 2942 } 2943 2944 /* 2945 * We assume that kernel-preloaded object does not need 2946 * relocation. It is currently written into read-only page, 2947 * handling relocations would mean we need to allocate at 2948 * least one additional page per AS. 2949 */ 2950 dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p", 2951 obj->path, obj->mapbase, obj->phdr, seg0, 2952 obj->relocbase + seg0->p_vaddr, obj->dynamic); 2953 2954 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2955 obj_count++; 2956 obj_loads++; 2957 linkmap_add(obj); /* for GDB & dlinfo() */ 2958 max_stack_flags |= obj->stack_flags; 2959 2960 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, 0, 0, obj->path); 2961 return (0); 2962 } 2963 2964 Obj_Entry * 2965 obj_from_addr(const void *addr) 2966 { 2967 Obj_Entry *obj; 2968 2969 TAILQ_FOREACH(obj, &obj_list, next) { 2970 if (obj->marker) 2971 continue; 2972 if (addr < (void *) obj->mapbase) 2973 continue; 2974 if (addr < (void *)(obj->mapbase + obj->mapsize)) 2975 return obj; 2976 } 2977 return (NULL); 2978 } 2979 2980 static void 2981 preinit_main(void) 2982 { 2983 Elf_Addr *preinit_addr; 2984 int index; 2985 2986 preinit_addr = (Elf_Addr *)obj_main->preinit_array; 2987 if (preinit_addr == NULL) 2988 return; 2989 2990 for (index = 0; index < obj_main->preinit_array_num; index++) { 2991 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) { 2992 dbg("calling preinit function for %s at %p", obj_main->path, 2993 (void *)preinit_addr[index]); 2994 LD_UTRACE(UTRACE_INIT_CALL, obj_main, (void *)preinit_addr[index], 2995 0, 0, obj_main->path); 2996 call_init_pointer(obj_main, preinit_addr[index]); 2997 } 2998 } 2999 } 3000 3001 /* 3002 * Call the finalization functions for each of the objects in "list" 3003 * belonging to the DAG of "root" and referenced once. If NULL "root" 3004 * is specified, every finalization function will be called regardless 3005 * of the reference count and the list elements won't be freed. All of 3006 * the objects are expected to have non-NULL fini functions. 3007 */ 3008 static void 3009 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate) 3010 { 3011 Objlist_Entry *elm; 3012 struct dlerror_save *saved_msg; 3013 Elf_Addr *fini_addr; 3014 int index; 3015 3016 assert(root == NULL || root->refcount == 1); 3017 3018 if (root != NULL) 3019 root->doomed = true; 3020 3021 /* 3022 * Preserve the current error message since a fini function might 3023 * call into the dynamic linker and overwrite it. 3024 */ 3025 saved_msg = errmsg_save(); 3026 do { 3027 STAILQ_FOREACH(elm, list, link) { 3028 if (root != NULL && (elm->obj->refcount != 1 || 3029 objlist_find(&root->dagmembers, elm->obj) == NULL)) 3030 continue; 3031 /* Remove object from fini list to prevent recursive invocation. */ 3032 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 3033 /* Ensure that new references cannot be acquired. */ 3034 elm->obj->doomed = true; 3035 3036 hold_object(elm->obj); 3037 lock_release(rtld_bind_lock, lockstate); 3038 /* 3039 * It is legal to have both DT_FINI and DT_FINI_ARRAY defined. 3040 * When this happens, DT_FINI_ARRAY is processed first. 3041 */ 3042 fini_addr = (Elf_Addr *)elm->obj->fini_array; 3043 if (fini_addr != NULL && elm->obj->fini_array_num > 0) { 3044 for (index = elm->obj->fini_array_num - 1; index >= 0; 3045 index--) { 3046 if (fini_addr[index] != 0 && fini_addr[index] != 1) { 3047 dbg("calling fini function for %s at %p", 3048 elm->obj->path, (void *)fini_addr[index]); 3049 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, 3050 (void *)fini_addr[index], 0, 0, elm->obj->path); 3051 call_initfini_pointer(elm->obj, fini_addr[index]); 3052 } 3053 } 3054 } 3055 if (elm->obj->fini != (Elf_Addr)NULL) { 3056 dbg("calling fini function for %s at %p", elm->obj->path, 3057 (void *)elm->obj->fini); 3058 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 3059 0, 0, elm->obj->path); 3060 call_initfini_pointer(elm->obj, elm->obj->fini); 3061 } 3062 wlock_acquire(rtld_bind_lock, lockstate); 3063 unhold_object(elm->obj); 3064 /* No need to free anything if process is going down. */ 3065 if (root != NULL) 3066 free(elm); 3067 /* 3068 * We must restart the list traversal after every fini call 3069 * because a dlclose() call from the fini function or from 3070 * another thread might have modified the reference counts. 3071 */ 3072 break; 3073 } 3074 } while (elm != NULL); 3075 errmsg_restore(saved_msg); 3076 } 3077 3078 /* 3079 * Call the initialization functions for each of the objects in 3080 * "list". All of the objects are expected to have non-NULL init 3081 * functions. 3082 */ 3083 static void 3084 objlist_call_init(Objlist *list, RtldLockState *lockstate) 3085 { 3086 Objlist_Entry *elm; 3087 Obj_Entry *obj; 3088 struct dlerror_save *saved_msg; 3089 Elf_Addr *init_addr; 3090 void (*reg)(void (*)(void)); 3091 int index; 3092 3093 /* 3094 * Clean init_scanned flag so that objects can be rechecked and 3095 * possibly initialized earlier if any of vectors called below 3096 * cause the change by using dlopen. 3097 */ 3098 TAILQ_FOREACH(obj, &obj_list, next) { 3099 if (obj->marker) 3100 continue; 3101 obj->init_scanned = false; 3102 } 3103 3104 /* 3105 * Preserve the current error message since an init function might 3106 * call into the dynamic linker and overwrite it. 3107 */ 3108 saved_msg = errmsg_save(); 3109 STAILQ_FOREACH(elm, list, link) { 3110 if (elm->obj->init_done) /* Initialized early. */ 3111 continue; 3112 /* 3113 * Race: other thread might try to use this object before current 3114 * one completes the initialization. Not much can be done here 3115 * without better locking. 3116 */ 3117 elm->obj->init_done = true; 3118 hold_object(elm->obj); 3119 reg = NULL; 3120 if (elm->obj == obj_main && obj_main->crt_no_init) { 3121 reg = (void (*)(void (*)(void)))get_program_var_addr( 3122 "__libc_atexit", lockstate); 3123 } 3124 lock_release(rtld_bind_lock, lockstate); 3125 if (reg != NULL) { 3126 reg(rtld_exit); 3127 rtld_exit_ptr = rtld_nop_exit; 3128 } 3129 3130 /* 3131 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. 3132 * When this happens, DT_INIT is processed first. 3133 */ 3134 if (elm->obj->init != (Elf_Addr)NULL) { 3135 dbg("calling init function for %s at %p", elm->obj->path, 3136 (void *)elm->obj->init); 3137 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 3138 0, 0, elm->obj->path); 3139 call_init_pointer(elm->obj, elm->obj->init); 3140 } 3141 init_addr = (Elf_Addr *)elm->obj->init_array; 3142 if (init_addr != NULL) { 3143 for (index = 0; index < elm->obj->init_array_num; index++) { 3144 if (init_addr[index] != 0 && init_addr[index] != 1) { 3145 dbg("calling init function for %s at %p", elm->obj->path, 3146 (void *)init_addr[index]); 3147 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, 3148 (void *)init_addr[index], 0, 0, elm->obj->path); 3149 call_init_pointer(elm->obj, init_addr[index]); 3150 } 3151 } 3152 } 3153 wlock_acquire(rtld_bind_lock, lockstate); 3154 unhold_object(elm->obj); 3155 } 3156 errmsg_restore(saved_msg); 3157 } 3158 3159 static void 3160 objlist_clear(Objlist *list) 3161 { 3162 Objlist_Entry *elm; 3163 3164 while (!STAILQ_EMPTY(list)) { 3165 elm = STAILQ_FIRST(list); 3166 STAILQ_REMOVE_HEAD(list, link); 3167 free(elm); 3168 } 3169 } 3170 3171 static Objlist_Entry * 3172 objlist_find(Objlist *list, const Obj_Entry *obj) 3173 { 3174 Objlist_Entry *elm; 3175 3176 STAILQ_FOREACH(elm, list, link) 3177 if (elm->obj == obj) 3178 return elm; 3179 return (NULL); 3180 } 3181 3182 static void 3183 objlist_init(Objlist *list) 3184 { 3185 STAILQ_INIT(list); 3186 } 3187 3188 static void 3189 objlist_push_head(Objlist *list, Obj_Entry *obj) 3190 { 3191 Objlist_Entry *elm; 3192 3193 elm = NEW(Objlist_Entry); 3194 elm->obj = obj; 3195 STAILQ_INSERT_HEAD(list, elm, link); 3196 } 3197 3198 static void 3199 objlist_push_tail(Objlist *list, Obj_Entry *obj) 3200 { 3201 Objlist_Entry *elm; 3202 3203 elm = NEW(Objlist_Entry); 3204 elm->obj = obj; 3205 STAILQ_INSERT_TAIL(list, elm, link); 3206 } 3207 3208 static void 3209 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj) 3210 { 3211 Objlist_Entry *elm, *listelm; 3212 3213 STAILQ_FOREACH(listelm, list, link) { 3214 if (listelm->obj == listobj) 3215 break; 3216 } 3217 elm = NEW(Objlist_Entry); 3218 elm->obj = obj; 3219 if (listelm != NULL) 3220 STAILQ_INSERT_AFTER(list, listelm, elm, link); 3221 else 3222 STAILQ_INSERT_TAIL(list, elm, link); 3223 } 3224 3225 static void 3226 objlist_remove(Objlist *list, Obj_Entry *obj) 3227 { 3228 Objlist_Entry *elm; 3229 3230 if ((elm = objlist_find(list, obj)) != NULL) { 3231 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 3232 free(elm); 3233 } 3234 } 3235 3236 /* 3237 * Relocate dag rooted in the specified object. 3238 * Returns 0 on success, or -1 on failure. 3239 */ 3240 3241 static int 3242 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj, 3243 int flags, RtldLockState *lockstate) 3244 { 3245 Objlist_Entry *elm; 3246 int error; 3247 3248 error = 0; 3249 STAILQ_FOREACH(elm, &root->dagmembers, link) { 3250 error = relocate_object(elm->obj, bind_now, rtldobj, flags, 3251 lockstate); 3252 if (error == -1) 3253 break; 3254 } 3255 return (error); 3256 } 3257 3258 /* 3259 * Prepare for, or clean after, relocating an object marked with 3260 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only 3261 * segments are remapped read-write. After relocations are done, the 3262 * segment's permissions are returned back to the modes specified in 3263 * the phdrs. If any relocation happened, or always for wired 3264 * program, COW is triggered. 3265 */ 3266 static int 3267 reloc_textrel_prot(Obj_Entry *obj, bool before) 3268 { 3269 const Elf_Phdr *ph; 3270 void *base; 3271 size_t l, sz; 3272 int prot; 3273 3274 for (l = obj->phsize / sizeof(*ph), ph = obj->phdr; l > 0; 3275 l--, ph++) { 3276 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0) 3277 continue; 3278 base = obj->relocbase + rtld_trunc_page(ph->p_vaddr); 3279 sz = rtld_round_page(ph->p_vaddr + ph->p_filesz) - 3280 rtld_trunc_page(ph->p_vaddr); 3281 prot = before ? (PROT_READ | PROT_WRITE) : 3282 convert_prot(ph->p_flags); 3283 if (mprotect(base, sz, prot) == -1) { 3284 _rtld_error("%s: Cannot write-%sable text segment: %s", 3285 obj->path, before ? "en" : "dis", 3286 rtld_strerror(errno)); 3287 return (-1); 3288 } 3289 } 3290 return (0); 3291 } 3292 3293 /* Process RELR relative relocations. */ 3294 static void 3295 reloc_relr(Obj_Entry *obj) 3296 { 3297 const Elf_Relr *relr, *relrlim; 3298 Elf_Addr *where; 3299 3300 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize); 3301 for (relr = obj->relr; relr < relrlim; relr++) { 3302 Elf_Relr entry = *relr; 3303 3304 if ((entry & 1) == 0) { 3305 where = (Elf_Addr *)(obj->relocbase + entry); 3306 *where++ += (Elf_Addr)obj->relocbase; 3307 } else { 3308 for (long i = 0; (entry >>= 1) != 0; i++) 3309 if ((entry & 1) != 0) 3310 where[i] += (Elf_Addr)obj->relocbase; 3311 where += CHAR_BIT * sizeof(Elf_Relr) - 1; 3312 } 3313 } 3314 } 3315 3316 /* 3317 * Relocate single object. 3318 * Returns 0 on success, or -1 on failure. 3319 */ 3320 static int 3321 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, 3322 int flags, RtldLockState *lockstate) 3323 { 3324 3325 if (obj->relocated) 3326 return (0); 3327 obj->relocated = true; 3328 if (obj != rtldobj) 3329 dbg("relocating \"%s\"", obj->path); 3330 3331 if (obj->symtab == NULL || obj->strtab == NULL || 3332 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) 3333 dbg("object %s has no run-time symbol table", obj->path); 3334 3335 /* There are relocations to the write-protected text segment. */ 3336 if (obj->textrel && reloc_textrel_prot(obj, true) != 0) 3337 return (-1); 3338 3339 /* Process the non-PLT non-IFUNC relocations. */ 3340 if (reloc_non_plt(obj, rtldobj, flags, lockstate)) 3341 return (-1); 3342 reloc_relr(obj); 3343 3344 /* Re-protected the text segment. */ 3345 if (obj->textrel && reloc_textrel_prot(obj, false) != 0) 3346 return (-1); 3347 3348 /* Set the special PLT or GOT entries. */ 3349 init_pltgot(obj); 3350 3351 /* Process the PLT relocations. */ 3352 if (reloc_plt(obj, flags, lockstate) == -1) 3353 return (-1); 3354 /* Relocate the jump slots if we are doing immediate binding. */ 3355 if ((obj->bind_now || bind_now) && reloc_jmpslots(obj, flags, 3356 lockstate) == -1) 3357 return (-1); 3358 3359 if (!obj->mainprog && obj_enforce_relro(obj) == -1) 3360 return (-1); 3361 3362 /* 3363 * Set up the magic number and version in the Obj_Entry. These 3364 * were checked in the crt1.o from the original ElfKit, so we 3365 * set them for backward compatibility. 3366 */ 3367 obj->magic = RTLD_MAGIC; 3368 obj->version = RTLD_VERSION; 3369 3370 return (0); 3371 } 3372 3373 /* 3374 * Relocate newly-loaded shared objects. The argument is a pointer to 3375 * the Obj_Entry for the first such object. All objects from the first 3376 * to the end of the list of objects are relocated. Returns 0 on success, 3377 * or -1 on failure. 3378 */ 3379 static int 3380 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj, 3381 int flags, RtldLockState *lockstate) 3382 { 3383 Obj_Entry *obj; 3384 int error; 3385 3386 for (error = 0, obj = first; obj != NULL; 3387 obj = TAILQ_NEXT(obj, next)) { 3388 if (obj->marker) 3389 continue; 3390 error = relocate_object(obj, bind_now, rtldobj, flags, 3391 lockstate); 3392 if (error == -1) 3393 break; 3394 } 3395 return (error); 3396 } 3397 3398 /* 3399 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots 3400 * referencing STT_GNU_IFUNC symbols is postponed till the other 3401 * relocations are done. The indirect functions specified as 3402 * ifunc are allowed to call other symbols, so we need to have 3403 * objects relocated before asking for resolution from indirects. 3404 * 3405 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion, 3406 * instead of the usual lazy handling of PLT slots. It is 3407 * consistent with how GNU does it. 3408 */ 3409 static int 3410 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags, 3411 RtldLockState *lockstate) 3412 { 3413 3414 if (obj->ifuncs_resolved) 3415 return (0); 3416 obj->ifuncs_resolved = true; 3417 if (!obj->irelative && !obj->irelative_nonplt && 3418 !((obj->bind_now || bind_now) && obj->gnu_ifunc) && 3419 !obj->non_plt_gnu_ifunc) 3420 return (0); 3421 if (obj_disable_relro(obj) == -1 || 3422 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) || 3423 (obj->irelative_nonplt && reloc_iresolve_nonplt(obj, 3424 lockstate) == -1) || 3425 ((obj->bind_now || bind_now) && obj->gnu_ifunc && 3426 reloc_gnu_ifunc(obj, flags, lockstate) == -1) || 3427 (obj->non_plt_gnu_ifunc && reloc_non_plt(obj, &obj_rtld, 3428 flags | SYMLOOK_IFUNC, lockstate) == -1) || 3429 obj_enforce_relro(obj) == -1) 3430 return (-1); 3431 return (0); 3432 } 3433 3434 static int 3435 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags, 3436 RtldLockState *lockstate) 3437 { 3438 Objlist_Entry *elm; 3439 Obj_Entry *obj; 3440 3441 STAILQ_FOREACH(elm, list, link) { 3442 obj = elm->obj; 3443 if (obj->marker) 3444 continue; 3445 if (resolve_object_ifunc(obj, bind_now, flags, 3446 lockstate) == -1) 3447 return (-1); 3448 } 3449 return (0); 3450 } 3451 3452 /* 3453 * Cleanup procedure. It will be called (by the atexit mechanism) just 3454 * before the process exits. 3455 */ 3456 static void 3457 rtld_exit(void) 3458 { 3459 RtldLockState lockstate; 3460 3461 wlock_acquire(rtld_bind_lock, &lockstate); 3462 dbg("rtld_exit()"); 3463 objlist_call_fini(&list_fini, NULL, &lockstate); 3464 /* No need to remove the items from the list, since we are exiting. */ 3465 if (!libmap_disable) 3466 lm_fini(); 3467 lock_release(rtld_bind_lock, &lockstate); 3468 } 3469 3470 static void 3471 rtld_nop_exit(void) 3472 { 3473 } 3474 3475 /* 3476 * Iterate over a search path, translate each element, and invoke the 3477 * callback on the result. 3478 */ 3479 static void * 3480 path_enumerate(const char *path, path_enum_proc callback, 3481 const char *refobj_path, void *arg) 3482 { 3483 const char *trans; 3484 if (path == NULL) 3485 return (NULL); 3486 3487 path += strspn(path, ":;"); 3488 while (*path != '\0') { 3489 size_t len; 3490 char *res; 3491 3492 len = strcspn(path, ":;"); 3493 trans = lm_findn(refobj_path, path, len); 3494 if (trans) 3495 res = callback(trans, strlen(trans), arg); 3496 else 3497 res = callback(path, len, arg); 3498 3499 if (res != NULL) 3500 return (res); 3501 3502 path += len; 3503 path += strspn(path, ":;"); 3504 } 3505 3506 return (NULL); 3507 } 3508 3509 struct try_library_args { 3510 const char *name; 3511 size_t namelen; 3512 char *buffer; 3513 size_t buflen; 3514 int fd; 3515 }; 3516 3517 static void * 3518 try_library_path(const char *dir, size_t dirlen, void *param) 3519 { 3520 struct try_library_args *arg; 3521 int fd; 3522 3523 arg = param; 3524 if (*dir == '/' || trust) { 3525 char *pathname; 3526 3527 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 3528 return (NULL); 3529 3530 pathname = arg->buffer; 3531 strncpy(pathname, dir, dirlen); 3532 pathname[dirlen] = '/'; 3533 strcpy(pathname + dirlen + 1, arg->name); 3534 3535 dbg(" Trying \"%s\"", pathname); 3536 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY); 3537 if (fd >= 0) { 3538 dbg(" Opened \"%s\", fd %d", pathname, fd); 3539 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 3540 strcpy(pathname, arg->buffer); 3541 arg->fd = fd; 3542 return (pathname); 3543 } else { 3544 dbg(" Failed to open \"%s\": %s", 3545 pathname, rtld_strerror(errno)); 3546 } 3547 } 3548 return (NULL); 3549 } 3550 3551 static char * 3552 search_library_path(const char *name, const char *path, 3553 const char *refobj_path, int *fdp) 3554 { 3555 char *p; 3556 struct try_library_args arg; 3557 3558 if (path == NULL) 3559 return (NULL); 3560 3561 arg.name = name; 3562 arg.namelen = strlen(name); 3563 arg.buffer = xmalloc(PATH_MAX); 3564 arg.buflen = PATH_MAX; 3565 arg.fd = -1; 3566 3567 p = path_enumerate(path, try_library_path, refobj_path, &arg); 3568 *fdp = arg.fd; 3569 3570 free(arg.buffer); 3571 3572 return (p); 3573 } 3574 3575 3576 /* 3577 * Finds the library with the given name using the directory descriptors 3578 * listed in the LD_LIBRARY_PATH_FDS environment variable. 3579 * 3580 * Returns a freshly-opened close-on-exec file descriptor for the library, 3581 * or -1 if the library cannot be found. 3582 */ 3583 static char * 3584 search_library_pathfds(const char *name, const char *path, int *fdp) 3585 { 3586 char *envcopy, *fdstr, *found, *last_token; 3587 size_t len; 3588 int dirfd, fd; 3589 3590 dbg("%s('%s', '%s', fdp)", __func__, name, path); 3591 3592 /* Don't load from user-specified libdirs into setuid binaries. */ 3593 if (!trust) 3594 return (NULL); 3595 3596 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */ 3597 if (path == NULL) 3598 return (NULL); 3599 3600 /* LD_LIBRARY_PATH_FDS only works with relative paths. */ 3601 if (name[0] == '/') { 3602 dbg("Absolute path (%s) passed to %s", name, __func__); 3603 return (NULL); 3604 } 3605 3606 /* 3607 * Use strtok_r() to walk the FD:FD:FD list. This requires a local 3608 * copy of the path, as strtok_r rewrites separator tokens 3609 * with '\0'. 3610 */ 3611 found = NULL; 3612 envcopy = xstrdup(path); 3613 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL; 3614 fdstr = strtok_r(NULL, ":", &last_token)) { 3615 dirfd = parse_integer(fdstr); 3616 if (dirfd < 0) { 3617 _rtld_error("failed to parse directory FD: '%s'", 3618 fdstr); 3619 break; 3620 } 3621 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY); 3622 if (fd >= 0) { 3623 *fdp = fd; 3624 len = strlen(fdstr) + strlen(name) + 3; 3625 found = xmalloc(len); 3626 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 0) { 3627 _rtld_error("error generating '%d/%s'", 3628 dirfd, name); 3629 rtld_die(); 3630 } 3631 dbg("open('%s') => %d", found, fd); 3632 break; 3633 } 3634 } 3635 free(envcopy); 3636 3637 return (found); 3638 } 3639 3640 3641 int 3642 dlclose(void *handle) 3643 { 3644 RtldLockState lockstate; 3645 int error; 3646 3647 wlock_acquire(rtld_bind_lock, &lockstate); 3648 error = dlclose_locked(handle, &lockstate); 3649 lock_release(rtld_bind_lock, &lockstate); 3650 return (error); 3651 } 3652 3653 static int 3654 dlclose_locked(void *handle, RtldLockState *lockstate) 3655 { 3656 Obj_Entry *root; 3657 3658 root = dlcheck(handle); 3659 if (root == NULL) 3660 return (-1); 3661 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount, 3662 root->path); 3663 3664 /* Unreference the object and its dependencies. */ 3665 root->dl_refcount--; 3666 3667 if (root->refcount == 1) { 3668 /* 3669 * The object will be no longer referenced, so we must unload it. 3670 * First, call the fini functions. 3671 */ 3672 objlist_call_fini(&list_fini, root, lockstate); 3673 3674 unref_dag(root); 3675 3676 /* Finish cleaning up the newly-unreferenced objects. */ 3677 GDB_STATE(RT_DELETE,&root->linkmap); 3678 unload_object(root, lockstate); 3679 GDB_STATE(RT_CONSISTENT,NULL); 3680 } else 3681 unref_dag(root); 3682 3683 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL); 3684 return (0); 3685 } 3686 3687 char * 3688 dlerror(void) 3689 { 3690 if (*(lockinfo.dlerror_seen()) != 0) 3691 return (NULL); 3692 *lockinfo.dlerror_seen() = 1; 3693 return (lockinfo.dlerror_loc()); 3694 } 3695 3696 /* 3697 * This function is deprecated and has no effect. 3698 */ 3699 void 3700 dllockinit(void *context, 3701 void *(*_lock_create)(void *context) __unused, 3702 void (*_rlock_acquire)(void *lock) __unused, 3703 void (*_wlock_acquire)(void *lock) __unused, 3704 void (*_lock_release)(void *lock) __unused, 3705 void (*_lock_destroy)(void *lock) __unused, 3706 void (*context_destroy)(void *context)) 3707 { 3708 static void *cur_context; 3709 static void (*cur_context_destroy)(void *); 3710 3711 /* Just destroy the context from the previous call, if necessary. */ 3712 if (cur_context_destroy != NULL) 3713 cur_context_destroy(cur_context); 3714 cur_context = context; 3715 cur_context_destroy = context_destroy; 3716 } 3717 3718 void * 3719 dlopen(const char *name, int mode) 3720 { 3721 3722 return (rtld_dlopen(name, -1, mode)); 3723 } 3724 3725 void * 3726 fdlopen(int fd, int mode) 3727 { 3728 3729 return (rtld_dlopen(NULL, fd, mode)); 3730 } 3731 3732 static void * 3733 rtld_dlopen(const char *name, int fd, int mode) 3734 { 3735 RtldLockState lockstate; 3736 int lo_flags; 3737 3738 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name); 3739 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 3740 if (ld_tracing != NULL) { 3741 rlock_acquire(rtld_bind_lock, &lockstate); 3742 if (sigsetjmp(lockstate.env, 0) != 0) 3743 lock_upgrade(rtld_bind_lock, &lockstate); 3744 environ = __DECONST(char **, *get_program_var_addr("environ", &lockstate)); 3745 lock_release(rtld_bind_lock, &lockstate); 3746 } 3747 lo_flags = RTLD_LO_DLOPEN; 3748 if (mode & RTLD_NODELETE) 3749 lo_flags |= RTLD_LO_NODELETE; 3750 if (mode & RTLD_NOLOAD) 3751 lo_flags |= RTLD_LO_NOLOAD; 3752 if (mode & RTLD_DEEPBIND) 3753 lo_flags |= RTLD_LO_DEEPBIND; 3754 if (ld_tracing != NULL) 3755 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS; 3756 3757 return (dlopen_object(name, fd, obj_main, lo_flags, 3758 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL)); 3759 } 3760 3761 static void 3762 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate) 3763 { 3764 3765 obj->dl_refcount--; 3766 unref_dag(obj); 3767 if (obj->refcount == 0) 3768 unload_object(obj, lockstate); 3769 } 3770 3771 static Obj_Entry * 3772 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags, 3773 int mode, RtldLockState *lockstate) 3774 { 3775 Obj_Entry *obj; 3776 Objlist initlist; 3777 RtldLockState mlockstate; 3778 int result; 3779 3780 dbg("dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x", 3781 name != NULL ? name : "<null>", fd, refobj == NULL ? "<null>" : 3782 refobj->path, lo_flags, mode); 3783 objlist_init(&initlist); 3784 3785 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) { 3786 wlock_acquire(rtld_bind_lock, &mlockstate); 3787 lockstate = &mlockstate; 3788 } 3789 GDB_STATE(RT_ADD,NULL); 3790 3791 obj = NULL; 3792 if (name == NULL && fd == -1) { 3793 obj = obj_main; 3794 obj->refcount++; 3795 } else { 3796 obj = load_object(name, fd, refobj, lo_flags); 3797 } 3798 3799 if (obj) { 3800 obj->dl_refcount++; 3801 if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) 3802 objlist_push_tail(&list_global, obj); 3803 3804 if (!obj->init_done) { 3805 /* We loaded something new and have to init something. */ 3806 if ((lo_flags & RTLD_LO_DEEPBIND) != 0) 3807 obj->deepbind = true; 3808 result = 0; 3809 if ((lo_flags & (RTLD_LO_EARLY | RTLD_LO_IGNSTLS)) == 0 && 3810 obj->static_tls && !allocate_tls_offset(obj)) { 3811 _rtld_error("%s: No space available " 3812 "for static Thread Local Storage", obj->path); 3813 result = -1; 3814 } 3815 if (result != -1) 3816 result = load_needed_objects(obj, lo_flags & (RTLD_LO_DLOPEN | 3817 RTLD_LO_EARLY | RTLD_LO_IGNSTLS | RTLD_LO_TRACE)); 3818 init_dag(obj); 3819 ref_dag(obj); 3820 if (result != -1) 3821 result = rtld_verify_versions(&obj->dagmembers); 3822 if (result != -1 && ld_tracing) 3823 goto trace; 3824 if (result == -1 || relocate_object_dag(obj, 3825 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld, 3826 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3827 lockstate) == -1) { 3828 dlopen_cleanup(obj, lockstate); 3829 obj = NULL; 3830 } else if (lo_flags & RTLD_LO_EARLY) { 3831 /* 3832 * Do not call the init functions for early loaded 3833 * filtees. The image is still not initialized enough 3834 * for them to work. 3835 * 3836 * Our object is found by the global object list and 3837 * will be ordered among all init calls done right 3838 * before transferring control to main. 3839 */ 3840 } else { 3841 /* Make list of init functions to call. */ 3842 initlist_add_objects(obj, obj, &initlist); 3843 } 3844 /* 3845 * Process all no_delete or global objects here, given 3846 * them own DAGs to prevent their dependencies from being 3847 * unloaded. This has to be done after we have loaded all 3848 * of the dependencies, so that we do not miss any. 3849 */ 3850 if (obj != NULL) 3851 process_z(obj); 3852 } else { 3853 /* 3854 * Bump the reference counts for objects on this DAG. If 3855 * this is the first dlopen() call for the object that was 3856 * already loaded as a dependency, initialize the dag 3857 * starting at it. 3858 */ 3859 init_dag(obj); 3860 ref_dag(obj); 3861 3862 if ((lo_flags & RTLD_LO_TRACE) != 0) 3863 goto trace; 3864 } 3865 if (obj != NULL && ((lo_flags & RTLD_LO_NODELETE) != 0 || 3866 obj->z_nodelete) && !obj->ref_nodel) { 3867 dbg("obj %s nodelete", obj->path); 3868 ref_dag(obj); 3869 obj->z_nodelete = obj->ref_nodel = true; 3870 } 3871 } 3872 3873 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0, 3874 name); 3875 GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); 3876 3877 if ((lo_flags & RTLD_LO_EARLY) == 0) { 3878 map_stacks_exec(lockstate); 3879 if (obj != NULL) 3880 distribute_static_tls(&initlist, lockstate); 3881 } 3882 3883 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == RTLD_NOW, 3884 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3885 lockstate) == -1) { 3886 objlist_clear(&initlist); 3887 dlopen_cleanup(obj, lockstate); 3888 if (lockstate == &mlockstate) 3889 lock_release(rtld_bind_lock, lockstate); 3890 return (NULL); 3891 } 3892 3893 if (!(lo_flags & RTLD_LO_EARLY)) { 3894 /* Call the init functions. */ 3895 objlist_call_init(&initlist, lockstate); 3896 } 3897 objlist_clear(&initlist); 3898 if (lockstate == &mlockstate) 3899 lock_release(rtld_bind_lock, lockstate); 3900 return (obj); 3901 trace: 3902 trace_loaded_objects(obj, false); 3903 if (lockstate == &mlockstate) 3904 lock_release(rtld_bind_lock, lockstate); 3905 exit(0); 3906 } 3907 3908 static void * 3909 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve, 3910 int flags) 3911 { 3912 DoneList donelist; 3913 const Obj_Entry *obj, *defobj; 3914 const Elf_Sym *def; 3915 SymLook req; 3916 RtldLockState lockstate; 3917 tls_index ti; 3918 void *sym; 3919 int res; 3920 3921 def = NULL; 3922 defobj = NULL; 3923 symlook_init(&req, name); 3924 req.ventry = ve; 3925 req.flags = flags | SYMLOOK_IN_PLT; 3926 req.lockstate = &lockstate; 3927 3928 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name); 3929 rlock_acquire(rtld_bind_lock, &lockstate); 3930 if (sigsetjmp(lockstate.env, 0) != 0) 3931 lock_upgrade(rtld_bind_lock, &lockstate); 3932 if (handle == NULL || handle == RTLD_NEXT || 3933 handle == RTLD_DEFAULT || handle == RTLD_SELF) { 3934 3935 if ((obj = obj_from_addr(retaddr)) == NULL) { 3936 _rtld_error("Cannot determine caller's shared object"); 3937 lock_release(rtld_bind_lock, &lockstate); 3938 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3939 return (NULL); 3940 } 3941 if (handle == NULL) { /* Just the caller's shared object. */ 3942 res = symlook_obj(&req, obj); 3943 if (res == 0) { 3944 def = req.sym_out; 3945 defobj = req.defobj_out; 3946 } 3947 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 3948 handle == RTLD_SELF) { /* ... caller included */ 3949 if (handle == RTLD_NEXT) 3950 obj = globallist_next(obj); 3951 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 3952 if (obj->marker) 3953 continue; 3954 res = symlook_obj(&req, obj); 3955 if (res == 0) { 3956 if (def == NULL || (ld_dynamic_weak && 3957 ELF_ST_BIND(req.sym_out->st_info) != STB_WEAK)) { 3958 def = req.sym_out; 3959 defobj = req.defobj_out; 3960 if (!ld_dynamic_weak || 3961 ELF_ST_BIND(def->st_info) != STB_WEAK) 3962 break; 3963 } 3964 } 3965 } 3966 /* 3967 * Search the dynamic linker itself, and possibly resolve the 3968 * symbol from there. This is how the application links to 3969 * dynamic linker services such as dlopen. 3970 * Note that we ignore ld_dynamic_weak == false case, 3971 * always overriding weak symbols by rtld definitions. 3972 */ 3973 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 3974 res = symlook_obj(&req, &obj_rtld); 3975 if (res == 0) { 3976 def = req.sym_out; 3977 defobj = req.defobj_out; 3978 } 3979 } 3980 } else { 3981 assert(handle == RTLD_DEFAULT); 3982 res = symlook_default(&req, obj); 3983 if (res == 0) { 3984 defobj = req.defobj_out; 3985 def = req.sym_out; 3986 } 3987 } 3988 } else { 3989 if ((obj = dlcheck(handle)) == NULL) { 3990 lock_release(rtld_bind_lock, &lockstate); 3991 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 3992 return (NULL); 3993 } 3994 3995 donelist_init(&donelist); 3996 if (obj->mainprog) { 3997 /* Handle obtained by dlopen(NULL, ...) implies global scope. */ 3998 res = symlook_global(&req, &donelist); 3999 if (res == 0) { 4000 def = req.sym_out; 4001 defobj = req.defobj_out; 4002 } 4003 /* 4004 * Search the dynamic linker itself, and possibly resolve the 4005 * symbol from there. This is how the application links to 4006 * dynamic linker services such as dlopen. 4007 */ 4008 if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { 4009 res = symlook_obj(&req, &obj_rtld); 4010 if (res == 0) { 4011 def = req.sym_out; 4012 defobj = req.defobj_out; 4013 } 4014 } 4015 } 4016 else { 4017 /* Search the whole DAG rooted at the given object. */ 4018 res = symlook_list(&req, &obj->dagmembers, &donelist); 4019 if (res == 0) { 4020 def = req.sym_out; 4021 defobj = req.defobj_out; 4022 } 4023 } 4024 } 4025 4026 if (def != NULL) { 4027 lock_release(rtld_bind_lock, &lockstate); 4028 4029 /* 4030 * The value required by the caller is derived from the value 4031 * of the symbol. this is simply the relocated value of the 4032 * symbol. 4033 */ 4034 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 4035 sym = make_function_pointer(def, defobj); 4036 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 4037 sym = rtld_resolve_ifunc(defobj, def); 4038 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) { 4039 ti.ti_module = defobj->tlsindex; 4040 ti.ti_offset = def->st_value; 4041 sym = __tls_get_addr(&ti); 4042 } else 4043 sym = defobj->relocbase + def->st_value; 4044 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name); 4045 return (sym); 4046 } 4047 4048 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "", 4049 ve != NULL ? ve->name : ""); 4050 lock_release(rtld_bind_lock, &lockstate); 4051 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 4052 return (NULL); 4053 } 4054 4055 void * 4056 dlsym(void *handle, const char *name) 4057 { 4058 return (do_dlsym(handle, name, __builtin_return_address(0), NULL, 4059 SYMLOOK_DLSYM)); 4060 } 4061 4062 dlfunc_t 4063 dlfunc(void *handle, const char *name) 4064 { 4065 union { 4066 void *d; 4067 dlfunc_t f; 4068 } rv; 4069 4070 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL, 4071 SYMLOOK_DLSYM); 4072 return (rv.f); 4073 } 4074 4075 void * 4076 dlvsym(void *handle, const char *name, const char *version) 4077 { 4078 Ver_Entry ventry; 4079 4080 ventry.name = version; 4081 ventry.file = NULL; 4082 ventry.hash = elf_hash(version); 4083 ventry.flags= 0; 4084 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry, 4085 SYMLOOK_DLSYM)); 4086 } 4087 4088 int 4089 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info) 4090 { 4091 const Obj_Entry *obj; 4092 RtldLockState lockstate; 4093 4094 rlock_acquire(rtld_bind_lock, &lockstate); 4095 obj = obj_from_addr(addr); 4096 if (obj == NULL) { 4097 _rtld_error("No shared object contains address"); 4098 lock_release(rtld_bind_lock, &lockstate); 4099 return (0); 4100 } 4101 rtld_fill_dl_phdr_info(obj, phdr_info); 4102 lock_release(rtld_bind_lock, &lockstate); 4103 return (1); 4104 } 4105 4106 int 4107 dladdr(const void *addr, Dl_info *info) 4108 { 4109 const Obj_Entry *obj; 4110 const Elf_Sym *def; 4111 void *symbol_addr; 4112 unsigned long symoffset; 4113 RtldLockState lockstate; 4114 4115 rlock_acquire(rtld_bind_lock, &lockstate); 4116 obj = obj_from_addr(addr); 4117 if (obj == NULL) { 4118 _rtld_error("No shared object contains address"); 4119 lock_release(rtld_bind_lock, &lockstate); 4120 return (0); 4121 } 4122 info->dli_fname = obj->path; 4123 info->dli_fbase = obj->mapbase; 4124 info->dli_saddr = (void *)0; 4125 info->dli_sname = NULL; 4126 4127 /* 4128 * Walk the symbol list looking for the symbol whose address is 4129 * closest to the address sent in. 4130 */ 4131 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) { 4132 def = obj->symtab + symoffset; 4133 4134 /* 4135 * For skip the symbol if st_shndx is either SHN_UNDEF or 4136 * SHN_COMMON. 4137 */ 4138 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 4139 continue; 4140 4141 /* 4142 * If the symbol is greater than the specified address, or if it 4143 * is further away from addr than the current nearest symbol, 4144 * then reject it. 4145 */ 4146 symbol_addr = obj->relocbase + def->st_value; 4147 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 4148 continue; 4149 4150 /* Update our idea of the nearest symbol. */ 4151 info->dli_sname = obj->strtab + def->st_name; 4152 info->dli_saddr = symbol_addr; 4153 4154 /* Exact match? */ 4155 if (info->dli_saddr == addr) 4156 break; 4157 } 4158 lock_release(rtld_bind_lock, &lockstate); 4159 return (1); 4160 } 4161 4162 int 4163 dlinfo(void *handle, int request, void *p) 4164 { 4165 const Obj_Entry *obj; 4166 RtldLockState lockstate; 4167 int error; 4168 4169 rlock_acquire(rtld_bind_lock, &lockstate); 4170 4171 if (handle == NULL || handle == RTLD_SELF) { 4172 void *retaddr; 4173 4174 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 4175 if ((obj = obj_from_addr(retaddr)) == NULL) 4176 _rtld_error("Cannot determine caller's shared object"); 4177 } else 4178 obj = dlcheck(handle); 4179 4180 if (obj == NULL) { 4181 lock_release(rtld_bind_lock, &lockstate); 4182 return (-1); 4183 } 4184 4185 error = 0; 4186 switch (request) { 4187 case RTLD_DI_LINKMAP: 4188 *((struct link_map const **)p) = &obj->linkmap; 4189 break; 4190 case RTLD_DI_ORIGIN: 4191 error = rtld_dirname(obj->path, p); 4192 break; 4193 4194 case RTLD_DI_SERINFOSIZE: 4195 case RTLD_DI_SERINFO: 4196 error = do_search_info(obj, request, (struct dl_serinfo *)p); 4197 break; 4198 4199 default: 4200 _rtld_error("Invalid request %d passed to dlinfo()", request); 4201 error = -1; 4202 } 4203 4204 lock_release(rtld_bind_lock, &lockstate); 4205 4206 return (error); 4207 } 4208 4209 static void 4210 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info) 4211 { 4212 uintptr_t **dtvp; 4213 4214 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase; 4215 phdr_info->dlpi_name = obj->path; 4216 phdr_info->dlpi_phdr = obj->phdr; 4217 phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]); 4218 phdr_info->dlpi_tls_modid = obj->tlsindex; 4219 dtvp = &_tcb_get()->tcb_dtv; 4220 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(dtvp, 4221 obj->tlsindex, 0, true) + TLS_DTV_OFFSET; 4222 phdr_info->dlpi_adds = obj_loads; 4223 phdr_info->dlpi_subs = obj_loads - obj_count; 4224 } 4225 4226 int 4227 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param) 4228 { 4229 struct dl_phdr_info phdr_info; 4230 Obj_Entry *obj, marker; 4231 RtldLockState bind_lockstate, phdr_lockstate; 4232 int error; 4233 4234 init_marker(&marker); 4235 error = 0; 4236 4237 wlock_acquire(rtld_phdr_lock, &phdr_lockstate); 4238 wlock_acquire(rtld_bind_lock, &bind_lockstate); 4239 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) { 4240 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next); 4241 rtld_fill_dl_phdr_info(obj, &phdr_info); 4242 hold_object(obj); 4243 lock_release(rtld_bind_lock, &bind_lockstate); 4244 4245 error = callback(&phdr_info, sizeof phdr_info, param); 4246 4247 wlock_acquire(rtld_bind_lock, &bind_lockstate); 4248 unhold_object(obj); 4249 obj = globallist_next(&marker); 4250 TAILQ_REMOVE(&obj_list, &marker, next); 4251 if (error != 0) { 4252 lock_release(rtld_bind_lock, &bind_lockstate); 4253 lock_release(rtld_phdr_lock, &phdr_lockstate); 4254 return (error); 4255 } 4256 } 4257 4258 if (error == 0) { 4259 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info); 4260 lock_release(rtld_bind_lock, &bind_lockstate); 4261 error = callback(&phdr_info, sizeof(phdr_info), param); 4262 } 4263 lock_release(rtld_phdr_lock, &phdr_lockstate); 4264 return (error); 4265 } 4266 4267 static void * 4268 fill_search_info(const char *dir, size_t dirlen, void *param) 4269 { 4270 struct fill_search_info_args *arg; 4271 4272 arg = param; 4273 4274 if (arg->request == RTLD_DI_SERINFOSIZE) { 4275 arg->serinfo->dls_cnt ++; 4276 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 1; 4277 } else { 4278 struct dl_serpath *s_entry; 4279 4280 s_entry = arg->serpath; 4281 s_entry->dls_name = arg->strspace; 4282 s_entry->dls_flags = arg->flags; 4283 4284 strncpy(arg->strspace, dir, dirlen); 4285 arg->strspace[dirlen] = '\0'; 4286 4287 arg->strspace += dirlen + 1; 4288 arg->serpath++; 4289 } 4290 4291 return (NULL); 4292 } 4293 4294 static int 4295 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 4296 { 4297 struct dl_serinfo _info; 4298 struct fill_search_info_args args; 4299 4300 args.request = RTLD_DI_SERINFOSIZE; 4301 args.serinfo = &_info; 4302 4303 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 4304 _info.dls_cnt = 0; 4305 4306 path_enumerate(obj->rpath, fill_search_info, NULL, &args); 4307 path_enumerate(ld_library_path, fill_search_info, NULL, &args); 4308 path_enumerate(obj->runpath, fill_search_info, NULL, &args); 4309 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args); 4310 if (!obj->z_nodeflib) 4311 path_enumerate(ld_standard_library_path, fill_search_info, NULL, &args); 4312 4313 4314 if (request == RTLD_DI_SERINFOSIZE) { 4315 info->dls_size = _info.dls_size; 4316 info->dls_cnt = _info.dls_cnt; 4317 return (0); 4318 } 4319 4320 if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { 4321 _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); 4322 return (-1); 4323 } 4324 4325 args.request = RTLD_DI_SERINFO; 4326 args.serinfo = info; 4327 args.serpath = &info->dls_serpath[0]; 4328 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 4329 4330 args.flags = LA_SER_RUNPATH; 4331 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL) 4332 return (-1); 4333 4334 args.flags = LA_SER_LIBPATH; 4335 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != NULL) 4336 return (-1); 4337 4338 args.flags = LA_SER_RUNPATH; 4339 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL) 4340 return (-1); 4341 4342 args.flags = LA_SER_CONFIG; 4343 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, &args) 4344 != NULL) 4345 return (-1); 4346 4347 args.flags = LA_SER_DEFAULT; 4348 if (!obj->z_nodeflib && path_enumerate(ld_standard_library_path, 4349 fill_search_info, NULL, &args) != NULL) 4350 return (-1); 4351 return (0); 4352 } 4353 4354 static int 4355 rtld_dirname(const char *path, char *bname) 4356 { 4357 const char *endp; 4358 4359 /* Empty or NULL string gets treated as "." */ 4360 if (path == NULL || *path == '\0') { 4361 bname[0] = '.'; 4362 bname[1] = '\0'; 4363 return (0); 4364 } 4365 4366 /* Strip trailing slashes */ 4367 endp = path + strlen(path) - 1; 4368 while (endp > path && *endp == '/') 4369 endp--; 4370 4371 /* Find the start of the dir */ 4372 while (endp > path && *endp != '/') 4373 endp--; 4374 4375 /* Either the dir is "/" or there are no slashes */ 4376 if (endp == path) { 4377 bname[0] = *endp == '/' ? '/' : '.'; 4378 bname[1] = '\0'; 4379 return (0); 4380 } else { 4381 do { 4382 endp--; 4383 } while (endp > path && *endp == '/'); 4384 } 4385 4386 if (endp - path + 2 > PATH_MAX) 4387 { 4388 _rtld_error("Filename is too long: %s", path); 4389 return(-1); 4390 } 4391 4392 strncpy(bname, path, endp - path + 1); 4393 bname[endp - path + 1] = '\0'; 4394 return (0); 4395 } 4396 4397 static int 4398 rtld_dirname_abs(const char *path, char *base) 4399 { 4400 char *last; 4401 4402 if (realpath(path, base) == NULL) { 4403 _rtld_error("realpath \"%s\" failed (%s)", path, 4404 rtld_strerror(errno)); 4405 return (-1); 4406 } 4407 dbg("%s -> %s", path, base); 4408 last = strrchr(base, '/'); 4409 if (last == NULL) { 4410 _rtld_error("non-abs result from realpath \"%s\"", path); 4411 return (-1); 4412 } 4413 if (last != base) 4414 *last = '\0'; 4415 return (0); 4416 } 4417 4418 static void 4419 linkmap_add(Obj_Entry *obj) 4420 { 4421 struct link_map *l, *prev; 4422 4423 l = &obj->linkmap; 4424 l->l_name = obj->path; 4425 l->l_base = obj->mapbase; 4426 l->l_ld = obj->dynamic; 4427 l->l_addr = obj->relocbase; 4428 4429 if (r_debug.r_map == NULL) { 4430 r_debug.r_map = l; 4431 return; 4432 } 4433 4434 /* 4435 * Scan to the end of the list, but not past the entry for the 4436 * dynamic linker, which we want to keep at the very end. 4437 */ 4438 for (prev = r_debug.r_map; 4439 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 4440 prev = prev->l_next) 4441 ; 4442 4443 /* Link in the new entry. */ 4444 l->l_prev = prev; 4445 l->l_next = prev->l_next; 4446 if (l->l_next != NULL) 4447 l->l_next->l_prev = l; 4448 prev->l_next = l; 4449 } 4450 4451 static void 4452 linkmap_delete(Obj_Entry *obj) 4453 { 4454 struct link_map *l; 4455 4456 l = &obj->linkmap; 4457 if (l->l_prev == NULL) { 4458 if ((r_debug.r_map = l->l_next) != NULL) 4459 l->l_next->l_prev = NULL; 4460 return; 4461 } 4462 4463 if ((l->l_prev->l_next = l->l_next) != NULL) 4464 l->l_next->l_prev = l->l_prev; 4465 } 4466 4467 /* 4468 * Function for the debugger to set a breakpoint on to gain control. 4469 * 4470 * The two parameters allow the debugger to easily find and determine 4471 * what the runtime loader is doing and to whom it is doing it. 4472 * 4473 * When the loadhook trap is hit (r_debug_state, set at program 4474 * initialization), the arguments can be found on the stack: 4475 * 4476 * +8 struct link_map *m 4477 * +4 struct r_debug *rd 4478 * +0 RetAddr 4479 */ 4480 void 4481 r_debug_state(struct r_debug* rd __unused, struct link_map *m __unused) 4482 { 4483 /* 4484 * The following is a hack to force the compiler to emit calls to 4485 * this function, even when optimizing. If the function is empty, 4486 * the compiler is not obliged to emit any code for calls to it, 4487 * even when marked __noinline. However, gdb depends on those 4488 * calls being made. 4489 */ 4490 __compiler_membar(); 4491 } 4492 4493 /* 4494 * A function called after init routines have completed. This can be used to 4495 * break before a program's entry routine is called, and can be used when 4496 * main is not available in the symbol table. 4497 */ 4498 void 4499 _r_debug_postinit(struct link_map *m __unused) 4500 { 4501 4502 /* See r_debug_state(). */ 4503 __compiler_membar(); 4504 } 4505 4506 static void 4507 release_object(Obj_Entry *obj) 4508 { 4509 4510 if (obj->holdcount > 0) { 4511 obj->unholdfree = true; 4512 return; 4513 } 4514 munmap(obj->mapbase, obj->mapsize); 4515 linkmap_delete(obj); 4516 obj_free(obj); 4517 } 4518 4519 /* 4520 * Get address of the pointer variable in the main program. 4521 * Prefer non-weak symbol over the weak one. 4522 */ 4523 static const void ** 4524 get_program_var_addr(const char *name, RtldLockState *lockstate) 4525 { 4526 SymLook req; 4527 DoneList donelist; 4528 4529 symlook_init(&req, name); 4530 req.lockstate = lockstate; 4531 donelist_init(&donelist); 4532 if (symlook_global(&req, &donelist) != 0) 4533 return (NULL); 4534 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC) 4535 return ((const void **)make_function_pointer(req.sym_out, 4536 req.defobj_out)); 4537 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC) 4538 return ((const void **)rtld_resolve_ifunc(req.defobj_out, req.sym_out)); 4539 else 4540 return ((const void **)(req.defobj_out->relocbase + 4541 req.sym_out->st_value)); 4542 } 4543 4544 /* 4545 * Set a pointer variable in the main program to the given value. This 4546 * is used to set key variables such as "environ" before any of the 4547 * init functions are called. 4548 */ 4549 static void 4550 set_program_var(const char *name, const void *value) 4551 { 4552 const void **addr; 4553 4554 if ((addr = get_program_var_addr(name, NULL)) != NULL) { 4555 dbg("\"%s\": *%p <-- %p", name, addr, value); 4556 *addr = value; 4557 } 4558 } 4559 4560 /* 4561 * Search the global objects, including dependencies and main object, 4562 * for the given symbol. 4563 */ 4564 static int 4565 symlook_global(SymLook *req, DoneList *donelist) 4566 { 4567 SymLook req1; 4568 const Objlist_Entry *elm; 4569 int res; 4570 4571 symlook_init_from_req(&req1, req); 4572 4573 /* Search all objects loaded at program start up. */ 4574 if (req->defobj_out == NULL || (ld_dynamic_weak && 4575 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) { 4576 res = symlook_list(&req1, &list_main, donelist); 4577 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL || 4578 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4579 req->sym_out = req1.sym_out; 4580 req->defobj_out = req1.defobj_out; 4581 assert(req->defobj_out != NULL); 4582 } 4583 } 4584 4585 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 4586 STAILQ_FOREACH(elm, &list_global, link) { 4587 if (req->defobj_out != NULL && (!ld_dynamic_weak || 4588 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)) 4589 break; 4590 res = symlook_list(&req1, &elm->obj->dagmembers, donelist); 4591 if (res == 0 && (req->defobj_out == NULL || 4592 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4593 req->sym_out = req1.sym_out; 4594 req->defobj_out = req1.defobj_out; 4595 assert(req->defobj_out != NULL); 4596 } 4597 } 4598 4599 return (req->sym_out != NULL ? 0 : ESRCH); 4600 } 4601 4602 /* 4603 * Given a symbol name in a referencing object, find the corresponding 4604 * definition of the symbol. Returns a pointer to the symbol, or NULL if 4605 * no definition was found. Returns a pointer to the Obj_Entry of the 4606 * defining object via the reference parameter DEFOBJ_OUT. 4607 */ 4608 static int 4609 symlook_default(SymLook *req, const Obj_Entry *refobj) 4610 { 4611 DoneList donelist; 4612 const Objlist_Entry *elm; 4613 SymLook req1; 4614 int res; 4615 4616 donelist_init(&donelist); 4617 symlook_init_from_req(&req1, req); 4618 4619 /* 4620 * Look first in the referencing object if linked symbolically, 4621 * and similarly handle protected symbols. 4622 */ 4623 res = symlook_obj(&req1, refobj); 4624 if (res == 0 && (refobj->symbolic || 4625 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED)) { 4626 req->sym_out = req1.sym_out; 4627 req->defobj_out = req1.defobj_out; 4628 assert(req->defobj_out != NULL); 4629 } 4630 if (refobj->symbolic || req->defobj_out != NULL) 4631 donelist_check(&donelist, refobj); 4632 4633 if (!refobj->deepbind) 4634 symlook_global(req, &donelist); 4635 4636 /* Search all dlopened DAGs containing the referencing object. */ 4637 STAILQ_FOREACH(elm, &refobj->dldags, link) { 4638 if (req->sym_out != NULL && (!ld_dynamic_weak || 4639 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)) 4640 break; 4641 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist); 4642 if (res == 0 && (req->sym_out == NULL || 4643 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4644 req->sym_out = req1.sym_out; 4645 req->defobj_out = req1.defobj_out; 4646 assert(req->defobj_out != NULL); 4647 } 4648 } 4649 4650 if (refobj->deepbind) 4651 symlook_global(req, &donelist); 4652 4653 /* 4654 * Search the dynamic linker itself, and possibly resolve the 4655 * symbol from there. This is how the application links to 4656 * dynamic linker services such as dlopen. 4657 */ 4658 if (req->sym_out == NULL || 4659 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 4660 res = symlook_obj(&req1, &obj_rtld); 4661 if (res == 0) { 4662 req->sym_out = req1.sym_out; 4663 req->defobj_out = req1.defobj_out; 4664 assert(req->defobj_out != NULL); 4665 } 4666 } 4667 4668 return (req->sym_out != NULL ? 0 : ESRCH); 4669 } 4670 4671 static int 4672 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp) 4673 { 4674 const Elf_Sym *def; 4675 const Obj_Entry *defobj; 4676 const Objlist_Entry *elm; 4677 SymLook req1; 4678 int res; 4679 4680 def = NULL; 4681 defobj = NULL; 4682 STAILQ_FOREACH(elm, objlist, link) { 4683 if (donelist_check(dlp, elm->obj)) 4684 continue; 4685 symlook_init_from_req(&req1, req); 4686 if ((res = symlook_obj(&req1, elm->obj)) == 0) { 4687 if (def == NULL || (ld_dynamic_weak && 4688 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4689 def = req1.sym_out; 4690 defobj = req1.defobj_out; 4691 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK) 4692 break; 4693 } 4694 } 4695 } 4696 if (def != NULL) { 4697 req->sym_out = def; 4698 req->defobj_out = defobj; 4699 return (0); 4700 } 4701 return (ESRCH); 4702 } 4703 4704 /* 4705 * Search the chain of DAGS cointed to by the given Needed_Entry 4706 * for a symbol of the given name. Each DAG is scanned completely 4707 * before advancing to the next one. Returns a pointer to the symbol, 4708 * or NULL if no definition was found. 4709 */ 4710 static int 4711 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp) 4712 { 4713 const Elf_Sym *def; 4714 const Needed_Entry *n; 4715 const Obj_Entry *defobj; 4716 SymLook req1; 4717 int res; 4718 4719 def = NULL; 4720 defobj = NULL; 4721 symlook_init_from_req(&req1, req); 4722 for (n = needed; n != NULL; n = n->next) { 4723 if (n->obj == NULL || 4724 (res = symlook_list(&req1, &n->obj->dagmembers, dlp)) != 0) 4725 continue; 4726 if (def == NULL || (ld_dynamic_weak && 4727 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4728 def = req1.sym_out; 4729 defobj = req1.defobj_out; 4730 if (!ld_dynamic_weak || ELF_ST_BIND(def->st_info) != STB_WEAK) 4731 break; 4732 } 4733 } 4734 if (def != NULL) { 4735 req->sym_out = def; 4736 req->defobj_out = defobj; 4737 return (0); 4738 } 4739 return (ESRCH); 4740 } 4741 4742 static int 4743 symlook_obj_load_filtees(SymLook *req, SymLook *req1, const Obj_Entry *obj, 4744 Needed_Entry *needed) 4745 { 4746 DoneList donelist; 4747 int flags; 4748 4749 flags = (req->flags & SYMLOOK_EARLY) != 0 ? RTLD_LO_EARLY : 0; 4750 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4751 donelist_init(&donelist); 4752 symlook_init_from_req(req1, req); 4753 return (symlook_needed(req1, needed, &donelist)); 4754 } 4755 4756 /* 4757 * Search the symbol table of a single shared object for a symbol of 4758 * the given name and version, if requested. Returns a pointer to the 4759 * symbol, or NULL if no definition was found. If the object is 4760 * filter, return filtered symbol from filtee. 4761 * 4762 * The symbol's hash value is passed in for efficiency reasons; that 4763 * eliminates many recomputations of the hash value. 4764 */ 4765 int 4766 symlook_obj(SymLook *req, const Obj_Entry *obj) 4767 { 4768 SymLook req1; 4769 int res, mres; 4770 4771 /* 4772 * If there is at least one valid hash at this point, we prefer to 4773 * use the faster GNU version if available. 4774 */ 4775 if (obj->valid_hash_gnu) 4776 mres = symlook_obj1_gnu(req, obj); 4777 else if (obj->valid_hash_sysv) 4778 mres = symlook_obj1_sysv(req, obj); 4779 else 4780 return (EINVAL); 4781 4782 if (mres == 0) { 4783 if (obj->needed_filtees != NULL) { 4784 res = symlook_obj_load_filtees(req, &req1, obj, 4785 obj->needed_filtees); 4786 if (res == 0) { 4787 req->sym_out = req1.sym_out; 4788 req->defobj_out = req1.defobj_out; 4789 } 4790 return (res); 4791 } 4792 if (obj->needed_aux_filtees != NULL) { 4793 res = symlook_obj_load_filtees(req, &req1, obj, 4794 obj->needed_aux_filtees); 4795 if (res == 0) { 4796 req->sym_out = req1.sym_out; 4797 req->defobj_out = req1.defobj_out; 4798 return (res); 4799 } 4800 } 4801 } 4802 return (mres); 4803 } 4804 4805 /* Symbol match routine common to both hash functions */ 4806 static bool 4807 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result, 4808 const unsigned long symnum) 4809 { 4810 Elf_Versym verndx; 4811 const Elf_Sym *symp; 4812 const char *strp; 4813 4814 symp = obj->symtab + symnum; 4815 strp = obj->strtab + symp->st_name; 4816 4817 switch (ELF_ST_TYPE(symp->st_info)) { 4818 case STT_FUNC: 4819 case STT_NOTYPE: 4820 case STT_OBJECT: 4821 case STT_COMMON: 4822 case STT_GNU_IFUNC: 4823 if (symp->st_value == 0) 4824 return (false); 4825 /* fallthrough */ 4826 case STT_TLS: 4827 if (symp->st_shndx != SHN_UNDEF) 4828 break; 4829 else if (((req->flags & SYMLOOK_IN_PLT) == 0) && 4830 (ELF_ST_TYPE(symp->st_info) == STT_FUNC)) 4831 break; 4832 /* fallthrough */ 4833 default: 4834 return (false); 4835 } 4836 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0) 4837 return (false); 4838 4839 if (req->ventry == NULL) { 4840 if (obj->versyms != NULL) { 4841 verndx = VER_NDX(obj->versyms[symnum]); 4842 if (verndx > obj->vernum) { 4843 _rtld_error( 4844 "%s: symbol %s references wrong version %d", 4845 obj->path, obj->strtab + symnum, verndx); 4846 return (false); 4847 } 4848 /* 4849 * If we are not called from dlsym (i.e. this 4850 * is a normal relocation from unversioned 4851 * binary), accept the symbol immediately if 4852 * it happens to have first version after this 4853 * shared object became versioned. Otherwise, 4854 * if symbol is versioned and not hidden, 4855 * remember it. If it is the only symbol with 4856 * this name exported by the shared object, it 4857 * will be returned as a match by the calling 4858 * function. If symbol is global (verndx < 2) 4859 * accept it unconditionally. 4860 */ 4861 if ((req->flags & SYMLOOK_DLSYM) == 0 && 4862 verndx == VER_NDX_GIVEN) { 4863 result->sym_out = symp; 4864 return (true); 4865 } 4866 else if (verndx >= VER_NDX_GIVEN) { 4867 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) 4868 == 0) { 4869 if (result->vsymp == NULL) 4870 result->vsymp = symp; 4871 result->vcount++; 4872 } 4873 return (false); 4874 } 4875 } 4876 result->sym_out = symp; 4877 return (true); 4878 } 4879 if (obj->versyms == NULL) { 4880 if (object_match_name(obj, req->ventry->name)) { 4881 _rtld_error("%s: object %s should provide version %s " 4882 "for symbol %s", obj_rtld.path, obj->path, 4883 req->ventry->name, obj->strtab + symnum); 4884 return (false); 4885 } 4886 } else { 4887 verndx = VER_NDX(obj->versyms[symnum]); 4888 if (verndx > obj->vernum) { 4889 _rtld_error("%s: symbol %s references wrong version %d", 4890 obj->path, obj->strtab + symnum, verndx); 4891 return (false); 4892 } 4893 if (obj->vertab[verndx].hash != req->ventry->hash || 4894 strcmp(obj->vertab[verndx].name, req->ventry->name)) { 4895 /* 4896 * Version does not match. Look if this is a 4897 * global symbol and if it is not hidden. If 4898 * global symbol (verndx < 2) is available, 4899 * use it. Do not return symbol if we are 4900 * called by dlvsym, because dlvsym looks for 4901 * a specific version and default one is not 4902 * what dlvsym wants. 4903 */ 4904 if ((req->flags & SYMLOOK_DLSYM) || 4905 (verndx >= VER_NDX_GIVEN) || 4906 (obj->versyms[symnum] & VER_NDX_HIDDEN)) 4907 return (false); 4908 } 4909 } 4910 result->sym_out = symp; 4911 return (true); 4912 } 4913 4914 /* 4915 * Search for symbol using SysV hash function. 4916 * obj->buckets is known not to be NULL at this point; the test for this was 4917 * performed with the obj->valid_hash_sysv assignment. 4918 */ 4919 static int 4920 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj) 4921 { 4922 unsigned long symnum; 4923 Sym_Match_Result matchres; 4924 4925 matchres.sym_out = NULL; 4926 matchres.vsymp = NULL; 4927 matchres.vcount = 0; 4928 4929 for (symnum = obj->buckets[req->hash % obj->nbuckets]; 4930 symnum != STN_UNDEF; symnum = obj->chains[symnum]) { 4931 if (symnum >= obj->nchains) 4932 return (ESRCH); /* Bad object */ 4933 4934 if (matched_symbol(req, obj, &matchres, symnum)) { 4935 req->sym_out = matchres.sym_out; 4936 req->defobj_out = obj; 4937 return (0); 4938 } 4939 } 4940 if (matchres.vcount == 1) { 4941 req->sym_out = matchres.vsymp; 4942 req->defobj_out = obj; 4943 return (0); 4944 } 4945 return (ESRCH); 4946 } 4947 4948 /* Search for symbol using GNU hash function */ 4949 static int 4950 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj) 4951 { 4952 Elf_Addr bloom_word; 4953 const Elf32_Word *hashval; 4954 Elf32_Word bucket; 4955 Sym_Match_Result matchres; 4956 unsigned int h1, h2; 4957 unsigned long symnum; 4958 4959 matchres.sym_out = NULL; 4960 matchres.vsymp = NULL; 4961 matchres.vcount = 0; 4962 4963 /* Pick right bitmask word from Bloom filter array */ 4964 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) & 4965 obj->maskwords_bm_gnu]; 4966 4967 /* Calculate modulus word size of gnu hash and its derivative */ 4968 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1); 4969 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1)); 4970 4971 /* Filter out the "definitely not in set" queries */ 4972 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0) 4973 return (ESRCH); 4974 4975 /* Locate hash chain and corresponding value element*/ 4976 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu]; 4977 if (bucket == 0) 4978 return (ESRCH); 4979 hashval = &obj->chain_zero_gnu[bucket]; 4980 do { 4981 if (((*hashval ^ req->hash_gnu) >> 1) == 0) { 4982 symnum = hashval - obj->chain_zero_gnu; 4983 if (matched_symbol(req, obj, &matchres, symnum)) { 4984 req->sym_out = matchres.sym_out; 4985 req->defobj_out = obj; 4986 return (0); 4987 } 4988 } 4989 } while ((*hashval++ & 1) == 0); 4990 if (matchres.vcount == 1) { 4991 req->sym_out = matchres.vsymp; 4992 req->defobj_out = obj; 4993 return (0); 4994 } 4995 return (ESRCH); 4996 } 4997 4998 static void 4999 trace_calc_fmts(const char **main_local, const char **fmt1, const char **fmt2) 5000 { 5001 *main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME); 5002 if (*main_local == NULL) 5003 *main_local = ""; 5004 5005 *fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1); 5006 if (*fmt1 == NULL) 5007 *fmt1 = "\t%o => %p (%x)\n"; 5008 5009 *fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2); 5010 if (*fmt2 == NULL) 5011 *fmt2 = "\t%o (%x)\n"; 5012 } 5013 5014 static void 5015 trace_print_obj(Obj_Entry *obj, const char *name, const char *path, 5016 const char *main_local, const char *fmt1, const char *fmt2) 5017 { 5018 const char *fmt; 5019 int c; 5020 5021 if (fmt1 == NULL) 5022 fmt = fmt2; 5023 else 5024 /* XXX bogus */ 5025 fmt = strncmp(name, "lib", 3) == 0 ? fmt1 : fmt2; 5026 5027 while ((c = *fmt++) != '\0') { 5028 switch (c) { 5029 default: 5030 rtld_putchar(c); 5031 continue; 5032 case '\\': 5033 switch (c = *fmt) { 5034 case '\0': 5035 continue; 5036 case 'n': 5037 rtld_putchar('\n'); 5038 break; 5039 case 't': 5040 rtld_putchar('\t'); 5041 break; 5042 } 5043 break; 5044 case '%': 5045 switch (c = *fmt) { 5046 case '\0': 5047 continue; 5048 case '%': 5049 default: 5050 rtld_putchar(c); 5051 break; 5052 case 'A': 5053 rtld_putstr(main_local); 5054 break; 5055 case 'a': 5056 rtld_putstr(obj_main->path); 5057 break; 5058 case 'o': 5059 rtld_putstr(name); 5060 break; 5061 case 'p': 5062 rtld_putstr(path); 5063 break; 5064 case 'x': 5065 rtld_printf("%p", obj != NULL ? 5066 obj->mapbase : NULL); 5067 break; 5068 } 5069 break; 5070 } 5071 ++fmt; 5072 } 5073 } 5074 5075 static void 5076 trace_loaded_objects(Obj_Entry *obj, bool show_preload) 5077 { 5078 const char *fmt1, *fmt2, *main_local; 5079 const char *name, *path; 5080 bool first_spurious, list_containers; 5081 5082 trace_calc_fmts(&main_local, &fmt1, &fmt2); 5083 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL) != NULL; 5084 5085 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5086 Needed_Entry *needed; 5087 5088 if (obj->marker) 5089 continue; 5090 if (list_containers && obj->needed != NULL) 5091 rtld_printf("%s:\n", obj->path); 5092 for (needed = obj->needed; needed; needed = needed->next) { 5093 if (needed->obj != NULL) { 5094 if (needed->obj->traced && !list_containers) 5095 continue; 5096 needed->obj->traced = true; 5097 path = needed->obj->path; 5098 } else 5099 path = "not found"; 5100 5101 name = obj->strtab + needed->name; 5102 trace_print_obj(needed->obj, name, path, main_local, 5103 fmt1, fmt2); 5104 } 5105 } 5106 5107 if (show_preload) { 5108 if (ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2) == NULL) 5109 fmt2 = "\t%p (%x)\n"; 5110 first_spurious = true; 5111 5112 TAILQ_FOREACH(obj, &obj_list, next) { 5113 if (obj->marker || obj == obj_main || obj->traced) 5114 continue; 5115 5116 if (list_containers && first_spurious) { 5117 rtld_printf("[preloaded]\n"); 5118 first_spurious = false; 5119 } 5120 5121 Name_Entry *fname = STAILQ_FIRST(&obj->names); 5122 name = fname == NULL ? "<unknown>" : fname->name; 5123 trace_print_obj(obj, name, obj->path, main_local, 5124 NULL, fmt2); 5125 } 5126 } 5127 } 5128 5129 /* 5130 * Unload a dlopened object and its dependencies from memory and from 5131 * our data structures. It is assumed that the DAG rooted in the 5132 * object has already been unreferenced, and that the object has a 5133 * reference count of 0. 5134 */ 5135 static void 5136 unload_object(Obj_Entry *root, RtldLockState *lockstate) 5137 { 5138 Obj_Entry marker, *obj, *next; 5139 5140 assert(root->refcount == 0); 5141 5142 /* 5143 * Pass over the DAG removing unreferenced objects from 5144 * appropriate lists. 5145 */ 5146 unlink_object(root); 5147 5148 /* Unmap all objects that are no longer referenced. */ 5149 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) { 5150 next = TAILQ_NEXT(obj, next); 5151 if (obj->marker || obj->refcount != 0) 5152 continue; 5153 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, 5154 obj->mapsize, 0, obj->path); 5155 dbg("unloading \"%s\"", obj->path); 5156 /* 5157 * Unlink the object now to prevent new references from 5158 * being acquired while the bind lock is dropped in 5159 * recursive dlclose() invocations. 5160 */ 5161 TAILQ_REMOVE(&obj_list, obj, next); 5162 obj_count--; 5163 5164 if (obj->filtees_loaded) { 5165 if (next != NULL) { 5166 init_marker(&marker); 5167 TAILQ_INSERT_BEFORE(next, &marker, next); 5168 unload_filtees(obj, lockstate); 5169 next = TAILQ_NEXT(&marker, next); 5170 TAILQ_REMOVE(&obj_list, &marker, next); 5171 } else 5172 unload_filtees(obj, lockstate); 5173 } 5174 release_object(obj); 5175 } 5176 } 5177 5178 static void 5179 unlink_object(Obj_Entry *root) 5180 { 5181 Objlist_Entry *elm; 5182 5183 if (root->refcount == 0) { 5184 /* Remove the object from the RTLD_GLOBAL list. */ 5185 objlist_remove(&list_global, root); 5186 5187 /* Remove the object from all objects' DAG lists. */ 5188 STAILQ_FOREACH(elm, &root->dagmembers, link) { 5189 objlist_remove(&elm->obj->dldags, root); 5190 if (elm->obj != root) 5191 unlink_object(elm->obj); 5192 } 5193 } 5194 } 5195 5196 static void 5197 ref_dag(Obj_Entry *root) 5198 { 5199 Objlist_Entry *elm; 5200 5201 assert(root->dag_inited); 5202 STAILQ_FOREACH(elm, &root->dagmembers, link) 5203 elm->obj->refcount++; 5204 } 5205 5206 static void 5207 unref_dag(Obj_Entry *root) 5208 { 5209 Objlist_Entry *elm; 5210 5211 assert(root->dag_inited); 5212 STAILQ_FOREACH(elm, &root->dagmembers, link) 5213 elm->obj->refcount--; 5214 } 5215 5216 /* 5217 * Common code for MD __tls_get_addr(). 5218 */ 5219 static void * 5220 tls_get_addr_slow(Elf_Addr **dtvp, int index, size_t offset, bool locked) 5221 { 5222 Elf_Addr *newdtv, *dtv; 5223 RtldLockState lockstate; 5224 int to_copy; 5225 5226 dtv = *dtvp; 5227 /* Check dtv generation in case new modules have arrived */ 5228 if (dtv[0] != tls_dtv_generation) { 5229 if (!locked) 5230 wlock_acquire(rtld_bind_lock, &lockstate); 5231 newdtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5232 to_copy = dtv[1]; 5233 if (to_copy > tls_max_index) 5234 to_copy = tls_max_index; 5235 memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); 5236 newdtv[0] = tls_dtv_generation; 5237 newdtv[1] = tls_max_index; 5238 free(dtv); 5239 if (!locked) 5240 lock_release(rtld_bind_lock, &lockstate); 5241 dtv = *dtvp = newdtv; 5242 } 5243 5244 /* Dynamically allocate module TLS if necessary */ 5245 if (dtv[index + 1] == 0) { 5246 /* Signal safe, wlock will block out signals. */ 5247 if (!locked) 5248 wlock_acquire(rtld_bind_lock, &lockstate); 5249 if (!dtv[index + 1]) 5250 dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); 5251 if (!locked) 5252 lock_release(rtld_bind_lock, &lockstate); 5253 } 5254 return ((void *)(dtv[index + 1] + offset)); 5255 } 5256 5257 void * 5258 tls_get_addr_common(uintptr_t **dtvp, int index, size_t offset) 5259 { 5260 uintptr_t *dtv; 5261 5262 dtv = *dtvp; 5263 /* Check dtv generation in case new modules have arrived */ 5264 if (__predict_true(dtv[0] == tls_dtv_generation && 5265 dtv[index + 1] != 0)) 5266 return ((void *)(dtv[index + 1] + offset)); 5267 return (tls_get_addr_slow(dtvp, index, offset, false)); 5268 } 5269 5270 #ifdef TLS_VARIANT_I 5271 5272 /* 5273 * Return pointer to allocated TLS block 5274 */ 5275 static void * 5276 get_tls_block_ptr(void *tcb, size_t tcbsize) 5277 { 5278 size_t extra_size, post_size, pre_size, tls_block_size; 5279 size_t tls_init_align; 5280 5281 tls_init_align = MAX(obj_main->tlsalign, 1); 5282 5283 /* Compute fragments sizes. */ 5284 extra_size = tcbsize - TLS_TCB_SIZE; 5285 post_size = calculate_tls_post_size(tls_init_align); 5286 tls_block_size = tcbsize + post_size; 5287 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 5288 5289 return ((char *)tcb - pre_size - extra_size); 5290 } 5291 5292 /* 5293 * Allocate Static TLS using the Variant I method. 5294 * 5295 * For details on the layout, see lib/libc/gen/tls.c. 5296 * 5297 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as 5298 * it is based on tls_last_offset, and TLS offsets here are really TCB 5299 * offsets, whereas libc's tls_static_space is just the executable's static 5300 * TLS segment. 5301 */ 5302 void * 5303 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 5304 { 5305 Obj_Entry *obj; 5306 char *tls_block; 5307 Elf_Addr *dtv, **tcb; 5308 Elf_Addr addr; 5309 Elf_Addr i; 5310 size_t extra_size, maxalign, post_size, pre_size, tls_block_size; 5311 size_t tls_init_align, tls_init_offset; 5312 5313 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) 5314 return (oldtcb); 5315 5316 assert(tcbsize >= TLS_TCB_SIZE); 5317 maxalign = MAX(tcbalign, tls_static_max_align); 5318 tls_init_align = MAX(obj_main->tlsalign, 1); 5319 5320 /* Compute fragmets sizes. */ 5321 extra_size = tcbsize - TLS_TCB_SIZE; 5322 post_size = calculate_tls_post_size(tls_init_align); 5323 tls_block_size = tcbsize + post_size; 5324 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 5325 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - post_size; 5326 5327 /* Allocate whole TLS block */ 5328 tls_block = xmalloc_aligned(tls_block_size, maxalign, 0); 5329 tcb = (Elf_Addr **)(tls_block + pre_size + extra_size); 5330 5331 if (oldtcb != NULL) { 5332 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize), 5333 tls_static_space); 5334 free(get_tls_block_ptr(oldtcb, tcbsize)); 5335 5336 /* Adjust the DTV. */ 5337 dtv = tcb[0]; 5338 for (i = 0; i < dtv[1]; i++) { 5339 if (dtv[i+2] >= (Elf_Addr)oldtcb && 5340 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) { 5341 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tcb; 5342 } 5343 } 5344 } else { 5345 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5346 tcb[0] = dtv; 5347 dtv[0] = tls_dtv_generation; 5348 dtv[1] = tls_max_index; 5349 5350 for (obj = globallist_curr(objs); obj != NULL; 5351 obj = globallist_next(obj)) { 5352 if (obj->tlsoffset == 0) 5353 continue; 5354 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1); 5355 addr = (Elf_Addr)tcb + obj->tlsoffset; 5356 if (tls_init_offset > 0) 5357 memset((void *)addr, 0, tls_init_offset); 5358 if (obj->tlsinitsize > 0) { 5359 memcpy((void *)(addr + tls_init_offset), obj->tlsinit, 5360 obj->tlsinitsize); 5361 } 5362 if (obj->tlssize > obj->tlsinitsize) { 5363 memset((void *)(addr + tls_init_offset + obj->tlsinitsize), 5364 0, obj->tlssize - obj->tlsinitsize - tls_init_offset); 5365 } 5366 dtv[obj->tlsindex + 1] = addr; 5367 } 5368 } 5369 5370 return (tcb); 5371 } 5372 5373 void 5374 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused) 5375 { 5376 Elf_Addr *dtv; 5377 Elf_Addr tlsstart, tlsend; 5378 size_t post_size; 5379 size_t dtvsize, i, tls_init_align __unused; 5380 5381 assert(tcbsize >= TLS_TCB_SIZE); 5382 tls_init_align = MAX(obj_main->tlsalign, 1); 5383 5384 /* Compute fragments sizes. */ 5385 post_size = calculate_tls_post_size(tls_init_align); 5386 5387 tlsstart = (Elf_Addr)tcb + TLS_TCB_SIZE + post_size; 5388 tlsend = (Elf_Addr)tcb + tls_static_space; 5389 5390 dtv = *(Elf_Addr **)tcb; 5391 dtvsize = dtv[1]; 5392 for (i = 0; i < dtvsize; i++) { 5393 if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) { 5394 free((void*)dtv[i+2]); 5395 } 5396 } 5397 free(dtv); 5398 free(get_tls_block_ptr(tcb, tcbsize)); 5399 } 5400 5401 #endif /* TLS_VARIANT_I */ 5402 5403 #ifdef TLS_VARIANT_II 5404 5405 /* 5406 * Allocate Static TLS using the Variant II method. 5407 */ 5408 void * 5409 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) 5410 { 5411 Obj_Entry *obj; 5412 size_t size, ralign; 5413 char *tls; 5414 Elf_Addr *dtv, *olddtv; 5415 Elf_Addr segbase, oldsegbase, addr; 5416 size_t i; 5417 5418 ralign = tcbalign; 5419 if (tls_static_max_align > ralign) 5420 ralign = tls_static_max_align; 5421 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign); 5422 5423 assert(tcbsize >= 2*sizeof(Elf_Addr)); 5424 tls = xmalloc_aligned(size, ralign, 0 /* XXX */); 5425 dtv = xcalloc(tls_max_index + 2, sizeof(Elf_Addr)); 5426 5427 segbase = (Elf_Addr)(tls + roundup(tls_static_space, ralign)); 5428 ((Elf_Addr *)segbase)[0] = segbase; 5429 ((Elf_Addr *)segbase)[1] = (Elf_Addr) dtv; 5430 5431 dtv[0] = tls_dtv_generation; 5432 dtv[1] = tls_max_index; 5433 5434 if (oldtls) { 5435 /* 5436 * Copy the static TLS block over whole. 5437 */ 5438 oldsegbase = (Elf_Addr) oldtls; 5439 memcpy((void *)(segbase - tls_static_space), 5440 (const void *)(oldsegbase - tls_static_space), 5441 tls_static_space); 5442 5443 /* 5444 * If any dynamic TLS blocks have been created tls_get_addr(), 5445 * move them over. 5446 */ 5447 olddtv = ((Elf_Addr **)oldsegbase)[1]; 5448 for (i = 0; i < olddtv[1]; i++) { 5449 if (olddtv[i + 2] < oldsegbase - size || 5450 olddtv[i + 2] > oldsegbase) { 5451 dtv[i + 2] = olddtv[i + 2]; 5452 olddtv[i + 2] = 0; 5453 } 5454 } 5455 5456 /* 5457 * We assume that this block was the one we created with 5458 * allocate_initial_tls(). 5459 */ 5460 free_tls(oldtls, 2 * sizeof(Elf_Addr), sizeof(Elf_Addr)); 5461 } else { 5462 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5463 if (obj->marker || obj->tlsoffset == 0) 5464 continue; 5465 addr = segbase - obj->tlsoffset; 5466 memset((void *)(addr + obj->tlsinitsize), 5467 0, obj->tlssize - obj->tlsinitsize); 5468 if (obj->tlsinit) { 5469 memcpy((void *)addr, obj->tlsinit, obj->tlsinitsize); 5470 obj->static_tls_copied = true; 5471 } 5472 dtv[obj->tlsindex + 1] = addr; 5473 } 5474 } 5475 5476 return ((void *)segbase); 5477 } 5478 5479 void 5480 free_tls(void *tls, size_t tcbsize __unused, size_t tcbalign) 5481 { 5482 Elf_Addr* dtv; 5483 size_t size, ralign; 5484 int dtvsize, i; 5485 Elf_Addr tlsstart, tlsend; 5486 5487 /* 5488 * Figure out the size of the initial TLS block so that we can 5489 * find stuff which ___tls_get_addr() allocated dynamically. 5490 */ 5491 ralign = tcbalign; 5492 if (tls_static_max_align > ralign) 5493 ralign = tls_static_max_align; 5494 size = roundup(tls_static_space, ralign); 5495 5496 dtv = ((Elf_Addr **)tls)[1]; 5497 dtvsize = dtv[1]; 5498 tlsend = (Elf_Addr)tls; 5499 tlsstart = tlsend - size; 5500 for (i = 0; i < dtvsize; i++) { 5501 if (dtv[i + 2] != 0 && (dtv[i + 2] < tlsstart || 5502 dtv[i + 2] > tlsend)) { 5503 free((void *)dtv[i + 2]); 5504 } 5505 } 5506 5507 free((void *)tlsstart); 5508 free((void *)dtv); 5509 } 5510 5511 #endif /* TLS_VARIANT_II */ 5512 5513 /* 5514 * Allocate TLS block for module with given index. 5515 */ 5516 void * 5517 allocate_module_tls(int index) 5518 { 5519 Obj_Entry *obj; 5520 char *p; 5521 5522 TAILQ_FOREACH(obj, &obj_list, next) { 5523 if (obj->marker) 5524 continue; 5525 if (obj->tlsindex == index) 5526 break; 5527 } 5528 if (obj == NULL) { 5529 _rtld_error("Can't find module with TLS index %d", index); 5530 rtld_die(); 5531 } 5532 5533 if (obj->tls_static) { 5534 #ifdef TLS_VARIANT_I 5535 p = (char *)_tcb_get() + obj->tlsoffset + TLS_TCB_SIZE; 5536 #else 5537 p = (char *)_tcb_get() - obj->tlsoffset; 5538 #endif 5539 return (p); 5540 } 5541 5542 obj->tls_dynamic = true; 5543 5544 p = xmalloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset); 5545 memcpy(p, obj->tlsinit, obj->tlsinitsize); 5546 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 5547 return (p); 5548 } 5549 5550 bool 5551 allocate_tls_offset(Obj_Entry *obj) 5552 { 5553 size_t off; 5554 5555 if (obj->tls_dynamic) 5556 return (false); 5557 5558 if (obj->tls_static) 5559 return (true); 5560 5561 if (obj->tlssize == 0) { 5562 obj->tls_static = true; 5563 return (true); 5564 } 5565 5566 if (tls_last_offset == 0) 5567 off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign, 5568 obj->tlspoffset); 5569 else 5570 off = calculate_tls_offset(tls_last_offset, tls_last_size, 5571 obj->tlssize, obj->tlsalign, obj->tlspoffset); 5572 5573 obj->tlsoffset = off; 5574 #ifdef TLS_VARIANT_I 5575 off += obj->tlssize; 5576 #endif 5577 5578 /* 5579 * If we have already fixed the size of the static TLS block, we 5580 * must stay within that size. When allocating the static TLS, we 5581 * leave a small amount of space spare to be used for dynamically 5582 * loading modules which use static TLS. 5583 */ 5584 if (tls_static_space != 0) { 5585 if (off > tls_static_space) 5586 return (false); 5587 } else if (obj->tlsalign > tls_static_max_align) { 5588 tls_static_max_align = obj->tlsalign; 5589 } 5590 5591 tls_last_offset = off; 5592 tls_last_size = obj->tlssize; 5593 obj->tls_static = true; 5594 5595 return (true); 5596 } 5597 5598 void 5599 free_tls_offset(Obj_Entry *obj) 5600 { 5601 5602 /* 5603 * If we were the last thing to allocate out of the static TLS 5604 * block, we give our space back to the 'allocator'. This is a 5605 * simplistic workaround to allow libGL.so.1 to be loaded and 5606 * unloaded multiple times. 5607 */ 5608 size_t off = obj->tlsoffset; 5609 #ifdef TLS_VARIANT_I 5610 off += obj->tlssize; 5611 #endif 5612 if (off == tls_last_offset) { 5613 tls_last_offset -= obj->tlssize; 5614 tls_last_size = 0; 5615 } 5616 } 5617 5618 void * 5619 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) 5620 { 5621 void *ret; 5622 RtldLockState lockstate; 5623 5624 wlock_acquire(rtld_bind_lock, &lockstate); 5625 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtls, 5626 tcbsize, tcbalign); 5627 lock_release(rtld_bind_lock, &lockstate); 5628 return (ret); 5629 } 5630 5631 void 5632 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 5633 { 5634 RtldLockState lockstate; 5635 5636 wlock_acquire(rtld_bind_lock, &lockstate); 5637 free_tls(tcb, tcbsize, tcbalign); 5638 lock_release(rtld_bind_lock, &lockstate); 5639 } 5640 5641 static void 5642 object_add_name(Obj_Entry *obj, const char *name) 5643 { 5644 Name_Entry *entry; 5645 size_t len; 5646 5647 len = strlen(name); 5648 entry = malloc(sizeof(Name_Entry) + len); 5649 5650 if (entry != NULL) { 5651 strcpy(entry->name, name); 5652 STAILQ_INSERT_TAIL(&obj->names, entry, link); 5653 } 5654 } 5655 5656 static int 5657 object_match_name(const Obj_Entry *obj, const char *name) 5658 { 5659 Name_Entry *entry; 5660 5661 STAILQ_FOREACH(entry, &obj->names, link) { 5662 if (strcmp(name, entry->name) == 0) 5663 return (1); 5664 } 5665 return (0); 5666 } 5667 5668 static Obj_Entry * 5669 locate_dependency(const Obj_Entry *obj, const char *name) 5670 { 5671 const Objlist_Entry *entry; 5672 const Needed_Entry *needed; 5673 5674 STAILQ_FOREACH(entry, &list_main, link) { 5675 if (object_match_name(entry->obj, name)) 5676 return (entry->obj); 5677 } 5678 5679 for (needed = obj->needed; needed != NULL; needed = needed->next) { 5680 if (strcmp(obj->strtab + needed->name, name) == 0 || 5681 (needed->obj != NULL && object_match_name(needed->obj, name))) { 5682 /* 5683 * If there is DT_NEEDED for the name we are looking for, 5684 * we are all set. Note that object might not be found if 5685 * dependency was not loaded yet, so the function can 5686 * return NULL here. This is expected and handled 5687 * properly by the caller. 5688 */ 5689 return (needed->obj); 5690 } 5691 } 5692 _rtld_error("%s: Unexpected inconsistency: dependency %s not found", 5693 obj->path, name); 5694 rtld_die(); 5695 } 5696 5697 static int 5698 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj, 5699 const Elf_Vernaux *vna) 5700 { 5701 const Elf_Verdef *vd; 5702 const char *vername; 5703 5704 vername = refobj->strtab + vna->vna_name; 5705 vd = depobj->verdef; 5706 if (vd == NULL) { 5707 _rtld_error("%s: version %s required by %s not defined", 5708 depobj->path, vername, refobj->path); 5709 return (-1); 5710 } 5711 for (;;) { 5712 if (vd->vd_version != VER_DEF_CURRENT) { 5713 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5714 depobj->path, vd->vd_version); 5715 return (-1); 5716 } 5717 if (vna->vna_hash == vd->vd_hash) { 5718 const Elf_Verdaux *aux = (const Elf_Verdaux *) 5719 ((const char *)vd + vd->vd_aux); 5720 if (strcmp(vername, depobj->strtab + aux->vda_name) == 0) 5721 return (0); 5722 } 5723 if (vd->vd_next == 0) 5724 break; 5725 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5726 } 5727 if (vna->vna_flags & VER_FLG_WEAK) 5728 return (0); 5729 _rtld_error("%s: version %s required by %s not found", 5730 depobj->path, vername, refobj->path); 5731 return (-1); 5732 } 5733 5734 static int 5735 rtld_verify_object_versions(Obj_Entry *obj) 5736 { 5737 const Elf_Verneed *vn; 5738 const Elf_Verdef *vd; 5739 const Elf_Verdaux *vda; 5740 const Elf_Vernaux *vna; 5741 const Obj_Entry *depobj; 5742 int maxvernum, vernum; 5743 5744 if (obj->ver_checked) 5745 return (0); 5746 obj->ver_checked = true; 5747 5748 maxvernum = 0; 5749 /* 5750 * Walk over defined and required version records and figure out 5751 * max index used by any of them. Do very basic sanity checking 5752 * while there. 5753 */ 5754 vn = obj->verneed; 5755 while (vn != NULL) { 5756 if (vn->vn_version != VER_NEED_CURRENT) { 5757 _rtld_error("%s: Unsupported version %d of Elf_Verneed entry", 5758 obj->path, vn->vn_version); 5759 return (-1); 5760 } 5761 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 5762 for (;;) { 5763 vernum = VER_NEED_IDX(vna->vna_other); 5764 if (vernum > maxvernum) 5765 maxvernum = vernum; 5766 if (vna->vna_next == 0) 5767 break; 5768 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next); 5769 } 5770 if (vn->vn_next == 0) 5771 break; 5772 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 5773 } 5774 5775 vd = obj->verdef; 5776 while (vd != NULL) { 5777 if (vd->vd_version != VER_DEF_CURRENT) { 5778 _rtld_error("%s: Unsupported version %d of Elf_Verdef entry", 5779 obj->path, vd->vd_version); 5780 return (-1); 5781 } 5782 vernum = VER_DEF_IDX(vd->vd_ndx); 5783 if (vernum > maxvernum) 5784 maxvernum = vernum; 5785 if (vd->vd_next == 0) 5786 break; 5787 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5788 } 5789 5790 if (maxvernum == 0) 5791 return (0); 5792 5793 /* 5794 * Store version information in array indexable by version index. 5795 * Verify that object version requirements are satisfied along the 5796 * way. 5797 */ 5798 obj->vernum = maxvernum + 1; 5799 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry)); 5800 5801 vd = obj->verdef; 5802 while (vd != NULL) { 5803 if ((vd->vd_flags & VER_FLG_BASE) == 0) { 5804 vernum = VER_DEF_IDX(vd->vd_ndx); 5805 assert(vernum <= maxvernum); 5806 vda = (const Elf_Verdaux *)((const char *)vd + vd->vd_aux); 5807 obj->vertab[vernum].hash = vd->vd_hash; 5808 obj->vertab[vernum].name = obj->strtab + vda->vda_name; 5809 obj->vertab[vernum].file = NULL; 5810 obj->vertab[vernum].flags = 0; 5811 } 5812 if (vd->vd_next == 0) 5813 break; 5814 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 5815 } 5816 5817 vn = obj->verneed; 5818 while (vn != NULL) { 5819 depobj = locate_dependency(obj, obj->strtab + vn->vn_file); 5820 if (depobj == NULL) 5821 return (-1); 5822 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 5823 for (;;) { 5824 if (check_object_provided_version(obj, depobj, vna)) 5825 return (-1); 5826 vernum = VER_NEED_IDX(vna->vna_other); 5827 assert(vernum <= maxvernum); 5828 obj->vertab[vernum].hash = vna->vna_hash; 5829 obj->vertab[vernum].name = obj->strtab + vna->vna_name; 5830 obj->vertab[vernum].file = obj->strtab + vn->vn_file; 5831 obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ? 5832 VER_INFO_HIDDEN : 0; 5833 if (vna->vna_next == 0) 5834 break; 5835 vna = (const Elf_Vernaux *)((const char *)vna + vna->vna_next); 5836 } 5837 if (vn->vn_next == 0) 5838 break; 5839 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 5840 } 5841 return (0); 5842 } 5843 5844 static int 5845 rtld_verify_versions(const Objlist *objlist) 5846 { 5847 Objlist_Entry *entry; 5848 int rc; 5849 5850 rc = 0; 5851 STAILQ_FOREACH(entry, objlist, link) { 5852 /* 5853 * Skip dummy objects or objects that have their version requirements 5854 * already checked. 5855 */ 5856 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL) 5857 continue; 5858 if (rtld_verify_object_versions(entry->obj) == -1) { 5859 rc = -1; 5860 if (ld_tracing == NULL) 5861 break; 5862 } 5863 } 5864 if (rc == 0 || ld_tracing != NULL) 5865 rc = rtld_verify_object_versions(&obj_rtld); 5866 return (rc); 5867 } 5868 5869 const Ver_Entry * 5870 fetch_ventry(const Obj_Entry *obj, unsigned long symnum) 5871 { 5872 Elf_Versym vernum; 5873 5874 if (obj->vertab) { 5875 vernum = VER_NDX(obj->versyms[symnum]); 5876 if (vernum >= obj->vernum) { 5877 _rtld_error("%s: symbol %s has wrong verneed value %d", 5878 obj->path, obj->strtab + symnum, vernum); 5879 } else if (obj->vertab[vernum].hash != 0) { 5880 return (&obj->vertab[vernum]); 5881 } 5882 } 5883 return (NULL); 5884 } 5885 5886 int 5887 _rtld_get_stack_prot(void) 5888 { 5889 5890 return (stack_prot); 5891 } 5892 5893 int 5894 _rtld_is_dlopened(void *arg) 5895 { 5896 Obj_Entry *obj; 5897 RtldLockState lockstate; 5898 int res; 5899 5900 rlock_acquire(rtld_bind_lock, &lockstate); 5901 obj = dlcheck(arg); 5902 if (obj == NULL) 5903 obj = obj_from_addr(arg); 5904 if (obj == NULL) { 5905 _rtld_error("No shared object contains address"); 5906 lock_release(rtld_bind_lock, &lockstate); 5907 return (-1); 5908 } 5909 res = obj->dlopened ? 1 : 0; 5910 lock_release(rtld_bind_lock, &lockstate); 5911 return (res); 5912 } 5913 5914 static int 5915 obj_remap_relro(Obj_Entry *obj, int prot) 5916 { 5917 5918 if (obj->relro_size > 0 && mprotect(obj->relro_page, obj->relro_size, 5919 prot) == -1) { 5920 _rtld_error("%s: Cannot set relro protection to %#x: %s", 5921 obj->path, prot, rtld_strerror(errno)); 5922 return (-1); 5923 } 5924 return (0); 5925 } 5926 5927 static int 5928 obj_disable_relro(Obj_Entry *obj) 5929 { 5930 5931 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE)); 5932 } 5933 5934 static int 5935 obj_enforce_relro(Obj_Entry *obj) 5936 { 5937 5938 return (obj_remap_relro(obj, PROT_READ)); 5939 } 5940 5941 static void 5942 map_stacks_exec(RtldLockState *lockstate) 5943 { 5944 void (*thr_map_stacks_exec)(void); 5945 5946 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0) 5947 return; 5948 thr_map_stacks_exec = (void (*)(void))(uintptr_t) 5949 get_program_var_addr("__pthread_map_stacks_exec", lockstate); 5950 if (thr_map_stacks_exec != NULL) { 5951 stack_prot |= PROT_EXEC; 5952 thr_map_stacks_exec(); 5953 } 5954 } 5955 5956 static void 5957 distribute_static_tls(Objlist *list, RtldLockState *lockstate) 5958 { 5959 Objlist_Entry *elm; 5960 Obj_Entry *obj; 5961 void (*distrib)(size_t, void *, size_t, size_t); 5962 5963 distrib = (void (*)(size_t, void *, size_t, size_t))(uintptr_t) 5964 get_program_var_addr("__pthread_distribute_static_tls", lockstate); 5965 if (distrib == NULL) 5966 return; 5967 STAILQ_FOREACH(elm, list, link) { 5968 obj = elm->obj; 5969 if (obj->marker || !obj->tls_static || obj->static_tls_copied) 5970 continue; 5971 lock_release(rtld_bind_lock, lockstate); 5972 distrib(obj->tlsoffset, obj->tlsinit, obj->tlsinitsize, 5973 obj->tlssize); 5974 wlock_acquire(rtld_bind_lock, lockstate); 5975 obj->static_tls_copied = true; 5976 } 5977 } 5978 5979 void 5980 symlook_init(SymLook *dst, const char *name) 5981 { 5982 5983 bzero(dst, sizeof(*dst)); 5984 dst->name = name; 5985 dst->hash = elf_hash(name); 5986 dst->hash_gnu = gnu_hash(name); 5987 } 5988 5989 static void 5990 symlook_init_from_req(SymLook *dst, const SymLook *src) 5991 { 5992 5993 dst->name = src->name; 5994 dst->hash = src->hash; 5995 dst->hash_gnu = src->hash_gnu; 5996 dst->ventry = src->ventry; 5997 dst->flags = src->flags; 5998 dst->defobj_out = NULL; 5999 dst->sym_out = NULL; 6000 dst->lockstate = src->lockstate; 6001 } 6002 6003 static int 6004 open_binary_fd(const char *argv0, bool search_in_path, 6005 const char **binpath_res) 6006 { 6007 char *binpath, *pathenv, *pe, *res1; 6008 const char *res; 6009 int fd; 6010 6011 binpath = NULL; 6012 res = NULL; 6013 if (search_in_path && strchr(argv0, '/') == NULL) { 6014 binpath = xmalloc(PATH_MAX); 6015 pathenv = getenv("PATH"); 6016 if (pathenv == NULL) { 6017 _rtld_error("-p and no PATH environment variable"); 6018 rtld_die(); 6019 } 6020 pathenv = strdup(pathenv); 6021 if (pathenv == NULL) { 6022 _rtld_error("Cannot allocate memory"); 6023 rtld_die(); 6024 } 6025 fd = -1; 6026 errno = ENOENT; 6027 while ((pe = strsep(&pathenv, ":")) != NULL) { 6028 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX) 6029 continue; 6030 if (binpath[0] != '\0' && 6031 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX) 6032 continue; 6033 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX) 6034 continue; 6035 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY); 6036 if (fd != -1 || errno != ENOENT) { 6037 res = binpath; 6038 break; 6039 } 6040 } 6041 free(pathenv); 6042 } else { 6043 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY); 6044 res = argv0; 6045 } 6046 6047 if (fd == -1) { 6048 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno)); 6049 rtld_die(); 6050 } 6051 if (res != NULL && res[0] != '/') { 6052 res1 = xmalloc(PATH_MAX); 6053 if (realpath(res, res1) != NULL) { 6054 if (res != argv0) 6055 free(__DECONST(char *, res)); 6056 res = res1; 6057 } else { 6058 free(res1); 6059 } 6060 } 6061 *binpath_res = res; 6062 return (fd); 6063 } 6064 6065 /* 6066 * Parse a set of command-line arguments. 6067 */ 6068 static int 6069 parse_args(char* argv[], int argc, bool *use_pathp, int *fdp, 6070 const char **argv0, bool *dir_ignore) 6071 { 6072 const char *arg; 6073 char machine[64]; 6074 size_t sz; 6075 int arglen, fd, i, j, mib[2]; 6076 char opt; 6077 bool seen_b, seen_f; 6078 6079 dbg("Parsing command-line arguments"); 6080 *use_pathp = false; 6081 *fdp = -1; 6082 *dir_ignore = false; 6083 seen_b = seen_f = false; 6084 6085 for (i = 1; i < argc; i++ ) { 6086 arg = argv[i]; 6087 dbg("argv[%d]: '%s'", i, arg); 6088 6089 /* 6090 * rtld arguments end with an explicit "--" or with the first 6091 * non-prefixed argument. 6092 */ 6093 if (strcmp(arg, "--") == 0) { 6094 i++; 6095 break; 6096 } 6097 if (arg[0] != '-') 6098 break; 6099 6100 /* 6101 * All other arguments are single-character options that can 6102 * be combined, so we need to search through `arg` for them. 6103 */ 6104 arglen = strlen(arg); 6105 for (j = 1; j < arglen; j++) { 6106 opt = arg[j]; 6107 if (opt == 'h') { 6108 print_usage(argv[0]); 6109 _exit(0); 6110 } else if (opt == 'b') { 6111 if (seen_f) { 6112 _rtld_error("Both -b and -f specified"); 6113 rtld_die(); 6114 } 6115 if (j != arglen - 1) { 6116 _rtld_error("Invalid options: %s", arg); 6117 rtld_die(); 6118 } 6119 i++; 6120 *argv0 = argv[i]; 6121 seen_b = true; 6122 break; 6123 } else if (opt == 'd') { 6124 *dir_ignore = true; 6125 } else if (opt == 'f') { 6126 if (seen_b) { 6127 _rtld_error("Both -b and -f specified"); 6128 rtld_die(); 6129 } 6130 6131 /* 6132 * -f XX can be used to specify a 6133 * descriptor for the binary named at 6134 * the command line (i.e., the later 6135 * argument will specify the process 6136 * name but the descriptor is what 6137 * will actually be executed). 6138 * 6139 * -f must be the last option in the 6140 * group, e.g., -abcf <fd>. 6141 */ 6142 if (j != arglen - 1) { 6143 _rtld_error("Invalid options: %s", arg); 6144 rtld_die(); 6145 } 6146 i++; 6147 fd = parse_integer(argv[i]); 6148 if (fd == -1) { 6149 _rtld_error( 6150 "Invalid file descriptor: '%s'", 6151 argv[i]); 6152 rtld_die(); 6153 } 6154 *fdp = fd; 6155 seen_f = true; 6156 break; 6157 } else if (opt == 'p') { 6158 *use_pathp = true; 6159 } else if (opt == 'u') { 6160 trust = false; 6161 } else if (opt == 'v') { 6162 machine[0] = '\0'; 6163 mib[0] = CTL_HW; 6164 mib[1] = HW_MACHINE; 6165 sz = sizeof(machine); 6166 sysctl(mib, nitems(mib), machine, &sz, NULL, 0); 6167 ld_elf_hints_path = ld_get_env_var( 6168 LD_ELF_HINTS_PATH); 6169 set_ld_elf_hints_path(); 6170 rtld_printf( 6171 "FreeBSD ld-elf.so.1 %s\n" 6172 "FreeBSD_version %d\n" 6173 "Default lib path %s\n" 6174 "Hints lib path %s\n" 6175 "Env prefix %s\n" 6176 "Default hint file %s\n" 6177 "Hint file %s\n" 6178 "libmap file %s\n" 6179 "Optional static TLS size %zd bytes\n", 6180 machine, 6181 __FreeBSD_version, ld_standard_library_path, 6182 gethints(false), 6183 ld_env_prefix, ld_elf_hints_default, 6184 ld_elf_hints_path, 6185 ld_path_libmap_conf, 6186 ld_static_tls_extra); 6187 _exit(0); 6188 } else { 6189 _rtld_error("Invalid argument: '%s'", arg); 6190 print_usage(argv[0]); 6191 rtld_die(); 6192 } 6193 } 6194 } 6195 6196 if (!seen_b) 6197 *argv0 = argv[i]; 6198 return (i); 6199 } 6200 6201 /* 6202 * Parse a file descriptor number without pulling in more of libc (e.g. atoi). 6203 */ 6204 static int 6205 parse_integer(const char *str) 6206 { 6207 static const int RADIX = 10; /* XXXJA: possibly support hex? */ 6208 const char *orig; 6209 int n; 6210 char c; 6211 6212 orig = str; 6213 n = 0; 6214 for (c = *str; c != '\0'; c = *++str) { 6215 if (c < '0' || c > '9') 6216 return (-1); 6217 6218 n *= RADIX; 6219 n += c - '0'; 6220 } 6221 6222 /* Make sure we actually parsed something. */ 6223 if (str == orig) 6224 return (-1); 6225 return (n); 6226 } 6227 6228 static void 6229 print_usage(const char *argv0) 6230 { 6231 6232 rtld_printf( 6233 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n" 6234 "\n" 6235 "Options:\n" 6236 " -h Display this help message\n" 6237 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n" 6238 " -d Ignore lack of exec permissions for the binary\n" 6239 " -f <FD> Execute <FD> instead of searching for <binary>\n" 6240 " -p Search in PATH for named binary\n" 6241 " -u Ignore LD_ environment variables\n" 6242 " -v Display identification information\n" 6243 " -- End of RTLD options\n" 6244 " <binary> Name of process to execute\n" 6245 " <args> Arguments to the executed process\n", argv0); 6246 } 6247 6248 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt } 6249 static const struct auxfmt { 6250 const char *name; 6251 const char *fmt; 6252 } auxfmts[] = { 6253 AUXFMT(AT_NULL, NULL), 6254 AUXFMT(AT_IGNORE, NULL), 6255 AUXFMT(AT_EXECFD, "%ld"), 6256 AUXFMT(AT_PHDR, "%p"), 6257 AUXFMT(AT_PHENT, "%lu"), 6258 AUXFMT(AT_PHNUM, "%lu"), 6259 AUXFMT(AT_PAGESZ, "%lu"), 6260 AUXFMT(AT_BASE, "%#lx"), 6261 AUXFMT(AT_FLAGS, "%#lx"), 6262 AUXFMT(AT_ENTRY, "%p"), 6263 AUXFMT(AT_NOTELF, NULL), 6264 AUXFMT(AT_UID, "%ld"), 6265 AUXFMT(AT_EUID, "%ld"), 6266 AUXFMT(AT_GID, "%ld"), 6267 AUXFMT(AT_EGID, "%ld"), 6268 AUXFMT(AT_EXECPATH, "%s"), 6269 AUXFMT(AT_CANARY, "%p"), 6270 AUXFMT(AT_CANARYLEN, "%lu"), 6271 AUXFMT(AT_OSRELDATE, "%lu"), 6272 AUXFMT(AT_NCPUS, "%lu"), 6273 AUXFMT(AT_PAGESIZES, "%p"), 6274 AUXFMT(AT_PAGESIZESLEN, "%lu"), 6275 AUXFMT(AT_TIMEKEEP, "%p"), 6276 AUXFMT(AT_STACKPROT, "%#lx"), 6277 AUXFMT(AT_EHDRFLAGS, "%#lx"), 6278 AUXFMT(AT_HWCAP, "%#lx"), 6279 AUXFMT(AT_HWCAP2, "%#lx"), 6280 AUXFMT(AT_BSDFLAGS, "%#lx"), 6281 AUXFMT(AT_ARGC, "%lu"), 6282 AUXFMT(AT_ARGV, "%p"), 6283 AUXFMT(AT_ENVC, "%p"), 6284 AUXFMT(AT_ENVV, "%p"), 6285 AUXFMT(AT_PS_STRINGS, "%p"), 6286 AUXFMT(AT_FXRNG, "%p"), 6287 AUXFMT(AT_KPRELOAD, "%p"), 6288 AUXFMT(AT_USRSTACKBASE, "%#lx"), 6289 AUXFMT(AT_USRSTACKLIM, "%#lx"), 6290 }; 6291 6292 static bool 6293 is_ptr_fmt(const char *fmt) 6294 { 6295 char last; 6296 6297 last = fmt[strlen(fmt) - 1]; 6298 return (last == 'p' || last == 's'); 6299 } 6300 6301 static void 6302 dump_auxv(Elf_Auxinfo **aux_info) 6303 { 6304 Elf_Auxinfo *auxp; 6305 const struct auxfmt *fmt; 6306 int i; 6307 6308 for (i = 0; i < AT_COUNT; i++) { 6309 auxp = aux_info[i]; 6310 if (auxp == NULL) 6311 continue; 6312 fmt = &auxfmts[i]; 6313 if (fmt->fmt == NULL) 6314 continue; 6315 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name); 6316 if (is_ptr_fmt(fmt->fmt)) { 6317 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt, 6318 auxp->a_un.a_ptr); 6319 } else { 6320 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt, 6321 auxp->a_un.a_val); 6322 } 6323 rtld_fdprintf(STDOUT_FILENO, "\n"); 6324 } 6325 } 6326 6327 /* 6328 * Overrides for libc_pic-provided functions. 6329 */ 6330 6331 int 6332 __getosreldate(void) 6333 { 6334 size_t len; 6335 int oid[2]; 6336 int error, osrel; 6337 6338 if (osreldate != 0) 6339 return (osreldate); 6340 6341 oid[0] = CTL_KERN; 6342 oid[1] = KERN_OSRELDATE; 6343 osrel = 0; 6344 len = sizeof(osrel); 6345 error = sysctl(oid, 2, &osrel, &len, NULL, 0); 6346 if (error == 0 && osrel > 0 && len == sizeof(osrel)) 6347 osreldate = osrel; 6348 return (osreldate); 6349 } 6350 const char * 6351 rtld_strerror(int errnum) 6352 { 6353 6354 if (errnum < 0 || errnum >= sys_nerr) 6355 return ("Unknown error"); 6356 return (sys_errlist[errnum]); 6357 } 6358 6359 char * 6360 getenv(const char *name) 6361 { 6362 return (__DECONST(char *, rtld_get_env_val(environ, name, 6363 strlen(name)))); 6364 } 6365 6366 /* malloc */ 6367 void * 6368 malloc(size_t nbytes) 6369 { 6370 6371 return (__crt_malloc(nbytes)); 6372 } 6373 6374 void * 6375 calloc(size_t num, size_t size) 6376 { 6377 6378 return (__crt_calloc(num, size)); 6379 } 6380 6381 void 6382 free(void *cp) 6383 { 6384 6385 __crt_free(cp); 6386 } 6387 6388 void * 6389 realloc(void *cp, size_t nbytes) 6390 { 6391 6392 return (__crt_realloc(cp, nbytes)); 6393 } 6394 6395 extern int _rtld_version__FreeBSD_version __exported; 6396 int _rtld_version__FreeBSD_version = __FreeBSD_version; 6397 6398 extern char _rtld_version_laddr_offset __exported; 6399 char _rtld_version_laddr_offset; 6400 6401 extern char _rtld_version_dlpi_tls_data __exported; 6402 char _rtld_version_dlpi_tls_data; 6403