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