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