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