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