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