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