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