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