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