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