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