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