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