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