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