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