xref: /freebsd/libexec/rtld-elf/rtld.c (revision 601752d5a7bef087e755da5a2b158fa35cb51ccb)
1 /*-
2  * Copyright 1996-1998 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  *      $Id: rtld.c,v 1.20 1999/04/09 00:28:31 jdp Exp $
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 
41 #include <dlfcn.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "debug.h"
52 #include "rtld.h"
53 
54 /*
55  * Version number queried by dlversion().  The first 3 digits represent
56  * the base FreeBSD release.  The last 3 digits are a serial number.
57  * Increase this when you fix a significant bug or add a significant
58  * feature.
59  */
60 #define DL_VERSION	400001
61 
62 /*
63  * Debugging support.
64  */
65 
66 #define assert(cond)	((cond) ? (void) 0 :\
67     (msg("oops: " __XSTRING(__LINE__) "\n"), abort()))
68 #define msg(s)		(write(1, s, strlen(s)))
69 #define trace()		msg("trace: " __XSTRING(__LINE__) "\n");
70 
71 #define END_SYM		"end"
72 
73 /* Types. */
74 typedef void (*func_ptr_type)();
75 
76 /*
77  * Function declarations.
78  */
79 static void call_fini_functions(Obj_Entry *);
80 static void call_init_functions(Obj_Entry *);
81 static void die(void);
82 static void digest_dynamic(Obj_Entry *);
83 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t);
84 static Obj_Entry *dlcheck(void *);
85 static char *find_library(const char *, const Obj_Entry *);
86 static const char *gethints(void);
87 static void init_rtld(caddr_t);
88 static bool is_exported(const Elf_Sym *);
89 static void linkmap_add(Obj_Entry *);
90 static void linkmap_delete(Obj_Entry *);
91 static int load_needed_objects(Obj_Entry *);
92 static int load_preload_objects(void);
93 static Obj_Entry *load_object(char *);
94 static Obj_Entry *obj_from_addr(const void *);
95 static int relocate_objects(Obj_Entry *, bool);
96 static void rtld_exit(void);
97 static char *search_library_path(const char *, const char *);
98 static void unref_object_dag(Obj_Entry *);
99 static void trace_loaded_objects(Obj_Entry *obj);
100 
101 void r_debug_state(void);
102 void xprintf(const char *, ...);
103 
104 #ifdef DEBUG
105 static const char *basename(const char *);
106 #endif
107 
108 /*
109  * Data declarations.
110  */
111 static char *error_message;	/* Message for dlerror(), or NULL */
112 struct r_debug r_debug;	/* for GDB; */
113 static bool trust;		/* False for setuid and setgid programs */
114 static char *ld_bind_now;	/* Environment variable for immediate binding */
115 static char *ld_debug;		/* Environment variable for debugging */
116 static char *ld_library_path;	/* Environment variable for search path */
117 static char *ld_preload;	/* Environment variable for libraries to
118 				   load first */
119 static char *ld_tracing;	/* Called from ldd to print libs */
120 static Obj_Entry **main_tail;	/* Value of obj_tail after loading main and
121 				   its needed shared libraries */
122 static Obj_Entry *obj_list;	/* Head of linked list of shared objects */
123 static Obj_Entry **obj_tail;	/* Link field of last object in list */
124 static Obj_Entry *obj_main;	/* The main program shared object */
125 static Obj_Entry obj_rtld;	/* The dynamic linker shared object */
126 
127 static Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
128 
129 #define GDB_STATE(s)	r_debug.r_state = s; r_debug_state();
130 
131 extern Elf_Dyn _DYNAMIC;
132 #pragma weak _DYNAMIC
133 
134 /*
135  * These are the functions the dynamic linker exports to application
136  * programs.  They are the only symbols the dynamic linker is willing
137  * to export from itself.
138  */
139 static func_ptr_type exports[] = {
140     (func_ptr_type) &_rtld_error,
141     (func_ptr_type) &dlclose,
142     (func_ptr_type) &dlerror,
143     (func_ptr_type) &dlopen,
144     (func_ptr_type) &dlsym,
145     (func_ptr_type) &dladdr,
146     (func_ptr_type) &dlversion,
147     NULL
148 };
149 
150 /*
151  * Global declarations normally provided by crt1.  The dynamic linker is
152  * not build with crt1, so we have to provide them ourselves.
153  */
154 char *__progname;
155 char **environ;
156 
157 /*
158  * Main entry point for dynamic linking.  The first argument is the
159  * stack pointer.  The stack is expected to be laid out as described
160  * in the SVR4 ABI specification, Intel 386 Processor Supplement.
161  * Specifically, the stack pointer points to a word containing
162  * ARGC.  Following that in the stack is a null-terminated sequence
163  * of pointers to argument strings.  Then comes a null-terminated
164  * sequence of pointers to environment strings.  Finally, there is a
165  * sequence of "auxiliary vector" entries.
166  *
167  * The second argument points to a place to store the dynamic linker's
168  * exit procedure pointer and the third to a place to store the main
169  * program's object.
170  *
171  * The return value is the main program's entry point.
172  */
173 func_ptr_type
174 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
175 {
176     Elf_Auxinfo *aux_info[AT_COUNT];
177     int i;
178     int argc;
179     char **argv;
180     char **env;
181     Elf_Auxinfo *aux;
182     Elf_Auxinfo *auxp;
183 
184     /*
185      * On entry, the dynamic linker itself has not been relocated yet.
186      * Be very careful not to reference any global data until after
187      * init_rtld has returned.  It is OK to reference file-scope statics
188      * and string constants, and to call static and global functions.
189      */
190 
191     /* Find the auxiliary vector on the stack. */
192     argc = *sp++;
193     argv = (char **) sp;
194     sp += argc + 1;	/* Skip over arguments and NULL terminator */
195     env = (char **) sp;
196     while (*sp++ != 0)	/* Skip over environment, and NULL terminator */
197 	;
198     aux = (Elf_Auxinfo *) sp;
199 
200     /* Digest the auxiliary vector. */
201     for (i = 0;  i < AT_COUNT;  i++)
202 	aux_info[i] = NULL;
203     for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
204 	if (auxp->a_type < AT_COUNT)
205 	    aux_info[auxp->a_type] = auxp;
206     }
207 
208     /* Initialize and relocate ourselves. */
209     assert(aux_info[AT_BASE] != NULL);
210     init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
211 
212     __progname = obj_rtld.path;
213     environ = env;
214 
215     trust = geteuid() == getuid() && getegid() == getgid();
216 
217     ld_bind_now = getenv("LD_BIND_NOW");
218     if (trust) {
219 	ld_debug = getenv("LD_DEBUG");
220 	ld_library_path = getenv("LD_LIBRARY_PATH");
221 	ld_preload = getenv("LD_PRELOAD");
222     }
223     ld_tracing = getenv("LD_TRACE_LOADED_OBJECTS");
224 
225     if (ld_debug != NULL && *ld_debug != '\0')
226 	debug = 1;
227     dbg("%s is initialized, base address = %p", __progname,
228 	(caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
229     dbg("RTLD dynamic = %p", obj_rtld.dynamic);
230     dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
231 
232     /*
233      * Load the main program, or process its program header if it is
234      * already loaded.
235      */
236     if (aux_info[AT_EXECFD] != NULL) {	/* Load the main program. */
237 	int fd = aux_info[AT_EXECFD]->a_un.a_val;
238 	dbg("loading main program");
239 	obj_main = map_object(fd);
240 	close(fd);
241 	if (obj_main == NULL)
242 	    die();
243     } else {				/* Main program already loaded. */
244 	const Elf_Phdr *phdr;
245 	int phnum;
246 	caddr_t entry;
247 
248 	dbg("processing main program's program header");
249 	assert(aux_info[AT_PHDR] != NULL);
250 	phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
251 	assert(aux_info[AT_PHNUM] != NULL);
252 	phnum = aux_info[AT_PHNUM]->a_un.a_val;
253 	assert(aux_info[AT_PHENT] != NULL);
254 	assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
255 	assert(aux_info[AT_ENTRY] != NULL);
256 	entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
257 	obj_main = digest_phdr(phdr, phnum, entry);
258     }
259 
260     obj_main->path = xstrdup(argv[0] ? argv[0] : "(null)");
261     obj_main->mainprog = true;
262     digest_dynamic(obj_main);
263 
264     linkmap_add(obj_main);
265     linkmap_add(&obj_rtld);
266 
267     /* Link the main program into the list of objects. */
268     *obj_tail = obj_main;
269     obj_tail = &obj_main->next;
270     obj_main->refcount++;
271 
272     /* Initialize a fake symbol for resolving undefined weak references. */
273     sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
274     sym_zero.st_shndx = SHN_ABS;
275 
276     dbg("loading LD_PRELOAD libraries");
277     if (load_preload_objects() == -1)
278 	die();
279 
280     dbg("loading needed objects");
281     if (load_needed_objects(obj_main) == -1)
282 	die();
283     main_tail = obj_tail;
284 
285     if (ld_tracing) {		/* We're done */
286 	trace_loaded_objects(obj_main);
287 	exit(0);
288     }
289 
290     dbg("relocating objects");
291     if (relocate_objects(obj_main,
292 	ld_bind_now != NULL && *ld_bind_now != '\0') == -1)
293 	die();
294 
295     dbg("doing copy relocations");
296     if (do_copy_relocations(obj_main) == -1)
297 	die();
298 
299     dbg("calling _init functions");
300     call_init_functions(obj_main->next);
301 
302     dbg("transferring control to program entry point = %p", obj_main->entry);
303 
304     r_debug_state();		/* say hello to gdb! */
305 
306     /* Return the exit procedure and the program entry point. */
307     *exit_proc = rtld_exit;
308     *objp = obj_main;
309     return (func_ptr_type) obj_main->entry;
310 }
311 
312 caddr_t
313 _rtld_bind(const Obj_Entry *obj, Elf_Word reloff)
314 {
315     const Elf_Rel *rel;
316     const Elf_Sym *def;
317     const Obj_Entry *defobj;
318     Elf_Addr *where;
319     caddr_t target;
320 
321     if (obj->pltrel)
322 	rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
323     else
324 	rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
325 
326     where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
327     def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true);
328     if (def == NULL)
329 	die();
330 
331     target = (caddr_t) (defobj->relocbase + def->st_value);
332 
333     dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
334       defobj->strtab + def->st_name, basename(obj->path),
335       target, basename(defobj->path));
336 
337     *where = (Elf_Addr) target;
338     return target;
339 }
340 
341 /*
342  * Error reporting function.  Use it like printf.  If formats the message
343  * into a buffer, and sets things up so that the next call to dlerror()
344  * will return the message.
345  */
346 void
347 _rtld_error(const char *fmt, ...)
348 {
349     static char buf[512];
350     va_list ap;
351 
352     va_start(ap, fmt);
353     vsnprintf(buf, sizeof buf, fmt, ap);
354     error_message = buf;
355     va_end(ap);
356 }
357 
358 #ifdef DEBUG
359 static const char *
360 basename(const char *name)
361 {
362     const char *p = strrchr(name, '/');
363     return p != NULL ? p + 1 : name;
364 }
365 #endif
366 
367 static void
368 call_fini_functions(Obj_Entry *first)
369 {
370     Obj_Entry *obj;
371 
372     for (obj = first;  obj != NULL;  obj = obj->next)
373 	if (obj->fini != NULL)
374 	    (*obj->fini)();
375 }
376 
377 static void
378 call_init_functions(Obj_Entry *first)
379 {
380     if (first != NULL) {
381 	call_init_functions(first->next);
382 	if (first->init != NULL)
383 	    (*first->init)();
384     }
385 }
386 
387 static void
388 die(void)
389 {
390     const char *msg = dlerror();
391 
392     if (msg == NULL)
393 	msg = "Fatal error";
394     errx(1, "%s", msg);
395 }
396 
397 /*
398  * Process a shared object's DYNAMIC section, and save the important
399  * information in its Obj_Entry structure.
400  */
401 static void
402 digest_dynamic(Obj_Entry *obj)
403 {
404     const Elf_Dyn *dynp;
405     Needed_Entry **needed_tail = &obj->needed;
406     const Elf_Dyn *dyn_rpath = NULL;
407     int plttype = DT_REL;
408 
409     for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
410 	switch (dynp->d_tag) {
411 
412 	case DT_REL:
413 	    obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
414 	    break;
415 
416 	case DT_RELSZ:
417 	    obj->relsize = dynp->d_un.d_val;
418 	    break;
419 
420 	case DT_RELENT:
421 	    assert(dynp->d_un.d_val == sizeof(Elf_Rel));
422 	    break;
423 
424 	case DT_JMPREL:
425 	    obj->pltrel = (const Elf_Rel *)
426 	      (obj->relocbase + dynp->d_un.d_ptr);
427 	    break;
428 
429 	case DT_PLTRELSZ:
430 	    obj->pltrelsize = dynp->d_un.d_val;
431 	    break;
432 
433 	case DT_RELA:
434 	    obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
435 	    break;
436 
437 	case DT_RELASZ:
438 	    obj->relasize = dynp->d_un.d_val;
439 	    break;
440 
441 	case DT_RELAENT:
442 	    assert(dynp->d_un.d_val == sizeof(Elf_Rela));
443 	    break;
444 
445 	case DT_PLTREL:
446 	    plttype = dynp->d_un.d_val;
447 	    assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
448 	    break;
449 
450 	case DT_SYMTAB:
451 	    obj->symtab = (const Elf_Sym *)
452 	      (obj->relocbase + dynp->d_un.d_ptr);
453 	    break;
454 
455 	case DT_SYMENT:
456 	    assert(dynp->d_un.d_val == sizeof(Elf_Sym));
457 	    break;
458 
459 	case DT_STRTAB:
460 	    obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
461 	    break;
462 
463 	case DT_STRSZ:
464 	    obj->strsize = dynp->d_un.d_val;
465 	    break;
466 
467 	case DT_HASH:
468 	    {
469 		const Elf_Addr *hashtab = (const Elf_Addr *)
470 		  (obj->relocbase + dynp->d_un.d_ptr);
471 		obj->nbuckets = hashtab[0];
472 		obj->nchains = hashtab[1];
473 		obj->buckets = hashtab + 2;
474 		obj->chains = obj->buckets + obj->nbuckets;
475 	    }
476 	    break;
477 
478 	case DT_NEEDED:
479 	    if (!obj->rtld) {
480 		Needed_Entry *nep = NEW(Needed_Entry);
481 		nep->name = dynp->d_un.d_val;
482 		nep->obj = NULL;
483 		nep->next = NULL;
484 
485 		*needed_tail = nep;
486 		needed_tail = &nep->next;
487 	    }
488 	    break;
489 
490 	case DT_PLTGOT:
491 	    obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
492 	    break;
493 
494 	case DT_TEXTREL:
495 	    obj->textrel = true;
496 	    break;
497 
498 	case DT_SYMBOLIC:
499 	    obj->symbolic = true;
500 	    break;
501 
502 	case DT_RPATH:
503 	    /*
504 	     * We have to wait until later to process this, because we
505 	     * might not have gotten the address of the string table yet.
506 	     */
507 	    dyn_rpath = dynp;
508 	    break;
509 
510 	case DT_SONAME:
511 	    /* Not used by the dynamic linker. */
512 	    break;
513 
514 	case DT_INIT:
515 	    obj->init = (void (*)(void)) (obj->relocbase + dynp->d_un.d_ptr);
516 	    break;
517 
518 	case DT_FINI:
519 	    obj->fini = (void (*)(void)) (obj->relocbase + dynp->d_un.d_ptr);
520 	    break;
521 
522 	case DT_DEBUG:
523 	    /* XXX - not implemented yet */
524 	    dbg("Filling in DT_DEBUG entry");
525 	    ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
526 	    break;
527 
528 	default:
529 	    xprintf("Ignored d_tag %d\n",dynp->d_tag);
530             break;
531 	}
532     }
533 
534     obj->traced = false;
535 
536     if (plttype == DT_RELA) {
537 	obj->pltrela = (const Elf_Rela *) obj->pltrel;
538 	obj->pltrel = NULL;
539 	obj->pltrelasize = obj->pltrelsize;
540 	obj->pltrelsize = 0;
541     }
542 
543     if (dyn_rpath != NULL)
544 	obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
545 }
546 
547 /*
548  * Process a shared object's program header.  This is used only for the
549  * main program, when the kernel has already loaded the main program
550  * into memory before calling the dynamic linker.  It creates and
551  * returns an Obj_Entry structure.
552  */
553 static Obj_Entry *
554 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry)
555 {
556     Obj_Entry *obj = CNEW(Obj_Entry);
557     const Elf_Phdr *phlimit = phdr + phnum;
558     const Elf_Phdr *ph;
559     int nsegs = 0;
560 
561     for (ph = phdr;  ph < phlimit;  ph++) {
562 	switch (ph->p_type) {
563 
564 	case PT_PHDR:
565 	    assert((const Elf_Phdr *) ph->p_vaddr == phdr);
566 	    obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
567 	    obj->phsize = ph->p_memsz;
568 	    break;
569 
570 	case PT_LOAD:
571 	    assert(nsegs < 2);
572 	    if (nsegs == 0) {	/* First load segment */
573 		obj->vaddrbase = trunc_page(ph->p_vaddr);
574 		obj->mapbase = (caddr_t) obj->vaddrbase;
575 		obj->relocbase = obj->mapbase - obj->vaddrbase;
576 		obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
577 		  obj->vaddrbase;
578 	    } else {		/* Last load segment */
579 		obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
580 		  obj->vaddrbase;
581 	    }
582 	    nsegs++;
583 	    break;
584 
585 	case PT_DYNAMIC:
586 	    obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
587 	    break;
588 	}
589     }
590     assert(nsegs == 2);
591 
592     obj->entry = entry;
593     return obj;
594 }
595 
596 static Obj_Entry *
597 dlcheck(void *handle)
598 {
599     Obj_Entry *obj;
600 
601     for (obj = obj_list;  obj != NULL;  obj = obj->next)
602 	if (obj == (Obj_Entry *) handle)
603 	    break;
604 
605     if (obj == NULL || obj->dl_refcount == 0) {
606 	_rtld_error("Invalid shared object handle %p", handle);
607 	return NULL;
608     }
609     return obj;
610 }
611 
612 /*
613  * Hash function for symbol table lookup.  Don't even think about changing
614  * this.  It is specified by the System V ABI.
615  */
616 unsigned long
617 elf_hash(const char *name)
618 {
619     const unsigned char *p = (const unsigned char *) name;
620     unsigned long h = 0;
621     unsigned long g;
622 
623     while (*p != '\0') {
624 	h = (h << 4) + *p++;
625 	if ((g = h & 0xf0000000) != 0)
626 	    h ^= g >> 24;
627 	h &= ~g;
628     }
629     return h;
630 }
631 
632 /*
633  * Find the library with the given name, and return its full pathname.
634  * The returned string is dynamically allocated.  Generates an error
635  * message and returns NULL if the library cannot be found.
636  *
637  * If the second argument is non-NULL, then it refers to an already-
638  * loaded shared object, whose library search path will be searched.
639  *
640  * The search order is:
641  *   LD_LIBRARY_PATH
642  *   ldconfig hints
643  *   rpath in the referencing file
644  *   /usr/lib
645  */
646 static char *
647 find_library(const char *name, const Obj_Entry *refobj)
648 {
649     char *pathname;
650 
651     if (strchr(name, '/') != NULL) {	/* Hard coded pathname */
652 	if (name[0] != '/' && !trust) {
653 	    _rtld_error("Absolute pathname required for shared object \"%s\"",
654 	      name);
655 	    return NULL;
656 	}
657 	return xstrdup(name);
658     }
659 
660     dbg(" Searching for \"%s\"", name);
661 
662     if ((refobj != NULL &&
663       (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
664       (pathname = search_library_path(name, ld_library_path)) != NULL ||
665       (pathname = search_library_path(name, gethints())) != NULL ||
666       (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
667 	return pathname;
668 
669     _rtld_error("Shared object \"%s\" not found", name);
670     return NULL;
671 }
672 
673 /*
674  * Given a symbol number in a referencing object, find the corresponding
675  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
676  * no definition was found.  Returns a pointer to the Obj_Entry of the
677  * defining object via the reference parameter DEFOBJ_OUT.
678  */
679 const Elf_Sym *
680 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
681     const Obj_Entry **defobj_out, bool in_plt)
682 {
683     const Elf_Sym *ref;
684     const Elf_Sym *strongdef;
685     const Elf_Sym *weakdef;
686     const Obj_Entry *obj;
687     const Obj_Entry *strongobj;
688     const Obj_Entry *weakobj;
689     const char *name;
690     unsigned long hash;
691 
692     ref = refobj->symtab + symnum;
693     name = refobj->strtab + ref->st_name;
694     hash = elf_hash(name);
695 
696     if (refobj->symbolic) {	/* Look first in the referencing object */
697 	const Elf_Sym *def = symlook_obj(name, hash, refobj, in_plt);
698 	if (def != NULL) {
699 	    *defobj_out = refobj;
700 	    return def;
701 	}
702     }
703 
704     /*
705      * Look in all loaded objects.  Skip the referencing object, if
706      * we have already searched it.  We keep track of the first weak
707      * definition and the first strong definition we encounter.  If
708      * we find a strong definition we stop searching, because there
709      * won't be anything better than that.
710      */
711     strongdef = weakdef = NULL;
712     strongobj = weakobj = NULL;
713     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
714 	if (obj != refobj || !refobj->symbolic) {
715 	    const Elf_Sym *def = symlook_obj(name, hash, obj, in_plt);
716 	    if (def != NULL) {
717 		if (ELF_ST_BIND(def->st_info) == STB_WEAK) {
718 		    if (weakdef == NULL) {
719 			weakdef = def;
720 			weakobj = obj;
721 		    }
722 		} else {
723 		    strongdef = def;
724 		    strongobj = obj;
725 		    break;	/* We are done. */
726 		}
727 	    }
728 	}
729     }
730 
731     /*
732      * If we still don't have a strong definition, search the dynamic
733      * linker itself, and possibly resolve the symbol from there.
734      * This is how the application links to dynamic linker services
735      * such as dlopen.  Only the values listed in the "exports" array
736      * can be resolved from the dynamic linker.
737      */
738     if (strongdef == NULL) {
739 	const Elf_Sym *def = symlook_obj(name, hash, &obj_rtld, in_plt);
740 	if (def != NULL && is_exported(def)) {
741 	    if (ELF_ST_BIND(def->st_info) == STB_WEAK) {
742 		if (weakdef == NULL) {
743 		    weakdef = def;
744 		    weakobj = &obj_rtld;
745 		}
746 	    } else {
747 		strongdef = def;
748 		strongobj = &obj_rtld;
749 	    }
750 	}
751     }
752 
753     if (strongdef != NULL) {
754 	*defobj_out = strongobj;
755 	return strongdef;
756     }
757     if (weakdef != NULL) {
758 	*defobj_out = weakobj;
759 	return weakdef;
760     }
761 
762     if (ELF_ST_BIND(ref->st_info) == STB_WEAK) {
763 	*defobj_out = obj_main;
764 	return &sym_zero;
765     }
766 
767     _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
768     return NULL;
769 }
770 
771 /*
772  * Return the search path from the ldconfig hints file, reading it if
773  * necessary.  Returns NULL if there are problems with the hints file,
774  * or if the search path there is empty.
775  */
776 static const char *
777 gethints(void)
778 {
779     static char *hints;
780 
781     if (hints == NULL) {
782 	int fd;
783 	struct elfhints_hdr hdr;
784 	char *p;
785 
786 	/* Keep from trying again in case the hints file is bad. */
787 	hints = "";
788 
789 	if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
790 	    return NULL;
791 	if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
792 	  hdr.magic != ELFHINTS_MAGIC ||
793 	  hdr.version != 1) {
794 	    close(fd);
795 	    return NULL;
796 	}
797 	p = xmalloc(hdr.dirlistlen + 1);
798 	if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
799 	  read(fd, p, hdr.dirlistlen + 1) != hdr.dirlistlen + 1) {
800 	    free(p);
801 	    close(fd);
802 	    return NULL;
803 	}
804 	hints = p;
805 	close(fd);
806     }
807     return hints[0] != '\0' ? hints : NULL;
808 }
809 
810 /*
811  * Initialize the dynamic linker.  The argument is the address at which
812  * the dynamic linker has been mapped into memory.  The primary task of
813  * this function is to relocate the dynamic linker.
814  */
815 static void
816 init_rtld(caddr_t mapbase)
817 {
818     /*
819      * Conjure up an Obj_Entry structure for the dynamic linker.
820      *
821      * The "path" member is supposed to be dynamically-allocated, but we
822      * aren't yet initialized sufficiently to do that.  Below we will
823      * replace the static version with a dynamically-allocated copy.
824      */
825     obj_rtld.path = "/usr/libexec/ld-elf.so.1";
826     obj_rtld.rtld = true;
827     obj_rtld.mapbase = mapbase;
828 #ifdef PIC
829     obj_rtld.relocbase = mapbase;
830 #endif
831     if (&_DYNAMIC != 0) {
832 	obj_rtld.dynamic = rtld_dynamic(&obj_rtld);
833 	digest_dynamic(&obj_rtld);
834 	assert(obj_rtld.needed == NULL);
835 	assert(!obj_rtld.textrel);
836 
837 	/*
838 	 * Temporarily put the dynamic linker entry into the object list, so
839 	 * that symbols can be found.
840 	 */
841 	obj_list = &obj_rtld;
842 	obj_tail = &obj_rtld.next;
843 
844 	relocate_objects(&obj_rtld, true);
845     }
846 
847     /* Make the object list empty again. */
848     obj_list = NULL;
849     obj_tail = &obj_list;
850 
851     /* Replace the path with a dynamically allocated copy. */
852     obj_rtld.path = xstrdup(obj_rtld.path);
853 
854     r_debug.r_brk = r_debug_state;
855     r_debug.r_state = RT_CONSISTENT;
856 }
857 
858 static bool
859 is_exported(const Elf_Sym *def)
860 {
861     func_ptr_type value;
862     const func_ptr_type *p;
863 
864     value = (func_ptr_type)(obj_rtld.relocbase + def->st_value);
865     for (p = exports;  *p != NULL;  p++)
866 	if (*p == value)
867 	    return true;
868     return false;
869 }
870 
871 /*
872  * Given a shared object, traverse its list of needed objects, and load
873  * each of them.  Returns 0 on success.  Generates an error message and
874  * returns -1 on failure.
875  */
876 static int
877 load_needed_objects(Obj_Entry *first)
878 {
879     Obj_Entry *obj;
880 
881     for (obj = first;  obj != NULL;  obj = obj->next) {
882 	Needed_Entry *needed;
883 
884 	for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
885 	    const char *name = obj->strtab + needed->name;
886 	    char *path = find_library(name, obj);
887 
888 	    needed->obj = NULL;
889 	    if (path == NULL && !ld_tracing)
890 		return -1;
891 
892 	    if (path) {
893 		needed->obj = load_object(path);
894 		if (needed->obj == NULL && !ld_tracing)
895 		    return -1;		/* XXX - cleanup */
896 	    }
897 	}
898     }
899 
900     return 0;
901 }
902 
903 static int
904 load_preload_objects(void)
905 {
906     char *p = ld_preload;
907 
908     if (p == NULL)
909 	return NULL;
910 
911     p += strspn(p, ":;");
912     while (*p != '\0') {
913 	size_t len = strcspn(p, ":;");
914 	char *path;
915 	char savech;
916 
917 	savech = p[len];
918 	p[len] = '\0';
919 	if ((path = find_library(p, NULL)) == NULL)
920 	    return -1;
921 	if (load_object(path) == NULL)
922 	    return -1;	/* XXX - cleanup */
923 	p[len] = savech;
924 	p += len;
925 	p += strspn(p, ":;");
926     }
927     return 0;
928 }
929 
930 /*
931  * Load a shared object into memory, if it is not already loaded.  The
932  * argument must be a string allocated on the heap.  This function assumes
933  * responsibility for freeing it when necessary.
934  *
935  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
936  * on failure.
937  */
938 static Obj_Entry *
939 load_object(char *path)
940 {
941     Obj_Entry *obj;
942 
943     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
944 	if (strcmp(obj->path, path) == 0)
945 	    break;
946 
947     if (obj == NULL) {	/* First use of this object, so we must map it in */
948 	int fd;
949 
950 	if ((fd = open(path, O_RDONLY)) == -1) {
951 	    _rtld_error("Cannot open \"%s\"", path);
952 	    return NULL;
953 	}
954 	obj = map_object(fd);
955 	close(fd);
956 	if (obj == NULL) {
957 	    free(path);
958 	    return NULL;
959 	}
960 
961 	obj->path = path;
962 	digest_dynamic(obj);
963 
964 	*obj_tail = obj;
965 	obj_tail = &obj->next;
966 	linkmap_add(obj);	/* for GDB */
967 
968 	dbg("  %p .. %p: %s", obj->mapbase,
969 	  obj->mapbase + obj->mapsize - 1, obj->path);
970 	if (obj->textrel)
971 	    dbg("  WARNING: %s has impure text", obj->path);
972     } else
973 	free(path);
974 
975     obj->refcount++;
976     return obj;
977 }
978 
979 static Obj_Entry *
980 obj_from_addr(const void *addr)
981 {
982     unsigned long endhash;
983     Obj_Entry *obj;
984 
985     endhash = elf_hash(END_SYM);
986     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
987 	const Elf_Sym *endsym;
988 
989 	if (addr < (void *) obj->mapbase)
990 	    continue;
991 	if ((endsym = symlook_obj(END_SYM, endhash, obj, true)) == NULL)
992 	    continue;	/* No "end" symbol?! */
993 	if (addr < (void *) (obj->relocbase + endsym->st_value))
994 	    return obj;
995     }
996     return NULL;
997 }
998 
999 /*
1000  * Relocate newly-loaded shared objects.  The argument is a pointer to
1001  * the Obj_Entry for the first such object.  All objects from the first
1002  * to the end of the list of objects are relocated.  Returns 0 on success,
1003  * or -1 on failure.
1004  */
1005 static int
1006 relocate_objects(Obj_Entry *first, bool bind_now)
1007 {
1008     Obj_Entry *obj;
1009 
1010     for (obj = first;  obj != NULL;  obj = obj->next) {
1011 	if (obj != &obj_rtld)
1012 	    dbg("relocating \"%s\"", obj->path);
1013 	if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1014 	    obj->symtab == NULL || obj->strtab == NULL) {
1015 	    _rtld_error("%s: Shared object has no run-time symbol table",
1016 	      obj->path);
1017 	    return -1;
1018 	}
1019 
1020 	if (obj->textrel) {
1021 	    /* There are relocations to the write-protected text segment. */
1022 	    if (mprotect(obj->mapbase, obj->textsize,
1023 	      PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1024 		_rtld_error("%s: Cannot write-enable text segment: %s",
1025 		  obj->path, strerror(errno));
1026 		return -1;
1027 	    }
1028 	}
1029 
1030 	/* Process the non-PLT relocations. */
1031 	if (reloc_non_plt(obj, &obj_rtld))
1032 		return -1;
1033 
1034 	if (obj->textrel) {	/* Re-protected the text segment. */
1035 	    if (mprotect(obj->mapbase, obj->textsize,
1036 	      PROT_READ|PROT_EXEC) == -1) {
1037 		_rtld_error("%s: Cannot write-protect text segment: %s",
1038 		  obj->path, strerror(errno));
1039 		return -1;
1040 	    }
1041 	}
1042 
1043 	/* Process the PLT relocations. */
1044 	if (reloc_plt(obj, bind_now))
1045 		return -1;
1046 
1047 	/*
1048 	 * Set up the magic number and version in the Obj_Entry.  These
1049 	 * were checked in the crt1.o from the original ElfKit, so we
1050 	 * set them for backward compatibility.
1051 	 */
1052 	obj->magic = RTLD_MAGIC;
1053 	obj->version = RTLD_VERSION;
1054 
1055 	/* Set the special PLT or GOT entries. */
1056 	init_pltgot(obj);
1057     }
1058 
1059     return 0;
1060 }
1061 
1062 /*
1063  * Cleanup procedure.  It will be called (by the atexit mechanism) just
1064  * before the process exits.
1065  */
1066 static void
1067 rtld_exit(void)
1068 {
1069     dbg("rtld_exit()");
1070     call_fini_functions(obj_list->next);
1071 }
1072 
1073 static char *
1074 search_library_path(const char *name, const char *path)
1075 {
1076     size_t namelen = strlen(name);
1077     const char *p = path;
1078 
1079     if (p == NULL)
1080 	return NULL;
1081 
1082     p += strspn(p, ":;");
1083     while (*p != '\0') {
1084 	size_t len = strcspn(p, ":;");
1085 
1086 	if (*p == '/' || trust) {
1087 	    char *pathname;
1088 	    const char *dir = p;
1089 	    size_t dirlen = len;
1090 
1091 	    pathname = xmalloc(dirlen + 1 + namelen + 1);
1092 	    strncpy(pathname, dir, dirlen);
1093 	    pathname[dirlen] = '/';
1094 	    strcpy(pathname + dirlen + 1, name);
1095 
1096 	    dbg("  Trying \"%s\"", pathname);
1097 	    if (access(pathname, F_OK) == 0)		/* We found it */
1098 		return pathname;
1099 
1100 	    free(pathname);
1101 	}
1102 	p += len;
1103 	p += strspn(p, ":;");
1104     }
1105 
1106     return NULL;
1107 }
1108 
1109 int
1110 dlclose(void *handle)
1111 {
1112     Obj_Entry *root = dlcheck(handle);
1113 
1114     if (root == NULL)
1115 	return -1;
1116 
1117     GDB_STATE(RT_DELETE);
1118 
1119     root->dl_refcount--;
1120     unref_object_dag(root);
1121     if (root->refcount == 0) {	/* We are finished with some objects. */
1122 	Obj_Entry *obj;
1123 	Obj_Entry **linkp;
1124 
1125 	/* Finalize objects that are about to be unmapped. */
1126 	for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1127 	    if (obj->refcount == 0 && obj->fini != NULL)
1128 		(*obj->fini)();
1129 
1130 	/* Unmap all objects that are no longer referenced. */
1131 	linkp = &obj_list->next;
1132 	while ((obj = *linkp) != NULL) {
1133 	    if (obj->refcount == 0) {
1134 		munmap(obj->mapbase, obj->mapsize);
1135 		free(obj->path);
1136 		while (obj->needed != NULL) {
1137 		    Needed_Entry *needed = obj->needed;
1138 		    obj->needed = needed->next;
1139 		    free(needed);
1140 		}
1141 		linkmap_delete(obj);
1142 		*linkp = obj->next;
1143 		free(obj);
1144 	    } else
1145 		linkp = &obj->next;
1146 	}
1147 	obj_tail = linkp;
1148     }
1149 
1150     GDB_STATE(RT_CONSISTENT);
1151 
1152     return 0;
1153 }
1154 
1155 const char *
1156 dlerror(void)
1157 {
1158     char *msg = error_message;
1159     error_message = NULL;
1160     return msg;
1161 }
1162 
1163 void *
1164 dlopen(const char *name, int mode)
1165 {
1166     Obj_Entry **old_obj_tail = obj_tail;
1167     Obj_Entry *obj = NULL;
1168 
1169     GDB_STATE(RT_ADD);
1170 
1171     if (name == NULL)
1172 	obj = obj_main;
1173     else {
1174 	char *path = find_library(name, obj_main);
1175 	if (path != NULL)
1176 	    obj = load_object(path);
1177     }
1178 
1179     if (obj) {
1180 	obj->dl_refcount++;
1181 	if (*old_obj_tail != NULL) {		/* We loaded something new. */
1182 	    assert(*old_obj_tail == obj);
1183 
1184 	    /* XXX - Clean up properly after an error. */
1185 	    if (load_needed_objects(obj) == -1) {
1186 		obj->dl_refcount--;
1187 		obj = NULL;
1188 	    } else if (relocate_objects(obj, mode == RTLD_NOW) == -1) {
1189 		obj->dl_refcount--;
1190 		obj = NULL;
1191 	    } else
1192 		call_init_functions(obj);
1193 	}
1194     }
1195 
1196     GDB_STATE(RT_CONSISTENT);
1197 
1198     return obj;
1199 }
1200 
1201 void *
1202 dlsym(void *handle, const char *name)
1203 {
1204     const Obj_Entry *obj;
1205     unsigned long hash;
1206     const Elf_Sym *def;
1207 
1208     hash = elf_hash(name);
1209     def = NULL;
1210 
1211     if (handle == NULL || handle == RTLD_NEXT) {
1212 	void *retaddr;
1213 
1214 	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
1215 	if ((obj = obj_from_addr(retaddr)) == NULL) {
1216 	    _rtld_error("Cannot determine caller's shared object");
1217 	    return NULL;
1218 	}
1219 	if (handle == NULL)	/* Just the caller's shared object. */
1220 	    def = symlook_obj(name, hash, obj, true);
1221 	else {			/* All the shared objects after the caller's */
1222 	    while ((obj = obj->next) != NULL)
1223 		if ((def = symlook_obj(name, hash, obj, true)) != NULL)
1224 		    break;
1225 	}
1226     } else {
1227 	if ((obj = dlcheck(handle)) == NULL)
1228 	    return NULL;
1229 
1230 	if (obj->mainprog) {
1231 	    /* Search main program and all libraries loaded by it. */
1232 	    for ( ;  obj != *main_tail;  obj = obj->next)
1233 		if ((def = symlook_obj(name, hash, obj, true)) != NULL)
1234 		    break;
1235 	} else {
1236 	    /*
1237 	     * XXX - This isn't correct.  The search should include the whole
1238 	     * DAG rooted at the given object.
1239 	     */
1240 	    def = symlook_obj(name, hash, obj, true);
1241 	}
1242     }
1243 
1244     if (def != NULL)
1245 	return obj->relocbase + def->st_value;
1246 
1247     _rtld_error("Undefined symbol \"%s\"", name);
1248     return NULL;
1249 }
1250 
1251 int
1252 dlversion(void)
1253 {
1254     return DL_VERSION;
1255 }
1256 
1257 int
1258 dladdr(const void *addr, Dl_info *info)
1259 {
1260     const Obj_Entry *obj;
1261     const Elf_Sym *def;
1262     void *symbol_addr;
1263     unsigned long symoffset;
1264 
1265     obj = obj_from_addr(addr);
1266     if (obj == NULL) {
1267         _rtld_error("No shared object contains address");
1268         return 0;
1269     }
1270     info->dli_fname = obj->path;
1271     info->dli_fbase = obj->mapbase;
1272     info->dli_saddr = (void *)0;
1273     info->dli_sname = NULL;
1274 
1275     /*
1276      * Walk the symbol list looking for the symbol whose address is
1277      * closest to the address sent in.
1278      */
1279     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1280         def = obj->symtab + symoffset;
1281 
1282         /*
1283          * For skip the symbol if st_shndx is either SHN_UNDEF or
1284          * SHN_COMMON.
1285          */
1286         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1287             continue;
1288 
1289         /*
1290          * If the symbol is greater than the specified address, or if it
1291          * is further away from addr than the current nearest symbol,
1292          * then reject it.
1293          */
1294         symbol_addr = obj->relocbase + def->st_value;
1295         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1296             continue;
1297 
1298         /* Update our idea of the nearest symbol. */
1299         info->dli_sname = obj->strtab + def->st_name;
1300         info->dli_saddr = symbol_addr;
1301 
1302         /* Exact match? */
1303         if (info->dli_saddr == addr)
1304             break;
1305     }
1306     return 1;
1307 }
1308 
1309 static void
1310 linkmap_add(Obj_Entry *obj)
1311 {
1312     struct link_map *l = &obj->linkmap;
1313     struct link_map *prev;
1314 
1315     obj->linkmap.l_name = obj->path;
1316     obj->linkmap.l_addr = obj->mapbase;
1317     obj->linkmap.l_ld = obj->dynamic;
1318 #ifdef __mips__
1319     /* GDB needs load offset on MIPS to use the symbols */
1320     obj->linkmap.l_offs = obj->relocbase;
1321 #endif
1322 
1323     if (r_debug.r_map == NULL) {
1324 	r_debug.r_map = l;
1325 	return;
1326     }
1327 
1328     /*
1329      * Scan to the end of the list, but not past the entry for the
1330      * dynamic linker, which we want to keep at the very end.
1331      */
1332     for (prev = r_debug.r_map;
1333       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
1334       prev = prev->l_next)
1335 	;
1336 
1337     /* Link in the new entry. */
1338     l->l_prev = prev;
1339     l->l_next = prev->l_next;
1340     if (l->l_next != NULL)
1341 	l->l_next->l_prev = l;
1342     prev->l_next = l;
1343 }
1344 
1345 static void
1346 linkmap_delete(Obj_Entry *obj)
1347 {
1348     struct link_map *l = &obj->linkmap;
1349 
1350     if (l->l_prev == NULL) {
1351 	if ((r_debug.r_map = l->l_next) != NULL)
1352 	    l->l_next->l_prev = NULL;
1353 	return;
1354     }
1355 
1356     if ((l->l_prev->l_next = l->l_next) != NULL)
1357 	l->l_next->l_prev = l->l_prev;
1358 }
1359 
1360 /*
1361  * Function for the debugger to set a breakpoint on to gain control.
1362  */
1363 void
1364 r_debug_state(void)
1365 {
1366 }
1367 
1368 /*
1369  * Search the symbol table of a single shared object for a symbol of
1370  * the given name.  Returns a pointer to the symbol, or NULL if no
1371  * definition was found.
1372  *
1373  * The symbol's hash value is passed in for efficiency reasons; that
1374  * eliminates many recomputations of the hash value.
1375  */
1376 const Elf_Sym *
1377 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
1378   bool in_plt)
1379 {
1380     if (obj->buckets != NULL) {
1381 	unsigned long symnum = obj->buckets[hash % obj->nbuckets];
1382 
1383 	while (symnum != STN_UNDEF) {
1384 	    const Elf_Sym *symp;
1385 	    const char *strp;
1386 
1387 	    assert(symnum < obj->nchains);
1388 	    symp = obj->symtab + symnum;
1389 	    assert(symp->st_name != 0);
1390 	    strp = obj->strtab + symp->st_name;
1391 
1392 	    if (strcmp(name, strp) == 0)
1393 		return symp->st_shndx != SHN_UNDEF ||
1394 		  (!in_plt && symp->st_value != 0 &&
1395 		  ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
1396 
1397 	    symnum = obj->chains[symnum];
1398 	}
1399     }
1400     return NULL;
1401 }
1402 
1403 static void
1404 trace_loaded_objects(Obj_Entry *obj)
1405 {
1406     char	*fmt1, *fmt2, *fmt, *main_local;
1407     int		c;
1408 
1409     if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
1410 	main_local = "";
1411 
1412     if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
1413 	fmt1 = "\t%o => %p (%x)\n";
1414 
1415     if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
1416 	fmt2 = "\t%o (%x)\n";
1417 
1418     for (; obj; obj = obj->next) {
1419 	Needed_Entry		*needed;
1420 	char			*name, *path;
1421 	bool			is_lib;
1422 
1423 	for (needed = obj->needed; needed; needed = needed->next) {
1424 	    if (needed->obj != NULL) {
1425 		if (needed->obj->traced)
1426 		    continue;
1427 		needed->obj->traced = true;
1428 		path = needed->obj->path;
1429 	    } else
1430 		path = "not found";
1431 
1432 	    name = (char *)obj->strtab + needed->name;
1433 	    is_lib = strncmp(name, "lib", 3) == 0;	/* XXX - bogus */
1434 
1435 	    fmt = is_lib ? fmt1 : fmt2;
1436 	    while ((c = *fmt++) != '\0') {
1437 		switch (c) {
1438 		default:
1439 		    putchar(c);
1440 		    continue;
1441 		case '\\':
1442 		    switch (c = *fmt) {
1443 		    case '\0':
1444 			continue;
1445 		    case 'n':
1446 			putchar('\n');
1447 			break;
1448 		    case 't':
1449 			putchar('\t');
1450 			break;
1451 		    }
1452 		    break;
1453 		case '%':
1454 		    switch (c = *fmt) {
1455 		    case '\0':
1456 			continue;
1457 		    case '%':
1458 		    default:
1459 			putchar(c);
1460 			break;
1461 		    case 'A':
1462 			printf("%s", main_local);
1463 			break;
1464 		    case 'a':
1465 			printf("%s", obj_main->path);
1466 			break;
1467 		    case 'o':
1468 			printf("%s", name);
1469 			break;
1470 #if 0
1471 		    case 'm':
1472 			printf("%d", sodp->sod_major);
1473 			break;
1474 		    case 'n':
1475 			printf("%d", sodp->sod_minor);
1476 			break;
1477 #endif
1478 		    case 'p':
1479 			printf("%s", path);
1480 			break;
1481 		    case 'x':
1482 			printf("%p", needed->obj ? needed->obj->mapbase : 0);
1483 			break;
1484 		    }
1485 		    break;
1486 		}
1487 		++fmt;
1488 	    }
1489 	}
1490     }
1491 }
1492 
1493 static void
1494 unref_object_dag(Obj_Entry *root)
1495 {
1496     assert(root->refcount != 0);
1497     root->refcount--;
1498     if (root->refcount == 0) {
1499 	const Needed_Entry *needed;
1500 
1501 	for (needed = root->needed;  needed != NULL;  needed = needed->next)
1502 	    unref_object_dag(needed->obj);
1503     }
1504 }
1505 
1506 /*
1507  * Non-mallocing printf, for use by malloc itself.
1508  * XXX - This doesn't belong in this module.
1509  */
1510 void
1511 xprintf(const char *fmt, ...)
1512 {
1513     char buf[256];
1514     va_list ap;
1515 
1516     va_start(ap, fmt);
1517     vsprintf(buf, fmt, ap);
1518     (void)write(1, buf, strlen(buf));
1519     va_end(ap);
1520 }
1521