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