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