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