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