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