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