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