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