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