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