Merge from vendor branch GCC:
[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.23 2005/05/11 19:47:06 dillon 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   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         if ((obj = dlcheck(handle)) == NULL) {
1857             rlock_release();
1858             return NULL;
1859         }
1860
1861         if (obj->mainprog) {
1862             DoneList donelist;
1863
1864             /* Search main program and all libraries loaded by it. */
1865             donelist_init(&donelist);
1866             def = symlook_list(name, hash, &list_main, &defobj, true,
1867               &donelist);
1868         } else {
1869             /*
1870              * XXX - This isn't correct.  The search should include the whole
1871              * DAG rooted at the given object.
1872              */
1873             def = symlook_obj(name, hash, obj, true);
1874             defobj = obj;
1875         }
1876     }
1877
1878     if (def != NULL) {
1879         rlock_release();
1880         return defobj->relocbase + def->st_value;
1881     }
1882
1883     _rtld_error("Undefined symbol \"%s\"", name);
1884     rlock_release();
1885     return NULL;
1886 }
1887
1888 int
1889 dladdr(const void *addr, Dl_info *info)
1890 {
1891     const Obj_Entry *obj;
1892     const Elf_Sym *def;
1893     void *symbol_addr;
1894     unsigned long symoffset;
1895  
1896     rlock_acquire();
1897     obj = obj_from_addr(addr);
1898     if (obj == NULL) {
1899         _rtld_error("No shared object contains address");
1900         rlock_release();
1901         return 0;
1902     }
1903     info->dli_fname = obj->path;
1904     info->dli_fbase = obj->mapbase;
1905     info->dli_saddr = (void *)0;
1906     info->dli_sname = NULL;
1907
1908     /*
1909      * Walk the symbol list looking for the symbol whose address is
1910      * closest to the address sent in.
1911      */
1912     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
1913         def = obj->symtab + symoffset;
1914
1915         /*
1916          * For skip the symbol if st_shndx is either SHN_UNDEF or
1917          * SHN_COMMON.
1918          */
1919         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
1920             continue;
1921
1922         /*
1923          * If the symbol is greater than the specified address, or if it
1924          * is further away from addr than the current nearest symbol,
1925          * then reject it.
1926          */
1927         symbol_addr = obj->relocbase + def->st_value;
1928         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
1929             continue;
1930
1931         /* Update our idea of the nearest symbol. */
1932         info->dli_sname = obj->strtab + def->st_name;
1933         info->dli_saddr = symbol_addr;
1934
1935         /* Exact match? */
1936         if (info->dli_saddr == addr)
1937             break;
1938     }
1939     rlock_release();
1940     return 1;
1941 }
1942
1943 int
1944 dlinfo(void *handle, int request, void *p)
1945 {
1946     const Obj_Entry *obj;
1947     int error;
1948
1949     rlock_acquire();
1950
1951     if (handle == NULL || handle == RTLD_SELF) {
1952         void *retaddr;
1953
1954         retaddr = __builtin_return_address(0);  /* __GNUC__ only */
1955         if ((obj = obj_from_addr(retaddr)) == NULL)
1956             _rtld_error("Cannot determine caller's shared object");
1957     } else
1958         obj = dlcheck(handle);
1959
1960     if (obj == NULL) {
1961         rlock_release();
1962         return (-1);
1963     }
1964
1965     error = 0;
1966     switch (request) {
1967     case RTLD_DI_LINKMAP:
1968         *((struct link_map const **)p) = &obj->linkmap;
1969         break;
1970     case RTLD_DI_ORIGIN:
1971         error = rtld_dirname(obj->path, p);
1972         break;
1973
1974     case RTLD_DI_SERINFOSIZE:
1975     case RTLD_DI_SERINFO:
1976         error = do_search_info(obj, request, (struct dl_serinfo *)p);
1977         break;
1978
1979     default:
1980         _rtld_error("Invalid request %d passed to dlinfo()", request);
1981         error = -1;
1982     }
1983
1984     rlock_release();
1985
1986     return (error);
1987 }
1988
1989 struct fill_search_info_args {
1990     int          request;
1991     unsigned int flags;
1992     Dl_serinfo  *serinfo;
1993     Dl_serpath  *serpath;
1994     char        *strspace;
1995 };
1996
1997 static void *
1998 fill_search_info(const char *dir, size_t dirlen, void *param)
1999 {
2000     struct fill_search_info_args *arg;
2001
2002     arg = param;
2003
2004     if (arg->request == RTLD_DI_SERINFOSIZE) {
2005         arg->serinfo->dls_cnt ++;
2006         arg->serinfo->dls_size += dirlen + 1;
2007     } else {
2008         struct dl_serpath *s_entry;
2009
2010         s_entry = arg->serpath;
2011         s_entry->dls_name  = arg->strspace;
2012         s_entry->dls_flags = arg->flags;
2013
2014         strncpy(arg->strspace, dir, dirlen);
2015         arg->strspace[dirlen] = '\0';
2016
2017         arg->strspace += dirlen + 1;
2018         arg->serpath++;
2019     }
2020
2021     return (NULL);
2022 }
2023
2024 static int
2025 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2026 {
2027     struct dl_serinfo _info;
2028     struct fill_search_info_args args;
2029
2030     args.request = RTLD_DI_SERINFOSIZE;
2031     args.serinfo = &_info;
2032
2033     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2034     _info.dls_cnt  = 0;
2035
2036     path_enumerate(ld_library_path, fill_search_info, &args);
2037     path_enumerate(obj->rpath, fill_search_info, &args);
2038     path_enumerate(gethints(), fill_search_info, &args);
2039     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2040
2041
2042     if (request == RTLD_DI_SERINFOSIZE) {
2043         info->dls_size = _info.dls_size;
2044         info->dls_cnt = _info.dls_cnt;
2045         return (0);
2046     }
2047
2048     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2049         _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2050         return (-1);
2051     }
2052
2053     args.request  = RTLD_DI_SERINFO;
2054     args.serinfo  = info;
2055     args.serpath  = &info->dls_serpath[0];
2056     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2057
2058     args.flags = LA_SER_LIBPATH;
2059     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2060         return (-1);
2061
2062     args.flags = LA_SER_RUNPATH;
2063     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2064         return (-1);
2065
2066     args.flags = LA_SER_CONFIG;
2067     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2068         return (-1);
2069
2070     args.flags = LA_SER_DEFAULT;
2071     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2072         return (-1);
2073     return (0);
2074 }
2075
2076 static int
2077 rtld_dirname(const char *path, char *bname)
2078 {
2079     const char *endp;
2080
2081     /* Empty or NULL string gets treated as "." */
2082     if (path == NULL || *path == '\0') {
2083         bname[0] = '.';
2084         bname[1] = '\0';
2085         return (0);
2086     }
2087
2088     /* Strip trailing slashes */
2089     endp = path + strlen(path) - 1;
2090     while (endp > path && *endp == '/')
2091         endp--;
2092
2093     /* Find the start of the dir */
2094     while (endp > path && *endp != '/')
2095         endp--;
2096
2097     /* Either the dir is "/" or there are no slashes */
2098     if (endp == path) {
2099         bname[0] = *endp == '/' ? '/' : '.';
2100         bname[1] = '\0';
2101         return (0);
2102     } else {
2103         do {
2104             endp--;
2105         } while (endp > path && *endp == '/');
2106     }
2107
2108     if (endp - path + 2 > PATH_MAX)
2109     {
2110         _rtld_error("Filename is too long: %s", path);
2111         return(-1);
2112     }
2113
2114     strncpy(bname, path, endp - path + 1);
2115     bname[endp - path + 1] = '\0';
2116     return (0);
2117 }
2118
2119 static void
2120 linkmap_add(Obj_Entry *obj)
2121 {
2122     struct link_map *l = &obj->linkmap;
2123     struct link_map *prev;
2124
2125     obj->linkmap.l_name = obj->path;
2126     obj->linkmap.l_addr = obj->mapbase;
2127     obj->linkmap.l_ld = obj->dynamic;
2128 #ifdef __mips__
2129     /* GDB needs load offset on MIPS to use the symbols */
2130     obj->linkmap.l_offs = obj->relocbase;
2131 #endif
2132
2133     if (r_debug.r_map == NULL) {
2134         r_debug.r_map = l;
2135         return;
2136     }
2137
2138     /*
2139      * Scan to the end of the list, but not past the entry for the
2140      * dynamic linker, which we want to keep at the very end.
2141      */
2142     for (prev = r_debug.r_map;
2143       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2144       prev = prev->l_next)
2145         ;
2146
2147     /* Link in the new entry. */
2148     l->l_prev = prev;
2149     l->l_next = prev->l_next;
2150     if (l->l_next != NULL)
2151         l->l_next->l_prev = l;
2152     prev->l_next = l;
2153 }
2154
2155 static void
2156 linkmap_delete(Obj_Entry *obj)
2157 {
2158     struct link_map *l = &obj->linkmap;
2159
2160     if (l->l_prev == NULL) {
2161         if ((r_debug.r_map = l->l_next) != NULL)
2162             l->l_next->l_prev = NULL;
2163         return;
2164     }
2165
2166     if ((l->l_prev->l_next = l->l_next) != NULL)
2167         l->l_next->l_prev = l->l_prev;
2168 }
2169
2170 /*
2171  * Function for the debugger to set a breakpoint on to gain control.
2172  *
2173  * The two parameters allow the debugger to easily find and determine
2174  * what the runtime loader is doing and to whom it is doing it.
2175  *
2176  * When the loadhook trap is hit (r_debug_state, set at program
2177  * initialization), the arguments can be found on the stack:
2178  *
2179  *  +8   struct link_map *m
2180  *  +4   struct r_debug  *rd
2181  *  +0   RetAddr
2182  */
2183 void
2184 r_debug_state(struct r_debug* rd, struct link_map *m)
2185 {
2186 }
2187
2188 /*
2189  * Get address of the pointer variable in the main program.
2190  */
2191 static const void **
2192 get_program_var_addr(const char *name)
2193 {
2194     const Obj_Entry *obj;
2195     unsigned long hash;
2196
2197     hash = elf_hash(name);
2198     for (obj = obj_main;  obj != NULL;  obj = obj->next) {
2199         const Elf_Sym *def;
2200
2201         if ((def = symlook_obj(name, hash, obj, false)) != NULL) {
2202             const void **addr;
2203
2204             addr = (const void **)(obj->relocbase + def->st_value);
2205             return addr;
2206         }
2207     }
2208     return NULL;
2209 }
2210
2211 /*
2212  * Set a pointer variable in the main program to the given value.  This
2213  * is used to set key variables such as "environ" before any of the
2214  * init functions are called.
2215  */
2216 static void
2217 set_program_var(const char *name, const void *value)
2218 {
2219     const void **addr;
2220
2221     if ((addr = get_program_var_addr(name)) != NULL) {
2222         dbg("\"%s\": *%p <-- %p", name, addr, value);
2223         *addr = value;
2224     }
2225 }
2226
2227 /*
2228  * This is a special version of getenv which is far more efficient
2229  * at finding LD_ environment vars.
2230  */
2231 static
2232 const char *
2233 _getenv_ld(const char *id)
2234 {
2235     const char *envp;
2236     int i, j;
2237     int idlen = strlen(id);
2238
2239     if (ld_index == LD_ARY_CACHE)
2240         return(getenv(id));
2241     if (ld_index == 0) {
2242         for (i = j = 0; (envp = environ[i]) != NULL && j < LD_ARY_CACHE; ++i) {
2243             if (envp[0] == 'L' && envp[1] == 'D' && envp[2] == '_')
2244                 ld_ary[j++] = envp;
2245         }
2246         if (j == 0)
2247                 ld_ary[j++] = "";
2248         ld_index = j;
2249     }
2250     for (i = ld_index - 1; i >= 0; --i) {
2251         if (strncmp(ld_ary[i], id, idlen) == 0 && ld_ary[i][idlen] == '=')
2252             return(ld_ary[i] + idlen + 1);
2253     }
2254     return(NULL);
2255 }
2256
2257 /*
2258  * Given a symbol name in a referencing object, find the corresponding
2259  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
2260  * no definition was found.  Returns a pointer to the Obj_Entry of the
2261  * defining object via the reference parameter DEFOBJ_OUT.
2262  */
2263 static const Elf_Sym *
2264 symlook_default(const char *name, unsigned long hash,
2265     const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt)
2266 {
2267     DoneList donelist;
2268     const Elf_Sym *def;
2269     const Elf_Sym *symp;
2270     const Obj_Entry *obj;
2271     const Obj_Entry *defobj;
2272     const Objlist_Entry *elm;
2273     def = NULL;
2274     defobj = NULL;
2275     donelist_init(&donelist);
2276
2277     /* Look first in the referencing object if linked symbolically. */
2278     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2279         symp = symlook_obj(name, hash, refobj, in_plt);
2280         if (symp != NULL) {
2281             def = symp;
2282             defobj = refobj;
2283         }
2284     }
2285
2286     /* Search all objects loaded at program start up. */
2287     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2288         symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist);
2289         if (symp != NULL &&
2290           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2291             def = symp;
2292             defobj = obj;
2293         }
2294     }
2295
2296     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2297     STAILQ_FOREACH(elm, &list_global, link) {
2298        if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2299            break;
2300        symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2301          &donelist);
2302         if (symp != NULL &&
2303           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2304             def = symp;
2305             defobj = obj;
2306         }
2307     }
2308
2309     /* Search all dlopened DAGs containing the referencing object. */
2310     STAILQ_FOREACH(elm, &refobj->dldags, link) {
2311         if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2312             break;
2313         symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt,
2314           &donelist);
2315         if (symp != NULL &&
2316           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2317             def = symp;
2318             defobj = obj;
2319         }
2320     }
2321
2322     /*
2323      * Search the dynamic linker itself, and possibly resolve the
2324      * symbol from there.  This is how the application links to
2325      * dynamic linker services such as dlopen.  Only the values listed
2326      * in the "exports" array can be resolved from the dynamic linker.
2327      */
2328     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2329         symp = symlook_obj(name, hash, &obj_rtld, in_plt);
2330         if (symp != NULL && is_exported(symp)) {
2331             def = symp;
2332             defobj = &obj_rtld;
2333         }
2334     }
2335
2336     if (def != NULL)
2337         *defobj_out = defobj;
2338     return def;
2339 }
2340
2341 static const Elf_Sym *
2342 symlook_list(const char *name, unsigned long hash, Objlist *objlist,
2343   const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp)
2344 {
2345     const Elf_Sym *symp;
2346     const Elf_Sym *def;
2347     const Obj_Entry *defobj;
2348     const Objlist_Entry *elm;
2349
2350     def = NULL;
2351     defobj = NULL;
2352     STAILQ_FOREACH(elm, objlist, link) {
2353         if (donelist_check(dlp, elm->obj))
2354             continue;
2355         if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) {
2356             if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2357                 def = symp;
2358                 defobj = elm->obj;
2359                 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2360                     break;
2361             }
2362         }
2363     }
2364     if (def != NULL)
2365         *defobj_out = defobj;
2366     return def;
2367 }
2368
2369 /*
2370  * Search the symbol table of a single shared object for a symbol of
2371  * the given name.  Returns a pointer to the symbol, or NULL if no
2372  * definition was found.
2373  *
2374  * The symbol's hash value is passed in for efficiency reasons; that
2375  * eliminates many recomputations of the hash value.
2376  */
2377 const Elf_Sym *
2378 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2379   bool in_plt)
2380 {
2381     if (obj->buckets != NULL) {
2382         unsigned long symnum = obj->buckets[hash % obj->nbuckets];
2383
2384         while (symnum != STN_UNDEF) {
2385             const Elf_Sym *symp;
2386             const char *strp;
2387
2388             if (symnum >= obj->nchains)
2389                 return NULL;    /* Bad object */
2390             symp = obj->symtab + symnum;
2391             strp = obj->strtab + symp->st_name;
2392
2393             if (name[0] == strp[0] && strcmp(name, strp) == 0)
2394                 return symp->st_shndx != SHN_UNDEF ||
2395                   (!in_plt && symp->st_value != 0 &&
2396                   ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL;
2397
2398             symnum = obj->chains[symnum];
2399         }
2400     }
2401     return NULL;
2402 }
2403
2404 static void
2405 trace_loaded_objects(Obj_Entry *obj)
2406 {
2407     const char *fmt1, *fmt2, *fmt, *main_local;
2408     int         c;
2409
2410     if ((main_local = _getenv_ld("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2411         main_local = "";
2412
2413     if ((fmt1 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2414         fmt1 = "\t%o => %p (%x)\n";
2415
2416     if ((fmt2 = _getenv_ld("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2417         fmt2 = "\t%o (%x)\n";
2418
2419     for (; obj; obj = obj->next) {
2420         Needed_Entry            *needed;
2421         char                    *name, *path;
2422         bool                    is_lib;
2423
2424         for (needed = obj->needed; needed; needed = needed->next) {
2425             if (needed->obj != NULL) {
2426                 if (needed->obj->traced)
2427                     continue;
2428                 needed->obj->traced = true;
2429                 path = needed->obj->path;
2430             } else
2431                 path = "not found";
2432
2433             name = (char *)obj->strtab + needed->name;
2434             is_lib = strncmp(name, "lib", 3) == 0;      /* XXX - bogus */
2435
2436             fmt = is_lib ? fmt1 : fmt2;
2437             while ((c = *fmt++) != '\0') {
2438                 switch (c) {
2439                 default:
2440                     putchar(c);
2441                     continue;
2442                 case '\\':
2443                     switch (c = *fmt) {
2444                     case '\0':
2445                         continue;
2446                     case 'n':
2447                         putchar('\n');
2448                         break;
2449                     case 't':
2450                         putchar('\t');
2451                         break;
2452                     }
2453                     break;
2454                 case '%':
2455                     switch (c = *fmt) {
2456                     case '\0':
2457                         continue;
2458                     case '%':
2459                     default:
2460                         putchar(c);
2461                         break;
2462                     case 'A':
2463                         printf("%s", main_local);
2464                         break;
2465                     case 'a':
2466                         printf("%s", obj_main->path);
2467                         break;
2468                     case 'o':
2469                         printf("%s", name);
2470                         break;
2471 #if 0
2472                     case 'm':
2473                         printf("%d", sodp->sod_major);
2474                         break;
2475                     case 'n':
2476                         printf("%d", sodp->sod_minor);
2477                         break;
2478 #endif
2479                     case 'p':
2480                         printf("%s", path);
2481                         break;
2482                     case 'x':
2483                         printf("%p", needed->obj ? needed->obj->mapbase : 0);
2484                         break;
2485                     }
2486                     break;
2487                 }
2488                 ++fmt;
2489             }
2490         }
2491     }
2492 }
2493
2494 /*
2495  * Unload a dlopened object and its dependencies from memory and from
2496  * our data structures.  It is assumed that the DAG rooted in the
2497  * object has already been unreferenced, and that the object has a
2498  * reference count of 0.
2499  */
2500 static void
2501 unload_object(Obj_Entry *root)
2502 {
2503     Obj_Entry *obj;
2504     Obj_Entry **linkp;
2505
2506     assert(root->refcount == 0);
2507
2508     /*
2509      * Pass over the DAG removing unreferenced objects from
2510      * appropriate lists.
2511      */ 
2512     unlink_object(root);
2513
2514     /* Unmap all objects that are no longer referenced. */
2515     linkp = &obj_list->next;
2516     while ((obj = *linkp) != NULL) {
2517         if (obj->refcount == 0) {
2518             dbg("unloading \"%s\"", obj->path);
2519             munmap(obj->mapbase, obj->mapsize);
2520             linkmap_delete(obj);
2521             *linkp = obj->next;
2522             obj_count--;
2523             obj_free(obj);
2524         } else
2525             linkp = &obj->next;
2526     }
2527     obj_tail = linkp;
2528 }
2529
2530 static void
2531 unlink_object(Obj_Entry *root)
2532 {
2533     const Needed_Entry *needed;
2534     Objlist_Entry *elm;
2535
2536     if (root->refcount == 0) {
2537         /* Remove the object from the RTLD_GLOBAL list. */
2538         objlist_remove(&list_global, root);
2539
2540         /* Remove the object from all objects' DAG lists. */
2541         STAILQ_FOREACH(elm, &root->dagmembers , link)
2542             objlist_remove(&elm->obj->dldags, root);
2543     }
2544
2545     for (needed = root->needed;  needed != NULL;  needed = needed->next)
2546         if (needed->obj != NULL)
2547             unlink_object(needed->obj);
2548 }
2549
2550 static void
2551 unref_dag(Obj_Entry *root)
2552 {
2553     const Needed_Entry *needed;
2554
2555     if (root->refcount == 0)
2556         return;
2557     root->refcount--;
2558     if (root->refcount == 0)
2559         for (needed = root->needed;  needed != NULL;  needed = needed->next)
2560             if (needed->obj != NULL)
2561                 unref_dag(needed->obj);
2562 }
2563
2564 /*
2565  * Common code for MD __tls_get_addr().
2566  */
2567 void *
2568 tls_get_addr_common(void **dtvp, int index, size_t offset)
2569 {
2570     Elf_Addr* dtv = *dtvp;
2571
2572     /* Check dtv generation in case new modules have arrived */
2573     if (dtv[0] != tls_dtv_generation) {
2574         Elf_Addr* newdtv;
2575         int to_copy;
2576
2577         wlock_acquire();
2578
2579         newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2580         to_copy = dtv[1];
2581         if (to_copy > tls_max_index)
2582             to_copy = tls_max_index;
2583         memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2584         newdtv[0] = tls_dtv_generation;
2585         newdtv[1] = tls_max_index;
2586         free(dtv);
2587         *dtvp = newdtv;
2588
2589         wlock_release();
2590     }
2591
2592     /* Dynamically allocate module TLS if necessary */
2593     if (!dtv[index + 1]) {
2594         /* XXX
2595          * here we should avoid to be re-entered by signal handler
2596          * code, I assume wlock_acquire will masked all signals,
2597          * otherwise there is race and dead lock thread itself.
2598          */
2599         wlock_acquire();
2600         if (!dtv[index + 1])
2601             dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2602         wlock_release();
2603     }
2604
2605     return (void*) (dtv[index + 1] + offset);
2606 }
2607
2608 #if defined(RTLD_STATIC_TLS_VARIANT_II)
2609
2610 /*
2611  * Allocate the static TLS area.  Return a pointer to the TCB.  The 
2612  * static area is based on negative offsets relative to the tcb.
2613  *
2614  * The TCB contains an errno pointer for the system call layer, but because
2615  * we are the RTLD we really have no idea how the caller was compiled so
2616  * the information has to be passed in.  errno can either be:
2617  *
2618  *      type 0  errno is a simple non-TLS global pointer.
2619  *              (special case for e.g. libc_rtld)
2620  *      type 1  errno accessed by GOT entry     (dynamically linked programs)
2621  *      type 2  errno accessed by %gs:OFFSET    (statically linked programs)
2622  */
2623 struct tls_tcb *
2624 allocate_tls(Obj_Entry *objs)
2625 {
2626     Obj_Entry *obj;
2627     size_t data_size;
2628     size_t dtv_size;
2629     struct tls_tcb *tcb;
2630     Elf_Addr *dtv;
2631     Elf_Addr addr;
2632
2633     /*
2634      * Allocate the new TCB.  static TLS storage is placed just before the
2635      * TCB to support the %gs:OFFSET (negative offset) model.
2636      */
2637     data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2638                 ~RTLD_STATIC_TLS_ALIGN_MASK;
2639     tcb = malloc(data_size + sizeof(*tcb));
2640     tcb = (void *)((char *)tcb + data_size);    /* actual tcb location */
2641
2642     dtv_size = (tls_max_index + 2) * sizeof(Elf_Addr);
2643     dtv = malloc(dtv_size);
2644     bzero(dtv, dtv_size);
2645
2646 #ifdef RTLD_TCB_HAS_SELF_POINTER
2647     tcb->tcb_self = tcb;
2648 #endif
2649     tcb->tcb_dtv = dtv;
2650     tcb->tcb_pthread = NULL;
2651
2652     dtv[0] = tls_dtv_generation;
2653     dtv[1] = tls_max_index;
2654
2655     for (obj = objs; obj; obj = obj->next) {
2656         if (obj->tlsoffset) {
2657             addr = (Elf_Addr)tcb - obj->tlsoffset;
2658             memset((void *)(addr + obj->tlsinitsize),
2659                    0, obj->tlssize - obj->tlsinitsize);
2660             if (obj->tlsinit)
2661                 memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
2662             dtv[obj->tlsindex + 1] = addr;
2663         }
2664     }
2665     return(tcb);
2666 }
2667
2668 void
2669 free_tls(struct tls_tcb *tcb)
2670 {
2671     Elf_Addr *dtv;
2672     int dtv_size, i;
2673     Elf_Addr tls_start, tls_end;
2674     size_t data_size;
2675
2676     data_size = (tls_static_space + RTLD_STATIC_TLS_ALIGN_MASK) &
2677                 ~RTLD_STATIC_TLS_ALIGN_MASK;
2678     dtv = tcb->tcb_dtv;
2679     dtv_size = dtv[1];
2680     tls_end = (Elf_Addr)tcb;
2681     tls_start = (Elf_Addr)tcb - data_size;
2682     for (i = 0; i < dtv_size; i++) {
2683         if (dtv[i+2] != NULL && (dtv[i+2] < tls_start || dtv[i+2] > tls_end)) {
2684             free((void *)dtv[i+2]);
2685         }
2686     }
2687     free((void *)tls_start);
2688 }
2689
2690 #else
2691 #error "Unsupported TLS layout"
2692 #endif
2693
2694 /*
2695  * Allocate TLS block for module with given index.
2696  */
2697 void *
2698 allocate_module_tls(int index)
2699 {
2700     Obj_Entry* obj;
2701     char* p;
2702
2703     for (obj = obj_list; obj; obj = obj->next) {
2704         if (obj->tlsindex == index)
2705             break;
2706     }
2707     if (!obj) {
2708         _rtld_error("Can't find module with TLS index %d", index);
2709         die();
2710     }
2711
2712     p = malloc(obj->tlssize);
2713     memcpy(p, obj->tlsinit, obj->tlsinitsize);
2714     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
2715
2716     return p;
2717 }
2718
2719 bool
2720 allocate_tls_offset(Obj_Entry *obj)
2721 {
2722     size_t off;
2723
2724     if (obj->tls_done)
2725         return true;
2726
2727     if (obj->tlssize == 0) {
2728         obj->tls_done = true;
2729         return true;
2730     }
2731
2732     if (obj->tlsindex == 1)
2733         off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
2734     else
2735         off = calculate_tls_offset(tls_last_offset, tls_last_size,
2736                                    obj->tlssize, obj->tlsalign);
2737
2738     /*
2739      * If we have already fixed the size of the static TLS block, we
2740      * must stay within that size. When allocating the static TLS, we
2741      * leave a small amount of space spare to be used for dynamically
2742      * loading modules which use static TLS.
2743      */
2744     if (tls_static_space) {
2745         if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
2746             return false;
2747     }
2748
2749     tls_last_offset = obj->tlsoffset = off;
2750     tls_last_size = obj->tlssize;
2751     obj->tls_done = true;
2752
2753     return true;
2754 }
2755
2756 void
2757 free_tls_offset(Obj_Entry *obj)
2758 {
2759 #ifdef RTLD_STATIC_TLS_VARIANT_II
2760     /*
2761      * If we were the last thing to allocate out of the static TLS
2762      * block, we give our space back to the 'allocator'. This is a
2763      * simplistic workaround to allow libGL.so.1 to be loaded and
2764      * unloaded multiple times. We only handle the Variant II
2765      * mechanism for now - this really needs a proper allocator.  
2766      */
2767     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
2768         == calculate_tls_end(tls_last_offset, tls_last_size)) {
2769         tls_last_offset -= obj->tlssize;
2770         tls_last_size = 0;
2771     }
2772 #endif
2773 }
2774
2775 struct tls_tcb *
2776 _rtld_allocate_tls(void)
2777 {
2778     struct tls_tcb *new_tcb;
2779
2780     wlock_acquire();
2781     new_tcb = allocate_tls(obj_list);
2782     wlock_release();
2783
2784     return (new_tcb);
2785 }
2786
2787 void
2788 _rtld_free_tls(struct tls_tcb *tcb)
2789 {
2790     wlock_acquire();
2791     free_tls(tcb);
2792     wlock_release();
2793 }
2794