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 } else { 2658 if (obj->init_scanned) 2659 return; 2660 obj->init_scanned = true; 2661 2662 /* Recursively process the successor objects. */ 2663 nobj = globallist_next(obj); 2664 if (nobj != NULL && obj != tail) 2665 initlist_add_objects(nobj, tail, list, iflist); 2666 2667 /* Recursively process the needed objects. */ 2668 if (obj->needed != NULL) 2669 initlist_add_neededs(obj->needed, list, iflist); 2670 if (obj->needed_filtees != NULL) 2671 initlist_add_neededs(obj->needed_filtees, list, 2672 iflist); 2673 if (obj->needed_aux_filtees != NULL) 2674 initlist_add_neededs(obj->needed_aux_filtees, list, 2675 iflist); 2676 2677 /* Add the object to the init list. */ 2678 objlist_push_tail(list, obj); 2679 2680 /* 2681 * Add the object to the global fini list in the 2682 * reverse order. 2683 */ 2684 if ((obj->fini != 0 || obj->fini_array != NULL) && 2685 !obj->on_fini_list) { 2686 objlist_push_head(&list_fini, obj); 2687 obj->on_fini_list = true; 2688 } 2689 } 2690 } 2691 2692 static void 2693 free_needed_filtees(Needed_Entry *n, RtldLockState *lockstate) 2694 { 2695 Needed_Entry *needed, *needed1; 2696 2697 for (needed = n; needed != NULL; needed = needed->next) { 2698 if (needed->obj != NULL) { 2699 dlclose_locked(needed->obj, lockstate); 2700 needed->obj = NULL; 2701 } 2702 } 2703 for (needed = n; needed != NULL; needed = needed1) { 2704 needed1 = needed->next; 2705 free(needed); 2706 } 2707 } 2708 2709 static void 2710 unload_filtees(Obj_Entry *obj, RtldLockState *lockstate) 2711 { 2712 free_needed_filtees(obj->needed_filtees, lockstate); 2713 obj->needed_filtees = NULL; 2714 free_needed_filtees(obj->needed_aux_filtees, lockstate); 2715 obj->needed_aux_filtees = NULL; 2716 obj->filtees_loaded = false; 2717 } 2718 2719 static void 2720 load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags, 2721 RtldLockState *lockstate) 2722 { 2723 for (; needed != NULL; needed = needed->next) { 2724 needed->obj = dlopen_object(obj->strtab + needed->name, -1, obj, 2725 flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : 2726 RTLD_LAZY) | RTLD_LOCAL, lockstate); 2727 } 2728 } 2729 2730 static void 2731 load_filtees(Obj_Entry *obj, int flags, RtldLockState *lockstate) 2732 { 2733 if (obj->filtees_loaded || obj->filtees_loading) 2734 return; 2735 lock_restart_for_upgrade(lockstate); 2736 obj->filtees_loading = true; 2737 load_filtee1(obj, obj->needed_filtees, flags, lockstate); 2738 load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate); 2739 obj->filtees_loaded = true; 2740 obj->filtees_loading = false; 2741 } 2742 2743 static int 2744 process_needed(Obj_Entry *obj, Needed_Entry *needed, int flags) 2745 { 2746 Obj_Entry *obj1; 2747 2748 for (; needed != NULL; needed = needed->next) { 2749 obj1 = needed->obj = load_object(obj->strtab + needed->name, -1, 2750 obj, flags & ~RTLD_LO_NOLOAD); 2751 if (obj1 == NULL && !ld_tracing && 2752 (flags & RTLD_LO_FILTEES) == 0) 2753 return (-1); 2754 } 2755 return (0); 2756 } 2757 2758 /* 2759 * Given a shared object, traverse its list of needed objects, and load 2760 * each of them. Returns 0 on success. Generates an error message and 2761 * returns -1 on failure. 2762 */ 2763 static int 2764 load_needed_objects(Obj_Entry *first, int flags) 2765 { 2766 Obj_Entry *obj; 2767 2768 for (obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 2769 if (obj->marker) 2770 continue; 2771 if (process_needed(obj, obj->needed, flags) == -1) 2772 return (-1); 2773 } 2774 return (0); 2775 } 2776 2777 static int 2778 load_preload_objects(const char *penv, bool isfd) 2779 { 2780 Obj_Entry *obj; 2781 const char *name; 2782 size_t len; 2783 char savech, *p, *psave; 2784 int fd; 2785 static const char delim[] = " \t:;"; 2786 2787 if (penv == NULL) 2788 return (0); 2789 2790 p = psave = xstrdup(penv); 2791 p += strspn(p, delim); 2792 while (*p != '\0') { 2793 len = strcspn(p, delim); 2794 2795 savech = p[len]; 2796 p[len] = '\0'; 2797 if (isfd) { 2798 name = NULL; 2799 fd = parse_integer(p); 2800 if (fd == -1) { 2801 free(psave); 2802 return (-1); 2803 } 2804 } else { 2805 name = p; 2806 fd = -1; 2807 } 2808 2809 obj = load_object(name, fd, NULL, 0); 2810 if (obj == NULL) { 2811 free(psave); 2812 return (-1); /* XXX - cleanup */ 2813 } 2814 obj->z_interpose = true; 2815 p[len] = savech; 2816 p += len; 2817 p += strspn(p, delim); 2818 } 2819 LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL); 2820 2821 free(psave); 2822 return (0); 2823 } 2824 2825 static const char * 2826 printable_path(const char *path) 2827 { 2828 return (path == NULL ? "<unknown>" : path); 2829 } 2830 2831 /* 2832 * Load a shared object into memory, if it is not already loaded. The 2833 * object may be specified by name or by user-supplied file descriptor 2834 * fd_u. In the later case, the fd_u descriptor is not closed, but its 2835 * duplicate is. 2836 * 2837 * Returns a pointer to the Obj_Entry for the object. Returns NULL 2838 * on failure. 2839 */ 2840 static Obj_Entry * 2841 load_object(const char *name, int fd_u, const Obj_Entry *refobj, int flags) 2842 { 2843 Obj_Entry *obj; 2844 int fd; 2845 struct stat sb; 2846 char *path; 2847 2848 fd = -1; 2849 if (name != NULL) { 2850 TAILQ_FOREACH(obj, &obj_list, next) { 2851 if (obj->marker || obj->doomed) 2852 continue; 2853 if (object_match_name(obj, name)) 2854 return (obj); 2855 } 2856 2857 path = find_library(name, refobj, &fd); 2858 if (path == NULL) 2859 return (NULL); 2860 } else 2861 path = NULL; 2862 2863 if (fd >= 0) { 2864 /* 2865 * search_library_pathfds() opens a fresh file descriptor for 2866 * the library, so there is no need to dup(). 2867 */ 2868 } else if (fd_u == -1) { 2869 /* 2870 * If we didn't find a match by pathname, or the name is not 2871 * supplied, open the file and check again by device and inode. 2872 * This avoids false mismatches caused by multiple links or ".." 2873 * in pathnames. 2874 * 2875 * To avoid a race, we open the file and use fstat() rather than 2876 * using stat(). 2877 */ 2878 if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_VERIFY)) == -1) { 2879 fd = try_fds_open(path, ld_library_dirs); 2880 if (fd == -1) { 2881 _rtld_error("Cannot open \"%s\"", path); 2882 free(path); 2883 return (NULL); 2884 } 2885 } 2886 } else { 2887 fd = fcntl(fd_u, F_DUPFD_CLOEXEC, 0); 2888 if (fd == -1) { 2889 _rtld_error("Cannot dup fd"); 2890 free(path); 2891 return (NULL); 2892 } 2893 } 2894 if (fstat(fd, &sb) == -1) { 2895 _rtld_error("Cannot fstat \"%s\"", printable_path(path)); 2896 close(fd); 2897 free(path); 2898 return (NULL); 2899 } 2900 TAILQ_FOREACH(obj, &obj_list, next) { 2901 if (obj->marker || obj->doomed) 2902 continue; 2903 if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) 2904 break; 2905 } 2906 if (obj != NULL) { 2907 if (name != NULL) 2908 object_add_name(obj, name); 2909 free(path); 2910 close(fd); 2911 return (obj); 2912 } 2913 if (flags & RTLD_LO_NOLOAD) { 2914 free(path); 2915 close(fd); 2916 return (NULL); 2917 } 2918 2919 /* First use of this object, so we must map it in */ 2920 obj = do_load_object(fd, name, path, &sb, flags); 2921 if (obj == NULL) 2922 free(path); 2923 close(fd); 2924 2925 return (obj); 2926 } 2927 2928 static Obj_Entry * 2929 do_load_object(int fd, const char *name, char *path, struct stat *sbp, 2930 int flags) 2931 { 2932 Obj_Entry *obj; 2933 struct statfs fs; 2934 2935 /* 2936 * First, make sure that environment variables haven't been 2937 * used to circumvent the noexec flag on a filesystem. 2938 * We ignore fstatfs(2) failures, since fd might reference 2939 * not a file, e.g. shmfd. 2940 */ 2941 if (dangerous_ld_env && fstatfs(fd, &fs) == 0 && 2942 (fs.f_flags & MNT_NOEXEC) != 0) { 2943 _rtld_error("Cannot execute objects on %s", fs.f_mntonname); 2944 return (NULL); 2945 } 2946 2947 dbg("loading \"%s\"", printable_path(path)); 2948 obj = map_object(fd, printable_path(path), sbp, false); 2949 if (obj == NULL) 2950 return (NULL); 2951 2952 /* 2953 * If DT_SONAME is present in the object, digest_dynamic2 already 2954 * added it to the object names. 2955 */ 2956 if (name != NULL) 2957 object_add_name(obj, name); 2958 obj->path = path; 2959 if (!digest_dynamic(obj, 0)) 2960 goto errp; 2961 dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d", obj->path, 2962 obj->valid_hash_sysv, obj->valid_hash_gnu, obj->dynsymcount); 2963 if (obj->z_pie && (flags & RTLD_LO_TRACE) == 0) { 2964 dbg("refusing to load PIE executable \"%s\"", obj->path); 2965 _rtld_error("Cannot load PIE binary %s as DSO", obj->path); 2966 goto errp; 2967 } 2968 if (obj->z_noopen && 2969 (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) == RTLD_LO_DLOPEN) { 2970 dbg("refusing to load non-loadable \"%s\"", obj->path); 2971 _rtld_error("Cannot dlopen non-loadable %s", obj->path); 2972 goto errp; 2973 } 2974 2975 obj->dlopened = (flags & RTLD_LO_DLOPEN) != 0; 2976 TAILQ_INSERT_TAIL(&obj_list, obj, next); 2977 obj_count++; 2978 obj_loads++; 2979 linkmap_add(obj); /* for GDB & dlinfo() */ 2980 max_stack_flags |= obj->stack_flags; 2981 2982 dbg(" %p .. %p: %s", obj->mapbase, obj->mapbase + obj->mapsize - 1, 2983 obj->path); 2984 if (obj->textrel) 2985 dbg(" WARNING: %s has impure text", obj->path); 2986 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 2987 obj->path); 2988 2989 return (obj); 2990 2991 errp: 2992 munmap(obj->mapbase, obj->mapsize); 2993 obj_free(obj); 2994 return (NULL); 2995 } 2996 2997 static int 2998 load_kpreload(const void *addr) 2999 { 3000 Obj_Entry *obj; 3001 const Elf_Ehdr *ehdr; 3002 const Elf_Phdr *phdr, *phlimit, *phdyn, *seg0, *segn; 3003 static const char kname[] = "[vdso]"; 3004 3005 ehdr = addr; 3006 if (!check_elf_headers(ehdr, "kpreload")) 3007 return (-1); 3008 obj = obj_new(); 3009 phdr = (const Elf_Phdr *)((const char *)addr + ehdr->e_phoff); 3010 obj->phdr = phdr; 3011 obj->phnum = ehdr->e_phnum; 3012 phlimit = phdr + ehdr->e_phnum; 3013 seg0 = segn = NULL; 3014 3015 for (; phdr < phlimit; phdr++) { 3016 switch (phdr->p_type) { 3017 case PT_DYNAMIC: 3018 phdyn = phdr; 3019 break; 3020 case PT_GNU_STACK: 3021 /* Absense of PT_GNU_STACK implies stack_flags == 0. */ 3022 obj->stack_flags = phdr->p_flags; 3023 break; 3024 case PT_LOAD: 3025 if (seg0 == NULL || seg0->p_vaddr > phdr->p_vaddr) 3026 seg0 = phdr; 3027 if (segn == NULL || 3028 segn->p_vaddr + segn->p_memsz < 3029 phdr->p_vaddr + phdr->p_memsz) 3030 segn = phdr; 3031 break; 3032 } 3033 } 3034 3035 obj->mapbase = __DECONST(caddr_t, addr); 3036 obj->mapsize = segn->p_vaddr + segn->p_memsz; 3037 obj->vaddrbase = 0; 3038 obj->relocbase = obj->mapbase; 3039 3040 object_add_name(obj, kname); 3041 obj->path = xstrdup(kname); 3042 obj->dynamic = (const Elf_Dyn *)(obj->relocbase + phdyn->p_vaddr); 3043 3044 if (!digest_dynamic(obj, 0)) { 3045 obj_free(obj); 3046 return (-1); 3047 } 3048 3049 /* 3050 * We assume that kernel-preloaded object does not need 3051 * relocation. It is currently written into read-only page, 3052 * handling relocations would mean we need to allocate at 3053 * least one additional page per AS. 3054 */ 3055 dbg("%s mapbase %p phdrs %p PT_LOAD phdr %p vaddr %p dynamic %p", 3056 obj->path, obj->mapbase, obj->phdr, seg0, 3057 obj->relocbase + seg0->p_vaddr, obj->dynamic); 3058 3059 TAILQ_INSERT_TAIL(&obj_list, obj, next); 3060 obj_count++; 3061 obj_loads++; 3062 linkmap_add(obj); /* for GDB & dlinfo() */ 3063 max_stack_flags |= obj->stack_flags; 3064 3065 LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0, 3066 obj->path); 3067 return (0); 3068 } 3069 3070 Obj_Entry * 3071 obj_from_addr(const void *addr) 3072 { 3073 Obj_Entry *obj; 3074 3075 TAILQ_FOREACH(obj, &obj_list, next) { 3076 if (obj->marker) 3077 continue; 3078 if (addr < (void *)obj->mapbase) 3079 continue; 3080 if (addr < (void *)(obj->mapbase + obj->mapsize)) 3081 return obj; 3082 } 3083 return (NULL); 3084 } 3085 3086 static void 3087 preinit_main(void) 3088 { 3089 uintptr_t *preinit_addr; 3090 int index; 3091 3092 preinit_addr = obj_main->preinit_array; 3093 if (preinit_addr == NULL) 3094 return; 3095 3096 for (index = 0; index < obj_main->preinit_array_num; index++) { 3097 if (preinit_addr[index] != 0 && preinit_addr[index] != 1) { 3098 dbg("calling preinit function for %s at %p", 3099 obj_main->path, (void *)preinit_addr[index]); 3100 LD_UTRACE(UTRACE_INIT_CALL, obj_main, 3101 (void *)preinit_addr[index], 0, 0, obj_main->path); 3102 call_init_pointer(obj_main, preinit_addr[index]); 3103 } 3104 } 3105 } 3106 3107 /* 3108 * Call the finalization functions for each of the objects in "list" 3109 * belonging to the DAG of "root" and referenced once. If NULL "root" 3110 * is specified, every finalization function will be called regardless 3111 * of the reference count and the list elements won't be freed. All of 3112 * the objects are expected to have non-NULL fini functions. 3113 */ 3114 static void 3115 objlist_call_fini(Objlist *list, Obj_Entry *root, RtldLockState *lockstate) 3116 { 3117 Objlist_Entry *elm; 3118 struct dlerror_save *saved_msg; 3119 uintptr_t *fini_addr; 3120 int index; 3121 3122 assert(root == NULL || root->refcount == 1); 3123 3124 if (root != NULL) 3125 root->doomed = true; 3126 3127 /* 3128 * Preserve the current error message since a fini function might 3129 * call into the dynamic linker and overwrite it. 3130 */ 3131 saved_msg = errmsg_save(); 3132 do { 3133 STAILQ_FOREACH(elm, list, link) { 3134 if (root != NULL && 3135 (elm->obj->refcount != 1 || 3136 objlist_find(&root->dagmembers, elm->obj) == 3137 NULL)) 3138 continue; 3139 /* Remove object from fini list to prevent recursive 3140 * invocation. */ 3141 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 3142 /* Ensure that new references cannot be acquired. */ 3143 elm->obj->doomed = true; 3144 3145 hold_object(elm->obj); 3146 lock_release(rtld_bind_lock, lockstate); 3147 /* 3148 * It is legal to have both DT_FINI and DT_FINI_ARRAY 3149 * defined. When this happens, DT_FINI_ARRAY is 3150 * processed first. 3151 */ 3152 fini_addr = elm->obj->fini_array; 3153 if (fini_addr != NULL && elm->obj->fini_array_num > 0) { 3154 for (index = elm->obj->fini_array_num - 1; 3155 index >= 0; index--) { 3156 if (fini_addr[index] != 0 && 3157 fini_addr[index] != 1) { 3158 dbg("calling fini function for %s at %p", 3159 elm->obj->path, 3160 (void *)fini_addr[index]); 3161 LD_UTRACE(UTRACE_FINI_CALL, 3162 elm->obj, 3163 (void *)fini_addr[index], 0, 3164 0, elm->obj->path); 3165 call_initfini_pointer(elm->obj, 3166 fini_addr[index]); 3167 } 3168 } 3169 } 3170 if (elm->obj->fini != 0) { 3171 dbg("calling fini function for %s at %p", 3172 elm->obj->path, (void *)elm->obj->fini); 3173 LD_UTRACE(UTRACE_FINI_CALL, elm->obj, 3174 (void *)elm->obj->fini, 0, 0, 3175 elm->obj->path); 3176 call_initfini_pointer(elm->obj, elm->obj->fini); 3177 } 3178 wlock_acquire(rtld_bind_lock, lockstate); 3179 unhold_object(elm->obj); 3180 /* No need to free anything if process is going down. */ 3181 if (root != NULL) 3182 free(elm); 3183 /* 3184 * We must restart the list traversal after every fini 3185 * call because a dlclose() call from the fini function 3186 * or from another thread might have modified the 3187 * reference counts. 3188 */ 3189 break; 3190 } 3191 } while (elm != NULL); 3192 errmsg_restore(saved_msg); 3193 } 3194 3195 /* 3196 * Call the initialization functions for each of the objects in 3197 * "list". All of the objects are expected to have non-NULL init 3198 * functions. 3199 */ 3200 static void 3201 objlist_call_init(Objlist *list, RtldLockState *lockstate) 3202 { 3203 Objlist_Entry *elm; 3204 Obj_Entry *obj; 3205 struct dlerror_save *saved_msg; 3206 uintptr_t *init_addr; 3207 void (*reg)(void (*)(void)); 3208 int index; 3209 3210 /* 3211 * Clean init_scanned flag so that objects can be rechecked and 3212 * possibly initialized earlier if any of vectors called below 3213 * cause the change by using dlopen. 3214 */ 3215 TAILQ_FOREACH(obj, &obj_list, next) { 3216 if (obj->marker) 3217 continue; 3218 obj->init_scanned = false; 3219 } 3220 3221 /* 3222 * Preserve the current error message since an init function might 3223 * call into the dynamic linker and overwrite it. 3224 */ 3225 saved_msg = errmsg_save(); 3226 STAILQ_FOREACH(elm, list, link) { 3227 if (elm->obj->init_done) /* Initialized early. */ 3228 continue; 3229 /* 3230 * Race: other thread might try to use this object before 3231 * current one completes the initialization. Not much can be 3232 * done here without better locking. 3233 */ 3234 elm->obj->init_done = true; 3235 hold_object(elm->obj); 3236 reg = NULL; 3237 if (elm->obj == obj_main && obj_main->crt_no_init) { 3238 reg = (void (*)(void (*)(void))) 3239 get_program_var_addr("__libc_atexit", lockstate); 3240 } 3241 lock_release(rtld_bind_lock, lockstate); 3242 if (reg != NULL) { 3243 reg(rtld_exit); 3244 rtld_exit_ptr = rtld_nop_exit; 3245 } 3246 3247 /* 3248 * It is legal to have both DT_INIT and DT_INIT_ARRAY defined. 3249 * When this happens, DT_INIT is processed first. 3250 */ 3251 if (elm->obj->init != 0) { 3252 dbg("calling init function for %s at %p", 3253 elm->obj->path, (void *)elm->obj->init); 3254 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, 3255 (void *)elm->obj->init, 0, 0, elm->obj->path); 3256 call_init_pointer(elm->obj, elm->obj->init); 3257 } 3258 init_addr = elm->obj->init_array; 3259 if (init_addr != NULL) { 3260 for (index = 0; index < elm->obj->init_array_num; 3261 index++) { 3262 if (init_addr[index] != 0 && 3263 init_addr[index] != 1) { 3264 dbg("calling init function for %s at %p", 3265 elm->obj->path, 3266 (void *)init_addr[index]); 3267 LD_UTRACE(UTRACE_INIT_CALL, elm->obj, 3268 (void *)init_addr[index], 0, 0, 3269 elm->obj->path); 3270 call_init_pointer(elm->obj, 3271 init_addr[index]); 3272 } 3273 } 3274 } 3275 wlock_acquire(rtld_bind_lock, lockstate); 3276 unhold_object(elm->obj); 3277 } 3278 errmsg_restore(saved_msg); 3279 } 3280 3281 static void 3282 objlist_clear(Objlist *list) 3283 { 3284 Objlist_Entry *elm; 3285 3286 while (!STAILQ_EMPTY(list)) { 3287 elm = STAILQ_FIRST(list); 3288 STAILQ_REMOVE_HEAD(list, link); 3289 free(elm); 3290 } 3291 } 3292 3293 static Objlist_Entry * 3294 objlist_find(Objlist *list, const Obj_Entry *obj) 3295 { 3296 Objlist_Entry *elm; 3297 3298 STAILQ_FOREACH(elm, list, link) 3299 if (elm->obj == obj) 3300 return elm; 3301 return (NULL); 3302 } 3303 3304 static void 3305 objlist_init(Objlist *list) 3306 { 3307 STAILQ_INIT(list); 3308 } 3309 3310 static void 3311 objlist_push_head(Objlist *list, Obj_Entry *obj) 3312 { 3313 Objlist_Entry *elm; 3314 3315 elm = NEW(Objlist_Entry); 3316 elm->obj = obj; 3317 STAILQ_INSERT_HEAD(list, elm, link); 3318 } 3319 3320 static void 3321 objlist_push_tail(Objlist *list, Obj_Entry *obj) 3322 { 3323 Objlist_Entry *elm; 3324 3325 elm = NEW(Objlist_Entry); 3326 elm->obj = obj; 3327 STAILQ_INSERT_TAIL(list, elm, link); 3328 } 3329 3330 static void 3331 objlist_put_after(Objlist *list, Obj_Entry *listobj, Obj_Entry *obj) 3332 { 3333 Objlist_Entry *elm, *listelm; 3334 3335 STAILQ_FOREACH(listelm, list, link) { 3336 if (listelm->obj == listobj) 3337 break; 3338 } 3339 elm = NEW(Objlist_Entry); 3340 elm->obj = obj; 3341 if (listelm != NULL) 3342 STAILQ_INSERT_AFTER(list, listelm, elm, link); 3343 else 3344 STAILQ_INSERT_TAIL(list, elm, link); 3345 } 3346 3347 static void 3348 objlist_remove(Objlist *list, Obj_Entry *obj) 3349 { 3350 Objlist_Entry *elm; 3351 3352 if ((elm = objlist_find(list, obj)) != NULL) { 3353 STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); 3354 free(elm); 3355 } 3356 } 3357 3358 /* 3359 * Relocate dag rooted in the specified object. 3360 * Returns 0 on success, or -1 on failure. 3361 */ 3362 3363 static int 3364 relocate_object_dag(Obj_Entry *root, bool bind_now, Obj_Entry *rtldobj, 3365 int flags, RtldLockState *lockstate) 3366 { 3367 Objlist_Entry *elm; 3368 int error; 3369 3370 error = 0; 3371 STAILQ_FOREACH(elm, &root->dagmembers, link) { 3372 error = relocate_object(elm->obj, bind_now, rtldobj, flags, 3373 lockstate); 3374 if (error == -1) 3375 break; 3376 } 3377 return (error); 3378 } 3379 3380 /* 3381 * Prepare for, or clean after, relocating an object marked with 3382 * DT_TEXTREL or DF_TEXTREL. Before relocating, all read-only 3383 * segments are remapped read-write. After relocations are done, the 3384 * segment's permissions are returned back to the modes specified in 3385 * the phdrs. If any relocation happened, or always for wired 3386 * program, COW is triggered. 3387 */ 3388 static int 3389 reloc_textrel_prot(Obj_Entry *obj, bool before) 3390 { 3391 const Elf_Phdr *ph; 3392 void *base; 3393 size_t sz; 3394 int prot; 3395 3396 for (ph = obj->phdr; ph < obj->phdr + obj->phnum; ph++) { 3397 if (ph->p_type != PT_LOAD || (ph->p_flags & PF_W) != 0) 3398 continue; 3399 base = obj->relocbase + rtld_trunc_page(ph->p_vaddr); 3400 sz = rtld_round_page(ph->p_vaddr + ph->p_filesz) - 3401 rtld_trunc_page(ph->p_vaddr); 3402 prot = before ? (PROT_READ | PROT_WRITE) : 3403 convert_prot(ph->p_flags); 3404 if (mprotect(base, sz, prot) == -1) { 3405 _rtld_error("%s: Cannot write-%sable text segment: %s", 3406 obj->path, before ? "en" : "dis", 3407 rtld_strerror(errno)); 3408 return (-1); 3409 } 3410 } 3411 return (0); 3412 } 3413 3414 /* Process RELR relative relocations. */ 3415 static void 3416 reloc_relr(Obj_Entry *obj) 3417 { 3418 const Elf_Relr *relr, *relrlim; 3419 Elf_Addr *where; 3420 3421 relrlim = (const Elf_Relr *)((const char *)obj->relr + obj->relrsize); 3422 for (relr = obj->relr; relr < relrlim; relr++) { 3423 Elf_Relr entry = *relr; 3424 3425 if ((entry & 1) == 0) { 3426 where = (Elf_Addr *)(obj->relocbase + entry); 3427 *where++ += (Elf_Addr)obj->relocbase; 3428 } else { 3429 for (long i = 0; (entry >>= 1) != 0; i++) 3430 if ((entry & 1) != 0) 3431 where[i] += (Elf_Addr)obj->relocbase; 3432 where += CHAR_BIT * sizeof(Elf_Relr) - 1; 3433 } 3434 } 3435 } 3436 3437 /* 3438 * Relocate single object. 3439 * Returns 0 on success, or -1 on failure. 3440 */ 3441 static int 3442 relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj, int flags, 3443 RtldLockState *lockstate) 3444 { 3445 if (obj->relocated) 3446 return (0); 3447 obj->relocated = true; 3448 if (obj != rtldobj) 3449 dbg("relocating \"%s\"", obj->path); 3450 3451 if (obj->symtab == NULL || obj->strtab == NULL || 3452 !(obj->valid_hash_sysv || obj->valid_hash_gnu)) 3453 dbg("object %s has no run-time symbol table", obj->path); 3454 3455 /* There are relocations to the write-protected text segment. */ 3456 if (obj->textrel && reloc_textrel_prot(obj, true) != 0) 3457 return (-1); 3458 3459 /* Process the non-PLT non-IFUNC relocations. */ 3460 if (reloc_non_plt(obj, rtldobj, flags, lockstate)) 3461 return (-1); 3462 reloc_relr(obj); 3463 3464 /* Re-protected the text segment. */ 3465 if (obj->textrel && reloc_textrel_prot(obj, false) != 0) 3466 return (-1); 3467 3468 /* Set the special PLT or GOT entries. */ 3469 init_pltgot(obj); 3470 3471 /* Process the PLT relocations. */ 3472 if (reloc_plt(obj, flags, lockstate) == -1) 3473 return (-1); 3474 /* Relocate the jump slots if we are doing immediate binding. */ 3475 if ((obj->bind_now || bind_now) && 3476 reloc_jmpslots(obj, flags, lockstate) == -1) 3477 return (-1); 3478 3479 if (obj != rtldobj && !obj->mainprog && obj_enforce_relro(obj) == -1) 3480 return (-1); 3481 3482 /* 3483 * Set up the magic number and version in the Obj_Entry. These 3484 * were checked in the crt1.o from the original ElfKit, so we 3485 * set them for backward compatibility. 3486 */ 3487 obj->magic = RTLD_MAGIC; 3488 obj->version = RTLD_VERSION; 3489 3490 return (0); 3491 } 3492 3493 /* 3494 * Relocate newly-loaded shared objects. The argument is a pointer to 3495 * the Obj_Entry for the first such object. All objects from the first 3496 * to the end of the list of objects are relocated. Returns 0 on success, 3497 * or -1 on failure. 3498 */ 3499 static int 3500 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj, int flags, 3501 RtldLockState *lockstate) 3502 { 3503 Obj_Entry *obj; 3504 int error; 3505 3506 for (error = 0, obj = first; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 3507 if (obj->marker) 3508 continue; 3509 error = relocate_object(obj, bind_now, rtldobj, flags, 3510 lockstate); 3511 if (error == -1) 3512 break; 3513 } 3514 return (error); 3515 } 3516 3517 /* 3518 * The handling of R_MACHINE_IRELATIVE relocations and jumpslots 3519 * referencing STT_GNU_IFUNC symbols is postponed till the other 3520 * relocations are done. The indirect functions specified as 3521 * ifunc are allowed to call other symbols, so we need to have 3522 * objects relocated before asking for resolution from indirects. 3523 * 3524 * The R_MACHINE_IRELATIVE slots are resolved in greedy fashion, 3525 * instead of the usual lazy handling of PLT slots. It is 3526 * consistent with how GNU does it. 3527 */ 3528 static int 3529 resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags, 3530 RtldLockState *lockstate) 3531 { 3532 if (obj->ifuncs_resolved) 3533 return (0); 3534 obj->ifuncs_resolved = true; 3535 if (!obj->irelative && !obj->irelative_nonplt && 3536 !((obj->bind_now || bind_now) && obj->gnu_ifunc) && 3537 !obj->non_plt_gnu_ifunc) 3538 return (0); 3539 if (obj_disable_relro(obj) == -1 || 3540 (obj->irelative && reloc_iresolve(obj, lockstate) == -1) || 3541 (obj->irelative_nonplt && 3542 reloc_iresolve_nonplt(obj, lockstate) == -1) || 3543 ((obj->bind_now || bind_now) && obj->gnu_ifunc && 3544 reloc_gnu_ifunc(obj, flags, lockstate) == -1) || 3545 (obj->non_plt_gnu_ifunc && 3546 reloc_non_plt(obj, &obj_rtld, flags | SYMLOOK_IFUNC, 3547 lockstate) == -1) || 3548 obj_enforce_relro(obj) == -1) 3549 return (-1); 3550 return (0); 3551 } 3552 3553 static int 3554 initlist_objects_ifunc(Objlist *list, bool bind_now, int flags, 3555 RtldLockState *lockstate) 3556 { 3557 Objlist_Entry *elm; 3558 Obj_Entry *obj; 3559 3560 STAILQ_FOREACH(elm, list, link) { 3561 obj = elm->obj; 3562 if (obj->marker) 3563 continue; 3564 if (resolve_object_ifunc(obj, bind_now, flags, lockstate) == -1) 3565 return (-1); 3566 } 3567 return (0); 3568 } 3569 3570 /* 3571 * Cleanup procedure. It will be called (by the atexit mechanism) just 3572 * before the process exits. 3573 */ 3574 static void 3575 rtld_exit(void) 3576 { 3577 RtldLockState lockstate; 3578 3579 wlock_acquire(rtld_bind_lock, &lockstate); 3580 dbg("rtld_exit()"); 3581 objlist_call_fini(&list_fini, NULL, &lockstate); 3582 /* No need to remove the items from the list, since we are exiting. */ 3583 if (!libmap_disable) 3584 lm_fini(); 3585 lock_release(rtld_bind_lock, &lockstate); 3586 } 3587 3588 static void 3589 rtld_nop_exit(void) 3590 { 3591 } 3592 3593 /* 3594 * Parse string of the format '#number/name", where number must be a 3595 * decimal number of the opened file descriptor listed in 3596 * LD_LIBRARY_PATH_FDS. If successful, tries to open dso name under 3597 * dirfd number and returns resulting fd. 3598 * On any error, returns -1. 3599 */ 3600 static int 3601 try_fds_open(const char *name, const char *path) 3602 { 3603 const char *n; 3604 char *envcopy, *fdstr, *last_token, *ncopy; 3605 size_t len; 3606 int fd, dirfd, dirfd_path; 3607 3608 if (!trust || name[0] != '#' || path == NULL) 3609 return (-1); 3610 3611 name++; 3612 n = strchr(name, '/'); 3613 if (n == NULL) 3614 return (-1); 3615 len = n - name; 3616 ncopy = xmalloc(len + 1); 3617 memcpy(ncopy, name, len); 3618 ncopy[len] = '\0'; 3619 dirfd = parse_integer(ncopy); 3620 free(ncopy); 3621 if (dirfd == -1) 3622 return (-1); 3623 3624 envcopy = xstrdup(path); 3625 dirfd_path = -1; 3626 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL; 3627 fdstr = strtok_r(NULL, ":", &last_token)) { 3628 dirfd_path = parse_integer(fdstr); 3629 if (dirfd_path == dirfd) 3630 break; 3631 } 3632 free(envcopy); 3633 if (dirfd_path != dirfd) 3634 return (-1); 3635 3636 fd = __sys_openat(dirfd, n + 1, O_RDONLY | O_CLOEXEC | O_VERIFY); 3637 return (fd); 3638 } 3639 3640 /* 3641 * Iterate over a search path, translate each element, and invoke the 3642 * callback on the result. 3643 */ 3644 static void * 3645 path_enumerate(const char *path, path_enum_proc callback, 3646 const char *refobj_path, void *arg) 3647 { 3648 const char *trans; 3649 if (path == NULL) 3650 return (NULL); 3651 3652 path += strspn(path, ":;"); 3653 while (*path != '\0') { 3654 size_t len; 3655 char *res; 3656 3657 len = strcspn(path, ":;"); 3658 trans = lm_findn(refobj_path, path, len); 3659 if (trans) 3660 res = callback(trans, strlen(trans), arg); 3661 else 3662 res = callback(path, len, arg); 3663 3664 if (res != NULL) 3665 return (res); 3666 3667 path += len; 3668 path += strspn(path, ":;"); 3669 } 3670 3671 return (NULL); 3672 } 3673 3674 struct try_library_args { 3675 const char *name; 3676 size_t namelen; 3677 char *buffer; 3678 size_t buflen; 3679 int fd; 3680 }; 3681 3682 static void * 3683 try_library_path(const char *dir, size_t dirlen, void *param) 3684 { 3685 struct try_library_args *arg; 3686 int fd; 3687 3688 arg = param; 3689 if (*dir == '/' || trust) { 3690 char *pathname; 3691 3692 if (dirlen + 1 + arg->namelen + 1 > arg->buflen) 3693 return (NULL); 3694 3695 pathname = arg->buffer; 3696 strncpy(pathname, dir, dirlen); 3697 pathname[dirlen] = '/'; 3698 strcpy(pathname + dirlen + 1, arg->name); 3699 3700 dbg(" Trying \"%s\"", pathname); 3701 fd = open(pathname, O_RDONLY | O_CLOEXEC | O_VERIFY); 3702 if (fd >= 0) { 3703 dbg(" Opened \"%s\", fd %d", pathname, fd); 3704 pathname = xmalloc(dirlen + 1 + arg->namelen + 1); 3705 strcpy(pathname, arg->buffer); 3706 arg->fd = fd; 3707 return (pathname); 3708 } else { 3709 dbg(" Failed to open \"%s\": %s", pathname, 3710 rtld_strerror(errno)); 3711 } 3712 } 3713 return (NULL); 3714 } 3715 3716 static char * 3717 search_library_path(const char *name, const char *path, const char *refobj_path, 3718 int *fdp) 3719 { 3720 char *p; 3721 struct try_library_args arg; 3722 3723 if (path == NULL) 3724 return (NULL); 3725 3726 arg.name = name; 3727 arg.namelen = strlen(name); 3728 arg.buffer = xmalloc(PATH_MAX); 3729 arg.buflen = PATH_MAX; 3730 arg.fd = -1; 3731 3732 p = path_enumerate(path, try_library_path, refobj_path, &arg); 3733 *fdp = arg.fd; 3734 3735 free(arg.buffer); 3736 3737 return (p); 3738 } 3739 3740 /* 3741 * Finds the library with the given name using the directory descriptors 3742 * listed in the LD_LIBRARY_PATH_FDS environment variable. 3743 * 3744 * Returns a freshly-opened close-on-exec file descriptor for the library, 3745 * or -1 if the library cannot be found. 3746 */ 3747 static char * 3748 search_library_pathfds(const char *name, const char *path, int *fdp) 3749 { 3750 char *envcopy, *fdstr, *found, *last_token; 3751 size_t len; 3752 int dirfd, fd; 3753 3754 dbg("%s('%s', '%s', fdp)", __func__, name, path); 3755 3756 /* Don't load from user-specified libdirs into setuid binaries. */ 3757 if (!trust) 3758 return (NULL); 3759 3760 /* We can't do anything if LD_LIBRARY_PATH_FDS isn't set. */ 3761 if (path == NULL) 3762 return (NULL); 3763 3764 /* LD_LIBRARY_PATH_FDS only works with relative paths. */ 3765 if (name[0] == '/') { 3766 dbg("Absolute path (%s) passed to %s", name, __func__); 3767 return (NULL); 3768 } 3769 3770 /* 3771 * Use strtok_r() to walk the FD:FD:FD list. This requires a local 3772 * copy of the path, as strtok_r rewrites separator tokens 3773 * with '\0'. 3774 */ 3775 found = NULL; 3776 envcopy = xstrdup(path); 3777 for (fdstr = strtok_r(envcopy, ":", &last_token); fdstr != NULL; 3778 fdstr = strtok_r(NULL, ":", &last_token)) { 3779 dirfd = parse_integer(fdstr); 3780 if (dirfd < 0) { 3781 _rtld_error("failed to parse directory FD: '%s'", 3782 fdstr); 3783 break; 3784 } 3785 fd = __sys_openat(dirfd, name, O_RDONLY | O_CLOEXEC | O_VERIFY); 3786 if (fd >= 0) { 3787 *fdp = fd; 3788 len = strlen(fdstr) + strlen(name) + 3; 3789 found = xmalloc(len); 3790 if (rtld_snprintf(found, len, "#%d/%s", dirfd, name) < 3791 0) { 3792 _rtld_error("error generating '%d/%s'", dirfd, 3793 name); 3794 rtld_die(); 3795 } 3796 dbg("open('%s') => %d", found, fd); 3797 break; 3798 } 3799 } 3800 free(envcopy); 3801 3802 return (found); 3803 } 3804 3805 int 3806 dlclose(void *handle) 3807 { 3808 RtldLockState lockstate; 3809 int error; 3810 3811 wlock_acquire(rtld_bind_lock, &lockstate); 3812 error = dlclose_locked(handle, &lockstate); 3813 lock_release(rtld_bind_lock, &lockstate); 3814 return (error); 3815 } 3816 3817 static int 3818 dlclose_locked(void *handle, RtldLockState *lockstate) 3819 { 3820 Obj_Entry *root; 3821 3822 root = dlcheck(handle); 3823 if (root == NULL) 3824 return (-1); 3825 LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount, 3826 root->path); 3827 3828 /* Unreference the object and its dependencies. */ 3829 root->dl_refcount--; 3830 3831 if (root->refcount == 1) { 3832 /* 3833 * The object will be no longer referenced, so we must unload 3834 * it. First, call the fini functions. 3835 */ 3836 objlist_call_fini(&list_fini, root, lockstate); 3837 3838 unref_dag(root); 3839 3840 /* Finish cleaning up the newly-unreferenced objects. */ 3841 GDB_STATE(RT_DELETE, &root->linkmap); 3842 unload_object(root, lockstate); 3843 GDB_STATE(RT_CONSISTENT, NULL); 3844 } else 3845 unref_dag(root); 3846 3847 LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL); 3848 return (0); 3849 } 3850 3851 char * 3852 dlerror(void) 3853 { 3854 if (*(lockinfo.dlerror_seen()) != 0) 3855 return (NULL); 3856 *lockinfo.dlerror_seen() = 1; 3857 return (lockinfo.dlerror_loc()); 3858 } 3859 3860 /* 3861 * This function is deprecated and has no effect. 3862 */ 3863 void 3864 dllockinit(void *context, void *(*_lock_create)(void *context)__unused, 3865 void (*_rlock_acquire)(void *lock) __unused, 3866 void (*_wlock_acquire)(void *lock) __unused, 3867 void (*_lock_release)(void *lock) __unused, 3868 void (*_lock_destroy)(void *lock) __unused, 3869 void (*context_destroy)(void *context)) 3870 { 3871 static void *cur_context; 3872 static void (*cur_context_destroy)(void *); 3873 3874 /* Just destroy the context from the previous call, if necessary. */ 3875 if (cur_context_destroy != NULL) 3876 cur_context_destroy(cur_context); 3877 cur_context = context; 3878 cur_context_destroy = context_destroy; 3879 } 3880 3881 void * 3882 dlopen(const char *name, int mode) 3883 { 3884 return (rtld_dlopen(name, -1, mode)); 3885 } 3886 3887 void * 3888 fdlopen(int fd, int mode) 3889 { 3890 return (rtld_dlopen(NULL, fd, mode)); 3891 } 3892 3893 static void * 3894 rtld_dlopen(const char *name, int fd, int mode) 3895 { 3896 RtldLockState lockstate; 3897 int lo_flags; 3898 3899 LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name); 3900 ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; 3901 if (ld_tracing != NULL) { 3902 rlock_acquire(rtld_bind_lock, &lockstate); 3903 if (sigsetjmp(lockstate.env, 0) != 0) 3904 lock_upgrade(rtld_bind_lock, &lockstate); 3905 environ = __DECONST(char **, 3906 *get_program_var_addr("environ", &lockstate)); 3907 lock_release(rtld_bind_lock, &lockstate); 3908 } 3909 lo_flags = RTLD_LO_DLOPEN; 3910 if (mode & RTLD_NODELETE) 3911 lo_flags |= RTLD_LO_NODELETE; 3912 if (mode & RTLD_NOLOAD) 3913 lo_flags |= RTLD_LO_NOLOAD; 3914 if (mode & RTLD_DEEPBIND) 3915 lo_flags |= RTLD_LO_DEEPBIND; 3916 if (ld_tracing != NULL) 3917 lo_flags |= RTLD_LO_TRACE | RTLD_LO_IGNSTLS; 3918 3919 return (dlopen_object(name, fd, obj_main, lo_flags, 3920 mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL)); 3921 } 3922 3923 static void 3924 dlopen_cleanup(Obj_Entry *obj, RtldLockState *lockstate) 3925 { 3926 obj->dl_refcount--; 3927 unref_dag(obj); 3928 if (obj->refcount == 0) 3929 unload_object(obj, lockstate); 3930 } 3931 3932 static Obj_Entry * 3933 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags, 3934 int mode, RtldLockState *lockstate) 3935 { 3936 Obj_Entry *obj; 3937 Objlist initlist; 3938 RtldLockState mlockstate; 3939 int result; 3940 3941 dbg( 3942 "dlopen_object name \"%s\" fd %d refobj \"%s\" lo_flags %#x mode %#x", 3943 name != NULL ? name : "<null>", fd, 3944 refobj == NULL ? "<null>" : refobj->path, lo_flags, mode); 3945 objlist_init(&initlist); 3946 3947 if (lockstate == NULL && !(lo_flags & RTLD_LO_EARLY)) { 3948 wlock_acquire(rtld_bind_lock, &mlockstate); 3949 lockstate = &mlockstate; 3950 } 3951 GDB_STATE(RT_ADD, NULL); 3952 3953 obj = NULL; 3954 if (name == NULL && fd == -1) { 3955 obj = obj_main; 3956 obj->refcount++; 3957 } else { 3958 obj = load_object(name, fd, refobj, lo_flags); 3959 } 3960 3961 if (obj != NULL) { 3962 obj->dl_refcount++; 3963 if ((mode & RTLD_GLOBAL) != 0 && 3964 objlist_find(&list_global, obj) == NULL) 3965 objlist_push_tail(&list_global, obj); 3966 3967 if (!obj->init_done) { 3968 /* We loaded something new and have to init something. 3969 */ 3970 if ((lo_flags & RTLD_LO_DEEPBIND) != 0) 3971 obj->deepbind = true; 3972 result = 0; 3973 if ((lo_flags & (RTLD_LO_EARLY | 3974 RTLD_LO_IGNSTLS)) == 0 && 3975 obj->static_tls && !allocate_tls_offset(obj)) { 3976 _rtld_error( 3977 "%s: No space available for static Thread Local Storage", 3978 obj->path); 3979 result = -1; 3980 } 3981 if (result != -1) 3982 result = load_needed_objects(obj, 3983 lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY | 3984 RTLD_LO_IGNSTLS | RTLD_LO_TRACE)); 3985 init_dag(obj); 3986 ref_dag(obj); 3987 if (result != -1) 3988 result = rtld_verify_versions(&obj->dagmembers); 3989 if (result != -1 && ld_tracing) 3990 goto trace; 3991 if (result == -1 || relocate_object_dag(obj, 3992 (mode & RTLD_MODEMASK) == RTLD_NOW, &obj_rtld, 3993 (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 3994 lockstate) == -1) { 3995 dlopen_cleanup(obj, lockstate); 3996 obj = NULL; 3997 } else if ((lo_flags & RTLD_LO_EARLY) != 0) { 3998 /* 3999 * Do not call the init functions for early 4000 * loaded filtees. The image is still not 4001 * initialized enough for them to work. 4002 * 4003 * Our object is found by the global object list 4004 * and will be ordered among all init calls done 4005 * right before transferring control to main. 4006 */ 4007 } else { 4008 /* Make list of init functions to call. */ 4009 initlist_for_loaded_obj(obj, obj, &initlist); 4010 } 4011 /* 4012 * Process all no_delete or global objects here, given 4013 * them own DAGs to prevent their dependencies from 4014 * being unloaded. This has to be done after we have 4015 * loaded all of the dependencies, so that we do not 4016 * miss any. 4017 */ 4018 if (obj != NULL) 4019 process_z(obj); 4020 } else { 4021 /* 4022 * Bump the reference counts for objects on this DAG. If 4023 * this is the first dlopen() call for the object that 4024 * was already loaded as a dependency, initialize the 4025 * dag starting at it. 4026 */ 4027 init_dag(obj); 4028 ref_dag(obj); 4029 4030 if ((lo_flags & RTLD_LO_TRACE) != 0) 4031 goto trace; 4032 } 4033 if (obj != NULL && 4034 ((lo_flags & RTLD_LO_NODELETE) != 0 || obj->z_nodelete) && 4035 !obj->ref_nodel) { 4036 dbg("obj %s nodelete", obj->path); 4037 ref_dag(obj); 4038 obj->z_nodelete = obj->ref_nodel = true; 4039 } 4040 } 4041 4042 LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0, 4043 name); 4044 GDB_STATE(RT_CONSISTENT, obj ? &obj->linkmap : NULL); 4045 4046 if ((lo_flags & RTLD_LO_EARLY) == 0) { 4047 map_stacks_exec(lockstate); 4048 if (obj != NULL) 4049 distribute_static_tls(&initlist); 4050 } 4051 4052 if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) == 4053 RTLD_NOW, (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0, 4054 lockstate) == -1) { 4055 objlist_clear(&initlist); 4056 dlopen_cleanup(obj, lockstate); 4057 if (lockstate == &mlockstate) 4058 lock_release(rtld_bind_lock, lockstate); 4059 return (NULL); 4060 } 4061 4062 if ((lo_flags & RTLD_LO_EARLY) == 0) { 4063 /* Call the init functions. */ 4064 objlist_call_init(&initlist, lockstate); 4065 } 4066 objlist_clear(&initlist); 4067 if (lockstate == &mlockstate) 4068 lock_release(rtld_bind_lock, lockstate); 4069 return (obj); 4070 trace: 4071 trace_loaded_objects(obj, false); 4072 if (lockstate == &mlockstate) 4073 lock_release(rtld_bind_lock, lockstate); 4074 exit(0); 4075 } 4076 4077 static void * 4078 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve, 4079 int flags) 4080 { 4081 DoneList donelist; 4082 const Obj_Entry *obj, *defobj; 4083 const Elf_Sym *def; 4084 SymLook req; 4085 RtldLockState lockstate; 4086 tls_index ti; 4087 void *sym; 4088 int res; 4089 4090 def = NULL; 4091 defobj = NULL; 4092 symlook_init(&req, name); 4093 req.ventry = ve; 4094 req.flags = flags | SYMLOOK_IN_PLT; 4095 req.lockstate = &lockstate; 4096 4097 LD_UTRACE(UTRACE_DLSYM_START, handle, NULL, 0, 0, name); 4098 rlock_acquire(rtld_bind_lock, &lockstate); 4099 if (sigsetjmp(lockstate.env, 0) != 0) 4100 lock_upgrade(rtld_bind_lock, &lockstate); 4101 if (handle == NULL || handle == RTLD_NEXT || handle == RTLD_DEFAULT || 4102 handle == RTLD_SELF) { 4103 if ((obj = obj_from_addr(retaddr)) == NULL) { 4104 _rtld_error("Cannot determine caller's shared object"); 4105 lock_release(rtld_bind_lock, &lockstate); 4106 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 4107 return (NULL); 4108 } 4109 if (handle == NULL) { /* Just the caller's shared object. */ 4110 res = symlook_obj(&req, obj); 4111 if (res == 0) { 4112 def = req.sym_out; 4113 defobj = req.defobj_out; 4114 } 4115 } else if (handle == RTLD_NEXT || /* Objects after caller's */ 4116 handle == RTLD_SELF) { /* ... caller included */ 4117 if (handle == RTLD_NEXT) 4118 obj = globallist_next(obj); 4119 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 4120 if (obj->marker) 4121 continue; 4122 res = symlook_obj(&req, obj); 4123 if (res == 0) { 4124 if (def == NULL || 4125 (ld_dynamic_weak && 4126 ELF_ST_BIND( 4127 req.sym_out->st_info) != 4128 STB_WEAK)) { 4129 def = req.sym_out; 4130 defobj = req.defobj_out; 4131 if (!ld_dynamic_weak || 4132 ELF_ST_BIND(def->st_info) != 4133 STB_WEAK) 4134 break; 4135 } 4136 } 4137 } 4138 /* 4139 * Search the dynamic linker itself, and possibly 4140 * resolve the symbol from there. This is how the 4141 * application links to dynamic linker services such as 4142 * dlopen. Note that we ignore ld_dynamic_weak == false 4143 * case, always overriding weak symbols by rtld 4144 * definitions. 4145 */ 4146 if (def == NULL || 4147 ELF_ST_BIND(def->st_info) == STB_WEAK) { 4148 res = symlook_obj(&req, &obj_rtld); 4149 if (res == 0) { 4150 def = req.sym_out; 4151 defobj = req.defobj_out; 4152 } 4153 } 4154 } else { 4155 assert(handle == RTLD_DEFAULT); 4156 res = symlook_default(&req, obj); 4157 if (res == 0) { 4158 defobj = req.defobj_out; 4159 def = req.sym_out; 4160 } 4161 } 4162 } else { 4163 if ((obj = dlcheck(handle)) == NULL) { 4164 lock_release(rtld_bind_lock, &lockstate); 4165 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 4166 return (NULL); 4167 } 4168 4169 donelist_init(&donelist); 4170 if (obj->mainprog) { 4171 /* Handle obtained by dlopen(NULL, ...) implies global 4172 * scope. */ 4173 res = symlook_global(&req, &donelist); 4174 if (res == 0) { 4175 def = req.sym_out; 4176 defobj = req.defobj_out; 4177 } 4178 /* 4179 * Search the dynamic linker itself, and possibly 4180 * resolve the symbol from there. This is how the 4181 * application links to dynamic linker services such as 4182 * dlopen. 4183 */ 4184 if (def == NULL || 4185 ELF_ST_BIND(def->st_info) == STB_WEAK) { 4186 res = symlook_obj(&req, &obj_rtld); 4187 if (res == 0) { 4188 def = req.sym_out; 4189 defobj = req.defobj_out; 4190 } 4191 } 4192 } else { 4193 /* Search the whole DAG rooted at the given object. */ 4194 res = symlook_list(&req, &obj->dagmembers, &donelist); 4195 if (res == 0) { 4196 def = req.sym_out; 4197 defobj = req.defobj_out; 4198 } 4199 } 4200 } 4201 4202 if (def != NULL) { 4203 lock_release(rtld_bind_lock, &lockstate); 4204 4205 /* 4206 * The value required by the caller is derived from the value 4207 * of the symbol. this is simply the relocated value of the 4208 * symbol. 4209 */ 4210 if (ELF_ST_TYPE(def->st_info) == STT_FUNC) 4211 sym = make_function_pointer(def, defobj); 4212 else if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) 4213 sym = rtld_resolve_ifunc(defobj, def); 4214 else if (ELF_ST_TYPE(def->st_info) == STT_TLS) { 4215 ti.ti_module = defobj->tlsindex; 4216 ti.ti_offset = def->st_value - TLS_DTV_OFFSET; 4217 sym = __tls_get_addr(&ti); 4218 } else 4219 sym = defobj->relocbase + def->st_value; 4220 LD_UTRACE(UTRACE_DLSYM_STOP, handle, sym, 0, 0, name); 4221 return (sym); 4222 } 4223 4224 _rtld_error("Undefined symbol \"%s%s%s\"", name, ve != NULL ? "@" : "", 4225 ve != NULL ? ve->name : ""); 4226 lock_release(rtld_bind_lock, &lockstate); 4227 LD_UTRACE(UTRACE_DLSYM_STOP, handle, NULL, 0, 0, name); 4228 return (NULL); 4229 } 4230 4231 void * 4232 dlsym(void *handle, const char *name) 4233 { 4234 return (do_dlsym(handle, name, __builtin_return_address(0), NULL, 4235 SYMLOOK_DLSYM)); 4236 } 4237 4238 dlfunc_t 4239 dlfunc(void *handle, const char *name) 4240 { 4241 union { 4242 void *d; 4243 dlfunc_t f; 4244 } rv; 4245 4246 rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL, 4247 SYMLOOK_DLSYM); 4248 return (rv.f); 4249 } 4250 4251 void * 4252 dlvsym(void *handle, const char *name, const char *version) 4253 { 4254 Ver_Entry ventry; 4255 4256 ventry.name = version; 4257 ventry.file = NULL; 4258 ventry.hash = elf_hash(version); 4259 ventry.flags = 0; 4260 return (do_dlsym(handle, name, __builtin_return_address(0), &ventry, 4261 SYMLOOK_DLSYM)); 4262 } 4263 4264 int 4265 _rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info) 4266 { 4267 const Obj_Entry *obj; 4268 RtldLockState lockstate; 4269 4270 rlock_acquire(rtld_bind_lock, &lockstate); 4271 obj = obj_from_addr(addr); 4272 if (obj == NULL) { 4273 _rtld_error("No shared object contains address"); 4274 lock_release(rtld_bind_lock, &lockstate); 4275 return (0); 4276 } 4277 rtld_fill_dl_phdr_info(obj, phdr_info); 4278 lock_release(rtld_bind_lock, &lockstate); 4279 return (1); 4280 } 4281 4282 int 4283 dladdr(const void *addr, Dl_info *info) 4284 { 4285 const Obj_Entry *obj; 4286 const Elf_Sym *def; 4287 void *symbol_addr; 4288 unsigned long symoffset; 4289 RtldLockState lockstate; 4290 4291 rlock_acquire(rtld_bind_lock, &lockstate); 4292 obj = obj_from_addr(addr); 4293 if (obj == NULL) { 4294 _rtld_error("No shared object contains address"); 4295 lock_release(rtld_bind_lock, &lockstate); 4296 return (0); 4297 } 4298 info->dli_fname = obj->path; 4299 info->dli_fbase = obj->mapbase; 4300 info->dli_saddr = (void *)0; 4301 info->dli_sname = NULL; 4302 4303 /* 4304 * Walk the symbol list looking for the symbol whose address is 4305 * closest to the address sent in. 4306 */ 4307 for (symoffset = 0; symoffset < obj->dynsymcount; symoffset++) { 4308 def = obj->symtab + symoffset; 4309 4310 /* 4311 * For skip the symbol if st_shndx is either SHN_UNDEF or 4312 * SHN_COMMON. 4313 */ 4314 if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) 4315 continue; 4316 4317 /* 4318 * If the symbol is greater than the specified address, or if it 4319 * is further away from addr than the current nearest symbol, 4320 * then reject it. 4321 */ 4322 symbol_addr = obj->relocbase + def->st_value; 4323 if (symbol_addr > addr || symbol_addr < info->dli_saddr) 4324 continue; 4325 4326 /* Update our idea of the nearest symbol. */ 4327 info->dli_sname = obj->strtab + def->st_name; 4328 info->dli_saddr = symbol_addr; 4329 4330 /* Exact match? */ 4331 if (info->dli_saddr == addr) 4332 break; 4333 } 4334 lock_release(rtld_bind_lock, &lockstate); 4335 return (1); 4336 } 4337 4338 int 4339 dlinfo(void *handle, int request, void *p) 4340 { 4341 const Obj_Entry *obj; 4342 RtldLockState lockstate; 4343 int error; 4344 4345 rlock_acquire(rtld_bind_lock, &lockstate); 4346 4347 if (handle == NULL || handle == RTLD_SELF) { 4348 void *retaddr; 4349 4350 retaddr = __builtin_return_address(0); /* __GNUC__ only */ 4351 if ((obj = obj_from_addr(retaddr)) == NULL) 4352 _rtld_error("Cannot determine caller's shared object"); 4353 } else 4354 obj = dlcheck(handle); 4355 4356 if (obj == NULL) { 4357 lock_release(rtld_bind_lock, &lockstate); 4358 return (-1); 4359 } 4360 4361 error = 0; 4362 switch (request) { 4363 case RTLD_DI_LINKMAP: 4364 *((struct link_map const **)p) = &obj->linkmap; 4365 break; 4366 case RTLD_DI_ORIGIN: 4367 error = rtld_dirname(obj->path, p); 4368 break; 4369 4370 case RTLD_DI_SERINFOSIZE: 4371 case RTLD_DI_SERINFO: 4372 error = do_search_info(obj, request, (struct dl_serinfo *)p); 4373 break; 4374 4375 default: 4376 _rtld_error("Invalid request %d passed to dlinfo()", request); 4377 error = -1; 4378 } 4379 4380 lock_release(rtld_bind_lock, &lockstate); 4381 4382 return (error); 4383 } 4384 4385 static void 4386 rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info) 4387 { 4388 phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase; 4389 phdr_info->dlpi_name = obj->path; 4390 phdr_info->dlpi_phdr = obj->phdr; 4391 phdr_info->dlpi_phnum = obj->phnum; 4392 phdr_info->dlpi_tls_modid = obj->tlsindex; 4393 phdr_info->dlpi_tls_data = (char *)tls_get_addr_slow(_tcb_get(), 4394 obj->tlsindex, 0, true); 4395 phdr_info->dlpi_adds = obj_loads; 4396 phdr_info->dlpi_subs = obj_loads - obj_count; 4397 } 4398 4399 /* 4400 * It's completely UB to actually use this, so extreme caution is advised. It's 4401 * probably not what you want. 4402 */ 4403 int 4404 _dl_iterate_phdr_locked(__dl_iterate_hdr_callback callback, void *param) 4405 { 4406 struct dl_phdr_info phdr_info; 4407 Obj_Entry *obj; 4408 int error; 4409 4410 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL; 4411 obj = globallist_next(obj)) { 4412 rtld_fill_dl_phdr_info(obj, &phdr_info); 4413 error = callback(&phdr_info, sizeof(phdr_info), param); 4414 if (error != 0) 4415 return (error); 4416 } 4417 4418 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info); 4419 return (callback(&phdr_info, sizeof(phdr_info), param)); 4420 } 4421 4422 int 4423 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param) 4424 { 4425 struct dl_phdr_info phdr_info; 4426 Obj_Entry *obj, marker; 4427 RtldLockState bind_lockstate, phdr_lockstate; 4428 int error; 4429 4430 init_marker(&marker); 4431 error = 0; 4432 4433 wlock_acquire(rtld_phdr_lock, &phdr_lockstate); 4434 wlock_acquire(rtld_bind_lock, &bind_lockstate); 4435 for (obj = globallist_curr(TAILQ_FIRST(&obj_list)); obj != NULL;) { 4436 TAILQ_INSERT_AFTER(&obj_list, obj, &marker, next); 4437 rtld_fill_dl_phdr_info(obj, &phdr_info); 4438 hold_object(obj); 4439 lock_release(rtld_bind_lock, &bind_lockstate); 4440 4441 error = callback(&phdr_info, sizeof phdr_info, param); 4442 4443 wlock_acquire(rtld_bind_lock, &bind_lockstate); 4444 unhold_object(obj); 4445 obj = globallist_next(&marker); 4446 TAILQ_REMOVE(&obj_list, &marker, next); 4447 if (error != 0) { 4448 lock_release(rtld_bind_lock, &bind_lockstate); 4449 lock_release(rtld_phdr_lock, &phdr_lockstate); 4450 return (error); 4451 } 4452 } 4453 4454 if (error == 0) { 4455 rtld_fill_dl_phdr_info(&obj_rtld, &phdr_info); 4456 lock_release(rtld_bind_lock, &bind_lockstate); 4457 error = callback(&phdr_info, sizeof(phdr_info), param); 4458 } 4459 lock_release(rtld_phdr_lock, &phdr_lockstate); 4460 return (error); 4461 } 4462 4463 static void * 4464 fill_search_info(const char *dir, size_t dirlen, void *param) 4465 { 4466 struct fill_search_info_args *arg; 4467 4468 arg = param; 4469 4470 if (arg->request == RTLD_DI_SERINFOSIZE) { 4471 arg->serinfo->dls_cnt++; 4472 arg->serinfo->dls_size += sizeof(struct dl_serpath) + dirlen + 4473 1; 4474 } else { 4475 struct dl_serpath *s_entry; 4476 4477 s_entry = arg->serpath; 4478 s_entry->dls_name = arg->strspace; 4479 s_entry->dls_flags = arg->flags; 4480 4481 strncpy(arg->strspace, dir, dirlen); 4482 arg->strspace[dirlen] = '\0'; 4483 4484 arg->strspace += dirlen + 1; 4485 arg->serpath++; 4486 } 4487 4488 return (NULL); 4489 } 4490 4491 static int 4492 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) 4493 { 4494 struct dl_serinfo _info; 4495 struct fill_search_info_args args; 4496 4497 args.request = RTLD_DI_SERINFOSIZE; 4498 args.serinfo = &_info; 4499 4500 _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); 4501 _info.dls_cnt = 0; 4502 4503 path_enumerate(obj->rpath, fill_search_info, NULL, &args); 4504 path_enumerate(ld_library_path, fill_search_info, NULL, &args); 4505 path_enumerate(obj->runpath, fill_search_info, NULL, &args); 4506 path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, 4507 &args); 4508 if (!obj->z_nodeflib) 4509 path_enumerate(ld_standard_library_path, fill_search_info, NULL, 4510 &args); 4511 4512 if (request == RTLD_DI_SERINFOSIZE) { 4513 info->dls_size = _info.dls_size; 4514 info->dls_cnt = _info.dls_cnt; 4515 return (0); 4516 } 4517 4518 if (info->dls_cnt != _info.dls_cnt || 4519 info->dls_size != _info.dls_size) { 4520 _rtld_error( 4521 "Uninitialized Dl_serinfo struct passed to dlinfo()"); 4522 return (-1); 4523 } 4524 4525 args.request = RTLD_DI_SERINFO; 4526 args.serinfo = info; 4527 args.serpath = &info->dls_serpath[0]; 4528 args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; 4529 4530 args.flags = LA_SER_RUNPATH; 4531 if (path_enumerate(obj->rpath, fill_search_info, NULL, &args) != NULL) 4532 return (-1); 4533 4534 args.flags = LA_SER_LIBPATH; 4535 if (path_enumerate(ld_library_path, fill_search_info, NULL, &args) != 4536 NULL) 4537 return (-1); 4538 4539 args.flags = LA_SER_RUNPATH; 4540 if (path_enumerate(obj->runpath, fill_search_info, NULL, &args) != NULL) 4541 return (-1); 4542 4543 args.flags = LA_SER_CONFIG; 4544 if (path_enumerate(gethints(obj->z_nodeflib), fill_search_info, NULL, 4545 &args) != NULL) 4546 return (-1); 4547 4548 args.flags = LA_SER_DEFAULT; 4549 if (!obj->z_nodeflib && 4550 path_enumerate(ld_standard_library_path, fill_search_info, NULL, 4551 &args) != NULL) 4552 return (-1); 4553 return (0); 4554 } 4555 4556 static int 4557 rtld_dirname(const char *path, char *bname) 4558 { 4559 const char *endp; 4560 4561 /* Empty or NULL string gets treated as "." */ 4562 if (path == NULL || *path == '\0') { 4563 bname[0] = '.'; 4564 bname[1] = '\0'; 4565 return (0); 4566 } 4567 4568 /* Strip trailing slashes */ 4569 endp = path + strlen(path) - 1; 4570 while (endp > path && *endp == '/') 4571 endp--; 4572 4573 /* Find the start of the dir */ 4574 while (endp > path && *endp != '/') 4575 endp--; 4576 4577 /* Either the dir is "/" or there are no slashes */ 4578 if (endp == path) { 4579 bname[0] = *endp == '/' ? '/' : '.'; 4580 bname[1] = '\0'; 4581 return (0); 4582 } else { 4583 do { 4584 endp--; 4585 } while (endp > path && *endp == '/'); 4586 } 4587 4588 if (endp - path + 2 > PATH_MAX) { 4589 _rtld_error("Filename is too long: %s", path); 4590 return (-1); 4591 } 4592 4593 strncpy(bname, path, endp - path + 1); 4594 bname[endp - path + 1] = '\0'; 4595 return (0); 4596 } 4597 4598 static int 4599 rtld_dirname_abs(const char *path, char *base) 4600 { 4601 char *last; 4602 4603 if (realpath(path, base) == NULL) { 4604 _rtld_error("realpath \"%s\" failed (%s)", path, 4605 rtld_strerror(errno)); 4606 return (-1); 4607 } 4608 dbg("%s -> %s", path, base); 4609 last = strrchr(base, '/'); 4610 if (last == NULL) { 4611 _rtld_error("non-abs result from realpath \"%s\"", path); 4612 return (-1); 4613 } 4614 if (last != base) 4615 *last = '\0'; 4616 return (0); 4617 } 4618 4619 static void 4620 linkmap_add(Obj_Entry *obj) 4621 { 4622 struct link_map *l, *prev; 4623 4624 l = &obj->linkmap; 4625 l->l_name = obj->path; 4626 l->l_base = obj->mapbase; 4627 l->l_ld = obj->dynamic; 4628 l->l_addr = obj->relocbase; 4629 4630 if (r_debug.r_map == NULL) { 4631 r_debug.r_map = l; 4632 return; 4633 } 4634 4635 /* 4636 * Scan to the end of the list, but not past the entry for the 4637 * dynamic linker, which we want to keep at the very end. 4638 */ 4639 for (prev = r_debug.r_map; 4640 prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; 4641 prev = prev->l_next) 4642 ; 4643 4644 /* Link in the new entry. */ 4645 l->l_prev = prev; 4646 l->l_next = prev->l_next; 4647 if (l->l_next != NULL) 4648 l->l_next->l_prev = l; 4649 prev->l_next = l; 4650 } 4651 4652 static void 4653 linkmap_delete(Obj_Entry *obj) 4654 { 4655 struct link_map *l; 4656 4657 l = &obj->linkmap; 4658 if (l->l_prev == NULL) { 4659 if ((r_debug.r_map = l->l_next) != NULL) 4660 l->l_next->l_prev = NULL; 4661 return; 4662 } 4663 4664 if ((l->l_prev->l_next = l->l_next) != NULL) 4665 l->l_next->l_prev = l->l_prev; 4666 } 4667 4668 /* 4669 * Function for the debugger to set a breakpoint on to gain control. 4670 * 4671 * The two parameters allow the debugger to easily find and determine 4672 * what the runtime loader is doing and to whom it is doing it. 4673 * 4674 * When the loadhook trap is hit (r_debug_state, set at program 4675 * initialization), the arguments can be found on the stack: 4676 * 4677 * +8 struct link_map *m 4678 * +4 struct r_debug *rd 4679 * +0 RetAddr 4680 */ 4681 void 4682 r_debug_state(struct r_debug *rd __unused, struct link_map *m __unused) 4683 { 4684 /* 4685 * The following is a hack to force the compiler to emit calls to 4686 * this function, even when optimizing. If the function is empty, 4687 * the compiler is not obliged to emit any code for calls to it, 4688 * even when marked __noinline. However, gdb depends on those 4689 * calls being made. 4690 */ 4691 __compiler_membar(); 4692 } 4693 4694 /* 4695 * A function called after init routines have completed. This can be used to 4696 * break before a program's entry routine is called, and can be used when 4697 * main is not available in the symbol table. 4698 */ 4699 void 4700 _r_debug_postinit(struct link_map *m __unused) 4701 { 4702 /* See r_debug_state(). */ 4703 __compiler_membar(); 4704 } 4705 4706 static void 4707 release_object(Obj_Entry *obj) 4708 { 4709 if (obj->holdcount > 0) { 4710 obj->unholdfree = true; 4711 return; 4712 } 4713 munmap(obj->mapbase, obj->mapsize); 4714 linkmap_delete(obj); 4715 obj_free(obj); 4716 } 4717 4718 /* 4719 * Get address of the pointer variable in the main program. 4720 * Prefer non-weak symbol over the weak one. 4721 */ 4722 static const void ** 4723 get_program_var_addr(const char *name, RtldLockState *lockstate) 4724 { 4725 SymLook req; 4726 DoneList donelist; 4727 4728 symlook_init(&req, name); 4729 req.lockstate = lockstate; 4730 donelist_init(&donelist); 4731 if (symlook_global(&req, &donelist) != 0) 4732 return (NULL); 4733 if (ELF_ST_TYPE(req.sym_out->st_info) == STT_FUNC) 4734 return ((const void **)make_function_pointer(req.sym_out, 4735 req.defobj_out)); 4736 else if (ELF_ST_TYPE(req.sym_out->st_info) == STT_GNU_IFUNC) 4737 return ((const void **)rtld_resolve_ifunc(req.defobj_out, 4738 req.sym_out)); 4739 else 4740 return ((const void **)(req.defobj_out->relocbase + 4741 req.sym_out->st_value)); 4742 } 4743 4744 /* 4745 * Set a pointer variable in the main program to the given value. This 4746 * is used to set key variables such as "environ" before any of the 4747 * init functions are called. 4748 */ 4749 static void 4750 set_program_var(const char *name, const void *value) 4751 { 4752 const void **addr; 4753 4754 if ((addr = get_program_var_addr(name, NULL)) != NULL) { 4755 dbg("\"%s\": *%p <-- %p", name, addr, value); 4756 *addr = value; 4757 } 4758 } 4759 4760 /* 4761 * Search the global objects, including dependencies and main object, 4762 * for the given symbol. 4763 */ 4764 static int 4765 symlook_global(SymLook *req, DoneList *donelist) 4766 { 4767 SymLook req1; 4768 const Objlist_Entry *elm; 4769 int res; 4770 4771 symlook_init_from_req(&req1, req); 4772 4773 /* Search all objects loaded at program start up. */ 4774 if (req->defobj_out == NULL || (ld_dynamic_weak && 4775 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK)) { 4776 res = symlook_list(&req1, &list_main, donelist); 4777 if (res == 0 && (!ld_dynamic_weak || req->defobj_out == NULL || 4778 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4779 req->sym_out = req1.sym_out; 4780 req->defobj_out = req1.defobj_out; 4781 assert(req->defobj_out != NULL); 4782 } 4783 } 4784 4785 /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ 4786 STAILQ_FOREACH(elm, &list_global, link) { 4787 if (req->defobj_out != NULL && (!ld_dynamic_weak || 4788 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)) 4789 break; 4790 res = symlook_list(&req1, &elm->obj->dagmembers, donelist); 4791 if (res == 0 && (req->defobj_out == NULL || 4792 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4793 req->sym_out = req1.sym_out; 4794 req->defobj_out = req1.defobj_out; 4795 assert(req->defobj_out != NULL); 4796 } 4797 } 4798 4799 return (req->sym_out != NULL ? 0 : ESRCH); 4800 } 4801 4802 /* 4803 * Given a symbol name in a referencing object, find the corresponding 4804 * definition of the symbol. Returns a pointer to the symbol, or NULL if 4805 * no definition was found. Returns a pointer to the Obj_Entry of the 4806 * defining object via the reference parameter DEFOBJ_OUT. 4807 */ 4808 static int 4809 symlook_default(SymLook *req, const Obj_Entry *refobj) 4810 { 4811 DoneList donelist; 4812 const Objlist_Entry *elm; 4813 SymLook req1; 4814 int res; 4815 4816 donelist_init(&donelist); 4817 symlook_init_from_req(&req1, req); 4818 4819 /* 4820 * Look first in the referencing object if linked symbolically, 4821 * and similarly handle protected symbols. 4822 */ 4823 res = symlook_obj(&req1, refobj); 4824 if (res == 0 && (refobj->symbolic || 4825 ELF_ST_VISIBILITY(req1.sym_out->st_other) == STV_PROTECTED || 4826 refobj->deepbind)) { 4827 req->sym_out = req1.sym_out; 4828 req->defobj_out = req1.defobj_out; 4829 assert(req->defobj_out != NULL); 4830 } 4831 if (refobj->symbolic || req->defobj_out != NULL || refobj->deepbind) 4832 donelist_check(&donelist, refobj); 4833 4834 if (!refobj->deepbind) 4835 symlook_global(req, &donelist); 4836 4837 /* Search all dlopened DAGs containing the referencing object. */ 4838 STAILQ_FOREACH(elm, &refobj->dldags, link) { 4839 if (req->sym_out != NULL && (!ld_dynamic_weak || 4840 ELF_ST_BIND(req->sym_out->st_info) != STB_WEAK)) 4841 break; 4842 res = symlook_list(&req1, &elm->obj->dagmembers, &donelist); 4843 if (res == 0 && (req->sym_out == NULL || 4844 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4845 req->sym_out = req1.sym_out; 4846 req->defobj_out = req1.defobj_out; 4847 assert(req->defobj_out != NULL); 4848 } 4849 } 4850 4851 if (refobj->deepbind) 4852 symlook_global(req, &donelist); 4853 4854 /* 4855 * Search the dynamic linker itself, and possibly resolve the 4856 * symbol from there. This is how the application links to 4857 * dynamic linker services such as dlopen. 4858 */ 4859 if (req->sym_out == NULL || 4860 ELF_ST_BIND(req->sym_out->st_info) == STB_WEAK) { 4861 res = symlook_obj(&req1, &obj_rtld); 4862 if (res == 0) { 4863 req->sym_out = req1.sym_out; 4864 req->defobj_out = req1.defobj_out; 4865 assert(req->defobj_out != NULL); 4866 } 4867 } 4868 4869 return (req->sym_out != NULL ? 0 : ESRCH); 4870 } 4871 4872 static int 4873 symlook_list(SymLook *req, const Objlist *objlist, DoneList *dlp) 4874 { 4875 const Elf_Sym *def; 4876 const Obj_Entry *defobj; 4877 const Objlist_Entry *elm; 4878 SymLook req1; 4879 int res; 4880 4881 def = NULL; 4882 defobj = NULL; 4883 STAILQ_FOREACH(elm, objlist, link) { 4884 if (donelist_check(dlp, elm->obj)) 4885 continue; 4886 symlook_init_from_req(&req1, req); 4887 if ((res = symlook_obj(&req1, elm->obj)) == 0) { 4888 if (def == NULL || (ld_dynamic_weak && 4889 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4890 def = req1.sym_out; 4891 defobj = req1.defobj_out; 4892 if (!ld_dynamic_weak || 4893 ELF_ST_BIND(def->st_info) != STB_WEAK) 4894 break; 4895 } 4896 } 4897 } 4898 if (def != NULL) { 4899 req->sym_out = def; 4900 req->defobj_out = defobj; 4901 return (0); 4902 } 4903 return (ESRCH); 4904 } 4905 4906 /* 4907 * Search the chain of DAGS cointed to by the given Needed_Entry 4908 * for a symbol of the given name. Each DAG is scanned completely 4909 * before advancing to the next one. Returns a pointer to the symbol, 4910 * or NULL if no definition was found. 4911 */ 4912 static int 4913 symlook_needed(SymLook *req, const Needed_Entry *needed, DoneList *dlp) 4914 { 4915 const Elf_Sym *def; 4916 const Needed_Entry *n; 4917 const Obj_Entry *defobj; 4918 SymLook req1; 4919 int res; 4920 4921 def = NULL; 4922 defobj = NULL; 4923 symlook_init_from_req(&req1, req); 4924 for (n = needed; n != NULL; n = n->next) { 4925 if (n->obj == NULL || (res = symlook_list(&req1, 4926 &n->obj->dagmembers, dlp)) != 0) 4927 continue; 4928 if (def == NULL || (ld_dynamic_weak && 4929 ELF_ST_BIND(req1.sym_out->st_info) != STB_WEAK)) { 4930 def = req1.sym_out; 4931 defobj = req1.defobj_out; 4932 if (!ld_dynamic_weak || 4933 ELF_ST_BIND(def->st_info) != STB_WEAK) 4934 break; 4935 } 4936 } 4937 if (def != NULL) { 4938 req->sym_out = def; 4939 req->defobj_out = defobj; 4940 return (0); 4941 } 4942 return (ESRCH); 4943 } 4944 4945 static int 4946 symlook_obj_load_filtees(SymLook *req, SymLook *req1, const Obj_Entry *obj, 4947 Needed_Entry *needed) 4948 { 4949 DoneList donelist; 4950 int flags; 4951 4952 flags = (req->flags & SYMLOOK_EARLY) != 0 ? RTLD_LO_EARLY : 0; 4953 load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate); 4954 donelist_init(&donelist); 4955 symlook_init_from_req(req1, req); 4956 return (symlook_needed(req1, needed, &donelist)); 4957 } 4958 4959 /* 4960 * Search the symbol table of a single shared object for a symbol of 4961 * the given name and version, if requested. Returns a pointer to the 4962 * symbol, or NULL if no definition was found. If the object is 4963 * filter, return filtered symbol from filtee. 4964 * 4965 * The symbol's hash value is passed in for efficiency reasons; that 4966 * eliminates many recomputations of the hash value. 4967 */ 4968 int 4969 symlook_obj(SymLook *req, const Obj_Entry *obj) 4970 { 4971 SymLook req1; 4972 int res, mres; 4973 4974 /* 4975 * If there is at least one valid hash at this point, we prefer to 4976 * use the faster GNU version if available. 4977 */ 4978 if (obj->valid_hash_gnu) 4979 mres = symlook_obj1_gnu(req, obj); 4980 else if (obj->valid_hash_sysv) 4981 mres = symlook_obj1_sysv(req, obj); 4982 else 4983 return (EINVAL); 4984 4985 if (mres == 0) { 4986 if (obj->needed_filtees != NULL) { 4987 res = symlook_obj_load_filtees(req, &req1, obj, 4988 obj->needed_filtees); 4989 if (res == 0) { 4990 req->sym_out = req1.sym_out; 4991 req->defobj_out = req1.defobj_out; 4992 } 4993 return (res); 4994 } 4995 if (obj->needed_aux_filtees != NULL) { 4996 res = symlook_obj_load_filtees(req, &req1, obj, 4997 obj->needed_aux_filtees); 4998 if (res == 0) { 4999 req->sym_out = req1.sym_out; 5000 req->defobj_out = req1.defobj_out; 5001 return (res); 5002 } 5003 } 5004 } 5005 return (mres); 5006 } 5007 5008 /* Symbol match routine common to both hash functions */ 5009 static bool 5010 matched_symbol(SymLook *req, const Obj_Entry *obj, Sym_Match_Result *result, 5011 const unsigned long symnum) 5012 { 5013 Elf_Versym verndx; 5014 const Elf_Sym *symp; 5015 const char *strp; 5016 5017 symp = obj->symtab + symnum; 5018 strp = obj->strtab + symp->st_name; 5019 5020 switch (ELF_ST_TYPE(symp->st_info)) { 5021 case STT_FUNC: 5022 case STT_NOTYPE: 5023 case STT_OBJECT: 5024 case STT_COMMON: 5025 case STT_GNU_IFUNC: 5026 if (symp->st_value == 0) 5027 return (false); 5028 /* fallthrough */ 5029 case STT_TLS: 5030 if (symp->st_shndx != SHN_UNDEF) 5031 break; 5032 else if (((req->flags & SYMLOOK_IN_PLT) == 0) && 5033 (ELF_ST_TYPE(symp->st_info) == STT_FUNC)) 5034 break; 5035 /* fallthrough */ 5036 default: 5037 return (false); 5038 } 5039 if (req->name[0] != strp[0] || strcmp(req->name, strp) != 0) 5040 return (false); 5041 5042 if (req->ventry == NULL) { 5043 if (obj->versyms != NULL) { 5044 verndx = VER_NDX(obj->versyms[symnum]); 5045 if (verndx > obj->vernum) { 5046 _rtld_error( 5047 "%s: symbol %s references wrong version %d", 5048 obj->path, obj->strtab + symnum, verndx); 5049 return (false); 5050 } 5051 /* 5052 * If we are not called from dlsym (i.e. this 5053 * is a normal relocation from unversioned 5054 * binary), accept the symbol immediately if 5055 * it happens to have first version after this 5056 * shared object became versioned. Otherwise, 5057 * if symbol is versioned and not hidden, 5058 * remember it. If it is the only symbol with 5059 * this name exported by the shared object, it 5060 * will be returned as a match by the calling 5061 * function. If symbol is global (verndx < 2) 5062 * accept it unconditionally. 5063 */ 5064 if ((req->flags & SYMLOOK_DLSYM) == 0 && 5065 verndx == VER_NDX_GIVEN) { 5066 result->sym_out = symp; 5067 return (true); 5068 } else if (verndx >= VER_NDX_GIVEN) { 5069 if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 5070 0) { 5071 if (result->vsymp == NULL) 5072 result->vsymp = symp; 5073 result->vcount++; 5074 } 5075 return (false); 5076 } 5077 } 5078 result->sym_out = symp; 5079 return (true); 5080 } 5081 if (obj->versyms == NULL) { 5082 if (object_match_name(obj, req->ventry->name)) { 5083 _rtld_error( 5084 "%s: object %s should provide version %s for symbol %s", 5085 obj_rtld.path, obj->path, req->ventry->name, 5086 obj->strtab + symnum); 5087 return (false); 5088 } 5089 } else { 5090 verndx = VER_NDX(obj->versyms[symnum]); 5091 if (verndx > obj->vernum) { 5092 _rtld_error("%s: symbol %s references wrong version %d", 5093 obj->path, obj->strtab + symnum, verndx); 5094 return (false); 5095 } 5096 if (obj->vertab[verndx].hash != req->ventry->hash || 5097 strcmp(obj->vertab[verndx].name, req->ventry->name)) { 5098 /* 5099 * Version does not match. Look if this is a 5100 * global symbol and if it is not hidden. If 5101 * global symbol (verndx < 2) is available, 5102 * use it. Do not return symbol if we are 5103 * called by dlvsym, because dlvsym looks for 5104 * a specific version and default one is not 5105 * what dlvsym wants. 5106 */ 5107 if ((req->flags & SYMLOOK_DLSYM) || 5108 (verndx >= VER_NDX_GIVEN) || 5109 (obj->versyms[symnum] & VER_NDX_HIDDEN)) 5110 return (false); 5111 } 5112 } 5113 result->sym_out = symp; 5114 return (true); 5115 } 5116 5117 /* 5118 * Search for symbol using SysV hash function. 5119 * obj->buckets is known not to be NULL at this point; the test for this was 5120 * performed with the obj->valid_hash_sysv assignment. 5121 */ 5122 static int 5123 symlook_obj1_sysv(SymLook *req, const Obj_Entry *obj) 5124 { 5125 unsigned long symnum; 5126 Sym_Match_Result matchres; 5127 5128 matchres.sym_out = NULL; 5129 matchres.vsymp = NULL; 5130 matchres.vcount = 0; 5131 5132 for (symnum = obj->buckets[req->hash % obj->nbuckets]; 5133 symnum != STN_UNDEF; symnum = obj->chains[symnum]) { 5134 if (symnum >= obj->nchains) 5135 return (ESRCH); /* Bad object */ 5136 5137 if (matched_symbol(req, obj, &matchres, symnum)) { 5138 req->sym_out = matchres.sym_out; 5139 req->defobj_out = obj; 5140 return (0); 5141 } 5142 } 5143 if (matchres.vcount == 1) { 5144 req->sym_out = matchres.vsymp; 5145 req->defobj_out = obj; 5146 return (0); 5147 } 5148 return (ESRCH); 5149 } 5150 5151 /* Search for symbol using GNU hash function */ 5152 static int 5153 symlook_obj1_gnu(SymLook *req, const Obj_Entry *obj) 5154 { 5155 Elf_Addr bloom_word; 5156 const Elf32_Word *hashval; 5157 Elf32_Word bucket; 5158 Sym_Match_Result matchres; 5159 unsigned int h1, h2; 5160 unsigned long symnum; 5161 5162 matchres.sym_out = NULL; 5163 matchres.vsymp = NULL; 5164 matchres.vcount = 0; 5165 5166 /* Pick right bitmask word from Bloom filter array */ 5167 bloom_word = obj->bloom_gnu[(req->hash_gnu / __ELF_WORD_SIZE) & 5168 obj->maskwords_bm_gnu]; 5169 5170 /* Calculate modulus word size of gnu hash and its derivative */ 5171 h1 = req->hash_gnu & (__ELF_WORD_SIZE - 1); 5172 h2 = ((req->hash_gnu >> obj->shift2_gnu) & (__ELF_WORD_SIZE - 1)); 5173 5174 /* Filter out the "definitely not in set" queries */ 5175 if (((bloom_word >> h1) & (bloom_word >> h2) & 1) == 0) 5176 return (ESRCH); 5177 5178 /* Locate hash chain and corresponding value element*/ 5179 bucket = obj->buckets_gnu[req->hash_gnu % obj->nbuckets_gnu]; 5180 if (bucket == 0) 5181 return (ESRCH); 5182 hashval = &obj->chain_zero_gnu[bucket]; 5183 do { 5184 if (((*hashval ^ req->hash_gnu) >> 1) == 0) { 5185 symnum = hashval - obj->chain_zero_gnu; 5186 if (matched_symbol(req, obj, &matchres, symnum)) { 5187 req->sym_out = matchres.sym_out; 5188 req->defobj_out = obj; 5189 return (0); 5190 } 5191 } 5192 } while ((*hashval++ & 1) == 0); 5193 if (matchres.vcount == 1) { 5194 req->sym_out = matchres.vsymp; 5195 req->defobj_out = obj; 5196 return (0); 5197 } 5198 return (ESRCH); 5199 } 5200 5201 static void 5202 trace_calc_fmts(const char **main_local, const char **fmt1, const char **fmt2) 5203 { 5204 *main_local = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_PROGNAME); 5205 if (*main_local == NULL) 5206 *main_local = ""; 5207 5208 *fmt1 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT1); 5209 if (*fmt1 == NULL) 5210 *fmt1 = "\t%o => %p (%x)\n"; 5211 5212 *fmt2 = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2); 5213 if (*fmt2 == NULL) 5214 *fmt2 = "\t%o (%x)\n"; 5215 } 5216 5217 static void 5218 trace_print_obj(Obj_Entry *obj, const char *name, const char *path, 5219 const char *main_local, const char *fmt1, const char *fmt2) 5220 { 5221 const char *fmt; 5222 int c; 5223 5224 if (fmt1 == NULL) 5225 fmt = fmt2; 5226 else 5227 /* XXX bogus */ 5228 fmt = strncmp(name, "lib", 3) == 0 ? fmt1 : fmt2; 5229 5230 while ((c = *fmt++) != '\0') { 5231 switch (c) { 5232 default: 5233 rtld_putchar(c); 5234 continue; 5235 case '\\': 5236 switch (c = *fmt) { 5237 case '\0': 5238 continue; 5239 case 'n': 5240 rtld_putchar('\n'); 5241 break; 5242 case 't': 5243 rtld_putchar('\t'); 5244 break; 5245 } 5246 break; 5247 case '%': 5248 switch (c = *fmt) { 5249 case '\0': 5250 continue; 5251 case '%': 5252 default: 5253 rtld_putchar(c); 5254 break; 5255 case 'A': 5256 rtld_putstr(main_local); 5257 break; 5258 case 'a': 5259 rtld_putstr(obj_main->path); 5260 break; 5261 case 'o': 5262 rtld_putstr(name); 5263 break; 5264 case 'p': 5265 rtld_putstr(path); 5266 break; 5267 case 'x': 5268 rtld_printf("%p", 5269 obj != NULL ? obj->mapbase : NULL); 5270 break; 5271 } 5272 break; 5273 } 5274 ++fmt; 5275 } 5276 } 5277 5278 static void 5279 trace_loaded_objects(Obj_Entry *obj, bool show_preload) 5280 { 5281 const char *fmt1, *fmt2, *main_local; 5282 const char *name, *path; 5283 bool first_spurious, list_containers; 5284 5285 trace_calc_fmts(&main_local, &fmt1, &fmt2); 5286 list_containers = ld_get_env_var(LD_TRACE_LOADED_OBJECTS_ALL) != NULL; 5287 5288 for (; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5289 Needed_Entry *needed; 5290 5291 if (obj->marker) 5292 continue; 5293 if (list_containers && obj->needed != NULL) 5294 rtld_printf("%s:\n", obj->path); 5295 for (needed = obj->needed; needed; needed = needed->next) { 5296 if (needed->obj != NULL) { 5297 if (needed->obj->traced && !list_containers) 5298 continue; 5299 needed->obj->traced = true; 5300 path = needed->obj->path; 5301 } else 5302 path = "not found"; 5303 5304 name = obj->strtab + needed->name; 5305 trace_print_obj(needed->obj, name, path, main_local, 5306 fmt1, fmt2); 5307 } 5308 } 5309 5310 if (show_preload) { 5311 if (ld_get_env_var(LD_TRACE_LOADED_OBJECTS_FMT2) == NULL) 5312 fmt2 = "\t%p (%x)\n"; 5313 first_spurious = true; 5314 5315 TAILQ_FOREACH(obj, &obj_list, next) { 5316 if (obj->marker || obj == obj_main || obj->traced) 5317 continue; 5318 5319 if (list_containers && first_spurious) { 5320 rtld_printf("[preloaded]\n"); 5321 first_spurious = false; 5322 } 5323 5324 Name_Entry *fname = STAILQ_FIRST(&obj->names); 5325 name = fname == NULL ? "<unknown>" : fname->name; 5326 trace_print_obj(obj, name, obj->path, main_local, NULL, 5327 fmt2); 5328 } 5329 } 5330 } 5331 5332 /* 5333 * Unload a dlopened object and its dependencies from memory and from 5334 * our data structures. It is assumed that the DAG rooted in the 5335 * object has already been unreferenced, and that the object has a 5336 * reference count of 0. 5337 */ 5338 static void 5339 unload_object(Obj_Entry *root, RtldLockState *lockstate) 5340 { 5341 Obj_Entry marker, *obj, *next; 5342 5343 assert(root->refcount == 0); 5344 5345 /* 5346 * Pass over the DAG removing unreferenced objects from 5347 * appropriate lists. 5348 */ 5349 unlink_object(root); 5350 5351 /* Unmap all objects that are no longer referenced. */ 5352 for (obj = TAILQ_FIRST(&obj_list); obj != NULL; obj = next) { 5353 next = TAILQ_NEXT(obj, next); 5354 if (obj->marker || obj->refcount != 0) 5355 continue; 5356 LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 5357 0, obj->path); 5358 dbg("unloading \"%s\"", obj->path); 5359 /* 5360 * Unlink the object now to prevent new references from 5361 * being acquired while the bind lock is dropped in 5362 * recursive dlclose() invocations. 5363 */ 5364 TAILQ_REMOVE(&obj_list, obj, next); 5365 obj_count--; 5366 5367 if (obj->filtees_loaded) { 5368 if (next != NULL) { 5369 init_marker(&marker); 5370 TAILQ_INSERT_BEFORE(next, &marker, next); 5371 unload_filtees(obj, lockstate); 5372 next = TAILQ_NEXT(&marker, next); 5373 TAILQ_REMOVE(&obj_list, &marker, next); 5374 } else 5375 unload_filtees(obj, lockstate); 5376 } 5377 release_object(obj); 5378 } 5379 } 5380 5381 static void 5382 unlink_object(Obj_Entry *root) 5383 { 5384 Objlist_Entry *elm; 5385 5386 if (root->refcount == 0) { 5387 /* Remove the object from the RTLD_GLOBAL list. */ 5388 objlist_remove(&list_global, root); 5389 5390 /* Remove the object from all objects' DAG lists. */ 5391 STAILQ_FOREACH(elm, &root->dagmembers, link) { 5392 objlist_remove(&elm->obj->dldags, root); 5393 if (elm->obj != root) 5394 unlink_object(elm->obj); 5395 } 5396 } 5397 } 5398 5399 static void 5400 ref_dag(Obj_Entry *root) 5401 { 5402 Objlist_Entry *elm; 5403 5404 assert(root->dag_inited); 5405 STAILQ_FOREACH(elm, &root->dagmembers, link) 5406 elm->obj->refcount++; 5407 } 5408 5409 static void 5410 unref_dag(Obj_Entry *root) 5411 { 5412 Objlist_Entry *elm; 5413 5414 assert(root->dag_inited); 5415 STAILQ_FOREACH(elm, &root->dagmembers, link) 5416 elm->obj->refcount--; 5417 } 5418 5419 /* 5420 * Common code for MD __tls_get_addr(). 5421 */ 5422 static void * 5423 tls_get_addr_slow(struct tcb *tcb, int index, size_t offset, bool locked) 5424 { 5425 struct dtv *newdtv, *dtv; 5426 RtldLockState lockstate; 5427 int to_copy; 5428 5429 dtv = tcb->tcb_dtv; 5430 /* Check dtv generation in case new modules have arrived */ 5431 if (dtv->dtv_gen != tls_dtv_generation) { 5432 if (!locked) 5433 wlock_acquire(rtld_bind_lock, &lockstate); 5434 newdtv = xcalloc(1, sizeof(struct dtv) + tls_max_index * 5435 sizeof(struct dtv_slot)); 5436 to_copy = dtv->dtv_size; 5437 if (to_copy > tls_max_index) 5438 to_copy = tls_max_index; 5439 memcpy(newdtv->dtv_slots, dtv->dtv_slots, to_copy * 5440 sizeof(struct dtv_slot)); 5441 newdtv->dtv_gen = tls_dtv_generation; 5442 newdtv->dtv_size = tls_max_index; 5443 free(dtv); 5444 if (!locked) 5445 lock_release(rtld_bind_lock, &lockstate); 5446 dtv = tcb->tcb_dtv = newdtv; 5447 } 5448 5449 /* Dynamically allocate module TLS if necessary */ 5450 if (dtv->dtv_slots[index - 1].dtvs_tls == 0) { 5451 /* Signal safe, wlock will block out signals. */ 5452 if (!locked) 5453 wlock_acquire(rtld_bind_lock, &lockstate); 5454 if (!dtv->dtv_slots[index - 1].dtvs_tls) 5455 dtv->dtv_slots[index - 1].dtvs_tls = 5456 allocate_module_tls(tcb, index); 5457 if (!locked) 5458 lock_release(rtld_bind_lock, &lockstate); 5459 } 5460 return (dtv->dtv_slots[index - 1].dtvs_tls + offset); 5461 } 5462 5463 void * 5464 tls_get_addr_common(struct tcb *tcb, int index, size_t offset) 5465 { 5466 struct dtv *dtv; 5467 5468 dtv = tcb->tcb_dtv; 5469 /* Check dtv generation in case new modules have arrived */ 5470 if (__predict_true(dtv->dtv_gen == tls_dtv_generation && 5471 dtv->dtv_slots[index - 1].dtvs_tls != 0)) 5472 return (dtv->dtv_slots[index - 1].dtvs_tls + offset); 5473 return (tls_get_addr_slow(tcb, index, offset, false)); 5474 } 5475 5476 static struct tcb * 5477 tcb_from_tcb_list_entry(struct tcb_list_entry *tcbelm) 5478 { 5479 #ifdef TLS_VARIANT_I 5480 return ((struct tcb *)((char *)tcbelm - tcb_list_entry_offset)); 5481 #else 5482 return ((struct tcb *)((char *)tcbelm + tcb_list_entry_offset)); 5483 #endif 5484 } 5485 5486 static struct tcb_list_entry * 5487 tcb_list_entry_from_tcb(struct tcb *tcb) 5488 { 5489 #ifdef TLS_VARIANT_I 5490 return ((struct tcb_list_entry *)((char *)tcb + tcb_list_entry_offset)); 5491 #else 5492 return ((struct tcb_list_entry *)((char *)tcb - tcb_list_entry_offset)); 5493 #endif 5494 } 5495 5496 static void 5497 tcb_list_insert(struct tcb *tcb) 5498 { 5499 struct tcb_list_entry *tcbelm; 5500 5501 tcbelm = tcb_list_entry_from_tcb(tcb); 5502 TAILQ_INSERT_TAIL(&tcb_list, tcbelm, next); 5503 } 5504 5505 static void 5506 tcb_list_remove(struct tcb *tcb) 5507 { 5508 struct tcb_list_entry *tcbelm; 5509 5510 tcbelm = tcb_list_entry_from_tcb(tcb); 5511 TAILQ_REMOVE(&tcb_list, tcbelm, next); 5512 } 5513 5514 #ifdef TLS_VARIANT_I 5515 5516 /* 5517 * Return pointer to allocated TLS block 5518 */ 5519 static void * 5520 get_tls_block_ptr(void *tcb, size_t tcbsize) 5521 { 5522 size_t extra_size, post_size, pre_size, tls_block_size; 5523 size_t tls_init_align; 5524 5525 tls_init_align = MAX(obj_main->tlsalign, 1); 5526 5527 /* Compute fragments sizes. */ 5528 extra_size = tcbsize - TLS_TCB_SIZE; 5529 post_size = calculate_tls_post_size(tls_init_align); 5530 tls_block_size = tcbsize + post_size; 5531 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 5532 5533 return ((char *)tcb - pre_size - extra_size); 5534 } 5535 5536 /* 5537 * Allocate Static TLS using the Variant I method. 5538 * 5539 * For details on the layout, see lib/libc/gen/tls.c. 5540 * 5541 * NB: rtld's tls_static_space variable includes TLS_TCB_SIZE and post_size as 5542 * it is based on tls_last_offset, and TLS offsets here are really TCB 5543 * offsets, whereas libc's tls_static_space is just the executable's static 5544 * TLS segment. 5545 * 5546 * NB: This differs from NetBSD's ld.elf_so, where TLS offsets are relative to 5547 * the end of the TCB. 5548 */ 5549 void * 5550 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 5551 { 5552 Obj_Entry *obj; 5553 char *tls_block; 5554 struct dtv *dtv; 5555 struct tcb *tcb; 5556 char *addr; 5557 size_t i; 5558 size_t extra_size, maxalign, post_size, pre_size, tls_block_size; 5559 size_t tls_init_align, tls_init_offset, tls_bss_offset; 5560 5561 if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) 5562 return (oldtcb); 5563 5564 assert(tcbsize >= TLS_TCB_SIZE); 5565 maxalign = MAX(tcbalign, tls_static_max_align); 5566 tls_init_align = MAX(obj_main->tlsalign, 1); 5567 5568 /* Compute fragments sizes. */ 5569 extra_size = tcbsize - TLS_TCB_SIZE; 5570 post_size = calculate_tls_post_size(tls_init_align); 5571 tls_block_size = tcbsize + post_size; 5572 pre_size = roundup2(tls_block_size, tls_init_align) - tls_block_size; 5573 tls_block_size += pre_size + tls_static_space - TLS_TCB_SIZE - 5574 post_size; 5575 5576 /* Allocate whole TLS block */ 5577 tls_block = xmalloc_aligned(tls_block_size, maxalign, 0); 5578 tcb = (struct tcb *)(tls_block + pre_size + extra_size); 5579 5580 if (oldtcb != NULL) { 5581 memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize), 5582 tls_static_space); 5583 free(get_tls_block_ptr(oldtcb, tcbsize)); 5584 5585 /* Adjust the DTV. */ 5586 dtv = tcb->tcb_dtv; 5587 for (i = 0; i < dtv->dtv_size; i++) { 5588 if ((uintptr_t)dtv->dtv_slots[i].dtvs_tls >= 5589 (uintptr_t)oldtcb && 5590 (uintptr_t)dtv->dtv_slots[i].dtvs_tls < 5591 (uintptr_t)oldtcb + tls_static_space) { 5592 dtv->dtv_slots[i].dtvs_tls = (char *)tcb + 5593 (dtv->dtv_slots[i].dtvs_tls - 5594 (char *)oldtcb); 5595 } 5596 } 5597 } else { 5598 dtv = xcalloc(1, sizeof(struct dtv) + tls_max_index * 5599 sizeof(struct dtv_slot)); 5600 tcb->tcb_dtv = dtv; 5601 dtv->dtv_gen = tls_dtv_generation; 5602 dtv->dtv_size = tls_max_index; 5603 5604 for (obj = globallist_curr(objs); obj != NULL; 5605 obj = globallist_next(obj)) { 5606 if (obj->tlsoffset == 0) 5607 continue; 5608 tls_init_offset = obj->tlspoffset & (obj->tlsalign - 1); 5609 addr = (char *)tcb + obj->tlsoffset; 5610 if (tls_init_offset > 0) 5611 memset(addr, 0, tls_init_offset); 5612 if (obj->tlsinitsize > 0) { 5613 memcpy(addr + tls_init_offset, obj->tlsinit, 5614 obj->tlsinitsize); 5615 } 5616 if (obj->tlssize > obj->tlsinitsize) { 5617 tls_bss_offset = tls_init_offset + 5618 obj->tlsinitsize; 5619 memset(addr + tls_bss_offset, 0, 5620 obj->tlssize - tls_bss_offset); 5621 } 5622 dtv->dtv_slots[obj->tlsindex - 1].dtvs_tls = addr; 5623 } 5624 } 5625 5626 tcb_list_insert(tcb); 5627 return (tcb); 5628 } 5629 5630 void 5631 free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused) 5632 { 5633 struct dtv *dtv; 5634 uintptr_t tlsstart, tlsend; 5635 size_t post_size; 5636 size_t i, tls_init_align __unused; 5637 5638 tcb_list_remove(tcb); 5639 5640 assert(tcbsize >= TLS_TCB_SIZE); 5641 tls_init_align = MAX(obj_main->tlsalign, 1); 5642 5643 /* Compute fragments sizes. */ 5644 post_size = calculate_tls_post_size(tls_init_align); 5645 5646 tlsstart = (uintptr_t)tcb + TLS_TCB_SIZE + post_size; 5647 tlsend = (uintptr_t)tcb + tls_static_space; 5648 5649 dtv = ((struct tcb *)tcb)->tcb_dtv; 5650 for (i = 0; i < dtv->dtv_size; i++) { 5651 if (dtv->dtv_slots[i].dtvs_tls != NULL && 5652 ((uintptr_t)dtv->dtv_slots[i].dtvs_tls < tlsstart || 5653 (uintptr_t)dtv->dtv_slots[i].dtvs_tls >= tlsend)) { 5654 free(dtv->dtv_slots[i].dtvs_tls); 5655 } 5656 } 5657 free(dtv); 5658 free(get_tls_block_ptr(tcb, tcbsize)); 5659 } 5660 5661 #endif /* TLS_VARIANT_I */ 5662 5663 #ifdef TLS_VARIANT_II 5664 5665 /* 5666 * Allocate Static TLS using the Variant II method. 5667 */ 5668 void * 5669 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) 5670 { 5671 Obj_Entry *obj; 5672 size_t size, ralign; 5673 char *tls_block; 5674 struct dtv *dtv, *olddtv; 5675 struct tcb *tcb; 5676 char *addr; 5677 size_t i; 5678 5679 ralign = tcbalign; 5680 if (tls_static_max_align > ralign) 5681 ralign = tls_static_max_align; 5682 size = roundup(tls_static_space, ralign) + roundup(tcbsize, ralign); 5683 5684 assert(tcbsize >= 2 * sizeof(uintptr_t)); 5685 tls_block = xmalloc_aligned(size, ralign, 0 /* XXX */); 5686 dtv = xcalloc(1, sizeof(struct dtv) + tls_max_index * 5687 sizeof(struct dtv_slot)); 5688 5689 tcb = (struct tcb *)(tls_block + roundup(tls_static_space, ralign)); 5690 tcb->tcb_self = tcb; 5691 tcb->tcb_dtv = dtv; 5692 5693 dtv->dtv_gen = tls_dtv_generation; 5694 dtv->dtv_size = tls_max_index; 5695 5696 if (oldtcb != NULL) { 5697 /* 5698 * Copy the static TLS block over whole. 5699 */ 5700 memcpy((char *)tcb - tls_static_space, 5701 (const char *)oldtcb - tls_static_space, 5702 tls_static_space); 5703 5704 /* 5705 * If any dynamic TLS blocks have been created tls_get_addr(), 5706 * move them over. 5707 */ 5708 olddtv = ((struct tcb *)oldtcb)->tcb_dtv; 5709 for (i = 0; i < olddtv->dtv_size; i++) { 5710 if ((uintptr_t)olddtv->dtv_slots[i].dtvs_tls < 5711 (uintptr_t)oldtcb - size || 5712 (uintptr_t)olddtv->dtv_slots[i].dtvs_tls > 5713 (uintptr_t)oldtcb) { 5714 dtv->dtv_slots[i].dtvs_tls = 5715 olddtv->dtv_slots[i].dtvs_tls; 5716 olddtv->dtv_slots[i].dtvs_tls = NULL; 5717 } 5718 } 5719 5720 /* 5721 * We assume that this block was the one we created with 5722 * allocate_initial_tls(). 5723 */ 5724 free_tls(oldtcb, 2 * sizeof(uintptr_t), sizeof(uintptr_t)); 5725 } else { 5726 for (obj = objs; obj != NULL; obj = TAILQ_NEXT(obj, next)) { 5727 if (obj->marker || obj->tlsoffset == 0) 5728 continue; 5729 addr = (char *)tcb - obj->tlsoffset; 5730 memset(addr + obj->tlsinitsize, 0, obj->tlssize - 5731 obj->tlsinitsize); 5732 if (obj->tlsinit) { 5733 memcpy(addr, obj->tlsinit, obj->tlsinitsize); 5734 obj->static_tls_copied = true; 5735 } 5736 dtv->dtv_slots[obj->tlsindex - 1].dtvs_tls = addr; 5737 } 5738 } 5739 5740 tcb_list_insert(tcb); 5741 return (tcb); 5742 } 5743 5744 void 5745 free_tls(void *tcb, size_t tcbsize __unused, size_t tcbalign) 5746 { 5747 struct dtv *dtv; 5748 size_t size, ralign; 5749 size_t i; 5750 uintptr_t tlsstart, tlsend; 5751 5752 tcb_list_remove(tcb); 5753 5754 /* 5755 * Figure out the size of the initial TLS block so that we can 5756 * find stuff which ___tls_get_addr() allocated dynamically. 5757 */ 5758 ralign = tcbalign; 5759 if (tls_static_max_align > ralign) 5760 ralign = tls_static_max_align; 5761 size = roundup(tls_static_space, ralign); 5762 5763 dtv = ((struct tcb *)tcb)->tcb_dtv; 5764 tlsend = (uintptr_t)tcb; 5765 tlsstart = tlsend - size; 5766 for (i = 0; i < dtv->dtv_size; i++) { 5767 if (dtv->dtv_slots[i].dtvs_tls != NULL && 5768 ((uintptr_t)dtv->dtv_slots[i].dtvs_tls < tlsstart || 5769 (uintptr_t)dtv->dtv_slots[i].dtvs_tls > tlsend)) { 5770 free(dtv->dtv_slots[i].dtvs_tls); 5771 } 5772 } 5773 5774 free((void *)tlsstart); 5775 free(dtv); 5776 } 5777 5778 #endif /* TLS_VARIANT_II */ 5779 5780 /* 5781 * Allocate TLS block for module with given index. 5782 */ 5783 void * 5784 allocate_module_tls(struct tcb *tcb, int index) 5785 { 5786 Obj_Entry *obj; 5787 char *p; 5788 5789 TAILQ_FOREACH(obj, &obj_list, next) { 5790 if (obj->marker) 5791 continue; 5792 if (obj->tlsindex == index) 5793 break; 5794 } 5795 if (obj == NULL) { 5796 _rtld_error("Can't find module with TLS index %d", index); 5797 rtld_die(); 5798 } 5799 5800 if (obj->tls_static) { 5801 #ifdef TLS_VARIANT_I 5802 p = (char *)tcb + obj->tlsoffset; 5803 #else 5804 p = (char *)tcb - obj->tlsoffset; 5805 #endif 5806 return (p); 5807 } 5808 5809 obj->tls_dynamic = true; 5810 5811 p = xmalloc_aligned(obj->tlssize, obj->tlsalign, obj->tlspoffset); 5812 memcpy(p, obj->tlsinit, obj->tlsinitsize); 5813 memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); 5814 return (p); 5815 } 5816 5817 static bool 5818 allocate_tls_offset_common(size_t *offp, size_t tlssize, size_t tlsalign, 5819 size_t tlspoffset __unused) 5820 { 5821 size_t off; 5822 5823 if (tls_last_offset == 0) 5824 off = calculate_first_tls_offset(tlssize, tlsalign, 5825 tlspoffset); 5826 else 5827 off = calculate_tls_offset(tls_last_offset, tls_last_size, 5828 tlssize, tlsalign, tlspoffset); 5829 5830 *offp = off; 5831 #ifdef TLS_VARIANT_I 5832 off += tlssize; 5833 #endif 5834 5835 /* 5836 * If we have already fixed the size of the static TLS block, we 5837 * must stay within that size. When allocating the static TLS, we 5838 * leave a small amount of space spare to be used for dynamically 5839 * loading modules which use static TLS. 5840 */ 5841 if (tls_static_space != 0) { 5842 if (off > tls_static_space) 5843 return (false); 5844 } else if (tlsalign > tls_static_max_align) { 5845 tls_static_max_align = tlsalign; 5846 } 5847 5848 tls_last_offset = off; 5849 tls_last_size = tlssize; 5850 5851 return (true); 5852 } 5853 5854 bool 5855 allocate_tls_offset(Obj_Entry *obj) 5856 { 5857 if (obj->tls_dynamic) 5858 return (false); 5859 5860 if (obj->tls_static) 5861 return (true); 5862 5863 if (obj->tlssize == 0) { 5864 obj->tls_static = true; 5865 return (true); 5866 } 5867 5868 if (!allocate_tls_offset_common(&obj->tlsoffset, obj->tlssize, 5869 obj->tlsalign, obj->tlspoffset)) 5870 return (false); 5871 5872 obj->tls_static = true; 5873 5874 return (true); 5875 } 5876 5877 void 5878 free_tls_offset(Obj_Entry *obj) 5879 { 5880 /* 5881 * If we were the last thing to allocate out of the static TLS 5882 * block, we give our space back to the 'allocator'. This is a 5883 * simplistic workaround to allow libGL.so.1 to be loaded and 5884 * unloaded multiple times. 5885 */ 5886 size_t off = obj->tlsoffset; 5887 5888 #ifdef TLS_VARIANT_I 5889 off += obj->tlssize; 5890 #endif 5891 if (off == tls_last_offset) { 5892 tls_last_offset -= obj->tlssize; 5893 tls_last_size = 0; 5894 } 5895 } 5896 5897 void * 5898 _rtld_allocate_tls(void *oldtcb, size_t tcbsize, size_t tcbalign) 5899 { 5900 void *ret; 5901 RtldLockState lockstate; 5902 5903 wlock_acquire(rtld_bind_lock, &lockstate); 5904 ret = allocate_tls(globallist_curr(TAILQ_FIRST(&obj_list)), oldtcb, 5905 tcbsize, tcbalign); 5906 lock_release(rtld_bind_lock, &lockstate); 5907 return (ret); 5908 } 5909 5910 void 5911 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) 5912 { 5913 RtldLockState lockstate; 5914 5915 wlock_acquire(rtld_bind_lock, &lockstate); 5916 free_tls(tcb, tcbsize, tcbalign); 5917 lock_release(rtld_bind_lock, &lockstate); 5918 } 5919 5920 static void 5921 object_add_name(Obj_Entry *obj, const char *name) 5922 { 5923 Name_Entry *entry; 5924 size_t len; 5925 5926 len = strlen(name); 5927 entry = malloc(sizeof(Name_Entry) + len); 5928 5929 if (entry != NULL) { 5930 strcpy(entry->name, name); 5931 STAILQ_INSERT_TAIL(&obj->names, entry, link); 5932 } 5933 } 5934 5935 static int 5936 object_match_name(const Obj_Entry *obj, const char *name) 5937 { 5938 Name_Entry *entry; 5939 5940 STAILQ_FOREACH(entry, &obj->names, link) { 5941 if (strcmp(name, entry->name) == 0) 5942 return (1); 5943 } 5944 return (0); 5945 } 5946 5947 static Obj_Entry * 5948 locate_dependency(const Obj_Entry *obj, const char *name) 5949 { 5950 const Objlist_Entry *entry; 5951 const Needed_Entry *needed; 5952 5953 STAILQ_FOREACH(entry, &list_main, link) { 5954 if (object_match_name(entry->obj, name)) 5955 return (entry->obj); 5956 } 5957 5958 for (needed = obj->needed; needed != NULL; needed = needed->next) { 5959 if (strcmp(obj->strtab + needed->name, name) == 0 || 5960 (needed->obj != NULL && object_match_name(needed->obj, 5961 name))) { 5962 /* 5963 * If there is DT_NEEDED for the name we are looking 5964 * for, we are all set. Note that object might not be 5965 * found if dependency was not loaded yet, so the 5966 * function can return NULL here. This is expected and 5967 * handled properly by the caller. 5968 */ 5969 return (needed->obj); 5970 } 5971 } 5972 _rtld_error("%s: Unexpected inconsistency: dependency %s not found", 5973 obj->path, name); 5974 rtld_die(); 5975 } 5976 5977 static int 5978 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj, 5979 const Elf_Vernaux *vna) 5980 { 5981 const Elf_Verdef *vd; 5982 const char *vername; 5983 5984 vername = refobj->strtab + vna->vna_name; 5985 vd = depobj->verdef; 5986 if (vd == NULL) { 5987 _rtld_error("%s: version %s required by %s not defined", 5988 depobj->path, vername, refobj->path); 5989 return (-1); 5990 } 5991 for (;;) { 5992 if (vd->vd_version != VER_DEF_CURRENT) { 5993 _rtld_error( 5994 "%s: Unsupported version %d of Elf_Verdef entry", 5995 depobj->path, vd->vd_version); 5996 return (-1); 5997 } 5998 if (vna->vna_hash == vd->vd_hash) { 5999 const Elf_Verdaux *aux = 6000 (const Elf_Verdaux *)((const char *)vd + 6001 vd->vd_aux); 6002 if (strcmp(vername, depobj->strtab + aux->vda_name) == 6003 0) 6004 return (0); 6005 } 6006 if (vd->vd_next == 0) 6007 break; 6008 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 6009 } 6010 if (vna->vna_flags & VER_FLG_WEAK) 6011 return (0); 6012 _rtld_error("%s: version %s required by %s not found", depobj->path, 6013 vername, refobj->path); 6014 return (-1); 6015 } 6016 6017 static int 6018 rtld_verify_object_versions(Obj_Entry *obj) 6019 { 6020 const Elf_Verneed *vn; 6021 const Elf_Verdef *vd; 6022 const Elf_Verdaux *vda; 6023 const Elf_Vernaux *vna; 6024 const Obj_Entry *depobj; 6025 int maxvernum, vernum; 6026 6027 if (obj->ver_checked) 6028 return (0); 6029 obj->ver_checked = true; 6030 6031 maxvernum = 0; 6032 /* 6033 * Walk over defined and required version records and figure out 6034 * max index used by any of them. Do very basic sanity checking 6035 * while there. 6036 */ 6037 vn = obj->verneed; 6038 while (vn != NULL) { 6039 if (vn->vn_version != VER_NEED_CURRENT) { 6040 _rtld_error( 6041 "%s: Unsupported version %d of Elf_Verneed entry", 6042 obj->path, vn->vn_version); 6043 return (-1); 6044 } 6045 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 6046 for (;;) { 6047 vernum = VER_NEED_IDX(vna->vna_other); 6048 if (vernum > maxvernum) 6049 maxvernum = vernum; 6050 if (vna->vna_next == 0) 6051 break; 6052 vna = (const Elf_Vernaux *)((const char *)vna + 6053 vna->vna_next); 6054 } 6055 if (vn->vn_next == 0) 6056 break; 6057 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 6058 } 6059 6060 vd = obj->verdef; 6061 while (vd != NULL) { 6062 if (vd->vd_version != VER_DEF_CURRENT) { 6063 _rtld_error( 6064 "%s: Unsupported version %d of Elf_Verdef entry", 6065 obj->path, vd->vd_version); 6066 return (-1); 6067 } 6068 vernum = VER_DEF_IDX(vd->vd_ndx); 6069 if (vernum > maxvernum) 6070 maxvernum = vernum; 6071 if (vd->vd_next == 0) 6072 break; 6073 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 6074 } 6075 6076 if (maxvernum == 0) 6077 return (0); 6078 6079 /* 6080 * Store version information in array indexable by version index. 6081 * Verify that object version requirements are satisfied along the 6082 * way. 6083 */ 6084 obj->vernum = maxvernum + 1; 6085 obj->vertab = xcalloc(obj->vernum, sizeof(Ver_Entry)); 6086 6087 vd = obj->verdef; 6088 while (vd != NULL) { 6089 if ((vd->vd_flags & VER_FLG_BASE) == 0) { 6090 vernum = VER_DEF_IDX(vd->vd_ndx); 6091 assert(vernum <= maxvernum); 6092 vda = (const Elf_Verdaux *)((const char *)vd + 6093 vd->vd_aux); 6094 obj->vertab[vernum].hash = vd->vd_hash; 6095 obj->vertab[vernum].name = obj->strtab + vda->vda_name; 6096 obj->vertab[vernum].file = NULL; 6097 obj->vertab[vernum].flags = 0; 6098 } 6099 if (vd->vd_next == 0) 6100 break; 6101 vd = (const Elf_Verdef *)((const char *)vd + vd->vd_next); 6102 } 6103 6104 vn = obj->verneed; 6105 while (vn != NULL) { 6106 depobj = locate_dependency(obj, obj->strtab + vn->vn_file); 6107 if (depobj == NULL) 6108 return (-1); 6109 vna = (const Elf_Vernaux *)((const char *)vn + vn->vn_aux); 6110 for (;;) { 6111 if (check_object_provided_version(obj, depobj, vna)) 6112 return (-1); 6113 vernum = VER_NEED_IDX(vna->vna_other); 6114 assert(vernum <= maxvernum); 6115 obj->vertab[vernum].hash = vna->vna_hash; 6116 obj->vertab[vernum].name = obj->strtab + vna->vna_name; 6117 obj->vertab[vernum].file = obj->strtab + vn->vn_file; 6118 obj->vertab[vernum].flags = (vna->vna_other & 6119 VER_NEED_HIDDEN) != 0 ? VER_INFO_HIDDEN : 0; 6120 if (vna->vna_next == 0) 6121 break; 6122 vna = (const Elf_Vernaux *)((const char *)vna + 6123 vna->vna_next); 6124 } 6125 if (vn->vn_next == 0) 6126 break; 6127 vn = (const Elf_Verneed *)((const char *)vn + vn->vn_next); 6128 } 6129 return (0); 6130 } 6131 6132 static int 6133 rtld_verify_versions(const Objlist *objlist) 6134 { 6135 Objlist_Entry *entry; 6136 int rc; 6137 6138 rc = 0; 6139 STAILQ_FOREACH(entry, objlist, link) { 6140 /* 6141 * Skip dummy objects or objects that have their version 6142 * requirements already checked. 6143 */ 6144 if (entry->obj->strtab == NULL || entry->obj->vertab != NULL) 6145 continue; 6146 if (rtld_verify_object_versions(entry->obj) == -1) { 6147 rc = -1; 6148 if (ld_tracing == NULL) 6149 break; 6150 } 6151 } 6152 if (rc == 0 || ld_tracing != NULL) 6153 rc = rtld_verify_object_versions(&obj_rtld); 6154 return (rc); 6155 } 6156 6157 const Ver_Entry * 6158 fetch_ventry(const Obj_Entry *obj, unsigned long symnum) 6159 { 6160 Elf_Versym vernum; 6161 6162 if (obj->vertab) { 6163 vernum = VER_NDX(obj->versyms[symnum]); 6164 if (vernum >= obj->vernum) { 6165 _rtld_error("%s: symbol %s has wrong verneed value %d", 6166 obj->path, obj->strtab + symnum, vernum); 6167 } else if (obj->vertab[vernum].hash != 0) { 6168 return (&obj->vertab[vernum]); 6169 } 6170 } 6171 return (NULL); 6172 } 6173 6174 int 6175 _rtld_get_stack_prot(void) 6176 { 6177 return (stack_prot); 6178 } 6179 6180 int 6181 _rtld_is_dlopened(void *arg) 6182 { 6183 Obj_Entry *obj; 6184 RtldLockState lockstate; 6185 int res; 6186 6187 rlock_acquire(rtld_bind_lock, &lockstate); 6188 obj = dlcheck(arg); 6189 if (obj == NULL) 6190 obj = obj_from_addr(arg); 6191 if (obj == NULL) { 6192 _rtld_error("No shared object contains address"); 6193 lock_release(rtld_bind_lock, &lockstate); 6194 return (-1); 6195 } 6196 res = obj->dlopened ? 1 : 0; 6197 lock_release(rtld_bind_lock, &lockstate); 6198 return (res); 6199 } 6200 6201 static int 6202 obj_remap_relro(Obj_Entry *obj, int prot) 6203 { 6204 const Elf_Phdr *ph; 6205 caddr_t relro_page; 6206 size_t relro_size; 6207 6208 for (ph = obj->phdr; ph < obj->phdr + obj->phnum; ph++) { 6209 if (ph->p_type != PT_GNU_RELRO) 6210 continue; 6211 relro_page = obj->relocbase + rtld_trunc_page(ph->p_vaddr); 6212 relro_size = rtld_round_page(ph->p_vaddr + ph->p_memsz) - 6213 rtld_trunc_page(ph->p_vaddr); 6214 if (mprotect(relro_page, relro_size, prot) == -1) { 6215 _rtld_error( 6216 "%s: Cannot set relro protection to %#x: %s", 6217 obj->path, prot, rtld_strerror(errno)); 6218 return (-1); 6219 } 6220 break; 6221 } 6222 return (0); 6223 } 6224 6225 static int 6226 obj_disable_relro(Obj_Entry *obj) 6227 { 6228 return (obj_remap_relro(obj, PROT_READ | PROT_WRITE)); 6229 } 6230 6231 static int 6232 obj_enforce_relro(Obj_Entry *obj) 6233 { 6234 return (obj_remap_relro(obj, PROT_READ)); 6235 } 6236 6237 static void 6238 map_stacks_exec(RtldLockState *lockstate) 6239 { 6240 void (*thr_map_stacks_exec)(void); 6241 6242 if ((max_stack_flags & PF_X) == 0 || (stack_prot & PROT_EXEC) != 0) 6243 return; 6244 thr_map_stacks_exec = (void (*)(void))( 6245 uintptr_t)get_program_var_addr("__pthread_map_stacks_exec", 6246 lockstate); 6247 if (thr_map_stacks_exec != NULL) { 6248 stack_prot |= PROT_EXEC; 6249 thr_map_stacks_exec(); 6250 } 6251 } 6252 6253 static void 6254 distribute_static_tls(Objlist *list) 6255 { 6256 struct tcb_list_entry *tcbelm; 6257 Objlist_Entry *objelm; 6258 struct tcb *tcb; 6259 Obj_Entry *obj; 6260 char *tlsbase; 6261 6262 STAILQ_FOREACH(objelm, list, link) { 6263 obj = objelm->obj; 6264 if (obj->marker || !obj->tls_static || obj->static_tls_copied) 6265 continue; 6266 TAILQ_FOREACH(tcbelm, &tcb_list, next) { 6267 tcb = tcb_from_tcb_list_entry(tcbelm); 6268 #ifdef TLS_VARIANT_I 6269 tlsbase = (char *)tcb + obj->tlsoffset; 6270 #else 6271 tlsbase = (char *)tcb - obj->tlsoffset; 6272 #endif 6273 memcpy(tlsbase, obj->tlsinit, obj->tlsinitsize); 6274 memset(tlsbase + obj->tlsinitsize, 0, 6275 obj->tlssize - obj->tlsinitsize); 6276 } 6277 obj->static_tls_copied = true; 6278 } 6279 } 6280 6281 void 6282 symlook_init(SymLook *dst, const char *name) 6283 { 6284 bzero(dst, sizeof(*dst)); 6285 dst->name = name; 6286 dst->hash = elf_hash(name); 6287 dst->hash_gnu = gnu_hash(name); 6288 } 6289 6290 static void 6291 symlook_init_from_req(SymLook *dst, const SymLook *src) 6292 { 6293 dst->name = src->name; 6294 dst->hash = src->hash; 6295 dst->hash_gnu = src->hash_gnu; 6296 dst->ventry = src->ventry; 6297 dst->flags = src->flags; 6298 dst->defobj_out = NULL; 6299 dst->sym_out = NULL; 6300 dst->lockstate = src->lockstate; 6301 } 6302 6303 static int 6304 open_binary_fd(const char *argv0, bool search_in_path, const char **binpath_res) 6305 { 6306 char *binpath, *pathenv, *pe, *res1; 6307 const char *res; 6308 int fd; 6309 6310 binpath = NULL; 6311 res = NULL; 6312 if (search_in_path && strchr(argv0, '/') == NULL) { 6313 binpath = xmalloc(PATH_MAX); 6314 pathenv = getenv("PATH"); 6315 if (pathenv == NULL) { 6316 _rtld_error("-p and no PATH environment variable"); 6317 rtld_die(); 6318 } 6319 pathenv = strdup(pathenv); 6320 if (pathenv == NULL) { 6321 _rtld_error("Cannot allocate memory"); 6322 rtld_die(); 6323 } 6324 fd = -1; 6325 errno = ENOENT; 6326 while ((pe = strsep(&pathenv, ":")) != NULL) { 6327 if (strlcpy(binpath, pe, PATH_MAX) >= PATH_MAX) 6328 continue; 6329 if (binpath[0] != '\0' && 6330 strlcat(binpath, "/", PATH_MAX) >= PATH_MAX) 6331 continue; 6332 if (strlcat(binpath, argv0, PATH_MAX) >= PATH_MAX) 6333 continue; 6334 fd = open(binpath, O_RDONLY | O_CLOEXEC | O_VERIFY); 6335 if (fd != -1 || errno != ENOENT) { 6336 res = binpath; 6337 break; 6338 } 6339 } 6340 free(pathenv); 6341 } else { 6342 fd = open(argv0, O_RDONLY | O_CLOEXEC | O_VERIFY); 6343 res = argv0; 6344 } 6345 6346 if (fd == -1) { 6347 _rtld_error("Cannot open %s: %s", argv0, rtld_strerror(errno)); 6348 rtld_die(); 6349 } 6350 if (res != NULL && res[0] != '/') { 6351 res1 = xmalloc(PATH_MAX); 6352 if (realpath(res, res1) != NULL) { 6353 if (res != argv0) 6354 free(__DECONST(char *, res)); 6355 res = res1; 6356 } else { 6357 free(res1); 6358 } 6359 } 6360 *binpath_res = res; 6361 return (fd); 6362 } 6363 6364 /* 6365 * Parse a set of command-line arguments. 6366 */ 6367 static int 6368 parse_args(char *argv[], int argc, bool *use_pathp, int *fdp, 6369 const char **argv0, bool *dir_ignore) 6370 { 6371 const char *arg; 6372 char machine[64]; 6373 size_t sz; 6374 int arglen, fd, i, j, mib[2]; 6375 char opt; 6376 bool seen_b, seen_f; 6377 6378 dbg("Parsing command-line arguments"); 6379 *use_pathp = false; 6380 *fdp = -1; 6381 *dir_ignore = false; 6382 seen_b = seen_f = false; 6383 6384 for (i = 1; i < argc; i++) { 6385 arg = argv[i]; 6386 dbg("argv[%d]: '%s'", i, arg); 6387 6388 /* 6389 * rtld arguments end with an explicit "--" or with the first 6390 * non-prefixed argument. 6391 */ 6392 if (strcmp(arg, "--") == 0) { 6393 i++; 6394 break; 6395 } 6396 if (arg[0] != '-') 6397 break; 6398 6399 /* 6400 * All other arguments are single-character options that can 6401 * be combined, so we need to search through `arg` for them. 6402 */ 6403 arglen = strlen(arg); 6404 for (j = 1; j < arglen; j++) { 6405 opt = arg[j]; 6406 if (opt == 'h') { 6407 print_usage(argv[0]); 6408 _exit(0); 6409 } else if (opt == 'b') { 6410 if (seen_f) { 6411 _rtld_error("Both -b and -f specified"); 6412 rtld_die(); 6413 } 6414 if (j != arglen - 1) { 6415 _rtld_error("Invalid options: %s", arg); 6416 rtld_die(); 6417 } 6418 i++; 6419 *argv0 = argv[i]; 6420 seen_b = true; 6421 break; 6422 } else if (opt == 'd') { 6423 *dir_ignore = true; 6424 } else if (opt == 'f') { 6425 if (seen_b) { 6426 _rtld_error("Both -b and -f specified"); 6427 rtld_die(); 6428 } 6429 6430 /* 6431 * -f XX can be used to specify a 6432 * descriptor for the binary named at 6433 * the command line (i.e., the later 6434 * argument will specify the process 6435 * name but the descriptor is what 6436 * will actually be executed). 6437 * 6438 * -f must be the last option in the 6439 * group, e.g., -abcf <fd>. 6440 */ 6441 if (j != arglen - 1) { 6442 _rtld_error("Invalid options: %s", arg); 6443 rtld_die(); 6444 } 6445 i++; 6446 fd = parse_integer(argv[i]); 6447 if (fd == -1) { 6448 _rtld_error( 6449 "Invalid file descriptor: '%s'", 6450 argv[i]); 6451 rtld_die(); 6452 } 6453 *fdp = fd; 6454 seen_f = true; 6455 break; 6456 } else if (opt == 'o') { 6457 struct ld_env_var_desc *l; 6458 char *n, *v; 6459 u_int ll; 6460 6461 if (j != arglen - 1) { 6462 _rtld_error("Invalid options: %s", arg); 6463 rtld_die(); 6464 } 6465 i++; 6466 n = argv[i]; 6467 v = strchr(n, '='); 6468 if (v == NULL) { 6469 _rtld_error("No '=' in -o parameter"); 6470 rtld_die(); 6471 } 6472 for (ll = 0; ll < nitems(ld_env_vars); ll++) { 6473 l = &ld_env_vars[ll]; 6474 if (v - n == (ptrdiff_t)strlen(l->n) && 6475 strncmp(n, l->n, v - n) == 0) { 6476 l->val = v + 1; 6477 break; 6478 } 6479 } 6480 if (ll == nitems(ld_env_vars)) { 6481 _rtld_error("Unknown LD_ option %s", n); 6482 rtld_die(); 6483 } 6484 } else if (opt == 'p') { 6485 *use_pathp = true; 6486 } else if (opt == 'u') { 6487 u_int ll; 6488 6489 for (ll = 0; ll < nitems(ld_env_vars); ll++) 6490 ld_env_vars[ll].val = NULL; 6491 } else if (opt == 'v') { 6492 machine[0] = '\0'; 6493 mib[0] = CTL_HW; 6494 mib[1] = HW_MACHINE; 6495 sz = sizeof(machine); 6496 sysctl(mib, nitems(mib), machine, &sz, NULL, 0); 6497 ld_elf_hints_path = ld_get_env_var( 6498 LD_ELF_HINTS_PATH); 6499 set_ld_elf_hints_path(); 6500 rtld_printf( 6501 "FreeBSD ld-elf.so.1 %s\n" 6502 "FreeBSD_version %d\n" 6503 "Default lib path %s\n" 6504 "Hints lib path %s\n" 6505 "Env prefix %s\n" 6506 "Default hint file %s\n" 6507 "Hint file %s\n" 6508 "libmap file %s\n" 6509 "Optional static TLS size %zd bytes\n", 6510 machine, __FreeBSD_version, 6511 ld_standard_library_path, gethints(false), 6512 ld_env_prefix, ld_elf_hints_default, 6513 ld_elf_hints_path, ld_path_libmap_conf, 6514 ld_static_tls_extra); 6515 _exit(0); 6516 } else { 6517 _rtld_error("Invalid argument: '%s'", arg); 6518 print_usage(argv[0]); 6519 rtld_die(); 6520 } 6521 } 6522 } 6523 6524 if (!seen_b) 6525 *argv0 = argv[i]; 6526 return (i); 6527 } 6528 6529 /* 6530 * Parse a file descriptor number without pulling in more of libc (e.g. atoi). 6531 */ 6532 static int 6533 parse_integer(const char *str) 6534 { 6535 static const int RADIX = 10; /* XXXJA: possibly support hex? */ 6536 const char *orig; 6537 int n; 6538 char c; 6539 6540 orig = str; 6541 n = 0; 6542 for (c = *str; c != '\0'; c = *++str) { 6543 if (c < '0' || c > '9') 6544 return (-1); 6545 6546 if (n > INT_MAX / RADIX) 6547 return (-1); 6548 n *= RADIX; 6549 if (n > INT_MAX - (c - '0')) 6550 return (-1); 6551 n += c - '0'; 6552 } 6553 6554 /* Make sure we actually parsed something. */ 6555 if (str == orig) 6556 return (-1); 6557 return (n); 6558 } 6559 6560 static void 6561 print_usage(const char *argv0) 6562 { 6563 rtld_printf( 6564 "Usage: %s [-h] [-b <exe>] [-d] [-f <FD>] [-p] [--] <binary> [<args>]\n" 6565 "\n" 6566 "Options:\n" 6567 " -h Display this help message\n" 6568 " -b <exe> Execute <exe> instead of <binary>, arg0 is <binary>\n" 6569 " -d Ignore lack of exec permissions for the binary\n" 6570 " -f <FD> Execute <FD> instead of searching for <binary>\n" 6571 " -o <OPT>=<VAL> Set LD_<OPT> to <VAL>, without polluting env\n" 6572 " -p Search in PATH for named binary\n" 6573 " -u Ignore LD_ environment variables\n" 6574 " -v Display identification information\n" 6575 " -- End of RTLD options\n" 6576 " <binary> Name of process to execute\n" 6577 " <args> Arguments to the executed process\n", 6578 argv0); 6579 } 6580 6581 #define AUXFMT(at, xfmt) [at] = { .name = #at, .fmt = xfmt } 6582 static const struct auxfmt { 6583 const char *name; 6584 const char *fmt; 6585 } auxfmts[] = { 6586 AUXFMT(AT_NULL, NULL), 6587 AUXFMT(AT_IGNORE, NULL), 6588 AUXFMT(AT_EXECFD, "%ld"), 6589 AUXFMT(AT_PHDR, "%p"), 6590 AUXFMT(AT_PHENT, "%lu"), 6591 AUXFMT(AT_PHNUM, "%lu"), 6592 AUXFMT(AT_PAGESZ, "%lu"), 6593 AUXFMT(AT_BASE, "%#lx"), 6594 AUXFMT(AT_FLAGS, "%#lx"), 6595 AUXFMT(AT_ENTRY, "%p"), 6596 AUXFMT(AT_NOTELF, NULL), 6597 AUXFMT(AT_UID, "%ld"), 6598 AUXFMT(AT_EUID, "%ld"), 6599 AUXFMT(AT_GID, "%ld"), 6600 AUXFMT(AT_EGID, "%ld"), 6601 AUXFMT(AT_EXECPATH, "%s"), 6602 AUXFMT(AT_CANARY, "%p"), 6603 AUXFMT(AT_CANARYLEN, "%lu"), 6604 AUXFMT(AT_OSRELDATE, "%lu"), 6605 AUXFMT(AT_NCPUS, "%lu"), 6606 AUXFMT(AT_PAGESIZES, "%p"), 6607 AUXFMT(AT_PAGESIZESLEN, "%lu"), 6608 AUXFMT(AT_TIMEKEEP, "%p"), 6609 AUXFMT(AT_STACKPROT, "%#lx"), 6610 AUXFMT(AT_EHDRFLAGS, "%#lx"), 6611 AUXFMT(AT_HWCAP, "%#lx"), 6612 AUXFMT(AT_HWCAP2, "%#lx"), 6613 AUXFMT(AT_BSDFLAGS, "%#lx"), 6614 AUXFMT(AT_ARGC, "%lu"), 6615 AUXFMT(AT_ARGV, "%p"), 6616 AUXFMT(AT_ENVC, "%p"), 6617 AUXFMT(AT_ENVV, "%p"), 6618 AUXFMT(AT_PS_STRINGS, "%p"), 6619 AUXFMT(AT_FXRNG, "%p"), 6620 AUXFMT(AT_KPRELOAD, "%p"), 6621 AUXFMT(AT_USRSTACKBASE, "%#lx"), 6622 AUXFMT(AT_USRSTACKLIM, "%#lx"), 6623 /* AT_CHERI_STATS */ 6624 AUXFMT(AT_HWCAP3, "%#lx"), 6625 AUXFMT(AT_HWCAP4, "%#lx"), 6626 6627 }; 6628 6629 static bool 6630 is_ptr_fmt(const char *fmt) 6631 { 6632 char last; 6633 6634 last = fmt[strlen(fmt) - 1]; 6635 return (last == 'p' || last == 's'); 6636 } 6637 6638 static void 6639 dump_auxv(Elf_Auxinfo **aux_info) 6640 { 6641 Elf_Auxinfo *auxp; 6642 const struct auxfmt *fmt; 6643 int i; 6644 6645 for (i = 0; i < AT_COUNT; i++) { 6646 auxp = aux_info[i]; 6647 if (auxp == NULL) 6648 continue; 6649 fmt = &auxfmts[i]; 6650 if (fmt->fmt == NULL) 6651 continue; 6652 rtld_fdprintf(STDOUT_FILENO, "%s:\t", fmt->name); 6653 if (is_ptr_fmt(fmt->fmt)) { 6654 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt, 6655 auxp->a_un.a_ptr); 6656 } else { 6657 rtld_fdprintfx(STDOUT_FILENO, fmt->fmt, 6658 auxp->a_un.a_val); 6659 } 6660 rtld_fdprintf(STDOUT_FILENO, "\n"); 6661 } 6662 } 6663 6664 const char * 6665 rtld_get_var(const char *name) 6666 { 6667 const struct ld_env_var_desc *lvd; 6668 u_int i; 6669 6670 for (i = 0; i < nitems(ld_env_vars); i++) { 6671 lvd = &ld_env_vars[i]; 6672 if (strcmp(lvd->n, name) == 0) 6673 return (lvd->val); 6674 } 6675 return (NULL); 6676 } 6677 6678 static void 6679 rtld_recalc_dangerous_ld_env(void) 6680 { 6681 /* 6682 * Never reset dangerous_ld_env back to false if rtld was ever 6683 * contaminated with it set to true. 6684 */ 6685 dangerous_ld_env |= libmap_disable || libmap_override != NULL || 6686 ld_library_path != NULL || ld_preload != NULL || 6687 ld_elf_hints_path != NULL || ld_loadfltr || !ld_dynamic_weak || 6688 ld_get_env_var(LD_STATIC_TLS_EXTRA) != NULL; 6689 } 6690 6691 static void 6692 rtld_recalc_debug(const char *ld_debug) 6693 { 6694 if (ld_debug != NULL && *ld_debug != '\0') 6695 debug = 1; 6696 } 6697 6698 static void 6699 rtld_set_var_debug(struct ld_env_var_desc *lvd) 6700 { 6701 rtld_recalc_debug(lvd->val); 6702 } 6703 6704 static void 6705 rtld_set_var_library_path(struct ld_env_var_desc *lvd) 6706 { 6707 ld_library_path = lvd->val; 6708 } 6709 6710 static void 6711 rtld_set_var_library_path_fds(struct ld_env_var_desc *lvd) 6712 { 6713 ld_library_dirs = lvd->val; 6714 } 6715 6716 static void 6717 rtld_recalc_path_rpath(const char *library_path_rpath) 6718 { 6719 if (library_path_rpath != NULL) { 6720 if (library_path_rpath[0] == 'y' || 6721 library_path_rpath[0] == 'Y' || 6722 library_path_rpath[0] == '1') 6723 ld_library_path_rpath = true; 6724 else 6725 ld_library_path_rpath = false; 6726 } else { 6727 ld_library_path_rpath = false; 6728 } 6729 } 6730 6731 static void 6732 rtld_set_var_library_path_rpath(struct ld_env_var_desc *lvd) 6733 { 6734 rtld_recalc_path_rpath(lvd->val); 6735 } 6736 6737 static void 6738 rtld_recalc_bind_not(const char *bind_not_val) 6739 { 6740 if (ld_bind_now == NULL) 6741 ld_bind_not = bind_not_val != NULL; 6742 } 6743 6744 static void 6745 rtld_set_var_bind_now(struct ld_env_var_desc *lvd) 6746 { 6747 ld_bind_now = lvd->val; 6748 rtld_recalc_bind_not(ld_get_env_var(LD_BIND_NOT)); 6749 } 6750 6751 static void 6752 rtld_set_var_bind_not(struct ld_env_var_desc *lvd) 6753 { 6754 rtld_recalc_bind_not(lvd->val); 6755 } 6756 6757 static void 6758 rtld_set_var_dynamic_weak(struct ld_env_var_desc *lvd) 6759 { 6760 ld_dynamic_weak = lvd->val == NULL; 6761 } 6762 6763 static void 6764 rtld_set_var_loadfltr(struct ld_env_var_desc *lvd) 6765 { 6766 ld_loadfltr = lvd->val != NULL; 6767 } 6768 6769 static void 6770 rtld_set_var_libmap_disable(struct ld_env_var_desc *lvd) 6771 { 6772 libmap_disable = lvd->val != NULL; 6773 } 6774 6775 int 6776 rtld_set_var(const char *name, const char *val) 6777 { 6778 RtldLockState lockstate; 6779 struct ld_env_var_desc *lvd; 6780 u_int i; 6781 int error; 6782 6783 error = ENOENT; 6784 wlock_acquire(rtld_bind_lock, &lockstate); 6785 for (i = 0; i < nitems(ld_env_vars); i++) { 6786 lvd = &ld_env_vars[i]; 6787 if (strcmp(lvd->n, name) != 0) 6788 continue; 6789 if (!lvd->can_update || (lvd->unsecure && !trust)) { 6790 error = EPERM; 6791 break; 6792 } 6793 if (lvd->owned) 6794 free(__DECONST(char *, lvd->val)); 6795 if (val != NULL) 6796 lvd->val = xstrdup(val); 6797 else 6798 lvd->val = NULL; 6799 lvd->owned = true; 6800 if (lvd->on_update != NULL) 6801 lvd->on_update(lvd); 6802 error = 0; 6803 break; 6804 } 6805 if (error == 0) 6806 rtld_recalc_dangerous_ld_env(); 6807 lock_release(rtld_bind_lock, &lockstate); 6808 return (error); 6809 } 6810 6811 /* 6812 * Overrides for libc_pic-provided functions. 6813 */ 6814 6815 int 6816 __getosreldate(void) 6817 { 6818 size_t len; 6819 int oid[2]; 6820 int error, osrel; 6821 6822 if (osreldate != 0) 6823 return (osreldate); 6824 6825 oid[0] = CTL_KERN; 6826 oid[1] = KERN_OSRELDATE; 6827 osrel = 0; 6828 len = sizeof(osrel); 6829 error = sysctl(oid, 2, &osrel, &len, NULL, 0); 6830 if (error == 0 && osrel > 0 && len == sizeof(osrel)) 6831 osreldate = osrel; 6832 return (osreldate); 6833 } 6834 const char * 6835 rtld_strerror(int errnum) 6836 { 6837 if (errnum < 0 || errnum >= sys_nerr) 6838 return ("Unknown error"); 6839 return (sys_errlist[errnum]); 6840 } 6841 6842 char * 6843 getenv(const char *name) 6844 { 6845 return (__DECONST(char *, rtld_get_env_val(environ, name, 6846 strlen(name)))); 6847 } 6848 6849 /* malloc */ 6850 void * 6851 malloc(size_t nbytes) 6852 { 6853 return (__crt_malloc(nbytes)); 6854 } 6855 6856 void * 6857 calloc(size_t num, size_t size) 6858 { 6859 return (__crt_calloc(num, size)); 6860 } 6861 6862 void 6863 free(void *cp) 6864 { 6865 __crt_free(cp); 6866 } 6867 6868 void * 6869 realloc(void *cp, size_t nbytes) 6870 { 6871 return (__crt_realloc(cp, nbytes)); 6872 } 6873 6874 extern int _rtld_version__FreeBSD_version __exported; 6875 int _rtld_version__FreeBSD_version = __FreeBSD_version; 6876 6877 extern char _rtld_version_laddr_offset __exported; 6878 char _rtld_version_laddr_offset; 6879 6880 extern char _rtld_version_dlpi_tls_data __exported; 6881 char _rtld_version_dlpi_tls_data; 6882