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