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