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