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