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