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