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