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