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