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