]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - libexec/rtld-elf/rtld.c
Disable SSL renegotiation in order to protect against a serious
[FreeBSD/releng/7.2.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$
27  */
28
29 /*
30  * Dynamic linker for ELF.
31  *
32  * John Polstra <jdp@polstra.com>.
33  */
34
35 #ifndef __GNUC__
36 #error "GCC is needed to compile this file"
37 #endif
38
39 #include <sys/param.h>
40 #include <sys/mount.h>
41 #include <sys/mman.h>
42 #include <sys/stat.h>
43 #include <sys/uio.h>
44 #include <sys/ktrace.h>
45
46 #include <dlfcn.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55
56 #include "debug.h"
57 #include "rtld.h"
58 #include "libmap.h"
59 #include "rtld_tls.h"
60
61 #ifndef COMPAT_32BIT
62 #define PATH_RTLD       "/libexec/ld-elf.so.1"
63 #else
64 #define PATH_RTLD       "/libexec/ld-elf32.so.1"
65 #endif
66
67 /* Types. */
68 typedef void (*func_ptr_type)();
69 typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
70
71 /*
72  * This structure provides a reentrant way to keep a list of objects and
73  * check which ones have already been processed in some way.
74  */
75 typedef struct Struct_DoneList {
76     const Obj_Entry **objs;             /* Array of object pointers */
77     unsigned int num_alloc;             /* Allocated size of the array */
78     unsigned int num_used;              /* Number of array slots used */
79 } DoneList;
80
81 /*
82  * Function declarations.
83  */
84 static const char *basename(const char *);
85 static void die(void) __dead2;
86 static void digest_dynamic(Obj_Entry *, int);
87 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
88 static Obj_Entry *dlcheck(void *);
89 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *);
90 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
91 static bool donelist_check(DoneList *, const Obj_Entry *);
92 static void errmsg_restore(char *);
93 static char *errmsg_save(void);
94 static void *fill_search_info(const char *, size_t, void *);
95 static char *find_library(const char *, const Obj_Entry *);
96 static const char *gethints(void);
97 static void init_dag(Obj_Entry *);
98 static void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
99 static void init_rtld(caddr_t);
100 static void initlist_add_neededs(Needed_Entry *, Objlist *);
101 static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
102 static bool is_exported(const Elf_Sym *);
103 static void linkmap_add(Obj_Entry *);
104 static void linkmap_delete(Obj_Entry *);
105 static int load_needed_objects(Obj_Entry *);
106 static int load_preload_objects(void);
107 static Obj_Entry *load_object(const char *, const Obj_Entry *);
108 static Obj_Entry *obj_from_addr(const void *);
109 static void objlist_call_fini(Objlist *, int *lockstate);
110 static void objlist_call_init(Objlist *, int *lockstate);
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 *);
124 static void set_program_var(const char *, const void *);
125 static const Elf_Sym *symlook_default(const char *, unsigned long,
126   const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int);
127 static const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *,
128   const Obj_Entry **, const Ver_Entry *, int, DoneList *);
129 static const Elf_Sym *symlook_needed(const char *, unsigned long,
130   const Needed_Entry *, const Obj_Entry **, const Ver_Entry *,
131   int, DoneList *);
132 static void trace_loaded_objects(Obj_Entry *);
133 static void unlink_object(Obj_Entry *);
134 static void unload_object(Obj_Entry *);
135 static void unref_dag(Obj_Entry *);
136 static void ref_dag(Obj_Entry *);
137 static int  rtld_verify_versions(const Objlist *);
138 static int  rtld_verify_object_versions(Obj_Entry *);
139 static void object_add_name(Obj_Entry *, const char *);
140 static int  object_match_name(const Obj_Entry *, const char *);
141 static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
142
143 void r_debug_state(struct r_debug *, struct link_map *);
144
145 /*
146  * Data declarations.
147  */
148 static char *error_message;     /* Message for dlerror(), or NULL */
149 struct r_debug r_debug;         /* for GDB; */
150 static bool libmap_disable;     /* Disable libmap */
151 static char *libmap_override;   /* Maps to use in addition to libmap.conf */
152 static bool trust;              /* False for setuid and setgid programs */
153 static bool dangerous_ld_env;   /* True if environment variables have been
154                                    used to affect the libraries loaded */
155 static char *ld_bind_now;       /* Environment variable for immediate binding */
156 static char *ld_debug;          /* Environment variable for debugging */
157 static char *ld_library_path;   /* Environment variable for search path */
158 static char *ld_preload;        /* Environment variable for libraries to
159                                    load first */
160 static char *ld_tracing;        /* Called from ldd to print libs */
161 static char *ld_utrace;         /* Use utrace() to log events. */
162 static Obj_Entry *obj_list;     /* Head of linked list of shared objects */
163 static Obj_Entry **obj_tail;    /* Link field of last object in list */
164 static Obj_Entry *obj_main;     /* The main program shared object */
165 static Obj_Entry obj_rtld;      /* The dynamic linker shared object */
166 static unsigned int obj_count;  /* Number of objects in obj_list */
167 static unsigned int obj_loads;  /* Number of objects in obj_list */
168
169 static Objlist list_global =    /* Objects dlopened with RTLD_GLOBAL */
170   STAILQ_HEAD_INITIALIZER(list_global);
171 static Objlist list_main =      /* Objects loaded at program startup */
172   STAILQ_HEAD_INITIALIZER(list_main);
173 static Objlist list_fini =      /* Objects needing fini() calls */
174   STAILQ_HEAD_INITIALIZER(list_fini);
175
176 static Elf_Sym sym_zero;        /* For resolving undefined weak refs. */
177
178 #define GDB_STATE(s,m)  r_debug.r_state = s; r_debug_state(&r_debug,m);
179
180 extern Elf_Dyn _DYNAMIC;
181 #pragma weak _DYNAMIC
182 #ifndef RTLD_IS_DYNAMIC
183 #define RTLD_IS_DYNAMIC()       (&_DYNAMIC != NULL)
184 #endif
185
186 /*
187  * These are the functions the dynamic linker exports to application
188  * programs.  They are the only symbols the dynamic linker is willing
189  * to export from itself.
190  */
191 static func_ptr_type exports[] = {
192     (func_ptr_type) &_rtld_error,
193     (func_ptr_type) &dlclose,
194     (func_ptr_type) &dlerror,
195     (func_ptr_type) &dlopen,
196     (func_ptr_type) &dlsym,
197     (func_ptr_type) &dlvsym,
198     (func_ptr_type) &dladdr,
199     (func_ptr_type) &dllockinit,
200     (func_ptr_type) &dlinfo,
201     (func_ptr_type) &_rtld_thread_init,
202 #ifdef __i386__
203     (func_ptr_type) &___tls_get_addr,
204 #endif
205     (func_ptr_type) &__tls_get_addr,
206     (func_ptr_type) &_rtld_allocate_tls,
207     (func_ptr_type) &_rtld_free_tls,
208     (func_ptr_type) &dl_iterate_phdr,
209     (func_ptr_type) &_rtld_atfork_pre,
210     (func_ptr_type) &_rtld_atfork_post,
211     NULL
212 };
213
214 /*
215  * Global declarations normally provided by crt1.  The dynamic linker is
216  * not built with crt1, so we have to provide them ourselves.
217  */
218 char *__progname;
219 char **environ;
220
221 /*
222  * Globals to control TLS allocation.
223  */
224 size_t tls_last_offset;         /* Static TLS offset of last module */
225 size_t tls_last_size;           /* Static TLS size of last module */
226 size_t tls_static_space;        /* Static TLS space allocated */
227 int tls_dtv_generation = 1;     /* Used to detect when dtv size changes  */
228 int tls_max_index = 1;          /* Largest module index allocated */
229
230 /*
231  * Fill in a DoneList with an allocation large enough to hold all of
232  * the currently-loaded objects.  Keep this as a macro since it calls
233  * alloca and we want that to occur within the scope of the caller.
234  */
235 #define donelist_init(dlp)                                      \
236     ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]),   \
237     assert((dlp)->objs != NULL),                                \
238     (dlp)->num_alloc = obj_count,                               \
239     (dlp)->num_used = 0)
240
241 #define UTRACE_DLOPEN_START             1
242 #define UTRACE_DLOPEN_STOP              2
243 #define UTRACE_DLCLOSE_START            3
244 #define UTRACE_DLCLOSE_STOP             4
245 #define UTRACE_LOAD_OBJECT              5
246 #define UTRACE_UNLOAD_OBJECT            6
247 #define UTRACE_ADD_RUNDEP               7
248 #define UTRACE_PRELOAD_FINISHED         8
249 #define UTRACE_INIT_CALL                9
250 #define UTRACE_FINI_CALL                10
251
252 struct utrace_rtld {
253         char sig[4];                    /* 'RTLD' */
254         int event;
255         void *handle;
256         void *mapbase;                  /* Used for 'parent' and 'init/fini' */
257         size_t mapsize;
258         int refcnt;                     /* Used for 'mode' */
259         char name[MAXPATHLEN];
260 };
261
262 #define LD_UTRACE(e, h, mb, ms, r, n) do {                      \
263         if (ld_utrace != NULL)                                  \
264                 ld_utrace_log(e, h, mb, ms, r, n);              \
265 } while (0)
266
267 static void
268 ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
269     int refcnt, const char *name)
270 {
271         struct utrace_rtld ut;
272
273         ut.sig[0] = 'R';
274         ut.sig[1] = 'T';
275         ut.sig[2] = 'L';
276         ut.sig[3] = 'D';
277         ut.event = event;
278         ut.handle = handle;
279         ut.mapbase = mapbase;
280         ut.mapsize = mapsize;
281         ut.refcnt = refcnt;
282         bzero(ut.name, sizeof(ut.name));
283         if (name)
284                 strlcpy(ut.name, name, sizeof(ut.name));
285         utrace(&ut, sizeof(ut));
286 }
287
288 /*
289  * Main entry point for dynamic linking.  The first argument is the
290  * stack pointer.  The stack is expected to be laid out as described
291  * in the SVR4 ABI specification, Intel 386 Processor Supplement.
292  * Specifically, the stack pointer points to a word containing
293  * ARGC.  Following that in the stack is a null-terminated sequence
294  * of pointers to argument strings.  Then comes a null-terminated
295  * sequence of pointers to environment strings.  Finally, there is a
296  * sequence of "auxiliary vector" entries.
297  *
298  * The second argument points to a place to store the dynamic linker's
299  * exit procedure pointer and the third to a place to store the main
300  * program's object.
301  *
302  * The return value is the main program's entry point.
303  */
304 func_ptr_type
305 _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
306 {
307     Elf_Auxinfo *aux_info[AT_COUNT];
308     int i;
309     int argc;
310     char **argv;
311     char **env;
312     Elf_Auxinfo *aux;
313     Elf_Auxinfo *auxp;
314     const char *argv0;
315     Objlist_Entry *entry;
316     Obj_Entry *obj;
317     Obj_Entry **preload_tail;
318     Objlist initlist;
319     int lockstate;
320
321     /*
322      * On entry, the dynamic linker itself has not been relocated yet.
323      * Be very careful not to reference any global data until after
324      * init_rtld has returned.  It is OK to reference file-scope statics
325      * and string constants, and to call static and global functions.
326      */
327
328     /* Find the auxiliary vector on the stack. */
329     argc = *sp++;
330     argv = (char **) sp;
331     sp += argc + 1;     /* Skip over arguments and NULL terminator */
332     env = (char **) sp;
333     while (*sp++ != 0)  /* Skip over environment, and NULL terminator */
334         ;
335     aux = (Elf_Auxinfo *) sp;
336
337     /* Digest the auxiliary vector. */
338     for (i = 0;  i < AT_COUNT;  i++)
339         aux_info[i] = NULL;
340     for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
341         if (auxp->a_type < AT_COUNT)
342             aux_info[auxp->a_type] = auxp;
343     }
344
345     /* Initialize and relocate ourselves. */
346     assert(aux_info[AT_BASE] != NULL);
347     init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
348
349     __progname = obj_rtld.path;
350     argv0 = argv[0] != NULL ? argv[0] : "(null)";
351     environ = env;
352
353     trust = !issetugid();
354
355     ld_bind_now = getenv(LD_ "BIND_NOW");
356     /* 
357      * If the process is tainted, then we un-set the dangerous environment
358      * variables.  The process will be marked as tainted until setuid(2)
359      * is called.  If any child process calls setuid(2) we do not want any
360      * future processes to honor the potentially un-safe variables.
361      */
362     if (!trust) {
363         if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
364             unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
365             unsetenv(LD_ "DEBUG")) {
366                 _rtld_error("environment corrupt; aborting");
367                 die();
368         }
369     }
370     ld_debug = getenv(LD_ "DEBUG");
371     libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
372     libmap_override = getenv(LD_ "LIBMAP");
373     ld_library_path = getenv(LD_ "LIBRARY_PATH");
374     ld_preload = getenv(LD_ "PRELOAD");
375     dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
376         (ld_library_path != NULL) || (ld_preload != NULL);
377     ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
378     ld_utrace = getenv(LD_ "UTRACE");
379
380     if (ld_debug != NULL && *ld_debug != '\0')
381         debug = 1;
382     dbg("%s is initialized, base address = %p", __progname,
383         (caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
384     dbg("RTLD dynamic = %p", obj_rtld.dynamic);
385     dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
386
387     /*
388      * Load the main program, or process its program header if it is
389      * already loaded.
390      */
391     if (aux_info[AT_EXECFD] != NULL) {  /* Load the main program. */
392         int fd = aux_info[AT_EXECFD]->a_un.a_val;
393         dbg("loading main program");
394         obj_main = map_object(fd, argv0, NULL);
395         close(fd);
396         if (obj_main == NULL)
397             die();
398     } else {                            /* Main program already loaded. */
399         const Elf_Phdr *phdr;
400         int phnum;
401         caddr_t entry;
402
403         dbg("processing main program's program header");
404         assert(aux_info[AT_PHDR] != NULL);
405         phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
406         assert(aux_info[AT_PHNUM] != NULL);
407         phnum = aux_info[AT_PHNUM]->a_un.a_val;
408         assert(aux_info[AT_PHENT] != NULL);
409         assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
410         assert(aux_info[AT_ENTRY] != NULL);
411         entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
412         if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
413             die();
414     }
415
416     obj_main->path = xstrdup(argv0);
417     obj_main->mainprog = true;
418
419     /*
420      * Get the actual dynamic linker pathname from the executable if
421      * possible.  (It should always be possible.)  That ensures that
422      * gdb will find the right dynamic linker even if a non-standard
423      * one is being used.
424      */
425     if (obj_main->interp != NULL &&
426       strcmp(obj_main->interp, obj_rtld.path) != 0) {
427         free(obj_rtld.path);
428         obj_rtld.path = xstrdup(obj_main->interp);
429         __progname = obj_rtld.path;
430     }
431
432     digest_dynamic(obj_main, 0);
433
434     linkmap_add(obj_main);
435     linkmap_add(&obj_rtld);
436
437     /* Link the main program into the list of objects. */
438     *obj_tail = obj_main;
439     obj_tail = &obj_main->next;
440     obj_count++;
441     obj_loads++;
442     /* Make sure we don't call the main program's init and fini functions. */
443     obj_main->init = obj_main->fini = (Elf_Addr)NULL;
444
445     /* Initialize a fake symbol for resolving undefined weak references. */
446     sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
447     sym_zero.st_shndx = SHN_UNDEF;
448
449     if (!libmap_disable)
450         libmap_disable = (bool)lm_init(libmap_override);
451
452     dbg("loading LD_PRELOAD libraries");
453     if (load_preload_objects() == -1)
454         die();
455     preload_tail = obj_tail;
456
457     dbg("loading needed objects");
458     if (load_needed_objects(obj_main) == -1)
459         die();
460
461     /* Make a list of all objects loaded at startup. */
462     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
463         objlist_push_tail(&list_main, obj);
464         obj->refcount++;
465     }
466
467     dbg("checking for required versions");
468     if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
469         die();
470
471     if (ld_tracing) {           /* We're done */
472         trace_loaded_objects(obj_main);
473         exit(0);
474     }
475
476     if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
477        dump_relocations(obj_main);
478        exit (0);
479     }
480
481     /* setup TLS for main thread */
482     dbg("initializing initial thread local storage");
483     STAILQ_FOREACH(entry, &list_main, link) {
484         /*
485          * Allocate all the initial objects out of the static TLS
486          * block even if they didn't ask for it.
487          */
488         allocate_tls_offset(entry->obj);
489     }
490     allocate_initial_tls(obj_list);
491
492     if (relocate_objects(obj_main,
493         ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
494         die();
495
496     dbg("doing copy relocations");
497     if (do_copy_relocations(obj_main) == -1)
498         die();
499
500     if (getenv(LD_ "DUMP_REL_POST") != NULL) {
501        dump_relocations(obj_main);
502        exit (0);
503     }
504
505     dbg("initializing key program variables");
506     set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
507     set_program_var("environ", env);
508
509     dbg("initializing thread locks");
510     lockdflt_init();
511
512     /* Make a list of init functions to call. */
513     objlist_init(&initlist);
514     initlist_add_objects(obj_list, preload_tail, &initlist);
515
516     r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
517
518     lockstate = wlock_acquire(rtld_bind_lock);
519     objlist_call_init(&initlist, &lockstate);
520     objlist_clear(&initlist);
521     wlock_release(rtld_bind_lock, lockstate);
522
523     dbg("transferring control to program entry point = %p", obj_main->entry);
524
525     /* Return the exit procedure and the program entry point. */
526     *exit_proc = rtld_exit;
527     *objp = obj_main;
528     return (func_ptr_type) obj_main->entry;
529 }
530
531 Elf_Addr
532 _rtld_bind(Obj_Entry *obj, Elf_Size reloff)
533 {
534     const Elf_Rel *rel;
535     const Elf_Sym *def;
536     const Obj_Entry *defobj;
537     Elf_Addr *where;
538     Elf_Addr target;
539     int lockstate;
540
541     lockstate = rlock_acquire(rtld_bind_lock);
542     if (obj->pltrel)
543         rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
544     else
545         rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
546
547     where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
548     def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
549     if (def == NULL)
550         die();
551
552     target = (Elf_Addr)(defobj->relocbase + def->st_value);
553
554     dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
555       defobj->strtab + def->st_name, basename(obj->path),
556       (void *)target, basename(defobj->path));
557
558     /*
559      * Write the new contents for the jmpslot. Note that depending on
560      * architecture, the value which we need to return back to the
561      * lazy binding trampoline may or may not be the target
562      * address. The value returned from reloc_jmpslot() is the value
563      * that the trampoline needs.
564      */
565     target = reloc_jmpslot(where, target, defobj, obj, rel);
566     rlock_release(rtld_bind_lock, lockstate);
567     return target;
568 }
569
570 /*
571  * Error reporting function.  Use it like printf.  If formats the message
572  * into a buffer, and sets things up so that the next call to dlerror()
573  * will return the message.
574  */
575 void
576 _rtld_error(const char *fmt, ...)
577 {
578     static char buf[512];
579     va_list ap;
580
581     va_start(ap, fmt);
582     vsnprintf(buf, sizeof buf, fmt, ap);
583     error_message = buf;
584     va_end(ap);
585 }
586
587 /*
588  * Return a dynamically-allocated copy of the current error message, if any.
589  */
590 static char *
591 errmsg_save(void)
592 {
593     return error_message == NULL ? NULL : xstrdup(error_message);
594 }
595
596 /*
597  * Restore the current error message from a copy which was previously saved
598  * by errmsg_save().  The copy is freed.
599  */
600 static void
601 errmsg_restore(char *saved_msg)
602 {
603     if (saved_msg == NULL)
604         error_message = NULL;
605     else {
606         _rtld_error("%s", saved_msg);
607         free(saved_msg);
608     }
609 }
610
611 static const char *
612 basename(const char *name)
613 {
614     const char *p = strrchr(name, '/');
615     return p != NULL ? p + 1 : name;
616 }
617
618 static void
619 die(void)
620 {
621     const char *msg = dlerror();
622
623     if (msg == NULL)
624         msg = "Fatal error";
625     errx(1, "%s", msg);
626 }
627
628 /*
629  * Process a shared object's DYNAMIC section, and save the important
630  * information in its Obj_Entry structure.
631  */
632 static void
633 digest_dynamic(Obj_Entry *obj, int early)
634 {
635     const Elf_Dyn *dynp;
636     Needed_Entry **needed_tail = &obj->needed;
637     const Elf_Dyn *dyn_rpath = NULL;
638     const Elf_Dyn *dyn_soname = NULL;
639     int plttype = DT_REL;
640
641     obj->bind_now = false;
642     for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
643         switch (dynp->d_tag) {
644
645         case DT_REL:
646             obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
647             break;
648
649         case DT_RELSZ:
650             obj->relsize = dynp->d_un.d_val;
651             break;
652
653         case DT_RELENT:
654             assert(dynp->d_un.d_val == sizeof(Elf_Rel));
655             break;
656
657         case DT_JMPREL:
658             obj->pltrel = (const Elf_Rel *)
659               (obj->relocbase + dynp->d_un.d_ptr);
660             break;
661
662         case DT_PLTRELSZ:
663             obj->pltrelsize = dynp->d_un.d_val;
664             break;
665
666         case DT_RELA:
667             obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
668             break;
669
670         case DT_RELASZ:
671             obj->relasize = dynp->d_un.d_val;
672             break;
673
674         case DT_RELAENT:
675             assert(dynp->d_un.d_val == sizeof(Elf_Rela));
676             break;
677
678         case DT_PLTREL:
679             plttype = dynp->d_un.d_val;
680             assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
681             break;
682
683         case DT_SYMTAB:
684             obj->symtab = (const Elf_Sym *)
685               (obj->relocbase + dynp->d_un.d_ptr);
686             break;
687
688         case DT_SYMENT:
689             assert(dynp->d_un.d_val == sizeof(Elf_Sym));
690             break;
691
692         case DT_STRTAB:
693             obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
694             break;
695
696         case DT_STRSZ:
697             obj->strsize = dynp->d_un.d_val;
698             break;
699
700         case DT_VERNEED:
701             obj->verneed = (const Elf_Verneed *) (obj->relocbase +
702                 dynp->d_un.d_val);
703             break;
704
705         case DT_VERNEEDNUM:
706             obj->verneednum = dynp->d_un.d_val;
707             break;
708
709         case DT_VERDEF:
710             obj->verdef = (const Elf_Verdef *) (obj->relocbase +
711                 dynp->d_un.d_val);
712             break;
713
714         case DT_VERDEFNUM:
715             obj->verdefnum = dynp->d_un.d_val;
716             break;
717
718         case DT_VERSYM:
719             obj->versyms = (const Elf_Versym *)(obj->relocbase +
720                 dynp->d_un.d_val);
721             break;
722
723         case DT_HASH:
724             {
725                 const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
726                   (obj->relocbase + dynp->d_un.d_ptr);
727                 obj->nbuckets = hashtab[0];
728                 obj->nchains = hashtab[1];
729                 obj->buckets = hashtab + 2;
730                 obj->chains = obj->buckets + obj->nbuckets;
731             }
732             break;
733
734         case DT_NEEDED:
735             if (!obj->rtld) {
736                 Needed_Entry *nep = NEW(Needed_Entry);
737                 nep->name = dynp->d_un.d_val;
738                 nep->obj = NULL;
739                 nep->next = NULL;
740
741                 *needed_tail = nep;
742                 needed_tail = &nep->next;
743             }
744             break;
745
746         case DT_PLTGOT:
747             obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
748             break;
749
750         case DT_TEXTREL:
751             obj->textrel = true;
752             break;
753
754         case DT_SYMBOLIC:
755             obj->symbolic = true;
756             break;
757
758         case DT_RPATH:
759         case DT_RUNPATH:        /* XXX: process separately */
760             /*
761              * We have to wait until later to process this, because we
762              * might not have gotten the address of the string table yet.
763              */
764             dyn_rpath = dynp;
765             break;
766
767         case DT_SONAME:
768             dyn_soname = dynp;
769             break;
770
771         case DT_INIT:
772             obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
773             break;
774
775         case DT_FINI:
776             obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
777             break;
778
779         case DT_DEBUG:
780             /* XXX - not implemented yet */
781             if (!early)
782                 dbg("Filling in DT_DEBUG entry");
783             ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
784             break;
785
786         case DT_FLAGS:
787                 if (dynp->d_un.d_val & DF_ORIGIN) {
788                     obj->origin_path = xmalloc(PATH_MAX);
789                     if (rtld_dirname(obj->path, obj->origin_path) == -1)
790                         die();
791                 }
792                 if (dynp->d_un.d_val & DF_SYMBOLIC)
793                     obj->symbolic = true;
794                 if (dynp->d_un.d_val & DF_TEXTREL)
795                     obj->textrel = true;
796                 if (dynp->d_un.d_val & DF_BIND_NOW)
797                     obj->bind_now = true;
798                 if (dynp->d_un.d_val & DF_STATIC_TLS)
799                     ;
800             break;
801
802         default:
803             if (!early) {
804                 dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
805                     (long)dynp->d_tag);
806             }
807             break;
808         }
809     }
810
811     obj->traced = false;
812
813     if (plttype == DT_RELA) {
814         obj->pltrela = (const Elf_Rela *) obj->pltrel;
815         obj->pltrel = NULL;
816         obj->pltrelasize = obj->pltrelsize;
817         obj->pltrelsize = 0;
818     }
819
820     if (dyn_rpath != NULL)
821         obj->rpath = obj->strtab + dyn_rpath->d_un.d_val;
822
823     if (dyn_soname != NULL)
824         object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
825 }
826
827 /*
828  * Process a shared object's program header.  This is used only for the
829  * main program, when the kernel has already loaded the main program
830  * into memory before calling the dynamic linker.  It creates and
831  * returns an Obj_Entry structure.
832  */
833 static Obj_Entry *
834 digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
835 {
836     Obj_Entry *obj;
837     const Elf_Phdr *phlimit = phdr + phnum;
838     const Elf_Phdr *ph;
839     int nsegs = 0;
840
841     obj = obj_new();
842     for (ph = phdr;  ph < phlimit;  ph++) {
843         switch (ph->p_type) {
844
845         case PT_PHDR:
846             if ((const Elf_Phdr *)ph->p_vaddr != phdr) {
847                 _rtld_error("%s: invalid PT_PHDR", path);
848                 return NULL;
849             }
850             obj->phdr = (const Elf_Phdr *) ph->p_vaddr;
851             obj->phsize = ph->p_memsz;
852             break;
853
854         case PT_INTERP:
855             obj->interp = (const char *) ph->p_vaddr;
856             break;
857
858         case PT_LOAD:
859             if (nsegs == 0) {   /* First load segment */
860                 obj->vaddrbase = trunc_page(ph->p_vaddr);
861                 obj->mapbase = (caddr_t) obj->vaddrbase;
862                 obj->relocbase = obj->mapbase - obj->vaddrbase;
863                 obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
864                   obj->vaddrbase;
865             } else {            /* Last load segment */
866                 obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
867                   obj->vaddrbase;
868             }
869             nsegs++;
870             break;
871
872         case PT_DYNAMIC:
873             obj->dynamic = (const Elf_Dyn *) ph->p_vaddr;
874             break;
875
876         case PT_TLS:
877             obj->tlsindex = 1;
878             obj->tlssize = ph->p_memsz;
879             obj->tlsalign = ph->p_align;
880             obj->tlsinitsize = ph->p_filesz;
881             obj->tlsinit = (void*) ph->p_vaddr;
882             break;
883         }
884     }
885     if (nsegs < 1) {
886         _rtld_error("%s: too few PT_LOAD segments", path);
887         return NULL;
888     }
889
890     obj->entry = entry;
891     return obj;
892 }
893
894 static Obj_Entry *
895 dlcheck(void *handle)
896 {
897     Obj_Entry *obj;
898
899     for (obj = obj_list;  obj != NULL;  obj = obj->next)
900         if (obj == (Obj_Entry *) handle)
901             break;
902
903     if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
904         _rtld_error("Invalid shared object handle %p", handle);
905         return NULL;
906     }
907     return obj;
908 }
909
910 /*
911  * If the given object is already in the donelist, return true.  Otherwise
912  * add the object to the list and return false.
913  */
914 static bool
915 donelist_check(DoneList *dlp, const Obj_Entry *obj)
916 {
917     unsigned int i;
918
919     for (i = 0;  i < dlp->num_used;  i++)
920         if (dlp->objs[i] == obj)
921             return true;
922     /*
923      * Our donelist allocation should always be sufficient.  But if
924      * our threads locking isn't working properly, more shared objects
925      * could have been loaded since we allocated the list.  That should
926      * never happen, but we'll handle it properly just in case it does.
927      */
928     if (dlp->num_used < dlp->num_alloc)
929         dlp->objs[dlp->num_used++] = obj;
930     return false;
931 }
932
933 /*
934  * Hash function for symbol table lookup.  Don't even think about changing
935  * this.  It is specified by the System V ABI.
936  */
937 unsigned long
938 elf_hash(const char *name)
939 {
940     const unsigned char *p = (const unsigned char *) name;
941     unsigned long h = 0;
942     unsigned long g;
943
944     while (*p != '\0') {
945         h = (h << 4) + *p++;
946         if ((g = h & 0xf0000000) != 0)
947             h ^= g >> 24;
948         h &= ~g;
949     }
950     return h;
951 }
952
953 /*
954  * Find the library with the given name, and return its full pathname.
955  * The returned string is dynamically allocated.  Generates an error
956  * message and returns NULL if the library cannot be found.
957  *
958  * If the second argument is non-NULL, then it refers to an already-
959  * loaded shared object, whose library search path will be searched.
960  *
961  * The search order is:
962  *   LD_LIBRARY_PATH
963  *   rpath in the referencing file
964  *   ldconfig hints
965  *   /lib:/usr/lib
966  */
967 static char *
968 find_library(const char *xname, const Obj_Entry *refobj)
969 {
970     char *pathname;
971     char *name;
972
973     if (strchr(xname, '/') != NULL) {   /* Hard coded pathname */
974         if (xname[0] != '/' && !trust) {
975             _rtld_error("Absolute pathname required for shared object \"%s\"",
976               xname);
977             return NULL;
978         }
979         return xstrdup(xname);
980     }
981
982     if (libmap_disable || (refobj == NULL) ||
983         (name = lm_find(refobj->path, xname)) == NULL)
984         name = (char *)xname;
985
986     dbg(" Searching for \"%s\"", name);
987
988     if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
989       (refobj != NULL &&
990       (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
991       (pathname = search_library_path(name, gethints())) != NULL ||
992       (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
993         return pathname;
994
995     if(refobj != NULL && refobj->path != NULL) {
996         _rtld_error("Shared object \"%s\" not found, required by \"%s\"",
997           name, basename(refobj->path));
998     } else {
999         _rtld_error("Shared object \"%s\" not found", name);
1000     }
1001     return NULL;
1002 }
1003
1004 /*
1005  * Given a symbol number in a referencing object, find the corresponding
1006  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1007  * no definition was found.  Returns a pointer to the Obj_Entry of the
1008  * defining object via the reference parameter DEFOBJ_OUT.
1009  */
1010 const Elf_Sym *
1011 find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1012     const Obj_Entry **defobj_out, int flags, SymCache *cache)
1013 {
1014     const Elf_Sym *ref;
1015     const Elf_Sym *def;
1016     const Obj_Entry *defobj;
1017     const Ver_Entry *ventry;
1018     const char *name;
1019     unsigned long hash;
1020
1021     /*
1022      * If we have already found this symbol, get the information from
1023      * the cache.
1024      */
1025     if (symnum >= refobj->nchains)
1026         return NULL;    /* Bad object */
1027     if (cache != NULL && cache[symnum].sym != NULL) {
1028         *defobj_out = cache[symnum].obj;
1029         return cache[symnum].sym;
1030     }
1031
1032     ref = refobj->symtab + symnum;
1033     name = refobj->strtab + ref->st_name;
1034     defobj = NULL;
1035
1036     /*
1037      * We don't have to do a full scale lookup if the symbol is local.
1038      * We know it will bind to the instance in this load module; to
1039      * which we already have a pointer (ie ref). By not doing a lookup,
1040      * we not only improve performance, but it also avoids unresolvable
1041      * symbols when local symbols are not in the hash table. This has
1042      * been seen with the ia64 toolchain.
1043      */
1044     if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1045         if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1046             _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1047                 symnum);
1048         }
1049         ventry = fetch_ventry(refobj, symnum);
1050         hash = elf_hash(name);
1051         def = symlook_default(name, hash, refobj, &defobj, ventry, flags);
1052     } else {
1053         def = ref;
1054         defobj = refobj;
1055     }
1056
1057     /*
1058      * If we found no definition and the reference is weak, treat the
1059      * symbol as having the value zero.
1060      */
1061     if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1062         def = &sym_zero;
1063         defobj = obj_main;
1064     }
1065
1066     if (def != NULL) {
1067         *defobj_out = defobj;
1068         /* Record the information in the cache to avoid subsequent lookups. */
1069         if (cache != NULL) {
1070             cache[symnum].sym = def;
1071             cache[symnum].obj = defobj;
1072         }
1073     } else {
1074         if (refobj != &obj_rtld)
1075             _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1076     }
1077     return def;
1078 }
1079
1080 /*
1081  * Return the search path from the ldconfig hints file, reading it if
1082  * necessary.  Returns NULL if there are problems with the hints file,
1083  * or if the search path there is empty.
1084  */
1085 static const char *
1086 gethints(void)
1087 {
1088     static char *hints;
1089
1090     if (hints == NULL) {
1091         int fd;
1092         struct elfhints_hdr hdr;
1093         char *p;
1094
1095         /* Keep from trying again in case the hints file is bad. */
1096         hints = "";
1097
1098         if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1)
1099             return NULL;
1100         if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1101           hdr.magic != ELFHINTS_MAGIC ||
1102           hdr.version != 1) {
1103             close(fd);
1104             return NULL;
1105         }
1106         p = xmalloc(hdr.dirlistlen + 1);
1107         if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1108           read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1109             free(p);
1110             close(fd);
1111             return NULL;
1112         }
1113         hints = p;
1114         close(fd);
1115     }
1116     return hints[0] != '\0' ? hints : NULL;
1117 }
1118
1119 static void
1120 init_dag(Obj_Entry *root)
1121 {
1122     DoneList donelist;
1123
1124     donelist_init(&donelist);
1125     init_dag1(root, root, &donelist);
1126 }
1127
1128 static void
1129 init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1130 {
1131     const Needed_Entry *needed;
1132
1133     if (donelist_check(dlp, obj))
1134         return;
1135
1136     obj->refcount++;
1137     objlist_push_tail(&obj->dldags, root);
1138     objlist_push_tail(&root->dagmembers, obj);
1139     for (needed = obj->needed;  needed != NULL;  needed = needed->next)
1140         if (needed->obj != NULL)
1141             init_dag1(root, needed->obj, dlp);
1142 }
1143
1144 /*
1145  * Initialize the dynamic linker.  The argument is the address at which
1146  * the dynamic linker has been mapped into memory.  The primary task of
1147  * this function is to relocate the dynamic linker.
1148  */
1149 static void
1150 init_rtld(caddr_t mapbase)
1151 {
1152     Obj_Entry objtmp;   /* Temporary rtld object */
1153
1154     /*
1155      * Conjure up an Obj_Entry structure for the dynamic linker.
1156      *
1157      * The "path" member can't be initialized yet because string constatns
1158      * cannot yet be acessed. Below we will set it correctly.
1159      */
1160     memset(&objtmp, 0, sizeof(objtmp));
1161     objtmp.path = NULL;
1162     objtmp.rtld = true;
1163     objtmp.mapbase = mapbase;
1164 #ifdef PIC
1165     objtmp.relocbase = mapbase;
1166 #endif
1167     if (RTLD_IS_DYNAMIC()) {
1168         objtmp.dynamic = rtld_dynamic(&objtmp);
1169         digest_dynamic(&objtmp, 1);
1170         assert(objtmp.needed == NULL);
1171         assert(!objtmp.textrel);
1172
1173         /*
1174          * Temporarily put the dynamic linker entry into the object list, so
1175          * that symbols can be found.
1176          */
1177
1178         relocate_objects(&objtmp, true, &objtmp);
1179     }
1180
1181     /* Initialize the object list. */
1182     obj_tail = &obj_list;
1183
1184     /* Now that non-local variables can be accesses, copy out obj_rtld. */
1185     memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1186
1187     /* Replace the path with a dynamically allocated copy. */
1188     obj_rtld.path = xstrdup(PATH_RTLD);
1189
1190     r_debug.r_brk = r_debug_state;
1191     r_debug.r_state = RT_CONSISTENT;
1192 }
1193
1194 /*
1195  * Add the init functions from a needed object list (and its recursive
1196  * needed objects) to "list".  This is not used directly; it is a helper
1197  * function for initlist_add_objects().  The write lock must be held
1198  * when this function is called.
1199  */
1200 static void
1201 initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1202 {
1203     /* Recursively process the successor needed objects. */
1204     if (needed->next != NULL)
1205         initlist_add_neededs(needed->next, list);
1206
1207     /* Process the current needed object. */
1208     if (needed->obj != NULL)
1209         initlist_add_objects(needed->obj, &needed->obj->next, list);
1210 }
1211
1212 /*
1213  * Scan all of the DAGs rooted in the range of objects from "obj" to
1214  * "tail" and add their init functions to "list".  This recurses over
1215  * the DAGs and ensure the proper init ordering such that each object's
1216  * needed libraries are initialized before the object itself.  At the
1217  * same time, this function adds the objects to the global finalization
1218  * list "list_fini" in the opposite order.  The write lock must be
1219  * held when this function is called.
1220  */
1221 static void
1222 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1223 {
1224     if (obj->init_done)
1225         return;
1226     obj->init_done = true;
1227
1228     /* Recursively process the successor objects. */
1229     if (&obj->next != tail)
1230         initlist_add_objects(obj->next, tail, list);
1231
1232     /* Recursively process the needed objects. */
1233     if (obj->needed != NULL)
1234         initlist_add_neededs(obj->needed, list);
1235
1236     /* Add the object to the init list. */
1237     if (obj->init != (Elf_Addr)NULL)
1238         objlist_push_tail(list, obj);
1239
1240     /* Add the object to the global fini list in the reverse order. */
1241     if (obj->fini != (Elf_Addr)NULL)
1242         objlist_push_head(&list_fini, obj);
1243 }
1244
1245 #ifndef FPTR_TARGET
1246 #define FPTR_TARGET(f)  ((Elf_Addr) (f))
1247 #endif
1248
1249 static bool
1250 is_exported(const Elf_Sym *def)
1251 {
1252     Elf_Addr value;
1253     const func_ptr_type *p;
1254
1255     value = (Elf_Addr)(obj_rtld.relocbase + def->st_value);
1256     for (p = exports;  *p != NULL;  p++)
1257         if (FPTR_TARGET(*p) == value)
1258             return true;
1259     return false;
1260 }
1261
1262 /*
1263  * Given a shared object, traverse its list of needed objects, and load
1264  * each of them.  Returns 0 on success.  Generates an error message and
1265  * returns -1 on failure.
1266  */
1267 static int
1268 load_needed_objects(Obj_Entry *first)
1269 {
1270     Obj_Entry *obj;
1271
1272     for (obj = first;  obj != NULL;  obj = obj->next) {
1273         Needed_Entry *needed;
1274
1275         for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
1276             needed->obj = load_object(obj->strtab + needed->name, obj);
1277             if (needed->obj == NULL && !ld_tracing)
1278                 return -1;
1279         }
1280     }
1281
1282     return 0;
1283 }
1284
1285 static int
1286 load_preload_objects(void)
1287 {
1288     char *p = ld_preload;
1289     static const char delim[] = " \t:;";
1290
1291     if (p == NULL)
1292         return 0;
1293
1294     p += strspn(p, delim);
1295     while (*p != '\0') {
1296         size_t len = strcspn(p, delim);
1297         char savech;
1298
1299         savech = p[len];
1300         p[len] = '\0';
1301         if (load_object(p, NULL) == NULL)
1302             return -1;  /* XXX - cleanup */
1303         p[len] = savech;
1304         p += len;
1305         p += strspn(p, delim);
1306     }
1307     LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1308     return 0;
1309 }
1310
1311 /*
1312  * Load a shared object into memory, if it is not already loaded.
1313  *
1314  * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1315  * on failure.
1316  */
1317 static Obj_Entry *
1318 load_object(const char *name, const Obj_Entry *refobj)
1319 {
1320     Obj_Entry *obj;
1321     int fd = -1;
1322     struct stat sb;
1323     char *path;
1324
1325     for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1326         if (object_match_name(obj, name))
1327             return obj;
1328
1329     path = find_library(name, refobj);
1330     if (path == NULL)
1331         return NULL;
1332
1333     /*
1334      * If we didn't find a match by pathname, open the file and check
1335      * again by device and inode.  This avoids false mismatches caused
1336      * by multiple links or ".." in pathnames.
1337      *
1338      * To avoid a race, we open the file and use fstat() rather than
1339      * using stat().
1340      */
1341     if ((fd = open(path, O_RDONLY)) == -1) {
1342         _rtld_error("Cannot open \"%s\"", path);
1343         free(path);
1344         return NULL;
1345     }
1346     if (fstat(fd, &sb) == -1) {
1347         _rtld_error("Cannot fstat \"%s\"", path);
1348         close(fd);
1349         free(path);
1350         return NULL;
1351     }
1352     for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1353         if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1354             close(fd);
1355             break;
1356         }
1357     }
1358     if (obj != NULL) {
1359         object_add_name(obj, name);
1360         free(path);
1361         close(fd);
1362         return obj;
1363     }
1364
1365     /* First use of this object, so we must map it in */
1366     obj = do_load_object(fd, name, path, &sb);
1367     if (obj == NULL)
1368         free(path);
1369     close(fd);
1370
1371     return obj;
1372 }
1373
1374 static Obj_Entry *
1375 do_load_object(int fd, const char *name, char *path, struct stat *sbp)
1376 {
1377     Obj_Entry *obj;
1378     struct statfs fs;
1379
1380     /*
1381      * but first, make sure that environment variables haven't been
1382      * used to circumvent the noexec flag on a filesystem.
1383      */
1384     if (dangerous_ld_env) {
1385         if (fstatfs(fd, &fs) != 0) {
1386             _rtld_error("Cannot fstatfs \"%s\"", path);
1387                 return NULL;
1388         }
1389         if (fs.f_flags & MNT_NOEXEC) {
1390             _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1391             return NULL;
1392         }
1393     }
1394     dbg("loading \"%s\"", path);
1395     obj = map_object(fd, path, sbp);
1396     if (obj == NULL)
1397         return NULL;
1398
1399     object_add_name(obj, name);
1400     obj->path = path;
1401     digest_dynamic(obj, 0);
1402
1403     *obj_tail = obj;
1404     obj_tail = &obj->next;
1405     obj_count++;
1406     obj_loads++;
1407     linkmap_add(obj);   /* for GDB & dlinfo() */
1408
1409     dbg("  %p .. %p: %s", obj->mapbase,
1410          obj->mapbase + obj->mapsize - 1, obj->path);
1411     if (obj->textrel)
1412         dbg("  WARNING: %s has impure text", obj->path);
1413     LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1414         obj->path);    
1415
1416     return obj;
1417 }
1418
1419 static Obj_Entry *
1420 obj_from_addr(const void *addr)
1421 {
1422     Obj_Entry *obj;
1423
1424     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1425         if (addr < (void *) obj->mapbase)
1426             continue;
1427         if (addr < (void *) (obj->mapbase + obj->mapsize))
1428             return obj;
1429     }
1430     return NULL;
1431 }
1432
1433 /*
1434  * Call the finalization functions for each of the objects in "list"
1435  * which are unreferenced.  All of the objects are expected to have
1436  * non-NULL fini functions.
1437  */
1438 static void
1439 objlist_call_fini(Objlist *list, int *lockstate)
1440 {
1441     Objlist_Entry *elm;
1442     char *saved_msg;
1443
1444     /*
1445      * Preserve the current error message since a fini function might
1446      * call into the dynamic linker and overwrite it.
1447      */
1448     saved_msg = errmsg_save();
1449     wlock_release(rtld_bind_lock, *lockstate);
1450     STAILQ_FOREACH(elm, list, link) {
1451         if (elm->obj->refcount == 0) {
1452             dbg("calling fini function for %s at %p", elm->obj->path,
1453                 (void *)elm->obj->fini);
1454             LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1455                 elm->obj->path);
1456             call_initfini_pointer(elm->obj, elm->obj->fini);
1457         }
1458     }
1459     *lockstate = wlock_acquire(rtld_bind_lock);
1460     errmsg_restore(saved_msg);
1461 }
1462
1463 /*
1464  * Call the initialization functions for each of the objects in
1465  * "list".  All of the objects are expected to have non-NULL init
1466  * functions.
1467  */
1468 static void
1469 objlist_call_init(Objlist *list, int *lockstate)
1470 {
1471     Objlist_Entry *elm;
1472     char *saved_msg;
1473
1474     /*
1475      * Preserve the current error message since an init function might
1476      * call into the dynamic linker and overwrite it.
1477      */
1478     saved_msg = errmsg_save();
1479     wlock_release(rtld_bind_lock, *lockstate);
1480     STAILQ_FOREACH(elm, list, link) {
1481         dbg("calling init function for %s at %p", elm->obj->path,
1482             (void *)elm->obj->init);
1483         LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1484             elm->obj->path);
1485         call_initfini_pointer(elm->obj, elm->obj->init);
1486     }
1487     *lockstate = wlock_acquire(rtld_bind_lock);
1488     errmsg_restore(saved_msg);
1489 }
1490
1491 static void
1492 objlist_clear(Objlist *list)
1493 {
1494     Objlist_Entry *elm;
1495
1496     while (!STAILQ_EMPTY(list)) {
1497         elm = STAILQ_FIRST(list);
1498         STAILQ_REMOVE_HEAD(list, link);
1499         free(elm);
1500     }
1501 }
1502
1503 static Objlist_Entry *
1504 objlist_find(Objlist *list, const Obj_Entry *obj)
1505 {
1506     Objlist_Entry *elm;
1507
1508     STAILQ_FOREACH(elm, list, link)
1509         if (elm->obj == obj)
1510             return elm;
1511     return NULL;
1512 }
1513
1514 static void
1515 objlist_init(Objlist *list)
1516 {
1517     STAILQ_INIT(list);
1518 }
1519
1520 static void
1521 objlist_push_head(Objlist *list, Obj_Entry *obj)
1522 {
1523     Objlist_Entry *elm;
1524
1525     elm = NEW(Objlist_Entry);
1526     elm->obj = obj;
1527     STAILQ_INSERT_HEAD(list, elm, link);
1528 }
1529
1530 static void
1531 objlist_push_tail(Objlist *list, Obj_Entry *obj)
1532 {
1533     Objlist_Entry *elm;
1534
1535     elm = NEW(Objlist_Entry);
1536     elm->obj = obj;
1537     STAILQ_INSERT_TAIL(list, elm, link);
1538 }
1539
1540 static void
1541 objlist_remove(Objlist *list, Obj_Entry *obj)
1542 {
1543     Objlist_Entry *elm;
1544
1545     if ((elm = objlist_find(list, obj)) != NULL) {
1546         STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1547         free(elm);
1548     }
1549 }
1550
1551 /*
1552  * Remove all of the unreferenced objects from "list".
1553  */
1554 static void
1555 objlist_remove_unref(Objlist *list)
1556 {
1557     Objlist newlist;
1558     Objlist_Entry *elm;
1559
1560     STAILQ_INIT(&newlist);
1561     while (!STAILQ_EMPTY(list)) {
1562         elm = STAILQ_FIRST(list);
1563         STAILQ_REMOVE_HEAD(list, link);
1564         if (elm->obj->refcount == 0)
1565             free(elm);
1566         else
1567             STAILQ_INSERT_TAIL(&newlist, elm, link);
1568     }
1569     *list = newlist;
1570 }
1571
1572 /*
1573  * Relocate newly-loaded shared objects.  The argument is a pointer to
1574  * the Obj_Entry for the first such object.  All objects from the first
1575  * to the end of the list of objects are relocated.  Returns 0 on success,
1576  * or -1 on failure.
1577  */
1578 static int
1579 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1580 {
1581     Obj_Entry *obj;
1582
1583     for (obj = first;  obj != NULL;  obj = obj->next) {
1584         if (obj != rtldobj)
1585             dbg("relocating \"%s\"", obj->path);
1586         if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1587             obj->symtab == NULL || obj->strtab == NULL) {
1588             _rtld_error("%s: Shared object has no run-time symbol table",
1589               obj->path);
1590             return -1;
1591         }
1592
1593         if (obj->textrel) {
1594             /* There are relocations to the write-protected text segment. */
1595             if (mprotect(obj->mapbase, obj->textsize,
1596               PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1597                 _rtld_error("%s: Cannot write-enable text segment: %s",
1598                   obj->path, strerror(errno));
1599                 return -1;
1600             }
1601         }
1602
1603         /* Process the non-PLT relocations. */
1604         if (reloc_non_plt(obj, rtldobj))
1605                 return -1;
1606
1607         if (obj->textrel) {     /* Re-protected the text segment. */
1608             if (mprotect(obj->mapbase, obj->textsize,
1609               PROT_READ|PROT_EXEC) == -1) {
1610                 _rtld_error("%s: Cannot write-protect text segment: %s",
1611                   obj->path, strerror(errno));
1612                 return -1;
1613             }
1614         }
1615
1616         /* Process the PLT relocations. */
1617         if (reloc_plt(obj) == -1)
1618             return -1;
1619         /* Relocate the jump slots if we are doing immediate binding. */
1620         if (obj->bind_now || bind_now)
1621             if (reloc_jmpslots(obj) == -1)
1622                 return -1;
1623
1624
1625         /*
1626          * Set up the magic number and version in the Obj_Entry.  These
1627          * were checked in the crt1.o from the original ElfKit, so we
1628          * set them for backward compatibility.
1629          */
1630         obj->magic = RTLD_MAGIC;
1631         obj->version = RTLD_VERSION;
1632
1633         /* Set the special PLT or GOT entries. */
1634         init_pltgot(obj);
1635     }
1636
1637     return 0;
1638 }
1639
1640 /*
1641  * Cleanup procedure.  It will be called (by the atexit mechanism) just
1642  * before the process exits.
1643  */
1644 static void
1645 rtld_exit(void)
1646 {
1647     Obj_Entry *obj;
1648     int lockstate;
1649
1650     lockstate = wlock_acquire(rtld_bind_lock);
1651     dbg("rtld_exit()");
1652     /* Clear all the reference counts so the fini functions will be called. */
1653     for (obj = obj_list;  obj != NULL;  obj = obj->next)
1654         obj->refcount = 0;
1655     objlist_call_fini(&list_fini, &lockstate);
1656     /* No need to remove the items from the list, since we are exiting. */
1657     if (!libmap_disable)
1658         lm_fini();
1659     wlock_release(rtld_bind_lock, lockstate);
1660 }
1661
1662 static void *
1663 path_enumerate(const char *path, path_enum_proc callback, void *arg)
1664 {
1665 #ifdef COMPAT_32BIT
1666     const char *trans;
1667 #endif
1668     if (path == NULL)
1669         return (NULL);
1670
1671     path += strspn(path, ":;");
1672     while (*path != '\0') {
1673         size_t len;
1674         char  *res;
1675
1676         len = strcspn(path, ":;");
1677 #ifdef COMPAT_32BIT
1678         trans = lm_findn(NULL, path, len);
1679         if (trans)
1680             res = callback(trans, strlen(trans), arg);
1681         else
1682 #endif
1683         res = callback(path, len, arg);
1684
1685         if (res != NULL)
1686             return (res);
1687
1688         path += len;
1689         path += strspn(path, ":;");
1690     }
1691
1692     return (NULL);
1693 }
1694
1695 struct try_library_args {
1696     const char  *name;
1697     size_t       namelen;
1698     char        *buffer;
1699     size_t       buflen;
1700 };
1701
1702 static void *
1703 try_library_path(const char *dir, size_t dirlen, void *param)
1704 {
1705     struct try_library_args *arg;
1706
1707     arg = param;
1708     if (*dir == '/' || trust) {
1709         char *pathname;
1710
1711         if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1712                 return (NULL);
1713
1714         pathname = arg->buffer;
1715         strncpy(pathname, dir, dirlen);
1716         pathname[dirlen] = '/';
1717         strcpy(pathname + dirlen + 1, arg->name);
1718
1719         dbg("  Trying \"%s\"", pathname);
1720         if (access(pathname, F_OK) == 0) {              /* We found it */
1721             pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1722             strcpy(pathname, arg->buffer);
1723             return (pathname);
1724         }
1725     }
1726     return (NULL);
1727 }
1728
1729 static char *
1730 search_library_path(const char *name, const char *path)
1731 {
1732     char *p;
1733     struct try_library_args arg;
1734
1735     if (path == NULL)
1736         return NULL;
1737
1738     arg.name = name;
1739     arg.namelen = strlen(name);
1740     arg.buffer = xmalloc(PATH_MAX);
1741     arg.buflen = PATH_MAX;
1742
1743     p = path_enumerate(path, try_library_path, &arg);
1744
1745     free(arg.buffer);
1746
1747     return (p);
1748 }
1749
1750 int
1751 dlclose(void *handle)
1752 {
1753     Obj_Entry *root;
1754     int lockstate;
1755
1756     lockstate = wlock_acquire(rtld_bind_lock);
1757     root = dlcheck(handle);
1758     if (root == NULL) {
1759         wlock_release(rtld_bind_lock, lockstate);
1760         return -1;
1761     }
1762     LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1763         root->path);
1764
1765     /* Unreference the object and its dependencies. */
1766     root->dl_refcount--;
1767
1768     unref_dag(root);
1769
1770     if (root->refcount == 0) {
1771         /*
1772          * The object is no longer referenced, so we must unload it.
1773          * First, call the fini functions.
1774          */
1775         objlist_call_fini(&list_fini, &lockstate);
1776         objlist_remove_unref(&list_fini);
1777
1778         /* Finish cleaning up the newly-unreferenced objects. */
1779         GDB_STATE(RT_DELETE,&root->linkmap);
1780         unload_object(root);
1781         GDB_STATE(RT_CONSISTENT,NULL);
1782     }
1783     LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1784     wlock_release(rtld_bind_lock, lockstate);
1785     return 0;
1786 }
1787
1788 const char *
1789 dlerror(void)
1790 {
1791     char *msg = error_message;
1792     error_message = NULL;
1793     return msg;
1794 }
1795
1796 /*
1797  * This function is deprecated and has no effect.
1798  */
1799 void
1800 dllockinit(void *context,
1801            void *(*lock_create)(void *context),
1802            void (*rlock_acquire)(void *lock),
1803            void (*wlock_acquire)(void *lock),
1804            void (*lock_release)(void *lock),
1805            void (*lock_destroy)(void *lock),
1806            void (*context_destroy)(void *context))
1807 {
1808     static void *cur_context;
1809     static void (*cur_context_destroy)(void *);
1810
1811     /* Just destroy the context from the previous call, if necessary. */
1812     if (cur_context_destroy != NULL)
1813         cur_context_destroy(cur_context);
1814     cur_context = context;
1815     cur_context_destroy = context_destroy;
1816 }
1817
1818 void *
1819 dlopen(const char *name, int mode)
1820 {
1821     Obj_Entry **old_obj_tail;
1822     Obj_Entry *obj;
1823     Objlist initlist;
1824     int result, lockstate;
1825
1826     LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
1827     ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1828     if (ld_tracing != NULL)
1829         environ = (char **)*get_program_var_addr("environ");
1830
1831     objlist_init(&initlist);
1832
1833     lockstate = wlock_acquire(rtld_bind_lock);
1834     GDB_STATE(RT_ADD,NULL);
1835
1836     old_obj_tail = obj_tail;
1837     obj = NULL;
1838     if (name == NULL) {
1839         obj = obj_main;
1840         obj->refcount++;
1841     } else {
1842         obj = load_object(name, obj_main);
1843     }
1844
1845     if (obj) {
1846         obj->dl_refcount++;
1847         if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
1848             objlist_push_tail(&list_global, obj);
1849         mode &= RTLD_MODEMASK;
1850         if (*old_obj_tail != NULL) {            /* We loaded something new. */
1851             assert(*old_obj_tail == obj);
1852             result = load_needed_objects(obj);
1853             init_dag(obj);
1854             if (result != -1)
1855                 result = rtld_verify_versions(&obj->dagmembers);
1856             if (result != -1 && ld_tracing)
1857                 goto trace;
1858             if (result == -1 ||
1859               (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) {
1860                 obj->dl_refcount--;
1861                 unref_dag(obj);
1862                 if (obj->refcount == 0)
1863                     unload_object(obj);
1864                 obj = NULL;
1865             } else {
1866                 /* Make list of init functions to call. */
1867                 initlist_add_objects(obj, &obj->next, &initlist);
1868             }
1869         } else {
1870
1871             /* Bump the reference counts for objects on this DAG. */
1872             ref_dag(obj);
1873
1874             if (ld_tracing)
1875                 goto trace;
1876         }
1877     }
1878
1879     LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
1880         name);
1881     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
1882
1883     /* Call the init functions. */
1884     objlist_call_init(&initlist, &lockstate);
1885     objlist_clear(&initlist);
1886     wlock_release(rtld_bind_lock, lockstate);
1887     return obj;
1888 trace:
1889     trace_loaded_objects(obj);
1890     wlock_release(rtld_bind_lock, lockstate);
1891     exit(0);
1892 }
1893
1894 static void *
1895 do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
1896     int flags)
1897 {
1898     DoneList donelist;
1899     const Obj_Entry *obj, *defobj;
1900     const Elf_Sym *def, *symp;
1901     unsigned long hash;
1902     int lockstate;
1903
1904     hash = elf_hash(name);
1905     def = NULL;
1906     defobj = NULL;
1907     flags |= SYMLOOK_IN_PLT;
1908
1909     lockstate = rlock_acquire(rtld_bind_lock);
1910     if (handle == NULL || handle == RTLD_NEXT ||
1911         handle == RTLD_DEFAULT || handle == RTLD_SELF) {
1912
1913         if ((obj = obj_from_addr(retaddr)) == NULL) {
1914             _rtld_error("Cannot determine caller's shared object");
1915             rlock_release(rtld_bind_lock, lockstate);
1916             return NULL;
1917         }
1918         if (handle == NULL) {   /* Just the caller's shared object. */
1919             def = symlook_obj(name, hash, obj, ve, flags);
1920             defobj = obj;
1921         } else if (handle == RTLD_NEXT || /* Objects after caller's */
1922                    handle == RTLD_SELF) { /* ... caller included */
1923             if (handle == RTLD_NEXT)
1924                 obj = obj->next;
1925             for (; obj != NULL; obj = obj->next) {
1926                 if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) {
1927                     if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
1928                         def = symp;
1929                         defobj = obj;
1930                         if (ELF_ST_BIND(def->st_info) != STB_WEAK)
1931                             break;
1932                     }
1933                 }
1934             }
1935             /*
1936              * Search the dynamic linker itself, and possibly resolve the
1937              * symbol from there.  This is how the application links to
1938              * dynamic linker services such as dlopen.  Only the values listed
1939              * in the "exports" array can be resolved from the dynamic linker.
1940              */
1941             if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
1942                 symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
1943                 if (symp != NULL && is_exported(symp)) {
1944                     def = symp;
1945                     defobj = &obj_rtld;
1946                 }
1947             }
1948         } else {
1949             assert(handle == RTLD_DEFAULT);
1950             def = symlook_default(name, hash, obj, &defobj, ve, flags);
1951         }
1952     } else {
1953         if ((obj = dlcheck(handle)) == NULL) {
1954             rlock_release(rtld_bind_lock, lockstate);
1955             return NULL;
1956         }
1957
1958         donelist_init(&donelist);
1959         if (obj->mainprog) {
1960             /* Search main program and all libraries loaded by it. */
1961             def = symlook_list(name, hash, &list_main, &defobj, ve, flags,
1962                                &donelist);
1963         } else {
1964             Needed_Entry fake;
1965
1966             /* Search the whole DAG rooted at the given object. */
1967             fake.next = NULL;
1968             fake.obj = (Obj_Entry *)obj;
1969             fake.name = 0;
1970             def = symlook_needed(name, hash, &fake, &defobj, ve, flags,
1971                                  &donelist);
1972         }
1973     }
1974
1975     if (def != NULL) {
1976         rlock_release(rtld_bind_lock, lockstate);
1977
1978         /*
1979          * The value required by the caller is derived from the value
1980          * of the symbol. For the ia64 architecture, we need to
1981          * construct a function descriptor which the caller can use to
1982          * call the function with the right 'gp' value. For other
1983          * architectures and for non-functions, the value is simply
1984          * the relocated value of the symbol.
1985          */
1986         if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
1987             return make_function_pointer(def, defobj);
1988         else
1989             return defobj->relocbase + def->st_value;
1990     }
1991
1992     _rtld_error("Undefined symbol \"%s\"", name);
1993     rlock_release(rtld_bind_lock, lockstate);
1994     return NULL;
1995 }
1996
1997 void *
1998 dlsym(void *handle, const char *name)
1999 {
2000         return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2001             SYMLOOK_DLSYM);
2002 }
2003
2004 void *
2005 dlvsym(void *handle, const char *name, const char *version)
2006 {
2007         Ver_Entry ventry;
2008
2009         ventry.name = version;
2010         ventry.file = NULL;
2011         ventry.hash = elf_hash(version);
2012         ventry.flags= 0;
2013         return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2014             SYMLOOK_DLSYM);
2015 }
2016
2017 int
2018 dladdr(const void *addr, Dl_info *info)
2019 {
2020     const Obj_Entry *obj;
2021     const Elf_Sym *def;
2022     void *symbol_addr;
2023     unsigned long symoffset;
2024     int lockstate;
2025
2026     lockstate = rlock_acquire(rtld_bind_lock);
2027     obj = obj_from_addr(addr);
2028     if (obj == NULL) {
2029         _rtld_error("No shared object contains address");
2030         rlock_release(rtld_bind_lock, lockstate);
2031         return 0;
2032     }
2033     info->dli_fname = obj->path;
2034     info->dli_fbase = obj->mapbase;
2035     info->dli_saddr = (void *)0;
2036     info->dli_sname = NULL;
2037
2038     /*
2039      * Walk the symbol list looking for the symbol whose address is
2040      * closest to the address sent in.
2041      */
2042     for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2043         def = obj->symtab + symoffset;
2044
2045         /*
2046          * For skip the symbol if st_shndx is either SHN_UNDEF or
2047          * SHN_COMMON.
2048          */
2049         if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2050             continue;
2051
2052         /*
2053          * If the symbol is greater than the specified address, or if it
2054          * is further away from addr than the current nearest symbol,
2055          * then reject it.
2056          */
2057         symbol_addr = obj->relocbase + def->st_value;
2058         if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2059             continue;
2060
2061         /* Update our idea of the nearest symbol. */
2062         info->dli_sname = obj->strtab + def->st_name;
2063         info->dli_saddr = symbol_addr;
2064
2065         /* Exact match? */
2066         if (info->dli_saddr == addr)
2067             break;
2068     }
2069     rlock_release(rtld_bind_lock, lockstate);
2070     return 1;
2071 }
2072
2073 int
2074 dlinfo(void *handle, int request, void *p)
2075 {
2076     const Obj_Entry *obj;
2077     int error, lockstate;
2078
2079     lockstate = rlock_acquire(rtld_bind_lock);
2080
2081     if (handle == NULL || handle == RTLD_SELF) {
2082         void *retaddr;
2083
2084         retaddr = __builtin_return_address(0);  /* __GNUC__ only */
2085         if ((obj = obj_from_addr(retaddr)) == NULL)
2086             _rtld_error("Cannot determine caller's shared object");
2087     } else
2088         obj = dlcheck(handle);
2089
2090     if (obj == NULL) {
2091         rlock_release(rtld_bind_lock, lockstate);
2092         return (-1);
2093     }
2094
2095     error = 0;
2096     switch (request) {
2097     case RTLD_DI_LINKMAP:
2098         *((struct link_map const **)p) = &obj->linkmap;
2099         break;
2100     case RTLD_DI_ORIGIN:
2101         error = rtld_dirname(obj->path, p);
2102         break;
2103
2104     case RTLD_DI_SERINFOSIZE:
2105     case RTLD_DI_SERINFO:
2106         error = do_search_info(obj, request, (struct dl_serinfo *)p);
2107         break;
2108
2109     default:
2110         _rtld_error("Invalid request %d passed to dlinfo()", request);
2111         error = -1;
2112     }
2113
2114     rlock_release(rtld_bind_lock, lockstate);
2115
2116     return (error);
2117 }
2118
2119 int
2120 dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2121 {
2122     struct dl_phdr_info phdr_info;
2123     const Obj_Entry *obj;
2124     int error, bind_lockstate, phdr_lockstate;
2125
2126     phdr_lockstate = wlock_acquire(rtld_phdr_lock);
2127     bind_lockstate = rlock_acquire(rtld_bind_lock);
2128
2129     error = 0;
2130
2131     for (obj = obj_list;  obj != NULL;  obj = obj->next) {
2132         phdr_info.dlpi_addr = (Elf_Addr)obj->relocbase;
2133         phdr_info.dlpi_name = STAILQ_FIRST(&obj->names) ?
2134             STAILQ_FIRST(&obj->names)->name : obj->path;
2135         phdr_info.dlpi_phdr = obj->phdr;
2136         phdr_info.dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2137         phdr_info.dlpi_tls_modid = obj->tlsindex;
2138         phdr_info.dlpi_tls_data = obj->tlsinit;
2139         phdr_info.dlpi_adds = obj_loads;
2140         phdr_info.dlpi_subs = obj_loads - obj_count;
2141
2142         if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2143                 break;
2144
2145     }
2146     rlock_release(rtld_bind_lock, bind_lockstate);
2147     wlock_release(rtld_phdr_lock, phdr_lockstate);
2148
2149     return (error);
2150 }
2151
2152 struct fill_search_info_args {
2153     int          request;
2154     unsigned int flags;
2155     Dl_serinfo  *serinfo;
2156     Dl_serpath  *serpath;
2157     char        *strspace;
2158 };
2159
2160 static void *
2161 fill_search_info(const char *dir, size_t dirlen, void *param)
2162 {
2163     struct fill_search_info_args *arg;
2164
2165     arg = param;
2166
2167     if (arg->request == RTLD_DI_SERINFOSIZE) {
2168         arg->serinfo->dls_cnt ++;
2169         arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2170     } else {
2171         struct dl_serpath *s_entry;
2172
2173         s_entry = arg->serpath;
2174         s_entry->dls_name  = arg->strspace;
2175         s_entry->dls_flags = arg->flags;
2176
2177         strncpy(arg->strspace, dir, dirlen);
2178         arg->strspace[dirlen] = '\0';
2179
2180         arg->strspace += dirlen + 1;
2181         arg->serpath++;
2182     }
2183
2184     return (NULL);
2185 }
2186
2187 static int
2188 do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2189 {
2190     struct dl_serinfo _info;
2191     struct fill_search_info_args args;
2192
2193     args.request = RTLD_DI_SERINFOSIZE;
2194     args.serinfo = &_info;
2195
2196     _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2197     _info.dls_cnt  = 0;
2198
2199     path_enumerate(ld_library_path, fill_search_info, &args);
2200     path_enumerate(obj->rpath, fill_search_info, &args);
2201     path_enumerate(gethints(), fill_search_info, &args);
2202     path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2203
2204
2205     if (request == RTLD_DI_SERINFOSIZE) {
2206         info->dls_size = _info.dls_size;
2207         info->dls_cnt = _info.dls_cnt;
2208         return (0);
2209     }
2210
2211     if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2212         _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2213         return (-1);
2214     }
2215
2216     args.request  = RTLD_DI_SERINFO;
2217     args.serinfo  = info;
2218     args.serpath  = &info->dls_serpath[0];
2219     args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2220
2221     args.flags = LA_SER_LIBPATH;
2222     if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2223         return (-1);
2224
2225     args.flags = LA_SER_RUNPATH;
2226     if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2227         return (-1);
2228
2229     args.flags = LA_SER_CONFIG;
2230     if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2231         return (-1);
2232
2233     args.flags = LA_SER_DEFAULT;
2234     if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2235         return (-1);
2236     return (0);
2237 }
2238
2239 static int
2240 rtld_dirname(const char *path, char *bname)
2241 {
2242     const char *endp;
2243
2244     /* Empty or NULL string gets treated as "." */
2245     if (path == NULL || *path == '\0') {
2246         bname[0] = '.';
2247         bname[1] = '\0';
2248         return (0);
2249     }
2250
2251     /* Strip trailing slashes */
2252     endp = path + strlen(path) - 1;
2253     while (endp > path && *endp == '/')
2254         endp--;
2255
2256     /* Find the start of the dir */
2257     while (endp > path && *endp != '/')
2258         endp--;
2259
2260     /* Either the dir is "/" or there are no slashes */
2261     if (endp == path) {
2262         bname[0] = *endp == '/' ? '/' : '.';
2263         bname[1] = '\0';
2264         return (0);
2265     } else {
2266         do {
2267             endp--;
2268         } while (endp > path && *endp == '/');
2269     }
2270
2271     if (endp - path + 2 > PATH_MAX)
2272     {
2273         _rtld_error("Filename is too long: %s", path);
2274         return(-1);
2275     }
2276
2277     strncpy(bname, path, endp - path + 1);
2278     bname[endp - path + 1] = '\0';
2279     return (0);
2280 }
2281
2282 static void
2283 linkmap_add(Obj_Entry *obj)
2284 {
2285     struct link_map *l = &obj->linkmap;
2286     struct link_map *prev;
2287
2288     obj->linkmap.l_name = obj->path;
2289     obj->linkmap.l_addr = obj->mapbase;
2290     obj->linkmap.l_ld = obj->dynamic;
2291 #ifdef __mips__
2292     /* GDB needs load offset on MIPS to use the symbols */
2293     obj->linkmap.l_offs = obj->relocbase;
2294 #endif
2295
2296     if (r_debug.r_map == NULL) {
2297         r_debug.r_map = l;
2298         return;
2299     }
2300
2301     /*
2302      * Scan to the end of the list, but not past the entry for the
2303      * dynamic linker, which we want to keep at the very end.
2304      */
2305     for (prev = r_debug.r_map;
2306       prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2307       prev = prev->l_next)
2308         ;
2309
2310     /* Link in the new entry. */
2311     l->l_prev = prev;
2312     l->l_next = prev->l_next;
2313     if (l->l_next != NULL)
2314         l->l_next->l_prev = l;
2315     prev->l_next = l;
2316 }
2317
2318 static void
2319 linkmap_delete(Obj_Entry *obj)
2320 {
2321     struct link_map *l = &obj->linkmap;
2322
2323     if (l->l_prev == NULL) {
2324         if ((r_debug.r_map = l->l_next) != NULL)
2325             l->l_next->l_prev = NULL;
2326         return;
2327     }
2328
2329     if ((l->l_prev->l_next = l->l_next) != NULL)
2330         l->l_next->l_prev = l->l_prev;
2331 }
2332
2333 /*
2334  * Function for the debugger to set a breakpoint on to gain control.
2335  *
2336  * The two parameters allow the debugger to easily find and determine
2337  * what the runtime loader is doing and to whom it is doing it.
2338  *
2339  * When the loadhook trap is hit (r_debug_state, set at program
2340  * initialization), the arguments can be found on the stack:
2341  *
2342  *  +8   struct link_map *m
2343  *  +4   struct r_debug  *rd
2344  *  +0   RetAddr
2345  */
2346 void
2347 r_debug_state(struct r_debug* rd, struct link_map *m)
2348 {
2349 }
2350
2351 /*
2352  * Get address of the pointer variable in the main program.
2353  */
2354 static const void **
2355 get_program_var_addr(const char *name)
2356 {
2357     const Obj_Entry *obj;
2358     unsigned long hash;
2359
2360     hash = elf_hash(name);
2361     for (obj = obj_main;  obj != NULL;  obj = obj->next) {
2362         const Elf_Sym *def;
2363
2364         if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2365             const void **addr;
2366
2367             addr = (const void **)(obj->relocbase + def->st_value);
2368             return addr;
2369         }
2370     }
2371     return NULL;
2372 }
2373
2374 /*
2375  * Set a pointer variable in the main program to the given value.  This
2376  * is used to set key variables such as "environ" before any of the
2377  * init functions are called.
2378  */
2379 static void
2380 set_program_var(const char *name, const void *value)
2381 {
2382     const void **addr;
2383
2384     if ((addr = get_program_var_addr(name)) != NULL) {
2385         dbg("\"%s\": *%p <-- %p", name, addr, value);
2386         *addr = value;
2387     }
2388 }
2389
2390 /*
2391  * Given a symbol name in a referencing object, find the corresponding
2392  * definition of the symbol.  Returns a pointer to the symbol, or NULL if
2393  * no definition was found.  Returns a pointer to the Obj_Entry of the
2394  * defining object via the reference parameter DEFOBJ_OUT.
2395  */
2396 static const Elf_Sym *
2397 symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2398     const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2399 {
2400     DoneList donelist;
2401     const Elf_Sym *def;
2402     const Elf_Sym *symp;
2403     const Obj_Entry *obj;
2404     const Obj_Entry *defobj;
2405     const Objlist_Entry *elm;
2406     def = NULL;
2407     defobj = NULL;
2408     donelist_init(&donelist);
2409
2410     /* Look first in the referencing object if linked symbolically. */
2411     if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2412         symp = symlook_obj(name, hash, refobj, ventry, flags);
2413         if (symp != NULL) {
2414             def = symp;
2415             defobj = refobj;
2416         }
2417     }
2418
2419     /* Search all objects loaded at program start up. */
2420     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2421         symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2422             &donelist);
2423         if (symp != NULL &&
2424           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2425             def = symp;
2426             defobj = obj;
2427         }
2428     }
2429
2430     /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2431     STAILQ_FOREACH(elm, &list_global, link) {
2432        if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2433            break;
2434        symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2435            flags, &donelist);
2436         if (symp != NULL &&
2437           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2438             def = symp;
2439             defobj = obj;
2440         }
2441     }
2442
2443     /* Search all dlopened DAGs containing the referencing object. */
2444     STAILQ_FOREACH(elm, &refobj->dldags, link) {
2445         if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2446             break;
2447         symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2448             flags, &donelist);
2449         if (symp != NULL &&
2450           (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2451             def = symp;
2452             defobj = obj;
2453         }
2454     }
2455
2456     /*
2457      * Search the dynamic linker itself, and possibly resolve the
2458      * symbol from there.  This is how the application links to
2459      * dynamic linker services such as dlopen.  Only the values listed
2460      * in the "exports" array can be resolved from the dynamic linker.
2461      */
2462     if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2463         symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2464         if (symp != NULL && is_exported(symp)) {
2465             def = symp;
2466             defobj = &obj_rtld;
2467         }
2468     }
2469
2470     if (def != NULL)
2471         *defobj_out = defobj;
2472     return def;
2473 }
2474
2475 static const Elf_Sym *
2476 symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2477   const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2478   DoneList *dlp)
2479 {
2480     const Elf_Sym *symp;
2481     const Elf_Sym *def;
2482     const Obj_Entry *defobj;
2483     const Objlist_Entry *elm;
2484
2485     def = NULL;
2486     defobj = NULL;
2487     STAILQ_FOREACH(elm, objlist, link) {
2488         if (donelist_check(dlp, elm->obj))
2489             continue;
2490         if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2491             if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2492                 def = symp;
2493                 defobj = elm->obj;
2494                 if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2495                     break;
2496             }
2497         }
2498     }
2499     if (def != NULL)
2500         *defobj_out = defobj;
2501     return def;
2502 }
2503
2504 /*
2505  * Search the symbol table of a shared object and all objects needed
2506  * by it for a symbol of the given name.  Search order is
2507  * breadth-first.  Returns a pointer to the symbol, or NULL if no
2508  * definition was found.
2509  */
2510 static const Elf_Sym *
2511 symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2512   const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2513   DoneList *dlp)
2514 {
2515     const Elf_Sym *def, *def_w;
2516     const Needed_Entry *n;
2517     const Obj_Entry *obj, *defobj, *defobj1;
2518
2519     def = def_w = NULL;
2520     defobj = NULL;
2521     for (n = needed; n != NULL; n = n->next) {
2522         if ((obj = n->obj) == NULL ||
2523             donelist_check(dlp, obj) ||
2524             (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL)
2525             continue;
2526         defobj = obj;
2527         if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2528             *defobj_out = defobj;
2529             return (def);
2530         }
2531     }
2532     /*
2533      * There we come when either symbol definition is not found in
2534      * directly needed objects, or found symbol is weak.
2535      */
2536     for (n = needed; n != NULL; n = n->next) {
2537         if ((obj = n->obj) == NULL)
2538             continue;
2539         def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2540                                ventry, flags, dlp);
2541         if (def_w == NULL)
2542             continue;
2543         if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2544             def = def_w;
2545             defobj = defobj1;
2546         }
2547         if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2548             break;
2549     }
2550     if (def != NULL)
2551         *defobj_out = defobj;
2552     return (def);
2553 }
2554
2555 /*
2556  * Search the symbol table of a single shared object for a symbol of
2557  * the given name and version, if requested.  Returns a pointer to the
2558  * symbol, or NULL if no definition was found.
2559  *
2560  * The symbol's hash value is passed in for efficiency reasons; that
2561  * eliminates many recomputations of the hash value.
2562  */
2563 const Elf_Sym *
2564 symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2565     const Ver_Entry *ventry, int flags)
2566 {
2567     unsigned long symnum;
2568     const Elf_Sym *vsymp;
2569     Elf_Versym verndx;
2570     int vcount;
2571
2572     if (obj->buckets == NULL)
2573         return NULL;
2574
2575     vsymp = NULL;
2576     vcount = 0;
2577     symnum = obj->buckets[hash % obj->nbuckets];
2578
2579     for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
2580         const Elf_Sym *symp;
2581         const char *strp;
2582
2583         if (symnum >= obj->nchains)
2584                 return NULL;    /* Bad object */
2585
2586         symp = obj->symtab + symnum;
2587         strp = obj->strtab + symp->st_name;
2588
2589         switch (ELF_ST_TYPE(symp->st_info)) {
2590         case STT_FUNC:
2591         case STT_NOTYPE:
2592         case STT_OBJECT:
2593             if (symp->st_value == 0)
2594                 continue;
2595                 /* fallthrough */
2596         case STT_TLS:
2597             if (symp->st_shndx != SHN_UNDEF ||
2598                 ((flags & SYMLOOK_IN_PLT) == 0 &&
2599                  ELF_ST_TYPE(symp->st_info) == STT_FUNC))
2600                 break;
2601                 /* fallthrough */
2602         default:
2603             continue;
2604         }
2605         if (name[0] != strp[0] || strcmp(name, strp) != 0)
2606             continue;
2607
2608         if (ventry == NULL) {
2609             if (obj->versyms != NULL) {
2610                 verndx = VER_NDX(obj->versyms[symnum]);
2611                 if (verndx > obj->vernum) {
2612                     _rtld_error("%s: symbol %s references wrong version %d",
2613                         obj->path, obj->strtab + symnum, verndx);
2614                     continue;
2615                 }
2616                 /*
2617                  * If we are not called from dlsym (i.e. this is a normal
2618                  * relocation from unversioned binary, accept the symbol
2619                  * immediately if it happens to have first version after
2620                  * this shared object became versioned. Otherwise, if
2621                  * symbol is versioned and not hidden, remember it. If it
2622                  * is the only symbol with this name exported by the
2623                  * shared object, it will be returned as a match at the
2624                  * end of the function. If symbol is global (verndx < 2)
2625                  * accept it unconditionally.
2626                  */
2627                 if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
2628                     return symp;
2629                 else if (verndx >= VER_NDX_GIVEN) {
2630                     if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
2631                         if (vsymp == NULL)
2632                             vsymp = symp;
2633                         vcount ++;
2634                     }
2635                     continue;
2636                 }
2637             }
2638             return symp;
2639         } else {
2640             if (obj->versyms == NULL) {
2641                 if (object_match_name(obj, ventry->name)) {
2642                     _rtld_error("%s: object %s should provide version %s for "
2643                         "symbol %s", obj_rtld.path, obj->path, ventry->name,
2644                         obj->strtab + symnum);
2645                     continue;
2646                 }
2647             } else {
2648                 verndx = VER_NDX(obj->versyms[symnum]);
2649                 if (verndx > obj->vernum) {
2650                     _rtld_error("%s: symbol %s references wrong version %d",
2651                         obj->path, obj->strtab + symnum, verndx);
2652                     continue;
2653                 }
2654                 if (obj->vertab[verndx].hash != ventry->hash ||
2655                     strcmp(obj->vertab[verndx].name, ventry->name)) {
2656                     /*
2657                      * Version does not match. Look if this is a global symbol
2658                      * and if it is not hidden. If global symbol (verndx < 2)
2659                      * is available, use it. Do not return symbol if we are
2660                      * called by dlvsym, because dlvsym looks for a specific
2661                      * version and default one is not what dlvsym wants.
2662                      */
2663                     if ((flags & SYMLOOK_DLSYM) ||
2664                         (obj->versyms[symnum] & VER_NDX_HIDDEN) ||
2665                         (verndx >= VER_NDX_GIVEN))
2666                         continue;
2667                 }
2668             }
2669             return symp;
2670         }
2671     }
2672     return (vcount == 1) ? vsymp : NULL;
2673 }
2674
2675 static void
2676 trace_loaded_objects(Obj_Entry *obj)
2677 {
2678     char        *fmt1, *fmt2, *fmt, *main_local, *list_containers;
2679     int         c;
2680
2681     if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2682         main_local = "";
2683
2684     if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2685         fmt1 = "\t%o => %p (%x)\n";
2686
2687     if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2688         fmt2 = "\t%o (%x)\n";
2689
2690     list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2691
2692     for (; obj; obj = obj->next) {
2693         Needed_Entry            *needed;
2694         char                    *name, *path;
2695         bool                    is_lib;
2696
2697         if (list_containers && obj->needed != NULL)
2698             printf("%s:\n", obj->path);
2699         for (needed = obj->needed; needed; needed = needed->next) {
2700             if (needed->obj != NULL) {
2701                 if (needed->obj->traced && !list_containers)
2702                     continue;
2703                 needed->obj->traced = true;
2704                 path = needed->obj->path;
2705             } else
2706                 path = "not found";
2707
2708             name = (char *)obj->strtab + needed->name;
2709             is_lib = strncmp(name, "lib", 3) == 0;      /* XXX - bogus */
2710
2711             fmt = is_lib ? fmt1 : fmt2;
2712             while ((c = *fmt++) != '\0') {
2713                 switch (c) {
2714                 default:
2715                     putchar(c);
2716                     continue;
2717                 case '\\':
2718                     switch (c = *fmt) {
2719                     case '\0':
2720                         continue;
2721                     case 'n':
2722                         putchar('\n');
2723                         break;
2724                     case 't':
2725                         putchar('\t');
2726                         break;
2727                     }
2728                     break;
2729                 case '%':
2730                     switch (c = *fmt) {
2731                     case '\0':
2732                         continue;
2733                     case '%':
2734                     default:
2735                         putchar(c);
2736                         break;
2737                     case 'A':
2738                         printf("%s", main_local);
2739                         break;
2740                     case 'a':
2741                         printf("%s", obj_main->path);
2742                         break;
2743                     case 'o':
2744                         printf("%s", name);
2745                         break;
2746 #if 0
2747                     case 'm':
2748                         printf("%d", sodp->sod_major);
2749                         break;
2750                     case 'n':
2751                         printf("%d", sodp->sod_minor);
2752                         break;
2753 #endif
2754                     case 'p':
2755                         printf("%s", path);
2756                         break;
2757                     case 'x':
2758                         printf("%p", needed->obj ? needed->obj->mapbase : 0);
2759                         break;
2760                     }
2761                     break;
2762                 }
2763                 ++fmt;
2764             }
2765         }
2766     }
2767 }
2768
2769 /*
2770  * Unload a dlopened object and its dependencies from memory and from
2771  * our data structures.  It is assumed that the DAG rooted in the
2772  * object has already been unreferenced, and that the object has a
2773  * reference count of 0.
2774  */
2775 static void
2776 unload_object(Obj_Entry *root)
2777 {
2778     Obj_Entry *obj;
2779     Obj_Entry **linkp;
2780
2781     assert(root->refcount == 0);
2782
2783     /*
2784      * Pass over the DAG removing unreferenced objects from
2785      * appropriate lists.
2786      */
2787     unlink_object(root);
2788
2789     /* Unmap all objects that are no longer referenced. */
2790     linkp = &obj_list->next;
2791     while ((obj = *linkp) != NULL) {
2792         if (obj->refcount == 0) {
2793             LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
2794                 obj->path);
2795             dbg("unloading \"%s\"", obj->path);
2796             munmap(obj->mapbase, obj->mapsize);
2797             linkmap_delete(obj);
2798             *linkp = obj->next;
2799             obj_count--;
2800             obj_free(obj);
2801         } else
2802             linkp = &obj->next;
2803     }
2804     obj_tail = linkp;
2805 }
2806
2807 static void
2808 unlink_object(Obj_Entry *root)
2809 {
2810     Objlist_Entry *elm;
2811
2812     if (root->refcount == 0) {
2813         /* Remove the object from the RTLD_GLOBAL list. */
2814         objlist_remove(&list_global, root);
2815
2816         /* Remove the object from all objects' DAG lists. */
2817         STAILQ_FOREACH(elm, &root->dagmembers, link) {
2818             objlist_remove(&elm->obj->dldags, root);
2819             if (elm->obj != root)
2820                 unlink_object(elm->obj);
2821         }
2822     }
2823 }
2824
2825 static void
2826 ref_dag(Obj_Entry *root)
2827 {
2828     Objlist_Entry *elm;
2829
2830     STAILQ_FOREACH(elm, &root->dagmembers, link)
2831         elm->obj->refcount++;
2832 }
2833
2834 static void
2835 unref_dag(Obj_Entry *root)
2836 {
2837     Objlist_Entry *elm;
2838
2839     STAILQ_FOREACH(elm, &root->dagmembers, link)
2840         elm->obj->refcount--;
2841 }
2842
2843 /*
2844  * Common code for MD __tls_get_addr().
2845  */
2846 void *
2847 tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
2848 {
2849     Elf_Addr* dtv = *dtvp;
2850     int lockstate;
2851
2852     /* Check dtv generation in case new modules have arrived */
2853     if (dtv[0] != tls_dtv_generation) {
2854         Elf_Addr* newdtv;
2855         int to_copy;
2856
2857         lockstate = wlock_acquire(rtld_bind_lock);
2858         newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2859         to_copy = dtv[1];
2860         if (to_copy > tls_max_index)
2861             to_copy = tls_max_index;
2862         memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
2863         newdtv[0] = tls_dtv_generation;
2864         newdtv[1] = tls_max_index;
2865         free(dtv);
2866         wlock_release(rtld_bind_lock, lockstate);
2867         *dtvp = newdtv;
2868     }
2869
2870     /* Dynamically allocate module TLS if necessary */
2871     if (!dtv[index + 1]) {
2872         /* Signal safe, wlock will block out signals. */
2873         lockstate = wlock_acquire(rtld_bind_lock);
2874         if (!dtv[index + 1])
2875             dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
2876         wlock_release(rtld_bind_lock, lockstate);
2877     }
2878     return (void*) (dtv[index + 1] + offset);
2879 }
2880
2881 /* XXX not sure what variants to use for arm. */
2882
2883 #if defined(__ia64__) || defined(__powerpc__)
2884
2885 /*
2886  * Allocate Static TLS using the Variant I method.
2887  */
2888 void *
2889 allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
2890 {
2891     Obj_Entry *obj;
2892     char *tcb;
2893     Elf_Addr **tls;
2894     Elf_Addr *dtv;
2895     Elf_Addr addr;
2896     int i;
2897
2898     if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
2899         return (oldtcb);
2900
2901     assert(tcbsize >= TLS_TCB_SIZE);
2902     tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
2903     tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
2904
2905     if (oldtcb != NULL) {
2906         memcpy(tls, oldtcb, tls_static_space);
2907         free(oldtcb);
2908
2909         /* Adjust the DTV. */
2910         dtv = tls[0];
2911         for (i = 0; i < dtv[1]; i++) {
2912             if (dtv[i+2] >= (Elf_Addr)oldtcb &&
2913                 dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
2914                 dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
2915             }
2916         }
2917     } else {
2918         dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
2919         tls[0] = dtv;
2920         dtv[0] = tls_dtv_generation;
2921         dtv[1] = tls_max_index;
2922
2923         for (obj = objs; obj; obj = obj->next) {
2924             if (obj->tlsoffset) {
2925                 addr = (Elf_Addr)tls + obj->tlsoffset;
2926                 memset((void*) (addr + obj->tlsinitsize),
2927                        0, obj->tlssize - obj->tlsinitsize);
2928                 if (obj->tlsinit)
2929                     memcpy((void*) addr, obj->tlsinit,
2930                            obj->tlsinitsize);
2931                 dtv[obj->tlsindex + 1] = addr;
2932             }
2933         }
2934     }
2935
2936     return (tcb);
2937 }
2938
2939 void
2940 free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
2941 {
2942     Elf_Addr *dtv;
2943     Elf_Addr tlsstart, tlsend;
2944     int dtvsize, i;
2945
2946     assert(tcbsize >= TLS_TCB_SIZE);
2947
2948     tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
2949     tlsend = tlsstart + tls_static_space;
2950
2951     dtv = *(Elf_Addr **)tlsstart;
2952     dtvsize = dtv[1];
2953     for (i = 0; i < dtvsize; i++) {
2954         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
2955             free((void*)dtv[i+2]);
2956         }
2957     }
2958     free(dtv);
2959     free(tcb);
2960 }
2961
2962 #endif
2963
2964 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
2965     defined(__arm__)
2966
2967 /*
2968  * Allocate Static TLS using the Variant II method.
2969  */
2970 void *
2971 allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
2972 {
2973     Obj_Entry *obj;
2974     size_t size;
2975     char *tls;
2976     Elf_Addr *dtv, *olddtv;
2977     Elf_Addr segbase, oldsegbase, addr;
2978     int i;
2979
2980     size = round(tls_static_space, tcbalign);
2981
2982     assert(tcbsize >= 2*sizeof(Elf_Addr));
2983     tls = calloc(1, size + tcbsize);
2984     dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
2985
2986     segbase = (Elf_Addr)(tls + size);
2987     ((Elf_Addr*)segbase)[0] = segbase;
2988     ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
2989
2990     dtv[0] = tls_dtv_generation;
2991     dtv[1] = tls_max_index;
2992
2993     if (oldtls) {
2994         /*
2995          * Copy the static TLS block over whole.
2996          */
2997         oldsegbase = (Elf_Addr) oldtls;
2998         memcpy((void *)(segbase - tls_static_space),
2999                (const void *)(oldsegbase - tls_static_space),
3000                tls_static_space);
3001
3002         /*
3003          * If any dynamic TLS blocks have been created tls_get_addr(),
3004          * move them over.
3005          */
3006         olddtv = ((Elf_Addr**)oldsegbase)[1];
3007         for (i = 0; i < olddtv[1]; i++) {
3008             if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3009                 dtv[i+2] = olddtv[i+2];
3010                 olddtv[i+2] = 0;
3011             }
3012         }
3013
3014         /*
3015          * We assume that this block was the one we created with
3016          * allocate_initial_tls().
3017          */
3018         free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3019     } else {
3020         for (obj = objs; obj; obj = obj->next) {
3021             if (obj->tlsoffset) {
3022                 addr = segbase - obj->tlsoffset;
3023                 memset((void*) (addr + obj->tlsinitsize),
3024                        0, obj->tlssize - obj->tlsinitsize);
3025                 if (obj->tlsinit)
3026                     memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3027                 dtv[obj->tlsindex + 1] = addr;
3028             }
3029         }
3030     }
3031
3032     return (void*) segbase;
3033 }
3034
3035 void
3036 free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3037 {
3038     size_t size;
3039     Elf_Addr* dtv;
3040     int dtvsize, i;
3041     Elf_Addr tlsstart, tlsend;
3042
3043     /*
3044      * Figure out the size of the initial TLS block so that we can
3045      * find stuff which ___tls_get_addr() allocated dynamically.
3046      */
3047     size = round(tls_static_space, tcbalign);
3048
3049     dtv = ((Elf_Addr**)tls)[1];
3050     dtvsize = dtv[1];
3051     tlsend = (Elf_Addr) tls;
3052     tlsstart = tlsend - size;
3053     for (i = 0; i < dtvsize; i++) {
3054         if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3055             free((void*) dtv[i+2]);
3056         }
3057     }
3058
3059     free((void*) tlsstart);
3060     free((void*) dtv);
3061 }
3062
3063 #endif
3064
3065 /*
3066  * Allocate TLS block for module with given index.
3067  */
3068 void *
3069 allocate_module_tls(int index)
3070 {
3071     Obj_Entry* obj;
3072     char* p;
3073
3074     for (obj = obj_list; obj; obj = obj->next) {
3075         if (obj->tlsindex == index)
3076             break;
3077     }
3078     if (!obj) {
3079         _rtld_error("Can't find module with TLS index %d", index);
3080         die();
3081     }
3082
3083     p = malloc(obj->tlssize);
3084     memcpy(p, obj->tlsinit, obj->tlsinitsize);
3085     memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3086
3087     return p;
3088 }
3089
3090 bool
3091 allocate_tls_offset(Obj_Entry *obj)
3092 {
3093     size_t off;
3094
3095     if (obj->tls_done)
3096         return true;
3097
3098     if (obj->tlssize == 0) {
3099         obj->tls_done = true;
3100         return true;
3101     }
3102
3103     if (obj->tlsindex == 1)
3104         off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3105     else
3106         off = calculate_tls_offset(tls_last_offset, tls_last_size,
3107                                    obj->tlssize, obj->tlsalign);
3108
3109     /*
3110      * If we have already fixed the size of the static TLS block, we
3111      * must stay within that size. When allocating the static TLS, we
3112      * leave a small amount of space spare to be used for dynamically
3113      * loading modules which use static TLS.
3114      */
3115     if (tls_static_space) {
3116         if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3117             return false;
3118     }
3119
3120     tls_last_offset = obj->tlsoffset = off;
3121     tls_last_size = obj->tlssize;
3122     obj->tls_done = true;
3123
3124     return true;
3125 }
3126
3127 void
3128 free_tls_offset(Obj_Entry *obj)
3129 {
3130 #if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3131     defined(__arm__)
3132     /*
3133      * If we were the last thing to allocate out of the static TLS
3134      * block, we give our space back to the 'allocator'. This is a
3135      * simplistic workaround to allow libGL.so.1 to be loaded and
3136      * unloaded multiple times. We only handle the Variant II
3137      * mechanism for now - this really needs a proper allocator.
3138      */
3139     if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3140         == calculate_tls_end(tls_last_offset, tls_last_size)) {
3141         tls_last_offset -= obj->tlssize;
3142         tls_last_size = 0;
3143     }
3144 #endif
3145 }
3146
3147 void *
3148 _rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3149 {
3150     void *ret;
3151     int lockstate;
3152
3153     lockstate = wlock_acquire(rtld_bind_lock);
3154     ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3155     wlock_release(rtld_bind_lock, lockstate);
3156     return (ret);
3157 }
3158
3159 void
3160 _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3161 {
3162     int lockstate;
3163
3164     lockstate = wlock_acquire(rtld_bind_lock);
3165     free_tls(tcb, tcbsize, tcbalign);
3166     wlock_release(rtld_bind_lock, lockstate);
3167 }
3168
3169 static void
3170 object_add_name(Obj_Entry *obj, const char *name)
3171 {
3172     Name_Entry *entry;
3173     size_t len;
3174
3175     len = strlen(name);
3176     entry = malloc(sizeof(Name_Entry) + len);
3177
3178     if (entry != NULL) {
3179         strcpy(entry->name, name);
3180         STAILQ_INSERT_TAIL(&obj->names, entry, link);
3181     }
3182 }
3183
3184 static int
3185 object_match_name(const Obj_Entry *obj, const char *name)
3186 {
3187     Name_Entry *entry;
3188
3189     STAILQ_FOREACH(entry, &obj->names, link) {
3190         if (strcmp(name, entry->name) == 0)
3191             return (1);
3192     }
3193     return (0);
3194 }
3195
3196 static Obj_Entry *
3197 locate_dependency(const Obj_Entry *obj, const char *name)
3198 {
3199     const Objlist_Entry *entry;
3200     const Needed_Entry *needed;
3201
3202     STAILQ_FOREACH(entry, &list_main, link) {
3203         if (object_match_name(entry->obj, name))
3204             return entry->obj;
3205     }
3206
3207     for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
3208         if (needed->obj == NULL)
3209             continue;
3210         if (object_match_name(needed->obj, name))
3211             return needed->obj;
3212     }
3213     _rtld_error("%s: Unexpected  inconsistency: dependency %s not found",
3214         obj->path, name);
3215     die();
3216 }
3217
3218 static int
3219 check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3220     const Elf_Vernaux *vna)
3221 {
3222     const Elf_Verdef *vd;
3223     const char *vername;
3224
3225     vername = refobj->strtab + vna->vna_name;
3226     vd = depobj->verdef;
3227     if (vd == NULL) {
3228         _rtld_error("%s: version %s required by %s not defined",
3229             depobj->path, vername, refobj->path);
3230         return (-1);
3231     }
3232     for (;;) {
3233         if (vd->vd_version != VER_DEF_CURRENT) {
3234             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3235                 depobj->path, vd->vd_version);
3236             return (-1);
3237         }
3238         if (vna->vna_hash == vd->vd_hash) {
3239             const Elf_Verdaux *aux = (const Elf_Verdaux *)
3240                 ((char *)vd + vd->vd_aux);
3241             if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3242                 return (0);
3243         }
3244         if (vd->vd_next == 0)
3245             break;
3246         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3247     }
3248     if (vna->vna_flags & VER_FLG_WEAK)
3249         return (0);
3250     _rtld_error("%s: version %s required by %s not found",
3251         depobj->path, vername, refobj->path);
3252     return (-1);
3253 }
3254
3255 static int
3256 rtld_verify_object_versions(Obj_Entry *obj)
3257 {
3258     const Elf_Verneed *vn;
3259     const Elf_Verdef  *vd;
3260     const Elf_Verdaux *vda;
3261     const Elf_Vernaux *vna;
3262     const Obj_Entry *depobj;
3263     int maxvernum, vernum;
3264
3265     maxvernum = 0;
3266     /*
3267      * Walk over defined and required version records and figure out
3268      * max index used by any of them. Do very basic sanity checking
3269      * while there.
3270      */
3271     vn = obj->verneed;
3272     while (vn != NULL) {
3273         if (vn->vn_version != VER_NEED_CURRENT) {
3274             _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3275                 obj->path, vn->vn_version);
3276             return (-1);
3277         }
3278         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3279         for (;;) {
3280             vernum = VER_NEED_IDX(vna->vna_other);
3281             if (vernum > maxvernum)
3282                 maxvernum = vernum;
3283             if (vna->vna_next == 0)
3284                  break;
3285             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3286         }
3287         if (vn->vn_next == 0)
3288             break;
3289         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3290     }
3291
3292     vd = obj->verdef;
3293     while (vd != NULL) {
3294         if (vd->vd_version != VER_DEF_CURRENT) {
3295             _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3296                 obj->path, vd->vd_version);
3297             return (-1);
3298         }
3299         vernum = VER_DEF_IDX(vd->vd_ndx);
3300         if (vernum > maxvernum)
3301                 maxvernum = vernum;
3302         if (vd->vd_next == 0)
3303             break;
3304         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3305     }
3306
3307     if (maxvernum == 0)
3308         return (0);
3309
3310     /*
3311      * Store version information in array indexable by version index.
3312      * Verify that object version requirements are satisfied along the
3313      * way.
3314      */
3315     obj->vernum = maxvernum + 1;
3316     obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3317
3318     vd = obj->verdef;
3319     while (vd != NULL) {
3320         if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3321             vernum = VER_DEF_IDX(vd->vd_ndx);
3322             assert(vernum <= maxvernum);
3323             vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3324             obj->vertab[vernum].hash = vd->vd_hash;
3325             obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3326             obj->vertab[vernum].file = NULL;
3327             obj->vertab[vernum].flags = 0;
3328         }
3329         if (vd->vd_next == 0)
3330             break;
3331         vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3332     }
3333
3334     vn = obj->verneed;
3335     while (vn != NULL) {
3336         depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3337         vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3338         for (;;) {
3339             if (check_object_provided_version(obj, depobj, vna))
3340                 return (-1);
3341             vernum = VER_NEED_IDX(vna->vna_other);
3342             assert(vernum <= maxvernum);
3343             obj->vertab[vernum].hash = vna->vna_hash;
3344             obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3345             obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3346             obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3347                 VER_INFO_HIDDEN : 0;
3348             if (vna->vna_next == 0)
3349                  break;
3350             vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3351         }
3352         if (vn->vn_next == 0)
3353             break;
3354         vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3355     }
3356     return 0;
3357 }
3358
3359 static int
3360 rtld_verify_versions(const Objlist *objlist)
3361 {
3362     Objlist_Entry *entry;
3363     int rc;
3364
3365     rc = 0;
3366     STAILQ_FOREACH(entry, objlist, link) {
3367         /*
3368          * Skip dummy objects or objects that have their version requirements
3369          * already checked.
3370          */
3371         if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3372             continue;
3373         if (rtld_verify_object_versions(entry->obj) == -1) {
3374             rc = -1;
3375             if (ld_tracing == NULL)
3376                 break;
3377         }
3378     }
3379     if (rc == 0 || ld_tracing != NULL)
3380         rc = rtld_verify_object_versions(&obj_rtld);
3381     return rc;
3382 }
3383
3384 const Ver_Entry *
3385 fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3386 {
3387     Elf_Versym vernum;
3388
3389     if (obj->vertab) {
3390         vernum = VER_NDX(obj->versyms[symnum]);
3391         if (vernum >= obj->vernum) {
3392             _rtld_error("%s: symbol %s has wrong verneed value %d",
3393                 obj->path, obj->strtab + symnum, vernum);
3394         } else if (obj->vertab[vernum].hash != 0) {
3395             return &obj->vertab[vernum];
3396         }
3397     }
3398     return NULL;
3399 }