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