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