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