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