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