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