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