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