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