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