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