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