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