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