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