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