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