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