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