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