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