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