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