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