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