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