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