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