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