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