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