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