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