xref: /freebsd/libexec/rtld-elf/rtld.c (revision 3fe92528afe8313fecf48822dde74bad5e380f48)
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, const 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 	DoneList donelist;
1855 	const Objlist *srch_list;
1856 	donelist_init(&donelist);
1857 	if (obj->mainprog) {
1858 	    /* Search main program and all libraries loaded by it. */
1859 	    srch_list = &list_main;
1860 	} else {
1861 	    /* Search the whole DAG rooted at the given object. */
1862 	    srch_list = &(obj->dagmembers);
1863 	}
1864 	def = symlook_list(name, hash, srch_list, &defobj, ve, flags,
1865 			   &donelist);
1866     }
1867 
1868     if (def != NULL) {
1869 	rlock_release(rtld_bind_lock, lockstate);
1870 
1871 	/*
1872 	 * The value required by the caller is derived from the value
1873 	 * of the symbol. For the ia64 architecture, we need to
1874 	 * construct a function descriptor which the caller can use to
1875 	 * call the function with the right 'gp' value. For other
1876 	 * architectures and for non-functions, the value is simply
1877 	 * the relocated value of the symbol.
1878 	 */
1879 	if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1880 	    return make_function_pointer(def, defobj);
1881 	else
1882 	    return defobj->relocbase + def->st_value;
1883     }
1884 
1885     _rtld_error("Undefined symbol \"%s\"", name);
1886     rlock_release(rtld_bind_lock, lockstate);
1887     return NULL;
1888 }
1889 
1890 void *
1891 dlsym(void *handle, const char *name)
1892 {
1893 	return do_dlsym(handle, name, __builtin_return_address(0), NULL,
1894 	    SYMLOOK_DLSYM);
1895 }
1896 
1897 void *
1898 dlvsym(void *handle, const char *name, const char *version)
1899 {
1900 	Ver_Entry ventry;
1901 
1902 	ventry.name = version;
1903 	ventry.file = NULL;
1904 	ventry.hash = elf_hash(version);
1905 	ventry.flags= 0;
1906 	return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
1907 	    SYMLOOK_DLSYM);
1908 }
1909 
1910 int
1911 dladdr(const void *addr, Dl_info *info)
1912 {
1913     const Obj_Entry *obj;
1914     const Elf_Sym *def;
1915     void *symbol_addr;
1916     unsigned long symoffset;
1917     int lockstate;
1918 
1919     lockstate = rlock_acquire(rtld_bind_lock);
1920     obj = obj_from_addr(addr);
1921     if (obj == NULL) {
1922         _rtld_error("No shared object contains address");
1923 	rlock_release(rtld_bind_lock, lockstate);
1924         return 0;
1925     }
1926     info->dli_fname = obj->path;
1927     info->dli_fbase = obj->mapbase;
1928     info->dli_saddr = (void *)0;
1929     info->dli_sname = NULL;
1930 
1931     /*
1932      * Walk the symbol list looking for the symbol whose address is
1933      * closest to the address sent in.
1934      */
1935     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1936         def = obj->symtab + symoffset;
1937 
1938         /*
1939          * For skip the symbol if st_shndx is either SHN_UNDEF or
1940          * SHN_COMMON.
1941          */
1942         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1943             continue;
1944 
1945         /*
1946          * If the symbol is greater than the specified address, or if it
1947          * is further away from addr than the current nearest symbol,
1948          * then reject it.
1949          */
1950         symbol_addr = obj->relocbase + def->st_value;
1951         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1952             continue;
1953 
1954         /* Update our idea of the nearest symbol. */
1955         info->dli_sname = obj->strtab + def->st_name;
1956         info->dli_saddr = symbol_addr;
1957 
1958         /* Exact match? */
1959         if (info->dli_saddr == addr)
1960             break;
1961     }
1962     rlock_release(rtld_bind_lock, lockstate);
1963     return 1;
1964 }
1965 
1966 int
1967 dlinfo(void *handle, int request, void *p)
1968 {
1969     const Obj_Entry *obj;
1970     int error, lockstate;
1971 
1972     lockstate = rlock_acquire(rtld_bind_lock);
1973 
1974     if (handle == NULL || handle == RTLD_SELF) {
1975 	void *retaddr;
1976 
1977 	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
1978 	if ((obj = obj_from_addr(retaddr)) == NULL)
1979 	    _rtld_error("Cannot determine caller's shared object");
1980     } else
1981 	obj = dlcheck(handle);
1982 
1983     if (obj == NULL) {
1984 	rlock_release(rtld_bind_lock, lockstate);
1985 	return (-1);
1986     }
1987 
1988     error = 0;
1989     switch (request) {
1990     case RTLD_DI_LINKMAP:
1991 	*((struct link_map const **)p) = &obj->linkmap;
1992 	break;
1993     case RTLD_DI_ORIGIN:
1994 	error = rtld_dirname(obj->path, p);
1995 	break;
1996 
1997     case RTLD_DI_SERINFOSIZE:
1998     case RTLD_DI_SERINFO:
1999 	error = do_search_info(obj, request, (struct dl_serinfo *)p);
2000 	break;
2001 
2002     default:
2003 	_rtld_error("Invalid request %d passed to dlinfo()", request);
2004 	error = -1;
2005     }
2006 
2007     rlock_release(rtld_bind_lock, lockstate);
2008 
2009     return (error);
2010 }
2011 
2012 struct fill_search_info_args {
2013     int		 request;
2014     unsigned int flags;
2015     Dl_serinfo  *serinfo;
2016     Dl_serpath  *serpath;
2017     char	*strspace;
2018 };
2019 
2020 static void *
2021 fill_search_info(const char *dir, size_t dirlen, void *param)
2022 {
2023     struct fill_search_info_args *arg;
2024 
2025     arg = param;
2026 
2027     if (arg->request == RTLD_DI_SERINFOSIZE) {
2028 	arg->serinfo->dls_cnt ++;
2029 	arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2030     } else {
2031 	struct dl_serpath *s_entry;
2032 
2033 	s_entry = arg->serpath;
2034 	s_entry->dls_name  = arg->strspace;
2035 	s_entry->dls_flags = arg->flags;
2036 
2037 	strncpy(arg->strspace, dir, dirlen);
2038 	arg->strspace[dirlen] = '\0';
2039 
2040 	arg->strspace += dirlen + 1;
2041 	arg->serpath++;
2042     }
2043 
2044     return (NULL);
2045 }
2046 
2047 static int
2048 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2049 {
2050     struct dl_serinfo _info;
2051     struct fill_search_info_args args;
2052 
2053     args.request = RTLD_DI_SERINFOSIZE;
2054     args.serinfo = &_info;
2055 
2056     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2057     _info.dls_cnt  = 0;
2058 
2059     path_enumerate(ld_library_path, fill_search_info, &args);
2060     path_enumerate(obj->rpath, fill_search_info, &args);
2061     path_enumerate(gethints(), fill_search_info, &args);
2062     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2063 
2064 
2065     if (request == RTLD_DI_SERINFOSIZE) {
2066 	info->dls_size = _info.dls_size;
2067 	info->dls_cnt = _info.dls_cnt;
2068 	return (0);
2069     }
2070 
2071     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2072 	_rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2073 	return (-1);
2074     }
2075 
2076     args.request  = RTLD_DI_SERINFO;
2077     args.serinfo  = info;
2078     args.serpath  = &info->dls_serpath[0];
2079     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2080 
2081     args.flags = LA_SER_LIBPATH;
2082     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2083 	return (-1);
2084 
2085     args.flags = LA_SER_RUNPATH;
2086     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2087 	return (-1);
2088 
2089     args.flags = LA_SER_CONFIG;
2090     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2091 	return (-1);
2092 
2093     args.flags = LA_SER_DEFAULT;
2094     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2095 	return (-1);
2096     return (0);
2097 }
2098 
2099 static int
2100 rtld_dirname(const char *path, char *bname)
2101 {
2102     const char *endp;
2103 
2104     /* Empty or NULL string gets treated as "." */
2105     if (path == NULL || *path == '\0') {
2106 	bname[0] = '.';
2107 	bname[1] = '\0';
2108 	return (0);
2109     }
2110 
2111     /* Strip trailing slashes */
2112     endp = path + strlen(path) - 1;
2113     while (endp > path && *endp == '/')
2114 	endp--;
2115 
2116     /* Find the start of the dir */
2117     while (endp > path && *endp != '/')
2118 	endp--;
2119 
2120     /* Either the dir is "/" or there are no slashes */
2121     if (endp == path) {
2122 	bname[0] = *endp == '/' ? '/' : '.';
2123 	bname[1] = '\0';
2124 	return (0);
2125     } else {
2126 	do {
2127 	    endp--;
2128 	} while (endp > path && *endp == '/');
2129     }
2130 
2131     if (endp - path + 2 > PATH_MAX)
2132     {
2133 	_rtld_error("Filename is too long: %s", path);
2134 	return(-1);
2135     }
2136 
2137     strncpy(bname, path, endp - path + 1);
2138     bname[endp - path + 1] = '\0';
2139     return (0);
2140 }
2141 
2142 static void
2143 linkmap_add(Obj_Entry *obj)
2144 {
2145     struct link_map *l = &obj->linkmap;
2146     struct link_map *prev;
2147 
2148     obj->linkmap.l_name = obj->path;
2149     obj->linkmap.l_addr = obj->mapbase;
2150     obj->linkmap.l_ld = obj->dynamic;
2151 #ifdef __mips__
2152     /* GDB needs load offset on MIPS to use the symbols */
2153     obj->linkmap.l_offs = obj->relocbase;
2154 #endif
2155 
2156     if (r_debug.r_map == NULL) {
2157 	r_debug.r_map = l;
2158 	return;
2159     }
2160 
2161     /*
2162      * Scan to the end of the list, but not past the entry for the
2163      * dynamic linker, which we want to keep at the very end.
2164      */
2165     for (prev = r_debug.r_map;
2166       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2167       prev = prev->l_next)
2168 	;
2169 
2170     /* Link in the new entry. */
2171     l->l_prev = prev;
2172     l->l_next = prev->l_next;
2173     if (l->l_next != NULL)
2174 	l->l_next->l_prev = l;
2175     prev->l_next = l;
2176 }
2177 
2178 static void
2179 linkmap_delete(Obj_Entry *obj)
2180 {
2181     struct link_map *l = &obj->linkmap;
2182 
2183     if (l->l_prev == NULL) {
2184 	if ((r_debug.r_map = l->l_next) != NULL)
2185 	    l->l_next->l_prev = NULL;
2186 	return;
2187     }
2188 
2189     if ((l->l_prev->l_next = l->l_next) != NULL)
2190 	l->l_next->l_prev = l->l_prev;
2191 }
2192 
2193 /*
2194  * Function for the debugger to set a breakpoint on to gain control.
2195  *
2196  * The two parameters allow the debugger to easily find and determine
2197  * what the runtime loader is doing and to whom it is doing it.
2198  *
2199  * When the loadhook trap is hit (r_debug_state, set at program
2200  * initialization), the arguments can be found on the stack:
2201  *
2202  *  +8   struct link_map *m
2203  *  +4   struct r_debug  *rd
2204  *  +0   RetAddr
2205  */
2206 void
2207 r_debug_state(struct r_debug* rd, struct link_map *m)
2208 {
2209 }
2210 
2211 /*
2212  * Get address of the pointer variable in the main program.
2213  */
2214 static const void **
2215 get_program_var_addr(const char *name)
2216 {
2217     const Obj_Entry *obj;
2218     unsigned long hash;
2219 
2220     hash = elf_hash(name);
2221     for (obj = obj_main;  obj != NULL;  obj = obj->next) {
2222 	const Elf_Sym *def;
2223 
2224 	if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2225 	    const void **addr;
2226 
2227 	    addr = (const void **)(obj->relocbase + def->st_value);
2228 	    return addr;
2229 	}
2230     }
2231     return NULL;
2232 }
2233 
2234 /*
2235  * Set a pointer variable in the main program to the given value.  This
2236  * is used to set key variables such as "environ" before any of the
2237  * init functions are called.
2238  */
2239 static void
2240 set_program_var(const char *name, const void *value)
2241 {
2242     const void **addr;
2243 
2244     if ((addr = get_program_var_addr(name)) != NULL) {
2245 	dbg("\"%s\": *%p <-- %p", name, addr, value);
2246 	*addr = value;
2247     }
2248 }
2249 
2250 /*
2251  * Given a symbol name in a referencing object, find the corresponding
2252  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
2253  * no definition was found.  Returns a pointer to the Obj_Entry of the
2254  * defining object via the reference parameter DEFOBJ_OUT.
2255  */
2256 static const Elf_Sym *
2257 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2258     const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2259 {
2260     DoneList donelist;
2261     const Elf_Sym *def;
2262     const Elf_Sym *symp;
2263     const Obj_Entry *obj;
2264     const Obj_Entry *defobj;
2265     const Objlist_Entry *elm;
2266     def = NULL;
2267     defobj = NULL;
2268     donelist_init(&donelist);
2269 
2270     /* Look first in the referencing object if linked symbolically. */
2271     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2272 	symp = symlook_obj(name, hash, refobj, ventry, flags);
2273 	if (symp != NULL) {
2274 	    def = symp;
2275 	    defobj = refobj;
2276 	}
2277     }
2278 
2279     /* Search all objects loaded at program start up. */
2280     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2281 	symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2282 	    &donelist);
2283 	if (symp != NULL &&
2284 	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2285 	    def = symp;
2286 	    defobj = obj;
2287 	}
2288     }
2289 
2290     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2291     STAILQ_FOREACH(elm, &list_global, link) {
2292        if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2293            break;
2294        symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2295 	   flags, &donelist);
2296 	if (symp != NULL &&
2297 	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2298 	    def = symp;
2299 	    defobj = obj;
2300 	}
2301     }
2302 
2303     /* Search all dlopened DAGs containing the referencing object. */
2304     STAILQ_FOREACH(elm, &refobj->dldags, link) {
2305 	if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2306 	    break;
2307 	symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2308 	    flags, &donelist);
2309 	if (symp != NULL &&
2310 	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2311 	    def = symp;
2312 	    defobj = obj;
2313 	}
2314     }
2315 
2316     /*
2317      * Search the dynamic linker itself, and possibly resolve the
2318      * symbol from there.  This is how the application links to
2319      * dynamic linker services such as dlopen.  Only the values listed
2320      * in the "exports" array can be resolved from the dynamic linker.
2321      */
2322     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2323 	symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2324 	if (symp != NULL && is_exported(symp)) {
2325 	    def = symp;
2326 	    defobj = &obj_rtld;
2327 	}
2328     }
2329 
2330     if (def != NULL)
2331 	*defobj_out = defobj;
2332     return def;
2333 }
2334 
2335 static const Elf_Sym *
2336 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2337   const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2338   DoneList *dlp)
2339 {
2340     const Elf_Sym *symp;
2341     const Elf_Sym *def;
2342     const Obj_Entry *defobj;
2343     const Objlist_Entry *elm;
2344 
2345     def = NULL;
2346     defobj = NULL;
2347     STAILQ_FOREACH(elm, objlist, link) {
2348 	if (donelist_check(dlp, elm->obj))
2349 	    continue;
2350 	if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2351 	    if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2352 		def = symp;
2353 		defobj = elm->obj;
2354 		if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2355 		    break;
2356 	    }
2357 	}
2358     }
2359     if (def != NULL)
2360 	*defobj_out = defobj;
2361     return def;
2362 }
2363 
2364 /*
2365  * Search the symbol table of a single shared object for a symbol of
2366  * the given name and version, if requested.  Returns a pointer to the
2367  * symbol, or NULL if no definition was found.
2368  *
2369  * The symbol's hash value is passed in for efficiency reasons; that
2370  * eliminates many recomputations of the hash value.
2371  */
2372 const Elf_Sym *
2373 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2374     const Ver_Entry *ventry, int flags)
2375 {
2376     unsigned long symnum;
2377     const Elf_Sym *vsymp;
2378     Elf_Versym verndx;
2379     int vcount;
2380 
2381     if (obj->buckets == NULL)
2382 	return NULL;
2383 
2384     vsymp = NULL;
2385     vcount = 0;
2386     symnum = obj->buckets[hash % obj->nbuckets];
2387 
2388     for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
2389 	const Elf_Sym *symp;
2390 	const char *strp;
2391 
2392 	if (symnum >= obj->nchains)
2393 		return NULL;	/* Bad object */
2394 
2395 	symp = obj->symtab + symnum;
2396 	strp = obj->strtab + symp->st_name;
2397 
2398 	switch (ELF_ST_TYPE(symp->st_info)) {
2399 	case STT_FUNC:
2400 	case STT_NOTYPE:
2401 	case STT_OBJECT:
2402 	    if (symp->st_value == 0)
2403 		continue;
2404 		/* fallthrough */
2405 	case STT_TLS:
2406 	    if (symp->st_shndx != SHN_UNDEF ||
2407 		((flags & SYMLOOK_IN_PLT) == 0 &&
2408 		 ELF_ST_TYPE(symp->st_info) == STT_FUNC))
2409 		break;
2410 		/* fallthrough */
2411 	default:
2412 	    continue;
2413 	}
2414 	if (name[0] != strp[0] || strcmp(name, strp) != 0)
2415 	    continue;
2416 
2417 	if (ventry == NULL) {
2418 	    if (obj->versyms != NULL) {
2419 		verndx = VER_NDX(obj->versyms[symnum]);
2420 		if (verndx > obj->vernum) {
2421 		    _rtld_error("%s: symbol %s references wrong version %d",
2422 			obj->path, obj->strtab + symnum, verndx);
2423 		    continue;
2424 		}
2425 		/*
2426 		 * If we are not called from dlsym (i.e. this is a normal
2427 		 * relocation from unversioned binary, accept the symbol
2428 		 * immediately if it happens to have first version after
2429 		 * this shared object became versioned. Otherwise, if
2430 		 * symbol is versioned and not hidden, remember it. If it
2431 		 * is the only symbol with this name exported by the
2432 		 * shared object, it will be returned as a match at the
2433 		 * end of the function. If symbol is global (verndx < 2)
2434 		 * accept it unconditionally.
2435 		 */
2436 		if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
2437 		    return symp;
2438 	        else if (verndx >= VER_NDX_GIVEN) {
2439 		    if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
2440 			if (vsymp == NULL)
2441 			    vsymp = symp;
2442 			vcount ++;
2443 		    }
2444 		    continue;
2445 		}
2446 	    }
2447 	    return symp;
2448 	} else {
2449 	    if (obj->versyms == NULL) {
2450 		if (object_match_name(obj, ventry->name)) {
2451 		    _rtld_error("%s: object %s should provide version %s for "
2452 			"symbol %s", obj_rtld.path, obj->path, ventry->name,
2453 			obj->strtab + symnum);
2454 		    continue;
2455 		}
2456 	    } else {
2457 		verndx = VER_NDX(obj->versyms[symnum]);
2458 		if (verndx > obj->vernum) {
2459 		    _rtld_error("%s: symbol %s references wrong version %d",
2460 			obj->path, obj->strtab + symnum, verndx);
2461 		    continue;
2462 		}
2463 		if (obj->vertab[verndx].hash != ventry->hash ||
2464 		    strcmp(obj->vertab[verndx].name, ventry->name)) {
2465 		    /*
2466 		     * Version does not match. Look if this is a global symbol
2467 		     * and if it is not hidden. If global symbol (verndx < 2)
2468 		     * is available, use it. Do not return symbol if we are
2469 		     * called by dlvsym, because dlvsym looks for a specific
2470 		     * version and default one is not what dlvsym wants.
2471 		     */
2472 		    if ((flags & SYMLOOK_DLSYM) ||
2473 			(obj->versyms[symnum] & VER_NDX_HIDDEN) ||
2474 			(verndx >= VER_NDX_GIVEN))
2475 			continue;
2476 		}
2477 	    }
2478 	    return symp;
2479 	}
2480     }
2481     return (vcount == 1) ? vsymp : NULL;
2482 }
2483 
2484 static void
2485 trace_loaded_objects(Obj_Entry *obj)
2486 {
2487     char	*fmt1, *fmt2, *fmt, *main_local, *list_containers;
2488     int		c;
2489 
2490     if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2491 	main_local = "";
2492 
2493     if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2494 	fmt1 = "\t%o => %p (%x)\n";
2495 
2496     if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2497 	fmt2 = "\t%o (%x)\n";
2498 
2499     list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2500 
2501     for (; obj; obj = obj->next) {
2502 	Needed_Entry		*needed;
2503 	char			*name, *path;
2504 	bool			is_lib;
2505 
2506 	if (list_containers && obj->needed != NULL)
2507 	    printf("%s:\n", obj->path);
2508 	for (needed = obj->needed; needed; needed = needed->next) {
2509 	    if (needed->obj != NULL) {
2510 		if (needed->obj->traced && !list_containers)
2511 		    continue;
2512 		needed->obj->traced = true;
2513 		path = needed->obj->path;
2514 	    } else
2515 		path = "not found";
2516 
2517 	    name = (char *)obj->strtab + needed->name;
2518 	    is_lib = strncmp(name, "lib", 3) == 0;	/* XXX - bogus */
2519 
2520 	    fmt = is_lib ? fmt1 : fmt2;
2521 	    while ((c = *fmt++) != '\0') {
2522 		switch (c) {
2523 		default:
2524 		    putchar(c);
2525 		    continue;
2526 		case '\\':
2527 		    switch (c = *fmt) {
2528 		    case '\0':
2529 			continue;
2530 		    case 'n':
2531 			putchar('\n');
2532 			break;
2533 		    case 't':
2534 			putchar('\t');
2535 			break;
2536 		    }
2537 		    break;
2538 		case '%':
2539 		    switch (c = *fmt) {
2540 		    case '\0':
2541 			continue;
2542 		    case '%':
2543 		    default:
2544 			putchar(c);
2545 			break;
2546 		    case 'A':
2547 			printf("%s", main_local);
2548 			break;
2549 		    case 'a':
2550 			printf("%s", obj_main->path);
2551 			break;
2552 		    case 'o':
2553 			printf("%s", name);
2554 			break;
2555 #if 0
2556 		    case 'm':
2557 			printf("%d", sodp->sod_major);
2558 			break;
2559 		    case 'n':
2560 			printf("%d", sodp->sod_minor);
2561 			break;
2562 #endif
2563 		    case 'p':
2564 			printf("%s", path);
2565 			break;
2566 		    case 'x':
2567 			printf("%p", needed->obj ? needed->obj->mapbase : 0);
2568 			break;
2569 		    }
2570 		    break;
2571 		}
2572 		++fmt;
2573 	    }
2574 	}
2575     }
2576 }
2577 
2578 /*
2579  * Unload a dlopened object and its dependencies from memory and from
2580  * our data structures.  It is assumed that the DAG rooted in the
2581  * object has already been unreferenced, and that the object has a
2582  * reference count of 0.
2583  */
2584 static void
2585 unload_object(Obj_Entry *root)
2586 {
2587     Obj_Entry *obj;
2588     Obj_Entry **linkp;
2589 
2590     assert(root->refcount == 0);
2591 
2592     /*
2593      * Pass over the DAG removing unreferenced objects from
2594      * appropriate lists.
2595      */
2596     unlink_object(root);
2597 
2598     /* Unmap all objects that are no longer referenced. */
2599     linkp = &obj_list->next;
2600     while ((obj = *linkp) != NULL) {
2601 	if (obj->refcount == 0) {
2602 	    dbg("unloading \"%s\"", obj->path);
2603 	    munmap(obj->mapbase, obj->mapsize);
2604 	    linkmap_delete(obj);
2605 	    *linkp = obj->next;
2606 	    obj_count--;
2607 	    obj_free(obj);
2608 	} else
2609 	    linkp = &obj->next;
2610     }
2611     obj_tail = linkp;
2612 }
2613 
2614 static void
2615 unlink_object(Obj_Entry *root)
2616 {
2617     Objlist_Entry *elm;
2618 
2619     if (root->refcount == 0) {
2620 	/* Remove the object from the RTLD_GLOBAL list. */
2621 	objlist_remove(&list_global, root);
2622 
2623     	/* Remove the object from all objects' DAG lists. */
2624     	STAILQ_FOREACH(elm, &root->dagmembers, link) {
2625 	    objlist_remove(&elm->obj->dldags, root);
2626 	    if (elm->obj != root)
2627 		unlink_object(elm->obj);
2628 	}
2629     }
2630 }
2631 
2632 static void
2633 ref_dag(Obj_Entry *root)
2634 {
2635     Objlist_Entry *elm;
2636 
2637     STAILQ_FOREACH(elm, &root->dagmembers, link)
2638 	elm->obj->refcount++;
2639 }
2640 
2641 static void
2642 unref_dag(Obj_Entry *root)
2643 {
2644     Objlist_Entry *elm;
2645 
2646     STAILQ_FOREACH(elm, &root->dagmembers, link)
2647 	elm->obj->refcount--;
2648 }
2649 
2650 /*
2651  * Common code for MD __tls_get_addr().
2652  */
2653 void *
2654 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
2655 {
2656     Elf_Addr* dtv = *dtvp;
2657     int lockstate;
2658 
2659     /* Check dtv generation in case new modules have arrived */
2660     if (dtv[0] != tls_dtv_generation) {
2661 	Elf_Addr* newdtv;
2662 	int to_copy;
2663 
2664 	lockstate = wlock_acquire(rtld_bind_lock);
2665 	newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2666 	to_copy = dtv[1];
2667 	if (to_copy > tls_max_index)
2668 	    to_copy = tls_max_index;
2669 	memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2670 	newdtv[0] = tls_dtv_generation;
2671 	newdtv[1] = tls_max_index;
2672 	free(dtv);
2673 	wlock_release(rtld_bind_lock, lockstate);
2674 	*dtvp = newdtv;
2675     }
2676 
2677     /* Dynamically allocate module TLS if necessary */
2678     if (!dtv[index + 1]) {
2679 	/* Signal safe, wlock will block out signals. */
2680 	lockstate = wlock_acquire(rtld_bind_lock);
2681 	if (!dtv[index + 1])
2682 	    dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2683 	wlock_release(rtld_bind_lock, lockstate);
2684     }
2685     return (void*) (dtv[index + 1] + offset);
2686 }
2687 
2688 /* XXX not sure what variants to use for arm. */
2689 
2690 #if defined(__ia64__) || defined(__powerpc__)
2691 
2692 /*
2693  * Allocate Static TLS using the Variant I method.
2694  */
2695 void *
2696 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
2697 {
2698     Obj_Entry *obj;
2699     char *tcb;
2700     Elf_Addr **tls;
2701     Elf_Addr *dtv;
2702     Elf_Addr addr;
2703     int i;
2704 
2705     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
2706 	return (oldtcb);
2707 
2708     assert(tcbsize >= TLS_TCB_SIZE);
2709     tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
2710     tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
2711 
2712     if (oldtcb != NULL) {
2713 	memcpy(tls, oldtcb, tls_static_space);
2714 	free(oldtcb);
2715 
2716 	/* Adjust the DTV. */
2717 	dtv = tls[0];
2718 	for (i = 0; i < dtv[1]; i++) {
2719 	    if (dtv[i+2] >= (Elf_Addr)oldtcb &&
2720 		dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
2721 		dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
2722 	    }
2723 	}
2724     } else {
2725 	dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
2726 	tls[0] = dtv;
2727 	dtv[0] = tls_dtv_generation;
2728 	dtv[1] = tls_max_index;
2729 
2730 	for (obj = objs; obj; obj = obj->next) {
2731 	    if (obj->tlsoffset) {
2732 		addr = (Elf_Addr)tls + obj->tlsoffset;
2733 		memset((void*) (addr + obj->tlsinitsize),
2734 		       0, obj->tlssize - obj->tlsinitsize);
2735 		if (obj->tlsinit)
2736 		    memcpy((void*) addr, obj->tlsinit,
2737 			   obj->tlsinitsize);
2738 		dtv[obj->tlsindex + 1] = addr;
2739 	    }
2740 	}
2741     }
2742 
2743     return (tcb);
2744 }
2745 
2746 void
2747 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2748 {
2749     Elf_Addr *dtv;
2750     Elf_Addr tlsstart, tlsend;
2751     int dtvsize, i;
2752 
2753     assert(tcbsize >= TLS_TCB_SIZE);
2754 
2755     tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
2756     tlsend = tlsstart + tls_static_space;
2757 
2758     dtv = *(Elf_Addr **)tlsstart;
2759     dtvsize = dtv[1];
2760     for (i = 0; i < dtvsize; i++) {
2761 	if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
2762 	    free((void*)dtv[i+2]);
2763 	}
2764     }
2765     free(dtv);
2766     free(tcb);
2767 }
2768 
2769 #endif
2770 
2771 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2772     defined(__arm__)
2773 
2774 /*
2775  * Allocate Static TLS using the Variant II method.
2776  */
2777 void *
2778 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2779 {
2780     Obj_Entry *obj;
2781     size_t size;
2782     char *tls;
2783     Elf_Addr *dtv, *olddtv;
2784     Elf_Addr segbase, oldsegbase, addr;
2785     int i;
2786 
2787     size = round(tls_static_space, tcbalign);
2788 
2789     assert(tcbsize >= 2*sizeof(Elf_Addr));
2790     tls = calloc(1, size + tcbsize);
2791     dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2792 
2793     segbase = (Elf_Addr)(tls + size);
2794     ((Elf_Addr*)segbase)[0] = segbase;
2795     ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
2796 
2797     dtv[0] = tls_dtv_generation;
2798     dtv[1] = tls_max_index;
2799 
2800     if (oldtls) {
2801 	/*
2802 	 * Copy the static TLS block over whole.
2803 	 */
2804 	oldsegbase = (Elf_Addr) oldtls;
2805 	memcpy((void *)(segbase - tls_static_space),
2806 	       (const void *)(oldsegbase - tls_static_space),
2807 	       tls_static_space);
2808 
2809 	/*
2810 	 * If any dynamic TLS blocks have been created tls_get_addr(),
2811 	 * move them over.
2812 	 */
2813 	olddtv = ((Elf_Addr**)oldsegbase)[1];
2814 	for (i = 0; i < olddtv[1]; i++) {
2815 	    if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
2816 		dtv[i+2] = olddtv[i+2];
2817 		olddtv[i+2] = 0;
2818 	    }
2819 	}
2820 
2821 	/*
2822 	 * We assume that this block was the one we created with
2823 	 * allocate_initial_tls().
2824 	 */
2825 	free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
2826     } else {
2827 	for (obj = objs; obj; obj = obj->next) {
2828 	    if (obj->tlsoffset) {
2829 		addr = segbase - obj->tlsoffset;
2830 		memset((void*) (addr + obj->tlsinitsize),
2831 		       0, obj->tlssize - obj->tlsinitsize);
2832 		if (obj->tlsinit)
2833 		    memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2834 		dtv[obj->tlsindex + 1] = addr;
2835 	    }
2836 	}
2837     }
2838 
2839     return (void*) segbase;
2840 }
2841 
2842 void
2843 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
2844 {
2845     size_t size;
2846     Elf_Addr* dtv;
2847     int dtvsize, i;
2848     Elf_Addr tlsstart, tlsend;
2849 
2850     /*
2851      * Figure out the size of the initial TLS block so that we can
2852      * find stuff which ___tls_get_addr() allocated dynamically.
2853      */
2854     size = round(tls_static_space, tcbalign);
2855 
2856     dtv = ((Elf_Addr**)tls)[1];
2857     dtvsize = dtv[1];
2858     tlsend = (Elf_Addr) tls;
2859     tlsstart = tlsend - size;
2860     for (i = 0; i < dtvsize; i++) {
2861 	if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
2862 	    free((void*) dtv[i+2]);
2863 	}
2864     }
2865 
2866     free((void*) tlsstart);
2867 }
2868 
2869 #endif
2870 
2871 /*
2872  * Allocate TLS block for module with given index.
2873  */
2874 void *
2875 allocate_module_tls(int index)
2876 {
2877     Obj_Entry* obj;
2878     char* p;
2879 
2880     for (obj = obj_list; obj; obj = obj->next) {
2881 	if (obj->tlsindex == index)
2882 	    break;
2883     }
2884     if (!obj) {
2885 	_rtld_error("Can't find module with TLS index %d", index);
2886 	die();
2887     }
2888 
2889     p = malloc(obj->tlssize);
2890     memcpy(p, obj->tlsinit, obj->tlsinitsize);
2891     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2892 
2893     return p;
2894 }
2895 
2896 bool
2897 allocate_tls_offset(Obj_Entry *obj)
2898 {
2899     size_t off;
2900 
2901     if (obj->tls_done)
2902 	return true;
2903 
2904     if (obj->tlssize == 0) {
2905 	obj->tls_done = true;
2906 	return true;
2907     }
2908 
2909     if (obj->tlsindex == 1)
2910 	off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2911     else
2912 	off = calculate_tls_offset(tls_last_offset, tls_last_size,
2913 				   obj->tlssize, obj->tlsalign);
2914 
2915     /*
2916      * If we have already fixed the size of the static TLS block, we
2917      * must stay within that size. When allocating the static TLS, we
2918      * leave a small amount of space spare to be used for dynamically
2919      * loading modules which use static TLS.
2920      */
2921     if (tls_static_space) {
2922 	if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2923 	    return false;
2924     }
2925 
2926     tls_last_offset = obj->tlsoffset = off;
2927     tls_last_size = obj->tlssize;
2928     obj->tls_done = true;
2929 
2930     return true;
2931 }
2932 
2933 void
2934 free_tls_offset(Obj_Entry *obj)
2935 {
2936 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2937     defined(__arm__)
2938     /*
2939      * If we were the last thing to allocate out of the static TLS
2940      * block, we give our space back to the 'allocator'. This is a
2941      * simplistic workaround to allow libGL.so.1 to be loaded and
2942      * unloaded multiple times. We only handle the Variant II
2943      * mechanism for now - this really needs a proper allocator.
2944      */
2945     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2946 	== calculate_tls_end(tls_last_offset, tls_last_size)) {
2947 	tls_last_offset -= obj->tlssize;
2948 	tls_last_size = 0;
2949     }
2950 #endif
2951 }
2952 
2953 void *
2954 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
2955 {
2956     void *ret;
2957     int lockstate;
2958 
2959     lockstate = wlock_acquire(rtld_bind_lock);
2960     ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
2961     wlock_release(rtld_bind_lock, lockstate);
2962     return (ret);
2963 }
2964 
2965 void
2966 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2967 {
2968     int lockstate;
2969 
2970     lockstate = wlock_acquire(rtld_bind_lock);
2971     free_tls(tcb, tcbsize, tcbalign);
2972     wlock_release(rtld_bind_lock, lockstate);
2973 }
2974 
2975 static void
2976 object_add_name(Obj_Entry *obj, const char *name)
2977 {
2978     Name_Entry *entry;
2979     size_t len;
2980 
2981     len = strlen(name);
2982     entry = malloc(sizeof(Name_Entry) + len);
2983 
2984     if (entry != NULL) {
2985 	strcpy(entry->name, name);
2986 	STAILQ_INSERT_TAIL(&obj->names, entry, link);
2987     }
2988 }
2989 
2990 static int
2991 object_match_name(const Obj_Entry *obj, const char *name)
2992 {
2993     Name_Entry *entry;
2994 
2995     STAILQ_FOREACH(entry, &obj->names, link) {
2996 	if (strcmp(name, entry->name) == 0)
2997 	    return (1);
2998     }
2999     return (0);
3000 }
3001 
3002 static Obj_Entry *
3003 locate_dependency(const Obj_Entry *obj, const char *name)
3004 {
3005     const Objlist_Entry *entry;
3006     const Needed_Entry *needed;
3007 
3008     STAILQ_FOREACH(entry, &list_main, link) {
3009 	if (object_match_name(entry->obj, name))
3010 	    return entry->obj;
3011     }
3012 
3013     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
3014 	if (needed->obj == NULL)
3015 	    continue;
3016 	if (object_match_name(needed->obj, name))
3017 	    return needed->obj;
3018     }
3019     _rtld_error("%s: Unexpected  inconsistency: dependency %s not found",
3020 	obj->path, name);
3021     die();
3022 }
3023 
3024 static int
3025 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3026     const Elf_Vernaux *vna)
3027 {
3028     const Elf_Verdef *vd;
3029     const char *vername;
3030 
3031     vername = refobj->strtab + vna->vna_name;
3032     vd = depobj->verdef;
3033     if (vd == NULL) {
3034 	_rtld_error("%s: version %s required by %s not defined",
3035 	    depobj->path, vername, refobj->path);
3036 	return (-1);
3037     }
3038     for (;;) {
3039 	if (vd->vd_version != VER_DEF_CURRENT) {
3040 	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3041 		depobj->path, vd->vd_version);
3042 	    return (-1);
3043 	}
3044 	if (vna->vna_hash == vd->vd_hash) {
3045 	    const Elf_Verdaux *aux = (const Elf_Verdaux *)
3046 		((char *)vd + vd->vd_aux);
3047 	    if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3048 		return (0);
3049 	}
3050 	if (vd->vd_next == 0)
3051 	    break;
3052 	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3053     }
3054     if (vna->vna_flags & VER_FLG_WEAK)
3055 	return (0);
3056     _rtld_error("%s: version %s required by %s not found",
3057 	depobj->path, vername, refobj->path);
3058     return (-1);
3059 }
3060 
3061 static int
3062 rtld_verify_object_versions(Obj_Entry *obj)
3063 {
3064     const Elf_Verneed *vn;
3065     const Elf_Verdef  *vd;
3066     const Elf_Verdaux *vda;
3067     const Elf_Vernaux *vna;
3068     const Obj_Entry *depobj;
3069     int maxvernum, vernum;
3070 
3071     maxvernum = 0;
3072     /*
3073      * Walk over defined and required version records and figure out
3074      * max index used by any of them. Do very basic sanity checking
3075      * while there.
3076      */
3077     vn = obj->verneed;
3078     while (vn != NULL) {
3079 	if (vn->vn_version != VER_NEED_CURRENT) {
3080 	    _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3081 		obj->path, vn->vn_version);
3082 	    return (-1);
3083 	}
3084 	vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3085 	for (;;) {
3086 	    vernum = VER_NEED_IDX(vna->vna_other);
3087 	    if (vernum > maxvernum)
3088 		maxvernum = vernum;
3089 	    if (vna->vna_next == 0)
3090 		 break;
3091 	    vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3092 	}
3093 	if (vn->vn_next == 0)
3094 	    break;
3095 	vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3096     }
3097 
3098     vd = obj->verdef;
3099     while (vd != NULL) {
3100 	if (vd->vd_version != VER_DEF_CURRENT) {
3101 	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3102 		obj->path, vd->vd_version);
3103 	    return (-1);
3104 	}
3105 	vernum = VER_DEF_IDX(vd->vd_ndx);
3106 	if (vernum > maxvernum)
3107 		maxvernum = vernum;
3108 	if (vd->vd_next == 0)
3109 	    break;
3110 	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3111     }
3112 
3113     if (maxvernum == 0)
3114 	return (0);
3115 
3116     /*
3117      * Store version information in array indexable by version index.
3118      * Verify that object version requirements are satisfied along the
3119      * way.
3120      */
3121     obj->vernum = maxvernum + 1;
3122     obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3123 
3124     vd = obj->verdef;
3125     while (vd != NULL) {
3126 	if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3127 	    vernum = VER_DEF_IDX(vd->vd_ndx);
3128 	    assert(vernum <= maxvernum);
3129 	    vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3130 	    obj->vertab[vernum].hash = vd->vd_hash;
3131 	    obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3132 	    obj->vertab[vernum].file = NULL;
3133 	    obj->vertab[vernum].flags = 0;
3134 	}
3135 	if (vd->vd_next == 0)
3136 	    break;
3137 	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3138     }
3139 
3140     vn = obj->verneed;
3141     while (vn != NULL) {
3142 	depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3143 	vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3144 	for (;;) {
3145 	    if (check_object_provided_version(obj, depobj, vna))
3146 		return (-1);
3147 	    vernum = VER_NEED_IDX(vna->vna_other);
3148 	    assert(vernum <= maxvernum);
3149 	    obj->vertab[vernum].hash = vna->vna_hash;
3150 	    obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3151 	    obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3152 	    obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3153 		VER_INFO_HIDDEN : 0;
3154 	    if (vna->vna_next == 0)
3155 		 break;
3156 	    vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3157 	}
3158 	if (vn->vn_next == 0)
3159 	    break;
3160 	vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3161     }
3162     return 0;
3163 }
3164 
3165 static int
3166 rtld_verify_versions(const Objlist *objlist)
3167 {
3168     Objlist_Entry *entry;
3169     int rc;
3170 
3171     rc = 0;
3172     STAILQ_FOREACH(entry, objlist, link) {
3173 	/*
3174 	 * Skip dummy objects or objects that have their version requirements
3175 	 * already checked.
3176 	 */
3177 	if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3178 	    continue;
3179 	if (rtld_verify_object_versions(entry->obj) == -1) {
3180 	    rc = -1;
3181 	    if (ld_tracing == NULL)
3182 		break;
3183 	}
3184     }
3185     return rc;
3186 }
3187 
3188 const Ver_Entry *
3189 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3190 {
3191     Elf_Versym vernum;
3192 
3193     if (obj->vertab) {
3194 	vernum = VER_NDX(obj->versyms[symnum]);
3195 	if (vernum >= obj->vernum) {
3196 	    _rtld_error("%s: symbol %s has wrong verneed value %d",
3197 		obj->path, obj->strtab + symnum, vernum);
3198 	} else if (obj->vertab[vernum].hash != 0) {
3199 	    return &obj->vertab[vernum];
3200 	}
3201     }
3202     return NULL;
3203 }
3204