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