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