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