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