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