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