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