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