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