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