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