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