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