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