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