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