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