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