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