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