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