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