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