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