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