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