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