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