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