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