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