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