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