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