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