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