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