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