rtld.c revision 212497
11590Srgrimes/*-
21590Srgrimes * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
31590Srgrimes * Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
489615Sdes * All rights reserved.
589615Sdes *
61590Srgrimes * Redistribution and use in source and binary forms, with or without
789615Sdes * modification, are permitted provided that the following conditions
889615Sdes * are met:
989615Sdes * 1. Redistributions of source code must retain the above copyright
1089615Sdes *    notice, this list of conditions and the following disclaimer.
1189615Sdes * 2. Redistributions in binary form must reproduce the above copyright
121590Srgrimes *    notice, this list of conditions and the following disclaimer in the
131590Srgrimes *    documentation and/or other materials provided with the distribution.
141590Srgrimes *
151590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
161590Srgrimes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
171590Srgrimes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
181590Srgrimes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
191590Srgrimes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
201590Srgrimes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
211590Srgrimes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
221590Srgrimes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
231590Srgrimes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
241590Srgrimes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
251590Srgrimes *
261590Srgrimes * $FreeBSD: head/libexec/rtld-elf/rtld.c 212497 2010-09-12 17:04:51Z nwhitehorn $
271590Srgrimes */
281590Srgrimes
291590Srgrimes/*
301590Srgrimes * Dynamic linker for ELF.
311590Srgrimes *
321590Srgrimes * John Polstra <jdp@polstra.com>.
331590Srgrimes */
341590Srgrimes
351590Srgrimes#ifndef __GNUC__
361590Srgrimes#error "GCC is needed to compile this file"
371590Srgrimes#endif
381590Srgrimes
391590Srgrimes#include <sys/param.h>
401590Srgrimes#include <sys/mount.h>
4187628Sdwmalone#include <sys/mman.h>
4287628Sdwmalone#include <sys/stat.h>
4387628Sdwmalone#include <sys/sysctl.h>
4487628Sdwmalone#include <sys/uio.h>
4587628Sdwmalone#include <sys/utsname.h>
4687628Sdwmalone#include <sys/ktrace.h>
4787233Smarkm
4887233Smarkm#include <dlfcn.h>
4987233Smarkm#include <err.h>
501590Srgrimes#include <errno.h>
511590Srgrimes#include <fcntl.h>
521590Srgrimes#include <stdarg.h>
531590Srgrimes#include <stdio.h>
541590Srgrimes#include <stdlib.h>
551590Srgrimes#include <string.h>
5687233Smarkm#include <unistd.h>
5787180Smarkm
5887180Smarkm#include "debug.h"
591590Srgrimes#include "rtld.h"
601590Srgrimes#include "libmap.h"
611590Srgrimes#include "rtld_tls.h"
6287180Smarkm
631590Srgrimes#ifndef COMPAT_32BIT
641590Srgrimes#define PATH_RTLD	"/libexec/ld-elf.so.1"
651590Srgrimes#else
661590Srgrimes#define PATH_RTLD	"/libexec/ld-elf32.so.1"
6740102Smarkm#endif
6841079Sjdp
691590Srgrimes/* Types. */
701590Srgrimestypedef void (*func_ptr_type)();
711590Srgrimestypedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
721590Srgrimes
731590Srgrimes/*
741590Srgrimes * This structure provides a reentrant way to keep a list of objects and
751590Srgrimes * check which ones have already been processed in some way.
761590Srgrimes */
771590Srgrimestypedef struct Struct_DoneList {
781590Srgrimes    const Obj_Entry **objs;		/* Array of object pointers */
7941279Sjdp    unsigned int num_alloc;		/* Allocated size of the array */
8091714Sdes    unsigned int num_used;		/* Number of array slots used */
813702Spst} DoneList;
8287173Smarkm
831590Srgrimes/*
841590Srgrimes * Function declarations.
8589994Sdes */
8689994Sdesstatic const char *basename(const char *);
8789994Sdesstatic void die(void) __dead2;
8889994Sdesstatic void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
8989994Sdes    const Elf_Dyn **);
9089994Sdesstatic void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *);
9189994Sdesstatic void digest_dynamic(Obj_Entry *, int);
9289994Sdesstatic Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
9389994Sdesstatic Obj_Entry *dlcheck(void *);
9489994Sdesstatic Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
9589994Sdesstatic int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
9689994Sdesstatic bool donelist_check(DoneList *, const Obj_Entry *);
9789994Sdesstatic void errmsg_restore(char *);
9889994Sdesstatic char *errmsg_save(void);
991590Srgrimesstatic void *fill_search_info(const char *, size_t, void *);
10087173Smarkmstatic char *find_library(const char *, const Obj_Entry *);
10187173Smarkmstatic const char *gethints(void);
10287173Smarkmstatic void init_dag(Obj_Entry *);
10376786Sobrienstatic void init_dag1(Obj_Entry *, Obj_Entry *, DoneList *);
10476786Sobrienstatic void init_rtld(caddr_t, Elf_Auxinfo **);
10589994Sdesstatic void initlist_add_neededs(Needed_Entry *, Objlist *);
10687173Smarkmstatic void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
10789994Sdesstatic void linkmap_add(Obj_Entry *);
10889994Sdesstatic void linkmap_delete(Obj_Entry *);
1091590Srgrimesstatic int load_needed_objects(Obj_Entry *, int);
1101590Srgrimesstatic int load_preload_objects(void);
1111590Srgrimesstatic Obj_Entry *load_object(const char *, const Obj_Entry *, int);
1121590Srgrimesstatic Obj_Entry *obj_from_addr(const void *);
1131590Srgrimesstatic void objlist_call_fini(Objlist *, bool, int *);
11489994Sdesstatic void objlist_call_init(Objlist *, int *);
1151590Srgrimesstatic void objlist_clear(Objlist *);
11642272Seivindstatic Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
11789994Sdesstatic void objlist_init(Objlist *);
11842272Seivindstatic void objlist_push_head(Objlist *, Obj_Entry *);
11989994Sdesstatic void objlist_push_tail(Objlist *, Obj_Entry *);
12089994Sdesstatic void objlist_remove(Objlist *, Obj_Entry *);
1211590Srgrimesstatic void *path_enumerate(const char *, path_enum_proc, void *);
12289994Sdesstatic int relocate_objects(Obj_Entry *, bool, Obj_Entry *);
12389994Sdesstatic int rtld_dirname(const char *, char *);
12489994Sdesstatic int rtld_dirname_abs(const char *, char *);
12589994Sdesstatic void rtld_exit(void);
12689994Sdesstatic char *search_library_path(const char *, const char *);
12789994Sdesstatic const void **get_program_var_addr(const char *);
12889994Sdesstatic void set_program_var(const char *, const void *);
12989994Sdesstatic const Elf_Sym *symlook_default(const char *, unsigned long,
13089994Sdes  const Obj_Entry *, const Obj_Entry **, const Ver_Entry *, int);
13189994Sdesstatic const Elf_Sym *symlook_list(const char *, unsigned long, const Objlist *,
13289994Sdes  const Obj_Entry **, const Ver_Entry *, int, DoneList *);
13389994Sdesstatic const Elf_Sym *symlook_needed(const char *, unsigned long,
13489994Sdes  const Needed_Entry *, const Obj_Entry **, const Ver_Entry *,
13589994Sdes  int, DoneList *);
13689994Sdesstatic void trace_loaded_objects(Obj_Entry *);
13789994Sdesstatic void unlink_object(Obj_Entry *);
13889994Sdesstatic void unload_object(Obj_Entry *);
13989994Sdesstatic void unref_dag(Obj_Entry *);
14089994Sdesstatic void ref_dag(Obj_Entry *);
14189994Sdesstatic int origin_subst_one(char **, const char *, const char *,
14294203Sru  const char *, char *);
14389994Sdesstatic char *origin_subst(const char *, const char *);
14494203Srustatic int  rtld_verify_versions(const Objlist *);
14589994Sdesstatic int  rtld_verify_object_versions(Obj_Entry *);
14689994Sdesstatic void object_add_name(Obj_Entry *, const char *);
14789994Sdesstatic int  object_match_name(const Obj_Entry *, const char *);
14889994Sdesstatic void ld_utrace_log(int, void *, void *, size_t, int, const char *);
14989994Sdesstatic void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
15089994Sdes    struct dl_phdr_info *phdr_info);
15189994Sdes
15291714Sdesvoid r_debug_state(struct r_debug *, struct link_map *);
15389994Sdes
15489994Sdes/*
15589994Sdes * Data declarations.
15689994Sdes */
15789994Sdesstatic char *error_message;	/* Message for dlerror(), or NULL */
1581590Srgrimesstruct r_debug r_debug;		/* for GDB; */
15989994Sdesstatic bool libmap_disable;	/* Disable libmap */
1601590Srgrimesstatic char *libmap_override;	/* Maps to use in addition to libmap.conf */
1611590Srgrimesstatic bool trust;		/* False for setuid and setgid programs */
1621590Srgrimesstatic bool dangerous_ld_env;	/* True if environment variables have been
16389994Sdes				   used to affect the libraries loaded */
16489994Sdesstatic char *ld_bind_now;	/* Environment variable for immediate binding */
16535559Speterstatic char *ld_debug;		/* Environment variable for debugging */
16646007Sachestatic char *ld_library_path;	/* Environment variable for search path */
16789994Sdesstatic char *ld_preload;	/* Environment variable for libraries to
16845431Sbrian				   load first */
16942272Seivindstatic char *ld_elf_hints_path;	/* Environment variable for alternative hints path */
17094203Srustatic char *ld_tracing;	/* Called from ldd to print libs */
17194203Srustatic char *ld_utrace;		/* Use utrace() to log events. */
17221528Sdavidnstatic Obj_Entry *obj_list;	/* Head of linked list of shared objects */
17374874Smarkmstatic Obj_Entry **obj_tail;	/* Link field of last object in list */
1741590Srgrimesstatic Obj_Entry *obj_main;	/* The main program shared object */
17542272Seivindstatic Obj_Entry obj_rtld;	/* The dynamic linker shared object */
17642272Seivindstatic unsigned int obj_count;	/* Number of objects in obj_list */
17776942Sguidostatic unsigned int obj_loads;	/* Number of objects in obj_list */
17842272Seivind
17942272Seivindstatic Objlist list_global =	/* Objects dlopened with RTLD_GLOBAL */
18089994Sdes  STAILQ_HEAD_INITIALIZER(list_global);
18176788Sobrienstatic Objlist list_main =	/* Objects loaded at program startup */
18276788Sobrien  STAILQ_HEAD_INITIALIZER(list_main);
18389994Sdesstatic Objlist list_fini =	/* Objects needing fini() calls */
18442272Seivind  STAILQ_HEAD_INITIALIZER(list_fini);
1851590Srgrimes
1861590SrgrimesElf_Sym sym_zero;		/* For resolving undefined weak refs. */
1871590Srgrimes
1881590Srgrimes#define GDB_STATE(s,m)	r_debug.r_state = s; r_debug_state(&r_debug,m);
1891590Srgrimes
1901590Srgrimesextern Elf_Dyn _DYNAMIC;
1911590Srgrimes#pragma weak _DYNAMIC
19235557Speter#ifndef RTLD_IS_DYNAMIC
19346007Sache#define	RTLD_IS_DYNAMIC()	(&_DYNAMIC != NULL)
19489994Sdes#endif
19524360Simp
1961590Srgrimesint osreldate, pagesize;
1971590Srgrimes
1981590Srgrimes/*
1991590Srgrimes * Global declarations normally provided by crt1.  The dynamic linker is
2001590Srgrimes * not built with crt1, so we have to provide them ourselves.
20189994Sdes */
2021590Srgrimeschar *__progname;
20389994Sdeschar **environ;
20481555Smike
20581555Smike/*
20689994Sdes * Globals to control TLS allocation.
2071590Srgrimes */
2081590Srgrimessize_t tls_last_offset;		/* Static TLS offset of last module */
2091590Srgrimessize_t tls_last_size;		/* Static TLS size of last module */
2101590Srgrimessize_t tls_static_space;	/* Static TLS space allocated */
2111590Srgrimesint tls_dtv_generation = 1;	/* Used to detect when dtv size changes  */
2121590Srgrimesint tls_max_index = 1;		/* Largest module index allocated */
2131590Srgrimes
21489994Sdes/*
2151590Srgrimes * Fill in a DoneList with an allocation large enough to hold all of
21627605Scharnier * the currently-loaded objects.  Keep this as a macro since it calls
2171590Srgrimes * alloca and we want that to occur within the scope of the caller.
2181590Srgrimes */
2191590Srgrimes#define donelist_init(dlp)					\
2201590Srgrimes    ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]),	\
22189994Sdes    assert((dlp)->objs != NULL),				\
22289994Sdes    (dlp)->num_alloc = obj_count,				\
22389994Sdes    (dlp)->num_used = 0)
22489994Sdes
2251590Srgrimes#define	UTRACE_DLOPEN_START		1
22689994Sdes#define	UTRACE_DLOPEN_STOP		2
2271590Srgrimes#define	UTRACE_DLCLOSE_START		3
22889994Sdes#define	UTRACE_DLCLOSE_STOP		4
2291590Srgrimes#define	UTRACE_LOAD_OBJECT		5
2301590Srgrimes#define	UTRACE_UNLOAD_OBJECT		6
2311590Srgrimes#define	UTRACE_ADD_RUNDEP		7
2321590Srgrimes#define	UTRACE_PRELOAD_FINISHED		8
23389994Sdes#define	UTRACE_INIT_CALL		9
23489994Sdes#define	UTRACE_FINI_CALL		10
23589994Sdes
2361590Srgrimesstruct utrace_rtld {
2371590Srgrimes	char sig[4];			/* 'RTLD' */
2381590Srgrimes	int event;
2391590Srgrimes	void *handle;
2401590Srgrimes	void *mapbase;			/* Used for 'parent' and 'init/fini' */
24123985Sdavidn	size_t mapsize;
2421590Srgrimes	int refcnt;			/* Used for 'mode' */
2431590Srgrimes	char name[MAXPATHLEN];
2441590Srgrimes};
2451590Srgrimes
24623985Sdavidn#define	LD_UTRACE(e, h, mb, ms, r, n) do {			\
24723985Sdavidn	if (ld_utrace != NULL)					\
24823985Sdavidn		ld_utrace_log(e, h, mb, ms, r, n);		\
24923985Sdavidn} while (0)
25089994Sdes
25189994Sdesstatic void
25276786Sobrienld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
25387173Smarkm    int refcnt, const char *name)
25489994Sdes{
25589994Sdes	struct utrace_rtld ut;
25689994Sdes
25789994Sdes	ut.sig[0] = 'R';
25823985Sdavidn	ut.sig[1] = 'T';
25923985Sdavidn	ut.sig[2] = 'L';
26021528Sdavidn	ut.sig[3] = 'D';
26189994Sdes	ut.event = event;
26289994Sdes	ut.handle = handle;
26389994Sdes	ut.mapbase = mapbase;
2641590Srgrimes	ut.mapsize = mapsize;
2651590Srgrimes	ut.refcnt = refcnt;
2661590Srgrimes	bzero(ut.name, sizeof(ut.name));
26789994Sdes	if (name)
26889994Sdes		strlcpy(ut.name, name, sizeof(ut.name));
26989994Sdes	utrace(&ut, sizeof(ut));
27089994Sdes}
2711590Srgrimes
2721590Srgrimes/*
27321528Sdavidn * Main entry point for dynamic linking.  The first argument is the
2741590Srgrimes * stack pointer.  The stack is expected to be laid out as described
2751590Srgrimes * in the SVR4 ABI specification, Intel 386 Processor Supplement.
2761590Srgrimes * Specifically, the stack pointer points to a word containing
2771590Srgrimes * ARGC.  Following that in the stack is a null-terminated sequence
2781590Srgrimes * of pointers to argument strings.  Then comes a null-terminated
27989994Sdes * sequence of pointers to environment strings.  Finally, there is a
2801590Srgrimes * sequence of "auxiliary vector" entries.
28189994Sdes *
2821590Srgrimes * The second argument points to a place to store the dynamic linker's
2831590Srgrimes * exit procedure pointer and the third to a place to store the main
28423985Sdavidn * program's object.
28589994Sdes *
2861590Srgrimes * The return value is the main program's entry point.
28789994Sdes */
28889994Sdesfunc_ptr_type
28989994Sdes_rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
29089994Sdes{
2913205Spst    Elf_Auxinfo *aux_info[AT_COUNT];
29289994Sdes    int i;
29389994Sdes    int argc;
29489994Sdes    char **argv;
29589994Sdes    char **env;
29689994Sdes    Elf_Auxinfo *aux;
29789994Sdes    Elf_Auxinfo *auxp;
29889994Sdes    const char *argv0;
29989994Sdes    Objlist_Entry *entry;
30089994Sdes    Obj_Entry *obj;
30189994Sdes    Obj_Entry **preload_tail;
30297376Sdes    Objlist initlist;
30389994Sdes    int lockstate;
30441279Sjdp
30541279Sjdp    /*
3061590Srgrimes     * On entry, the dynamic linker itself has not been relocated yet.
3071590Srgrimes     * Be very careful not to reference any global data until after
30889994Sdes     * init_rtld has returned.  It is OK to reference file-scope statics
30989994Sdes     * and string constants, and to call static and global functions.
31089994Sdes     */
3111590Srgrimes
31289994Sdes    /* Find the auxiliary vector on the stack. */
31389994Sdes    argc = *sp++;
31489994Sdes    argv = (char **) sp;
31589994Sdes    sp += argc + 1;	/* Skip over arguments and NULL terminator */
31689994Sdes    env = (char **) sp;
31789994Sdes    while (*sp++ != 0)	/* Skip over environment, and NULL terminator */
31889994Sdes	;
31989994Sdes    aux = (Elf_Auxinfo *) sp;
32089994Sdes
3211590Srgrimes    /* Digest the auxiliary vector. */
3221590Srgrimes    for (i = 0;  i < AT_COUNT;  i++)
32389994Sdes	aux_info[i] = NULL;
32489994Sdes    for (auxp = aux;  auxp->a_type != AT_NULL;  auxp++) {
32589994Sdes	if (auxp->a_type < AT_COUNT)
32689994Sdes	    aux_info[auxp->a_type] = auxp;
32797376Sdes    }
3281590Srgrimes
3291590Srgrimes    /* Initialize and relocate ourselves. */
33023985Sdavidn    assert(aux_info[AT_BASE] != NULL);
33123985Sdavidn    init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
33289994Sdes
33389994Sdes    __progname = obj_rtld.path;
33423985Sdavidn    argv0 = argv[0] != NULL ? argv[0] : "(null)";
33523985Sdavidn    environ = env;
33623985Sdavidn
3371590Srgrimes    trust = !issetugid();
33889994Sdes
3391590Srgrimes    ld_bind_now = getenv(LD_ "BIND_NOW");
34038374Sjkoshy    /*
3411590Srgrimes     * If the process is tainted, then we un-set the dangerous environment
3421590Srgrimes     * variables.  The process will be marked as tainted until setuid(2)
3431590Srgrimes     * is called.  If any child process calls setuid(2) we do not want any
3441590Srgrimes     * future processes to honor the potentially un-safe variables.
3451590Srgrimes     */
34676942Sguido    if (!trust) {
3471590Srgrimes        if (unsetenv(LD_ "PRELOAD") || unsetenv(LD_ "LIBMAP") ||
3481590Srgrimes	    unsetenv(LD_ "LIBRARY_PATH") || unsetenv(LD_ "LIBMAP_DISABLE") ||
3491590Srgrimes	    unsetenv(LD_ "DEBUG") || unsetenv(LD_ "ELF_HINTS_PATH")) {
35041279Sjdp		_rtld_error("environment corrupt; aborting");
35141279Sjdp		die();
35241279Sjdp	}
35341279Sjdp    }
35441279Sjdp    ld_debug = getenv(LD_ "DEBUG");
35521528Sdavidn    libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL;
35695243Sdes    libmap_override = getenv(LD_ "LIBMAP");
35795243Sdes    ld_library_path = getenv(LD_ "LIBRARY_PATH");
35897376Sdes    ld_preload = getenv(LD_ "PRELOAD");
35983519Srwatson    ld_elf_hints_path = getenv(LD_ "ELF_HINTS_PATH");
36083519Srwatson    dangerous_ld_env = libmap_disable || (libmap_override != NULL) ||
36183519Srwatson	(ld_library_path != NULL) || (ld_preload != NULL) ||
36283519Srwatson	(ld_elf_hints_path != NULL);
36383519Srwatson    ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS");
36483519Srwatson    ld_utrace = getenv(LD_ "UTRACE");
36583519Srwatson
36646007Sache    if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
36735557Speter	ld_elf_hints_path = _PATH_ELF_HINTS;
36821528Sdavidn
36926021Spst    if (ld_debug != NULL && *ld_debug != '\0')
37023985Sdavidn	debug = 1;
37197376Sdes    dbg("%s is initialized, base address = %p", __progname,
37223985Sdavidn	(caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
37323985Sdavidn    dbg("RTLD dynamic = %p", obj_rtld.dynamic);
37423985Sdavidn    dbg("RTLD pltgot  = %p", obj_rtld.pltgot);
37587173Smarkm
37687173Smarkm    /*
37787173Smarkm     * Load the main program, or process its program header if it is
37889994Sdes     * already loaded.
37987173Smarkm     */
3801590Srgrimes    if (aux_info[AT_EXECFD] != NULL) {	/* Load the main program. */
38135557Speter	int fd = aux_info[AT_EXECFD]->a_un.a_val;
38246007Sache	dbg("loading main program");
38321528Sdavidn	obj_main = map_object(fd, argv0, NULL);
38421528Sdavidn	close(fd);
38597376Sdes	if (obj_main == NULL)
38697376Sdes	    die();
38723985Sdavidn    } else {				/* Main program already loaded. */
38887173Smarkm	const Elf_Phdr *phdr;
38987173Smarkm	int phnum;
39087173Smarkm	caddr_t entry;
39189994Sdes
39287173Smarkm	dbg("processing main program's program header");
39323985Sdavidn	assert(aux_info[AT_PHDR] != NULL);
39423985Sdavidn	phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
39523985Sdavidn	assert(aux_info[AT_PHNUM] != NULL);
39681555Smike	phnum = aux_info[AT_PHNUM]->a_un.a_val;
39789994Sdes	assert(aux_info[AT_PHENT] != NULL);
39823985Sdavidn	assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
39921528Sdavidn	assert(aux_info[AT_ENTRY] != NULL);
4002224Sguido	entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
4012224Sguido	if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
4022224Sguido	    die();
4032224Sguido    }
4042224Sguido
4052224Sguido    if (aux_info[AT_EXECPATH] != 0) {
4062224Sguido	    char *kexecpath;
40750124Simp	    char buf[MAXPATHLEN];
40850124Simp
40950124Simp	    kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
41050124Simp	    dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
41150124Simp	    if (kexecpath[0] == '/')
41250124Simp		    obj_main->path = kexecpath;
41389994Sdes	    else if (getcwd(buf, sizeof(buf)) == NULL ||
41489994Sdes		     strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
41589994Sdes		     strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
41650124Simp		    obj_main->path = xstrdup(argv0);
41750124Simp	    else
4181590Srgrimes		    obj_main->path = xstrdup(buf);
41923985Sdavidn    } else {
42023985Sdavidn	    dbg("No AT_EXECPATH");
42123985Sdavidn	    obj_main->path = xstrdup(argv0);
42223985Sdavidn    }
42323985Sdavidn    dbg("obj_main path %s", obj_main->path);
42489994Sdes    obj_main->mainprog = true;
4251590Srgrimes
4261590Srgrimes    /*
4273205Spst     * Get the actual dynamic linker pathname from the executable if
4283205Spst     * possible.  (It should always be possible.)  That ensures that
42989994Sdes     * gdb will find the right dynamic linker even if a non-standard
43089994Sdes     * one is being used.
4313205Spst     */
43289994Sdes    if (obj_main->interp != NULL &&
43323985Sdavidn      strcmp(obj_main->interp, obj_rtld.path) != 0) {
43489994Sdes	free(obj_rtld.path);
43523985Sdavidn	obj_rtld.path = xstrdup(obj_main->interp);
43623985Sdavidn        __progname = obj_rtld.path;
43723985Sdavidn    }
43821528Sdavidn
43921528Sdavidn    digest_dynamic(obj_main, 0);
44023985Sdavidn
44189994Sdes    linkmap_add(obj_main);
44289994Sdes    linkmap_add(&obj_rtld);
44323985Sdavidn
44489994Sdes    /* Link the main program into the list of objects. */
44589994Sdes    *obj_tail = obj_main;
44623985Sdavidn    obj_tail = &obj_main->next;
44789994Sdes    obj_count++;
44823985Sdavidn    obj_loads++;
44923985Sdavidn    /* Make sure we don't call the main program's init and fini functions. */
45076788Sobrien    obj_main->init = obj_main->fini = (Elf_Addr)NULL;
45123985Sdavidn
45223985Sdavidn    /* Initialize a fake symbol for resolving undefined weak references. */
45323985Sdavidn    sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
45489994Sdes    sym_zero.st_shndx = SHN_UNDEF;
45589994Sdes    sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
45623985Sdavidn
45789994Sdes    if (!libmap_disable)
45821528Sdavidn        libmap_disable = (bool)lm_init(libmap_override);
45921528Sdavidn
46089994Sdes    dbg("loading LD_PRELOAD libraries");
46189994Sdes    if (load_preload_objects() == -1)
46221528Sdavidn	die();
46323985Sdavidn    preload_tail = obj_tail;
46474874Smarkm
46574874Smarkm    dbg("loading needed objects");
46674874Smarkm    if (load_needed_objects(obj_main, 0) == -1)
46797376Sdes	die();
46889994Sdes
46974874Smarkm    /* Make a list of all objects loaded at startup. */
47074874Smarkm    for (obj = obj_list;  obj != NULL;  obj = obj->next) {
47189994Sdes	objlist_push_tail(&list_main, obj);
47289994Sdes    	obj->refcount++;
47389994Sdes    }
47489994Sdes
47589994Sdes    dbg("checking for required versions");
47689994Sdes    if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
47797376Sdes	die();
47889994Sdes
47989994Sdes    if (ld_tracing) {		/* We're done */
48089994Sdes	trace_loaded_objects(obj_main);
48189994Sdes	exit(0);
48289994Sdes    }
48389994Sdes
48474874Smarkm    if (getenv(LD_ "DUMP_REL_PRE") != NULL) {
48589994Sdes       dump_relocations(obj_main);
48689994Sdes       exit (0);
48789994Sdes    }
48889994Sdes
48989994Sdes    /* setup TLS for main thread */
49089994Sdes    dbg("initializing initial thread local storage");
49189994Sdes    STAILQ_FOREACH(entry, &list_main, link) {
49289994Sdes	/*
49374874Smarkm	 * Allocate all the initial objects out of the static TLS
49489994Sdes	 * block even if they didn't ask for it.
49589994Sdes	 */
49674874Smarkm	allocate_tls_offset(entry->obj);
49789994Sdes    }
49889994Sdes    allocate_initial_tls(obj_list);
49974874Smarkm
50074874Smarkm    if (relocate_objects(obj_main,
50174874Smarkm	ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1)
50289994Sdes	die();
50321528Sdavidn
50497376Sdes    dbg("doing copy relocations");
50589994Sdes    if (do_copy_relocations(obj_main) == -1)
50689994Sdes	die();
50789994Sdes
50889994Sdes    if (getenv(LD_ "DUMP_REL_POST") != NULL) {
50989994Sdes       dump_relocations(obj_main);
51089994Sdes       exit (0);
51189994Sdes    }
51289994Sdes
51391714Sdes    dbg("initializing key program variables");
51489994Sdes    set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
51589994Sdes    set_program_var("environ", env);
51689994Sdes    set_program_var("__elf_aux_vector", aux);
51789994Sdes
51889994Sdes    dbg("initializing thread locks");
51989994Sdes    lockdflt_init();
52041279Sjdp
52197376Sdes    /* Make a list of init functions to call. */
52289994Sdes    objlist_init(&initlist);
52341279Sjdp    initlist_add_objects(obj_list, preload_tail, &initlist);
52441279Sjdp
52574874Smarkm    r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
52697376Sdes
52721528Sdavidn    lockstate = wlock_acquire(rtld_bind_lock);
5283205Spst    objlist_call_init(&initlist, &lockstate);
52921528Sdavidn    objlist_clear(&initlist);
53023148Sache    wlock_release(rtld_bind_lock, lockstate);
53121528Sdavidn
53289994Sdes    dbg("transferring control to program entry point = %p", obj_main->entry);
53341279Sjdp
53441279Sjdp    /* Return the exit procedure and the program entry point. */
53521528Sdavidn    *exit_proc = rtld_exit;
53621528Sdavidn    *objp = obj_main;
5371590Srgrimes    return (func_ptr_type) obj_main->entry;
53894203Sru}
53923985Sdavidn
54023985SdavidnElf_Addr
54189994Sdes_rtld_bind(Obj_Entry *obj, Elf_Size reloff)
54289994Sdes{
54323985Sdavidn    const Elf_Rel *rel;
54423985Sdavidn    const Elf_Sym *def;
54523985Sdavidn    const Obj_Entry *defobj;
54621528Sdavidn    Elf_Addr *where;
54789994Sdes    Elf_Addr target;
54889994Sdes    int lockstate;
54989994Sdes
55089994Sdes    lockstate = rlock_acquire(rtld_bind_lock);
55123985Sdavidn    if (obj->pltrel)
55286450Srwatson	rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
55386450Srwatson    else
55486450Srwatson	rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
55589994Sdes
55694203Sru    where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
55786450Srwatson    def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL);
55889994Sdes    if (def == NULL)
55989994Sdes	die();
56086450Srwatson
56186450Srwatson    target = (Elf_Addr)(defobj->relocbase + def->st_value);
56289994Sdes
56394203Sru    dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
56486450Srwatson      defobj->strtab + def->st_name, basename(obj->path),
5651590Srgrimes      (void *)target, basename(defobj->path));
5661590Srgrimes
56721528Sdavidn    /*
5683205Spst     * Write the new contents for the jmpslot. Note that depending on
5691590Srgrimes     * architecture, the value which we need to return back to the
5701590Srgrimes     * lazy binding trampoline may or may not be the target
5711590Srgrimes     * address. The value returned from reloc_jmpslot() is the value
5721590Srgrimes     * that the trampoline needs.
5731590Srgrimes     */
57423985Sdavidn    target = reloc_jmpslot(where, target, defobj, obj, rel);
57523985Sdavidn    rlock_release(rtld_bind_lock, lockstate);
57623985Sdavidn    return target;
57789994Sdes}
57889994Sdes
57981555Smike/*
58081555Smike * Error reporting function.  Use it like printf.  If formats the message
58181555Smike * into a buffer, and sets things up so that the next call to dlerror()
58289994Sdes * will return the message.
58389994Sdes */
58481555Smikevoid
58523985Sdavidn_rtld_error(const char *fmt, ...)
58689994Sdes{
58721528Sdavidn    static char buf[512];
58897376Sdes    va_list ap;
58989994Sdes
59089994Sdes    va_start(ap, fmt);
59189994Sdes    vsnprintf(buf, sizeof buf, fmt, ap);
5921590Srgrimes    error_message = buf;
5931590Srgrimes    va_end(ap);
59441279Sjdp}
59541279Sjdp
59641279Sjdp/*
59741279Sjdp * Return a dynamically-allocated copy of the current error message, if any.
59841279Sjdp */
59941279Sjdpstatic char *
60041279Sjdperrmsg_save(void)
60141279Sjdp{
60289994Sdes    return error_message == NULL ? NULL : xstrdup(error_message);
60341279Sjdp}
60441279Sjdp
60541279Sjdp/*
60641279Sjdp * Restore the current error message from a copy which was previously saved
60741279Sjdp * by errmsg_save().  The copy is freed.
60889994Sdes */
60989994Sdesstatic void
61041279Sjdperrmsg_restore(char *saved_msg)
61141279Sjdp{
61241279Sjdp    if (saved_msg == NULL)
61341279Sjdp	error_message = NULL;
61441279Sjdp    else {
61541279Sjdp	_rtld_error("%s", saved_msg);
61641279Sjdp	free(saved_msg);
61741279Sjdp    }
61841279Sjdp}
61941279Sjdp
62041279Sjdpstatic const char *
62141279Sjdpbasename(const char *name)
62241279Sjdp{
62341279Sjdp    const char *p = strrchr(name, '/');
62441279Sjdp    return p != NULL ? p + 1 : name;
62541279Sjdp}
62641279Sjdp
62741279Sjdpstatic struct utsname uts;
62841279Sjdp
62989994Sdesstatic int
63089994Sdesorigin_subst_one(char **res, const char *real, const char *kw, const char *subst,
63189994Sdes    char *may_free)
63241279Sjdp{
63341279Sjdp    const char *p, *p1;
63489994Sdes    char *res1;
63589994Sdes    int subst_len;
63689994Sdes    int kw_len;
63741279Sjdp
63841279Sjdp    res1 = *res = NULL;
63941279Sjdp    p = real;
64041279Sjdp    subst_len = kw_len = 0;
64141279Sjdp    for (;;) {
64241279Sjdp	 p1 = strstr(p, kw);
64341279Sjdp	 if (p1 != NULL) {
64441279Sjdp	     if (subst_len == 0) {
64541279Sjdp		 subst_len = strlen(subst);
64641279Sjdp		 kw_len = strlen(kw);
64789994Sdes	     }
64841279Sjdp	     if (*res == NULL) {
64941279Sjdp		 *res = xmalloc(PATH_MAX);
65041279Sjdp		 res1 = *res;
65174874Smarkm	     }
65274874Smarkm	     if ((res1 - *res) + subst_len + (p1 - p) >= PATH_MAX) {
65389994Sdes		 _rtld_error("Substitution of %s in %s cannot be performed",
65489994Sdes		     kw, real);
65589994Sdes		 if (may_free != NULL)
65689994Sdes		     free(may_free);
65789994Sdes		 free(res);
65889994Sdes		 return (false);
65989994Sdes	     }
66089994Sdes	     memcpy(res1, p, p1 - p);
66189994Sdes	     res1 += p1 - p;
66274874Smarkm	     memcpy(res1, subst, subst_len);
66374874Smarkm	     res1 += subst_len;
66489994Sdes	     p = p1 + kw_len;
66589994Sdes	 } else {
66689994Sdes	    if (*res == NULL) {
66774874Smarkm		if (may_free != NULL)
66889994Sdes		    *res = may_free;
66974874Smarkm		else
67041279Sjdp		    *res = xstrdup(real);
67174874Smarkm		return (true);
67274874Smarkm	    }
67389994Sdes	    *res1 = '\0';
67474874Smarkm	    if (may_free != NULL)
67574874Smarkm		free(may_free);
67689994Sdes	    if (strlcat(res1, p, PATH_MAX - (res1 - *res)) >= PATH_MAX) {
67741279Sjdp		free(res);
67872215Snectar		return (false);
67989994Sdes	    }
68089994Sdes	    return (true);
68189994Sdes	 }
68289994Sdes    }
68387177Smarkm}
68472215Snectar
68589994Sdesstatic char *
68689994Sdesorigin_subst(const char *real, const char *origin_path)
68772215Snectar{
68889994Sdes    char *res1, *res2, *res3, *res4;
68989994Sdes
69089994Sdes    if (uts.sysname[0] == '\0') {
69189994Sdes	if (uname(&uts) != 0) {
69289994Sdes	    _rtld_error("utsname failed: %d", errno);
69389994Sdes	    return (NULL);
69472215Snectar	}
69572215Snectar    }
69672215Snectar    if (!origin_subst_one(&res1, real, "$ORIGIN", origin_path, NULL) ||
69772215Snectar	!origin_subst_one(&res2, res1, "$OSNAME", uts.sysname, res1) ||
69889994Sdes	!origin_subst_one(&res3, res2, "$OSREL", uts.release, res2) ||
69972215Snectar	!origin_subst_one(&res4, res3, "$PLATFORM", uts.machine, res3))
70072215Snectar	    return (NULL);
70172215Snectar    return (res4);
70272215Snectar}
70389994Sdes
70472215Snectarstatic void
70572215Snectardie(void)
70689994Sdes{
70772215Snectar    const char *msg = dlerror();
70872215Snectar
70972215Snectar    if (msg == NULL)
71072215Snectar	msg = "Fatal error";
71172215Snectar    errx(1, "%s", msg);
71272215Snectar}
71372215Snectar
71472215Snectar/*
71572215Snectar * Process a shared object's DYNAMIC section, and save the important
71689994Sdes * information in its Obj_Entry structure.
71772215Snectar */
71889994Sdesstatic void
71972215Snectardigest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
72072215Snectar    const Elf_Dyn **dyn_soname)
72172215Snectar{
72289994Sdes    const Elf_Dyn *dynp;
72372215Snectar    Needed_Entry **needed_tail = &obj->needed;
72489994Sdes    int plttype = DT_REL;
72589994Sdes
72672215Snectar    *dyn_rpath = NULL;
72741279Sjdp    *dyn_soname = NULL;
72827605Scharnier
72987177Smarkm    obj->bind_now = false;
73027605Scharnier    for (dynp = obj->dynamic;  dynp->d_tag != DT_NULL;  dynp++) {
73176791Sobrien	switch (dynp->d_tag) {
73227605Scharnier
73327605Scharnier	case DT_REL:
73427605Scharnier	    obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr);
7351590Srgrimes	    break;
73623985Sdavidn
73789994Sdes	case DT_RELSZ:
73874874Smarkm	    obj->relsize = dynp->d_un.d_val;
73989994Sdes	    break;
74087177Smarkm
7411590Srgrimes	case DT_RELENT:
74289994Sdes	    assert(dynp->d_un.d_val == sizeof(Elf_Rel));
7431590Srgrimes	    break;
7441590Srgrimes
74589994Sdes	case DT_JMPREL:
74689994Sdes	    obj->pltrel = (const Elf_Rel *)
74789994Sdes	      (obj->relocbase + dynp->d_un.d_ptr);
74889994Sdes	    break;
74981555Smike
7501590Srgrimes	case DT_PLTRELSZ:
7511590Srgrimes	    obj->pltrelsize = dynp->d_un.d_val;
7521590Srgrimes	    break;
75389994Sdes
7541590Srgrimes	case DT_RELA:
75589994Sdes	    obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr);
7561590Srgrimes	    break;
7571590Srgrimes
75889994Sdes	case DT_RELASZ:
75997376Sdes	    obj->relasize = dynp->d_un.d_val;
76089994Sdes	    break;
76189994Sdes
76289994Sdes	case DT_RELAENT:
76389994Sdes	    assert(dynp->d_un.d_val == sizeof(Elf_Rela));
76489994Sdes	    break;
76589994Sdes
7661590Srgrimes	case DT_PLTREL:
76789994Sdes	    plttype = dynp->d_un.d_val;
7681590Srgrimes	    assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA);
7691590Srgrimes	    break;
77089994Sdes
77189994Sdes	case DT_SYMTAB:
77289994Sdes	    obj->symtab = (const Elf_Sym *)
77389994Sdes	      (obj->relocbase + dynp->d_un.d_ptr);
77489994Sdes	    break;
77589994Sdes
7761590Srgrimes	case DT_SYMENT:
77721528Sdavidn	    assert(dynp->d_un.d_val == sizeof(Elf_Sym));
77821528Sdavidn	    break;
77921528Sdavidn
78089994Sdes	case DT_STRTAB:
78189994Sdes	    obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr);
78289994Sdes	    break;
78389994Sdes
78489994Sdes	case DT_STRSZ:
78521528Sdavidn	    obj->strsize = dynp->d_un.d_val;
7861590Srgrimes	    break;
78789994Sdes
78889994Sdes	case DT_VERNEED:
7891590Srgrimes	    obj->verneed = (const Elf_Verneed *) (obj->relocbase +
79089994Sdes		dynp->d_un.d_val);
79189994Sdes	    break;
79221528Sdavidn
7931590Srgrimes	case DT_VERNEEDNUM:
79489994Sdes	    obj->verneednum = dynp->d_un.d_val;
79589994Sdes	    break;
79689994Sdes
79789994Sdes	case DT_VERDEF:
79889994Sdes	    obj->verdef = (const Elf_Verdef *) (obj->relocbase +
79989994Sdes		dynp->d_un.d_val);
80089994Sdes	    break;
80189994Sdes
80289994Sdes	case DT_VERDEFNUM:
8031590Srgrimes	    obj->verdefnum = dynp->d_un.d_val;
8041590Srgrimes	    break;
80589994Sdes
80689994Sdes	case DT_VERSYM:
80789994Sdes	    obj->versyms = (const Elf_Versym *)(obj->relocbase +
80889994Sdes		dynp->d_un.d_val);
80989994Sdes	    break;
81089994Sdes
81189994Sdes	case DT_HASH:
81289994Sdes	    {
81389994Sdes		const Elf_Hashelt *hashtab = (const Elf_Hashelt *)
81489994Sdes		  (obj->relocbase + dynp->d_un.d_ptr);
8151590Srgrimes		obj->nbuckets = hashtab[0];
81676788Sobrien		obj->nchains = hashtab[1];
81742272Seivind		obj->buckets = hashtab + 2;
8181590Srgrimes		obj->chains = obj->buckets + obj->nbuckets;
8191590Srgrimes	    }
8201590Srgrimes	    break;
82189994Sdes
8221590Srgrimes	case DT_NEEDED:
8231590Srgrimes	    if (!obj->rtld) {
8241590Srgrimes		Needed_Entry *nep = NEW(Needed_Entry);
8251590Srgrimes		nep->name = dynp->d_un.d_val;
82689994Sdes		nep->obj = NULL;
8271590Srgrimes		nep->next = NULL;
82889994Sdes
8291590Srgrimes		*needed_tail = nep;
8301590Srgrimes		needed_tail = &nep->next;
83189994Sdes	    }
8321590Srgrimes	    break;
8331590Srgrimes
8341590Srgrimes	case DT_PLTGOT:
8351590Srgrimes	    obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr);
8361590Srgrimes	    break;
8371590Srgrimes
8381590Srgrimes	case DT_TEXTREL:
83942272Seivind	    obj->textrel = true;
8401590Srgrimes	    break;
8411590Srgrimes
84287173Smarkm	case DT_SYMBOLIC:
84389994Sdes	    obj->symbolic = true;
8441590Srgrimes	    break;
8451590Srgrimes
84623985Sdavidn	case DT_RPATH:
84781555Smike	case DT_RUNPATH:	/* XXX: process separately */
84881555Smike	    /*
84981555Smike	     * We have to wait until later to process this, because we
85081555Smike	     * might not have gotten the address of the string table yet.
85181555Smike	     */
85289994Sdes	    *dyn_rpath = dynp;
8531590Srgrimes	    break;
8541590Srgrimes
8551590Srgrimes	case DT_SONAME:
85689994Sdes	    *dyn_soname = dynp;
85723985Sdavidn	    break;
85823985Sdavidn
85923985Sdavidn	case DT_INIT:
86023985Sdavidn	    obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
86189994Sdes	    break;
86223985Sdavidn
86389994Sdes	case DT_FINI:
86423985Sdavidn	    obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr);
86523985Sdavidn	    break;
86676788Sobrien
86723985Sdavidn	/*
86889994Sdes	 * Don't process DT_DEBUG on MIPS as the dynamic section
86923985Sdavidn	 * is mapped read-only. DT_MIPS_RLD_MAP is used instead.
87023985Sdavidn	 */
87189994Sdes
87289994Sdes#ifndef __mips__
87389994Sdes	case DT_DEBUG:
87423985Sdavidn	    /* XXX - not implemented yet */
87589994Sdes	    if (!early)
8761590Srgrimes		dbg("Filling in DT_DEBUG entry");
87789994Sdes	    ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
87889994Sdes	    break;
87923985Sdavidn#endif
88089994Sdes
88189994Sdes	case DT_FLAGS:
88289994Sdes		if ((dynp->d_un.d_val & DF_ORIGIN) && trust)
88389994Sdes		    obj->z_origin = true;
88489994Sdes		if (dynp->d_un.d_val & DF_SYMBOLIC)
88589994Sdes		    obj->symbolic = true;
88689994Sdes		if (dynp->d_un.d_val & DF_TEXTREL)
88789994Sdes		    obj->textrel = true;
88889994Sdes		if (dynp->d_un.d_val & DF_BIND_NOW)
88989994Sdes		    obj->bind_now = true;
89089994Sdes		if (dynp->d_un.d_val & DF_STATIC_TLS)
89189994Sdes		    ;
89289994Sdes	    break;
89389994Sdes#ifdef __mips__
89489994Sdes	case DT_MIPS_LOCAL_GOTNO:
89589994Sdes		obj->local_gotno = dynp->d_un.d_val;
89689994Sdes	    break;
89789994Sdes
89889994Sdes	case DT_MIPS_SYMTABNO:
89989994Sdes		obj->symtabno = dynp->d_un.d_val;
90089994Sdes		break;
90189994Sdes
90289994Sdes	case DT_MIPS_GOTSYM:
90389994Sdes		obj->gotsym = dynp->d_un.d_val;
90489994Sdes		break;
90589994Sdes
90689994Sdes	case DT_MIPS_RLD_MAP:
90789994Sdes#ifdef notyet
90889994Sdes		if (!early)
90989994Sdes			dbg("Filling in DT_DEBUG entry");
91089994Sdes		((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug;
91189994Sdes#endif
91289994Sdes		break;
91389994Sdes#endif
9141590Srgrimes
9151590Srgrimes	case DT_FLAGS_1:
916		if (dynp->d_un.d_val & DF_1_NOOPEN)
917		    obj->z_noopen = true;
918		if ((dynp->d_un.d_val & DF_1_ORIGIN) && trust)
919		    obj->z_origin = true;
920		if (dynp->d_un.d_val & DF_1_GLOBAL)
921			/* XXX */;
922		if (dynp->d_un.d_val & DF_1_BIND_NOW)
923		    obj->bind_now = true;
924		if (dynp->d_un.d_val & DF_1_NODELETE)
925		    obj->z_nodelete = true;
926	    break;
927
928	default:
929	    if (!early) {
930		dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag,
931		    (long)dynp->d_tag);
932	    }
933	    break;
934	}
935    }
936
937    obj->traced = false;
938
939    if (plttype == DT_RELA) {
940	obj->pltrela = (const Elf_Rela *) obj->pltrel;
941	obj->pltrel = NULL;
942	obj->pltrelasize = obj->pltrelsize;
943	obj->pltrelsize = 0;
944    }
945}
946
947static void
948digest_dynamic2(Obj_Entry *obj, const Elf_Dyn *dyn_rpath,
949    const Elf_Dyn *dyn_soname)
950{
951
952    if (obj->z_origin && obj->origin_path == NULL) {
953	obj->origin_path = xmalloc(PATH_MAX);
954	if (rtld_dirname_abs(obj->path, obj->origin_path) == -1)
955	    die();
956    }
957
958    if (dyn_rpath != NULL) {
959	obj->rpath = (char *)obj->strtab + dyn_rpath->d_un.d_val;
960	if (obj->z_origin)
961	    obj->rpath = origin_subst(obj->rpath, obj->origin_path);
962    }
963
964    if (dyn_soname != NULL)
965	object_add_name(obj, obj->strtab + dyn_soname->d_un.d_val);
966}
967
968static void
969digest_dynamic(Obj_Entry *obj, int early)
970{
971	const Elf_Dyn *dyn_rpath;
972	const Elf_Dyn *dyn_soname;
973
974	digest_dynamic1(obj, early, &dyn_rpath, &dyn_soname);
975	digest_dynamic2(obj, dyn_rpath, dyn_soname);
976}
977
978/*
979 * Process a shared object's program header.  This is used only for the
980 * main program, when the kernel has already loaded the main program
981 * into memory before calling the dynamic linker.  It creates and
982 * returns an Obj_Entry structure.
983 */
984static Obj_Entry *
985digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
986{
987    Obj_Entry *obj;
988    const Elf_Phdr *phlimit = phdr + phnum;
989    const Elf_Phdr *ph;
990    int nsegs = 0;
991
992    obj = obj_new();
993    for (ph = phdr;  ph < phlimit;  ph++) {
994	if (ph->p_type != PT_PHDR)
995	    continue;
996
997	obj->phdr = phdr;
998	obj->phsize = ph->p_memsz;
999	obj->relocbase = (caddr_t)phdr - ph->p_vaddr;
1000	break;
1001    }
1002
1003    for (ph = phdr;  ph < phlimit;  ph++) {
1004	switch (ph->p_type) {
1005
1006	case PT_INTERP:
1007	    obj->interp = (const char *)(ph->p_vaddr + obj->relocbase);
1008	    break;
1009
1010	case PT_LOAD:
1011	    if (nsegs == 0) {	/* First load segment */
1012		obj->vaddrbase = trunc_page(ph->p_vaddr);
1013		obj->mapbase = obj->vaddrbase + obj->relocbase;
1014		obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) -
1015		  obj->vaddrbase;
1016	    } else {		/* Last load segment */
1017		obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) -
1018		  obj->vaddrbase;
1019	    }
1020	    nsegs++;
1021	    break;
1022
1023	case PT_DYNAMIC:
1024	    obj->dynamic = (const Elf_Dyn *)(ph->p_vaddr + obj->relocbase);
1025	    break;
1026
1027	case PT_TLS:
1028	    obj->tlsindex = 1;
1029	    obj->tlssize = ph->p_memsz;
1030	    obj->tlsalign = ph->p_align;
1031	    obj->tlsinitsize = ph->p_filesz;
1032	    obj->tlsinit = (void*)(ph->p_vaddr + obj->relocbase);
1033	    break;
1034	}
1035    }
1036    if (nsegs < 1) {
1037	_rtld_error("%s: too few PT_LOAD segments", path);
1038	return NULL;
1039    }
1040
1041    obj->entry = entry;
1042    return obj;
1043}
1044
1045static Obj_Entry *
1046dlcheck(void *handle)
1047{
1048    Obj_Entry *obj;
1049
1050    for (obj = obj_list;  obj != NULL;  obj = obj->next)
1051	if (obj == (Obj_Entry *) handle)
1052	    break;
1053
1054    if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) {
1055	_rtld_error("Invalid shared object handle %p", handle);
1056	return NULL;
1057    }
1058    return obj;
1059}
1060
1061/*
1062 * If the given object is already in the donelist, return true.  Otherwise
1063 * add the object to the list and return false.
1064 */
1065static bool
1066donelist_check(DoneList *dlp, const Obj_Entry *obj)
1067{
1068    unsigned int i;
1069
1070    for (i = 0;  i < dlp->num_used;  i++)
1071	if (dlp->objs[i] == obj)
1072	    return true;
1073    /*
1074     * Our donelist allocation should always be sufficient.  But if
1075     * our threads locking isn't working properly, more shared objects
1076     * could have been loaded since we allocated the list.  That should
1077     * never happen, but we'll handle it properly just in case it does.
1078     */
1079    if (dlp->num_used < dlp->num_alloc)
1080	dlp->objs[dlp->num_used++] = obj;
1081    return false;
1082}
1083
1084/*
1085 * Hash function for symbol table lookup.  Don't even think about changing
1086 * this.  It is specified by the System V ABI.
1087 */
1088unsigned long
1089elf_hash(const char *name)
1090{
1091    const unsigned char *p = (const unsigned char *) name;
1092    unsigned long h = 0;
1093    unsigned long g;
1094
1095    while (*p != '\0') {
1096	h = (h << 4) + *p++;
1097	if ((g = h & 0xf0000000) != 0)
1098	    h ^= g >> 24;
1099	h &= ~g;
1100    }
1101    return h;
1102}
1103
1104/*
1105 * Find the library with the given name, and return its full pathname.
1106 * The returned string is dynamically allocated.  Generates an error
1107 * message and returns NULL if the library cannot be found.
1108 *
1109 * If the second argument is non-NULL, then it refers to an already-
1110 * loaded shared object, whose library search path will be searched.
1111 *
1112 * The search order is:
1113 *   LD_LIBRARY_PATH
1114 *   rpath in the referencing file
1115 *   ldconfig hints
1116 *   /lib:/usr/lib
1117 */
1118static char *
1119find_library(const char *xname, const Obj_Entry *refobj)
1120{
1121    char *pathname;
1122    char *name;
1123
1124    if (strchr(xname, '/') != NULL) {	/* Hard coded pathname */
1125	if (xname[0] != '/' && !trust) {
1126	    _rtld_error("Absolute pathname required for shared object \"%s\"",
1127	      xname);
1128	    return NULL;
1129	}
1130	if (refobj != NULL && refobj->z_origin)
1131	    return origin_subst(xname, refobj->origin_path);
1132	else
1133	    return xstrdup(xname);
1134    }
1135
1136    if (libmap_disable || (refobj == NULL) ||
1137	(name = lm_find(refobj->path, xname)) == NULL)
1138	name = (char *)xname;
1139
1140    dbg(" Searching for \"%s\"", name);
1141
1142    if ((pathname = search_library_path(name, ld_library_path)) != NULL ||
1143      (refobj != NULL &&
1144      (pathname = search_library_path(name, refobj->rpath)) != NULL) ||
1145      (pathname = search_library_path(name, gethints())) != NULL ||
1146      (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL)
1147	return pathname;
1148
1149    if(refobj != NULL && refobj->path != NULL) {
1150	_rtld_error("Shared object \"%s\" not found, required by \"%s\"",
1151	  name, basename(refobj->path));
1152    } else {
1153	_rtld_error("Shared object \"%s\" not found", name);
1154    }
1155    return NULL;
1156}
1157
1158/*
1159 * Given a symbol number in a referencing object, find the corresponding
1160 * definition of the symbol.  Returns a pointer to the symbol, or NULL if
1161 * no definition was found.  Returns a pointer to the Obj_Entry of the
1162 * defining object via the reference parameter DEFOBJ_OUT.
1163 */
1164const Elf_Sym *
1165find_symdef(unsigned long symnum, const Obj_Entry *refobj,
1166    const Obj_Entry **defobj_out, int flags, SymCache *cache)
1167{
1168    const Elf_Sym *ref;
1169    const Elf_Sym *def;
1170    const Obj_Entry *defobj;
1171    const Ver_Entry *ventry;
1172    const char *name;
1173    unsigned long hash;
1174
1175    /*
1176     * If we have already found this symbol, get the information from
1177     * the cache.
1178     */
1179    if (symnum >= refobj->nchains)
1180	return NULL;	/* Bad object */
1181    if (cache != NULL && cache[symnum].sym != NULL) {
1182	*defobj_out = cache[symnum].obj;
1183	return cache[symnum].sym;
1184    }
1185
1186    ref = refobj->symtab + symnum;
1187    name = refobj->strtab + ref->st_name;
1188    defobj = NULL;
1189
1190    /*
1191     * We don't have to do a full scale lookup if the symbol is local.
1192     * We know it will bind to the instance in this load module; to
1193     * which we already have a pointer (ie ref). By not doing a lookup,
1194     * we not only improve performance, but it also avoids unresolvable
1195     * symbols when local symbols are not in the hash table. This has
1196     * been seen with the ia64 toolchain.
1197     */
1198    if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) {
1199	if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) {
1200	    _rtld_error("%s: Bogus symbol table entry %lu", refobj->path,
1201		symnum);
1202	}
1203	ventry = fetch_ventry(refobj, symnum);
1204	hash = elf_hash(name);
1205	def = symlook_default(name, hash, refobj, &defobj, ventry, flags);
1206    } else {
1207	def = ref;
1208	defobj = refobj;
1209    }
1210
1211    /*
1212     * If we found no definition and the reference is weak, treat the
1213     * symbol as having the value zero.
1214     */
1215    if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) {
1216	def = &sym_zero;
1217	defobj = obj_main;
1218    }
1219
1220    if (def != NULL) {
1221	*defobj_out = defobj;
1222	/* Record the information in the cache to avoid subsequent lookups. */
1223	if (cache != NULL) {
1224	    cache[symnum].sym = def;
1225	    cache[symnum].obj = defobj;
1226	}
1227    } else {
1228	if (refobj != &obj_rtld)
1229	    _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name);
1230    }
1231    return def;
1232}
1233
1234/*
1235 * Return the search path from the ldconfig hints file, reading it if
1236 * necessary.  Returns NULL if there are problems with the hints file,
1237 * or if the search path there is empty.
1238 */
1239static const char *
1240gethints(void)
1241{
1242    static char *hints;
1243
1244    if (hints == NULL) {
1245	int fd;
1246	struct elfhints_hdr hdr;
1247	char *p;
1248
1249	/* Keep from trying again in case the hints file is bad. */
1250	hints = "";
1251
1252	if ((fd = open(ld_elf_hints_path, O_RDONLY)) == -1)
1253	    return NULL;
1254	if (read(fd, &hdr, sizeof hdr) != sizeof hdr ||
1255	  hdr.magic != ELFHINTS_MAGIC ||
1256	  hdr.version != 1) {
1257	    close(fd);
1258	    return NULL;
1259	}
1260	p = xmalloc(hdr.dirlistlen + 1);
1261	if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 ||
1262	  read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) {
1263	    free(p);
1264	    close(fd);
1265	    return NULL;
1266	}
1267	hints = p;
1268	close(fd);
1269    }
1270    return hints[0] != '\0' ? hints : NULL;
1271}
1272
1273static void
1274init_dag(Obj_Entry *root)
1275{
1276    DoneList donelist;
1277
1278    donelist_init(&donelist);
1279    init_dag1(root, root, &donelist);
1280}
1281
1282static void
1283init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp)
1284{
1285    const Needed_Entry *needed;
1286
1287    if (donelist_check(dlp, obj))
1288	return;
1289
1290    obj->refcount++;
1291    objlist_push_tail(&obj->dldags, root);
1292    objlist_push_tail(&root->dagmembers, obj);
1293    for (needed = obj->needed;  needed != NULL;  needed = needed->next)
1294	if (needed->obj != NULL)
1295	    init_dag1(root, needed->obj, dlp);
1296}
1297
1298/*
1299 * Initialize the dynamic linker.  The argument is the address at which
1300 * the dynamic linker has been mapped into memory.  The primary task of
1301 * this function is to relocate the dynamic linker.
1302 */
1303static void
1304init_rtld(caddr_t mapbase, Elf_Auxinfo **aux_info)
1305{
1306    Obj_Entry objtmp;	/* Temporary rtld object */
1307    const Elf_Dyn *dyn_rpath;
1308    const Elf_Dyn *dyn_soname;
1309
1310    /*
1311     * Conjure up an Obj_Entry structure for the dynamic linker.
1312     *
1313     * The "path" member can't be initialized yet because string constants
1314     * cannot yet be accessed. Below we will set it correctly.
1315     */
1316    memset(&objtmp, 0, sizeof(objtmp));
1317    objtmp.path = NULL;
1318    objtmp.rtld = true;
1319    objtmp.mapbase = mapbase;
1320#ifdef PIC
1321    objtmp.relocbase = mapbase;
1322#endif
1323    if (RTLD_IS_DYNAMIC()) {
1324	objtmp.dynamic = rtld_dynamic(&objtmp);
1325	digest_dynamic1(&objtmp, 1, &dyn_rpath, &dyn_soname);
1326	assert(objtmp.needed == NULL);
1327#if !defined(__mips__)
1328	/* MIPS and SH{3,5} have a bogus DT_TEXTREL. */
1329	assert(!objtmp.textrel);
1330#endif
1331
1332	/*
1333	 * Temporarily put the dynamic linker entry into the object list, so
1334	 * that symbols can be found.
1335	 */
1336
1337	relocate_objects(&objtmp, true, &objtmp);
1338    }
1339
1340    /* Initialize the object list. */
1341    obj_tail = &obj_list;
1342
1343    /* Now that non-local variables can be accesses, copy out obj_rtld. */
1344    memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld));
1345
1346    if (aux_info[AT_PAGESZ] != NULL)
1347	    pagesize = aux_info[AT_PAGESZ]->a_un.a_val;
1348    if (aux_info[AT_OSRELDATE] != NULL)
1349	    osreldate = aux_info[AT_OSRELDATE]->a_un.a_val;
1350
1351    digest_dynamic2(&obj_rtld, dyn_rpath, dyn_soname);
1352
1353    /* Replace the path with a dynamically allocated copy. */
1354    obj_rtld.path = xstrdup(PATH_RTLD);
1355
1356    r_debug.r_brk = r_debug_state;
1357    r_debug.r_state = RT_CONSISTENT;
1358}
1359
1360/*
1361 * Add the init functions from a needed object list (and its recursive
1362 * needed objects) to "list".  This is not used directly; it is a helper
1363 * function for initlist_add_objects().  The write lock must be held
1364 * when this function is called.
1365 */
1366static void
1367initlist_add_neededs(Needed_Entry *needed, Objlist *list)
1368{
1369    /* Recursively process the successor needed objects. */
1370    if (needed->next != NULL)
1371	initlist_add_neededs(needed->next, list);
1372
1373    /* Process the current needed object. */
1374    if (needed->obj != NULL)
1375	initlist_add_objects(needed->obj, &needed->obj->next, list);
1376}
1377
1378/*
1379 * Scan all of the DAGs rooted in the range of objects from "obj" to
1380 * "tail" and add their init functions to "list".  This recurses over
1381 * the DAGs and ensure the proper init ordering such that each object's
1382 * needed libraries are initialized before the object itself.  At the
1383 * same time, this function adds the objects to the global finalization
1384 * list "list_fini" in the opposite order.  The write lock must be
1385 * held when this function is called.
1386 */
1387static void
1388initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
1389{
1390    if (obj->init_scanned || obj->init_done)
1391	return;
1392    obj->init_scanned = true;
1393
1394    /* Recursively process the successor objects. */
1395    if (&obj->next != tail)
1396	initlist_add_objects(obj->next, tail, list);
1397
1398    /* Recursively process the needed objects. */
1399    if (obj->needed != NULL)
1400	initlist_add_neededs(obj->needed, list);
1401
1402    /* Add the object to the init list. */
1403    if (obj->init != (Elf_Addr)NULL)
1404	objlist_push_tail(list, obj);
1405
1406    /* Add the object to the global fini list in the reverse order. */
1407    if (obj->fini != (Elf_Addr)NULL && !obj->on_fini_list) {
1408	objlist_push_head(&list_fini, obj);
1409	obj->on_fini_list = true;
1410    }
1411}
1412
1413#ifndef FPTR_TARGET
1414#define FPTR_TARGET(f)	((Elf_Addr) (f))
1415#endif
1416
1417/*
1418 * Given a shared object, traverse its list of needed objects, and load
1419 * each of them.  Returns 0 on success.  Generates an error message and
1420 * returns -1 on failure.
1421 */
1422static int
1423load_needed_objects(Obj_Entry *first, int flags)
1424{
1425    Obj_Entry *obj, *obj1;
1426
1427    for (obj = first;  obj != NULL;  obj = obj->next) {
1428	Needed_Entry *needed;
1429
1430	for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
1431	    obj1 = needed->obj = load_object(obj->strtab + needed->name, obj,
1432		flags & ~RTLD_LO_NOLOAD);
1433	    if (obj1 == NULL && !ld_tracing)
1434		return -1;
1435	    if (obj1 != NULL && obj1->z_nodelete && !obj1->ref_nodel) {
1436		dbg("obj %s nodelete", obj1->path);
1437		init_dag(obj1);
1438		ref_dag(obj1);
1439		obj1->ref_nodel = true;
1440	    }
1441	}
1442    }
1443
1444    return 0;
1445}
1446
1447static int
1448load_preload_objects(void)
1449{
1450    char *p = ld_preload;
1451    static const char delim[] = " \t:;";
1452
1453    if (p == NULL)
1454	return 0;
1455
1456    p += strspn(p, delim);
1457    while (*p != '\0') {
1458	size_t len = strcspn(p, delim);
1459	char savech;
1460
1461	savech = p[len];
1462	p[len] = '\0';
1463	if (load_object(p, NULL, 0) == NULL)
1464	    return -1;	/* XXX - cleanup */
1465	p[len] = savech;
1466	p += len;
1467	p += strspn(p, delim);
1468    }
1469    LD_UTRACE(UTRACE_PRELOAD_FINISHED, NULL, NULL, 0, 0, NULL);
1470    return 0;
1471}
1472
1473/*
1474 * Load a shared object into memory, if it is not already loaded.
1475 *
1476 * Returns a pointer to the Obj_Entry for the object.  Returns NULL
1477 * on failure.
1478 */
1479static Obj_Entry *
1480load_object(const char *name, const Obj_Entry *refobj, int flags)
1481{
1482    Obj_Entry *obj;
1483    int fd = -1;
1484    struct stat sb;
1485    char *path;
1486
1487    for (obj = obj_list->next;  obj != NULL;  obj = obj->next)
1488	if (object_match_name(obj, name))
1489	    return obj;
1490
1491    path = find_library(name, refobj);
1492    if (path == NULL)
1493	return NULL;
1494
1495    /*
1496     * If we didn't find a match by pathname, open the file and check
1497     * again by device and inode.  This avoids false mismatches caused
1498     * by multiple links or ".." in pathnames.
1499     *
1500     * To avoid a race, we open the file and use fstat() rather than
1501     * using stat().
1502     */
1503    if ((fd = open(path, O_RDONLY)) == -1) {
1504	_rtld_error("Cannot open \"%s\"", path);
1505	free(path);
1506	return NULL;
1507    }
1508    if (fstat(fd, &sb) == -1) {
1509	_rtld_error("Cannot fstat \"%s\"", path);
1510	close(fd);
1511	free(path);
1512	return NULL;
1513    }
1514    for (obj = obj_list->next;  obj != NULL;  obj = obj->next) {
1515	if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) {
1516	    close(fd);
1517	    break;
1518	}
1519    }
1520    if (obj != NULL) {
1521	object_add_name(obj, name);
1522	free(path);
1523	close(fd);
1524	return obj;
1525    }
1526    if (flags & RTLD_LO_NOLOAD) {
1527	free(path);
1528	return (NULL);
1529    }
1530
1531    /* First use of this object, so we must map it in */
1532    obj = do_load_object(fd, name, path, &sb, flags);
1533    if (obj == NULL)
1534	free(path);
1535    close(fd);
1536
1537    return obj;
1538}
1539
1540static Obj_Entry *
1541do_load_object(int fd, const char *name, char *path, struct stat *sbp,
1542  int flags)
1543{
1544    Obj_Entry *obj;
1545    struct statfs fs;
1546
1547    /*
1548     * but first, make sure that environment variables haven't been
1549     * used to circumvent the noexec flag on a filesystem.
1550     */
1551    if (dangerous_ld_env) {
1552	if (fstatfs(fd, &fs) != 0) {
1553	    _rtld_error("Cannot fstatfs \"%s\"", path);
1554		return NULL;
1555	}
1556	if (fs.f_flags & MNT_NOEXEC) {
1557	    _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname);
1558	    return NULL;
1559	}
1560    }
1561    dbg("loading \"%s\"", path);
1562    obj = map_object(fd, path, sbp);
1563    if (obj == NULL)
1564        return NULL;
1565
1566    object_add_name(obj, name);
1567    obj->path = path;
1568    digest_dynamic(obj, 0);
1569    if (obj->z_noopen && (flags & (RTLD_LO_DLOPEN | RTLD_LO_TRACE)) ==
1570      RTLD_LO_DLOPEN) {
1571	dbg("refusing to load non-loadable \"%s\"", obj->path);
1572	_rtld_error("Cannot dlopen non-loadable %s", obj->path);
1573	munmap(obj->mapbase, obj->mapsize);
1574	obj_free(obj);
1575	return (NULL);
1576    }
1577
1578    *obj_tail = obj;
1579    obj_tail = &obj->next;
1580    obj_count++;
1581    obj_loads++;
1582    linkmap_add(obj);	/* for GDB & dlinfo() */
1583
1584    dbg("  %p .. %p: %s", obj->mapbase,
1585         obj->mapbase + obj->mapsize - 1, obj->path);
1586    if (obj->textrel)
1587	dbg("  WARNING: %s has impure text", obj->path);
1588    LD_UTRACE(UTRACE_LOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
1589	obj->path);
1590
1591    return obj;
1592}
1593
1594static Obj_Entry *
1595obj_from_addr(const void *addr)
1596{
1597    Obj_Entry *obj;
1598
1599    for (obj = obj_list;  obj != NULL;  obj = obj->next) {
1600	if (addr < (void *) obj->mapbase)
1601	    continue;
1602	if (addr < (void *) (obj->mapbase + obj->mapsize))
1603	    return obj;
1604    }
1605    return NULL;
1606}
1607
1608/*
1609 * Call the finalization functions for each of the objects in "list"
1610 * which are unreferenced.  All of the objects are expected to have
1611 * non-NULL fini functions.
1612 */
1613static void
1614objlist_call_fini(Objlist *list, bool force, int *lockstate)
1615{
1616    Objlist_Entry *elm, *elm_tmp;
1617    char *saved_msg;
1618
1619    /*
1620     * Preserve the current error message since a fini function might
1621     * call into the dynamic linker and overwrite it.
1622     */
1623    saved_msg = errmsg_save();
1624    STAILQ_FOREACH_SAFE(elm, list, link, elm_tmp) {
1625	if (elm->obj->refcount == 0 || force) {
1626	    dbg("calling fini function for %s at %p", elm->obj->path,
1627	        (void *)elm->obj->fini);
1628	    LD_UTRACE(UTRACE_FINI_CALL, elm->obj, (void *)elm->obj->fini, 0, 0,
1629		elm->obj->path);
1630	    /* Remove object from fini list to prevent recursive invocation. */
1631	    STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1632	    wlock_release(rtld_bind_lock, *lockstate);
1633	    call_initfini_pointer(elm->obj, elm->obj->fini);
1634	    *lockstate = wlock_acquire(rtld_bind_lock);
1635	    /* No need to free anything if process is going down. */
1636	    if (!force)
1637	    	free(elm);
1638	}
1639    }
1640    errmsg_restore(saved_msg);
1641}
1642
1643/*
1644 * Call the initialization functions for each of the objects in
1645 * "list".  All of the objects are expected to have non-NULL init
1646 * functions.
1647 */
1648static void
1649objlist_call_init(Objlist *list, int *lockstate)
1650{
1651    Objlist_Entry *elm;
1652    Obj_Entry *obj;
1653    char *saved_msg;
1654
1655    /*
1656     * Clean init_scanned flag so that objects can be rechecked and
1657     * possibly initialized earlier if any of vectors called below
1658     * cause the change by using dlopen.
1659     */
1660    for (obj = obj_list;  obj != NULL;  obj = obj->next)
1661	obj->init_scanned = false;
1662
1663    /*
1664     * Preserve the current error message since an init function might
1665     * call into the dynamic linker and overwrite it.
1666     */
1667    saved_msg = errmsg_save();
1668    STAILQ_FOREACH(elm, list, link) {
1669	if (elm->obj->init_done) /* Initialized early. */
1670	    continue;
1671	dbg("calling init function for %s at %p", elm->obj->path,
1672	    (void *)elm->obj->init);
1673	LD_UTRACE(UTRACE_INIT_CALL, elm->obj, (void *)elm->obj->init, 0, 0,
1674	    elm->obj->path);
1675	/*
1676	 * Race: other thread might try to use this object before current
1677	 * one completes the initilization. Not much can be done here
1678	 * without better locking.
1679	 */
1680	elm->obj->init_done = true;
1681    	wlock_release(rtld_bind_lock, *lockstate);
1682	call_initfini_pointer(elm->obj, elm->obj->init);
1683	*lockstate = wlock_acquire(rtld_bind_lock);
1684    }
1685    errmsg_restore(saved_msg);
1686}
1687
1688static void
1689objlist_clear(Objlist *list)
1690{
1691    Objlist_Entry *elm;
1692
1693    while (!STAILQ_EMPTY(list)) {
1694	elm = STAILQ_FIRST(list);
1695	STAILQ_REMOVE_HEAD(list, link);
1696	free(elm);
1697    }
1698}
1699
1700static Objlist_Entry *
1701objlist_find(Objlist *list, const Obj_Entry *obj)
1702{
1703    Objlist_Entry *elm;
1704
1705    STAILQ_FOREACH(elm, list, link)
1706	if (elm->obj == obj)
1707	    return elm;
1708    return NULL;
1709}
1710
1711static void
1712objlist_init(Objlist *list)
1713{
1714    STAILQ_INIT(list);
1715}
1716
1717static void
1718objlist_push_head(Objlist *list, Obj_Entry *obj)
1719{
1720    Objlist_Entry *elm;
1721
1722    elm = NEW(Objlist_Entry);
1723    elm->obj = obj;
1724    STAILQ_INSERT_HEAD(list, elm, link);
1725}
1726
1727static void
1728objlist_push_tail(Objlist *list, Obj_Entry *obj)
1729{
1730    Objlist_Entry *elm;
1731
1732    elm = NEW(Objlist_Entry);
1733    elm->obj = obj;
1734    STAILQ_INSERT_TAIL(list, elm, link);
1735}
1736
1737static void
1738objlist_remove(Objlist *list, Obj_Entry *obj)
1739{
1740    Objlist_Entry *elm;
1741
1742    if ((elm = objlist_find(list, obj)) != NULL) {
1743	STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
1744	free(elm);
1745    }
1746}
1747
1748/*
1749 * Relocate newly-loaded shared objects.  The argument is a pointer to
1750 * the Obj_Entry for the first such object.  All objects from the first
1751 * to the end of the list of objects are relocated.  Returns 0 on success,
1752 * or -1 on failure.
1753 */
1754static int
1755relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj)
1756{
1757    Obj_Entry *obj;
1758
1759    for (obj = first;  obj != NULL;  obj = obj->next) {
1760	if (obj != rtldobj)
1761	    dbg("relocating \"%s\"", obj->path);
1762	if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL ||
1763	    obj->symtab == NULL || obj->strtab == NULL) {
1764	    _rtld_error("%s: Shared object has no run-time symbol table",
1765	      obj->path);
1766	    return -1;
1767	}
1768
1769	if (obj->textrel) {
1770	    /* There are relocations to the write-protected text segment. */
1771	    if (mprotect(obj->mapbase, obj->textsize,
1772	      PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1773		_rtld_error("%s: Cannot write-enable text segment: %s",
1774		  obj->path, strerror(errno));
1775		return -1;
1776	    }
1777	}
1778
1779	/* Process the non-PLT relocations. */
1780	if (reloc_non_plt(obj, rtldobj))
1781		return -1;
1782
1783	if (obj->textrel) {	/* Re-protected the text segment. */
1784	    if (mprotect(obj->mapbase, obj->textsize,
1785	      PROT_READ|PROT_EXEC) == -1) {
1786		_rtld_error("%s: Cannot write-protect text segment: %s",
1787		  obj->path, strerror(errno));
1788		return -1;
1789	    }
1790	}
1791
1792	/* Process the PLT relocations. */
1793	if (reloc_plt(obj) == -1)
1794	    return -1;
1795	/* Relocate the jump slots if we are doing immediate binding. */
1796	if (obj->bind_now || bind_now)
1797	    if (reloc_jmpslots(obj) == -1)
1798		return -1;
1799
1800
1801	/*
1802	 * Set up the magic number and version in the Obj_Entry.  These
1803	 * were checked in the crt1.o from the original ElfKit, so we
1804	 * set them for backward compatibility.
1805	 */
1806	obj->magic = RTLD_MAGIC;
1807	obj->version = RTLD_VERSION;
1808
1809	/* Set the special PLT or GOT entries. */
1810	init_pltgot(obj);
1811    }
1812
1813    return 0;
1814}
1815
1816/*
1817 * Cleanup procedure.  It will be called (by the atexit mechanism) just
1818 * before the process exits.
1819 */
1820static void
1821rtld_exit(void)
1822{
1823    int	lockstate;
1824
1825    lockstate = wlock_acquire(rtld_bind_lock);
1826    dbg("rtld_exit()");
1827    objlist_call_fini(&list_fini, true, &lockstate);
1828    /* No need to remove the items from the list, since we are exiting. */
1829    if (!libmap_disable)
1830        lm_fini();
1831    wlock_release(rtld_bind_lock, lockstate);
1832}
1833
1834static void *
1835path_enumerate(const char *path, path_enum_proc callback, void *arg)
1836{
1837#ifdef COMPAT_32BIT
1838    const char *trans;
1839#endif
1840    if (path == NULL)
1841	return (NULL);
1842
1843    path += strspn(path, ":;");
1844    while (*path != '\0') {
1845	size_t len;
1846	char  *res;
1847
1848	len = strcspn(path, ":;");
1849#ifdef COMPAT_32BIT
1850	trans = lm_findn(NULL, path, len);
1851	if (trans)
1852	    res = callback(trans, strlen(trans), arg);
1853	else
1854#endif
1855	res = callback(path, len, arg);
1856
1857	if (res != NULL)
1858	    return (res);
1859
1860	path += len;
1861	path += strspn(path, ":;");
1862    }
1863
1864    return (NULL);
1865}
1866
1867struct try_library_args {
1868    const char	*name;
1869    size_t	 namelen;
1870    char	*buffer;
1871    size_t	 buflen;
1872};
1873
1874static void *
1875try_library_path(const char *dir, size_t dirlen, void *param)
1876{
1877    struct try_library_args *arg;
1878
1879    arg = param;
1880    if (*dir == '/' || trust) {
1881	char *pathname;
1882
1883	if (dirlen + 1 + arg->namelen + 1 > arg->buflen)
1884		return (NULL);
1885
1886	pathname = arg->buffer;
1887	strncpy(pathname, dir, dirlen);
1888	pathname[dirlen] = '/';
1889	strcpy(pathname + dirlen + 1, arg->name);
1890
1891	dbg("  Trying \"%s\"", pathname);
1892	if (access(pathname, F_OK) == 0) {		/* We found it */
1893	    pathname = xmalloc(dirlen + 1 + arg->namelen + 1);
1894	    strcpy(pathname, arg->buffer);
1895	    return (pathname);
1896	}
1897    }
1898    return (NULL);
1899}
1900
1901static char *
1902search_library_path(const char *name, const char *path)
1903{
1904    char *p;
1905    struct try_library_args arg;
1906
1907    if (path == NULL)
1908	return NULL;
1909
1910    arg.name = name;
1911    arg.namelen = strlen(name);
1912    arg.buffer = xmalloc(PATH_MAX);
1913    arg.buflen = PATH_MAX;
1914
1915    p = path_enumerate(path, try_library_path, &arg);
1916
1917    free(arg.buffer);
1918
1919    return (p);
1920}
1921
1922int
1923dlclose(void *handle)
1924{
1925    Obj_Entry *root;
1926    int lockstate;
1927
1928    lockstate = wlock_acquire(rtld_bind_lock);
1929    root = dlcheck(handle);
1930    if (root == NULL) {
1931	wlock_release(rtld_bind_lock, lockstate);
1932	return -1;
1933    }
1934    LD_UTRACE(UTRACE_DLCLOSE_START, handle, NULL, 0, root->dl_refcount,
1935	root->path);
1936
1937    /* Unreference the object and its dependencies. */
1938    root->dl_refcount--;
1939
1940    unref_dag(root);
1941
1942    if (root->refcount == 0) {
1943	/*
1944	 * The object is no longer referenced, so we must unload it.
1945	 * First, call the fini functions.
1946	 */
1947	objlist_call_fini(&list_fini, false, &lockstate);
1948
1949	/* Finish cleaning up the newly-unreferenced objects. */
1950	GDB_STATE(RT_DELETE,&root->linkmap);
1951	unload_object(root);
1952	GDB_STATE(RT_CONSISTENT,NULL);
1953    }
1954    LD_UTRACE(UTRACE_DLCLOSE_STOP, handle, NULL, 0, 0, NULL);
1955    wlock_release(rtld_bind_lock, lockstate);
1956    return 0;
1957}
1958
1959char *
1960dlerror(void)
1961{
1962    char *msg = error_message;
1963    error_message = NULL;
1964    return msg;
1965}
1966
1967/*
1968 * This function is deprecated and has no effect.
1969 */
1970void
1971dllockinit(void *context,
1972	   void *(*lock_create)(void *context),
1973           void (*rlock_acquire)(void *lock),
1974           void (*wlock_acquire)(void *lock),
1975           void (*lock_release)(void *lock),
1976           void (*lock_destroy)(void *lock),
1977	   void (*context_destroy)(void *context))
1978{
1979    static void *cur_context;
1980    static void (*cur_context_destroy)(void *);
1981
1982    /* Just destroy the context from the previous call, if necessary. */
1983    if (cur_context_destroy != NULL)
1984	cur_context_destroy(cur_context);
1985    cur_context = context;
1986    cur_context_destroy = context_destroy;
1987}
1988
1989void *
1990dlopen(const char *name, int mode)
1991{
1992    Obj_Entry **old_obj_tail;
1993    Obj_Entry *obj;
1994    Objlist initlist;
1995    int result, lockstate, nodelete, lo_flags;
1996
1997    LD_UTRACE(UTRACE_DLOPEN_START, NULL, NULL, 0, mode, name);
1998    ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1";
1999    if (ld_tracing != NULL)
2000	environ = (char **)*get_program_var_addr("environ");
2001    nodelete = mode & RTLD_NODELETE;
2002    lo_flags = RTLD_LO_DLOPEN;
2003    if (mode & RTLD_NOLOAD)
2004	    lo_flags |= RTLD_LO_NOLOAD;
2005    if (ld_tracing != NULL)
2006	    lo_flags |= RTLD_LO_TRACE;
2007
2008    objlist_init(&initlist);
2009
2010    lockstate = wlock_acquire(rtld_bind_lock);
2011    GDB_STATE(RT_ADD,NULL);
2012
2013    old_obj_tail = obj_tail;
2014    obj = NULL;
2015    if (name == NULL) {
2016	obj = obj_main;
2017	obj->refcount++;
2018    } else {
2019	obj = load_object(name, obj_main, lo_flags);
2020    }
2021
2022    if (obj) {
2023	obj->dl_refcount++;
2024	if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL)
2025	    objlist_push_tail(&list_global, obj);
2026	mode &= RTLD_MODEMASK;
2027	if (*old_obj_tail != NULL) {		/* We loaded something new. */
2028	    assert(*old_obj_tail == obj);
2029	    result = load_needed_objects(obj, RTLD_LO_DLOPEN);
2030	    init_dag(obj);
2031	    if (result != -1)
2032		result = rtld_verify_versions(&obj->dagmembers);
2033	    if (result != -1 && ld_tracing)
2034		goto trace;
2035	    if (result == -1 ||
2036	      (relocate_objects(obj, mode == RTLD_NOW, &obj_rtld)) == -1) {
2037		obj->dl_refcount--;
2038		unref_dag(obj);
2039		if (obj->refcount == 0)
2040		    unload_object(obj);
2041		obj = NULL;
2042	    } else {
2043		/* Make list of init functions to call. */
2044		initlist_add_objects(obj, &obj->next, &initlist);
2045	    }
2046	} else {
2047
2048	    /* Bump the reference counts for objects on this DAG. */
2049	    ref_dag(obj);
2050
2051	    if (ld_tracing)
2052		goto trace;
2053	}
2054	if (obj != NULL && (nodelete || obj->z_nodelete) && !obj->ref_nodel) {
2055	    dbg("obj %s nodelete", obj->path);
2056	    ref_dag(obj);
2057	    obj->z_nodelete = obj->ref_nodel = true;
2058	}
2059    }
2060
2061    LD_UTRACE(UTRACE_DLOPEN_STOP, obj, NULL, 0, obj ? obj->dl_refcount : 0,
2062	name);
2063    GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
2064
2065    /* Call the init functions. */
2066    objlist_call_init(&initlist, &lockstate);
2067    objlist_clear(&initlist);
2068    wlock_release(rtld_bind_lock, lockstate);
2069    return obj;
2070trace:
2071    trace_loaded_objects(obj);
2072    wlock_release(rtld_bind_lock, lockstate);
2073    exit(0);
2074}
2075
2076static void *
2077do_dlsym(void *handle, const char *name, void *retaddr, const Ver_Entry *ve,
2078    int flags)
2079{
2080    DoneList donelist;
2081    const Obj_Entry *obj, *defobj;
2082    const Elf_Sym *def, *symp;
2083    unsigned long hash;
2084    int lockstate;
2085
2086    hash = elf_hash(name);
2087    def = NULL;
2088    defobj = NULL;
2089    flags |= SYMLOOK_IN_PLT;
2090
2091    lockstate = rlock_acquire(rtld_bind_lock);
2092    if (handle == NULL || handle == RTLD_NEXT ||
2093	handle == RTLD_DEFAULT || handle == RTLD_SELF) {
2094
2095	if ((obj = obj_from_addr(retaddr)) == NULL) {
2096	    _rtld_error("Cannot determine caller's shared object");
2097	    rlock_release(rtld_bind_lock, lockstate);
2098	    return NULL;
2099	}
2100	if (handle == NULL) {	/* Just the caller's shared object. */
2101	    def = symlook_obj(name, hash, obj, ve, flags);
2102	    defobj = obj;
2103	} else if (handle == RTLD_NEXT || /* Objects after caller's */
2104		   handle == RTLD_SELF) { /* ... caller included */
2105	    if (handle == RTLD_NEXT)
2106		obj = obj->next;
2107	    for (; obj != NULL; obj = obj->next) {
2108	    	if ((symp = symlook_obj(name, hash, obj, ve, flags)) != NULL) {
2109		    if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2110			def = symp;
2111			defobj = obj;
2112			if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2113			    break;
2114		    }
2115		}
2116	    }
2117	    /*
2118	     * Search the dynamic linker itself, and possibly resolve the
2119	     * symbol from there.  This is how the application links to
2120	     * dynamic linker services such as dlopen.
2121	     */
2122	    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2123		symp = symlook_obj(name, hash, &obj_rtld, ve, flags);
2124		if (symp != NULL) {
2125		    def = symp;
2126		    defobj = &obj_rtld;
2127		}
2128	    }
2129	} else {
2130	    assert(handle == RTLD_DEFAULT);
2131	    def = symlook_default(name, hash, obj, &defobj, ve, flags);
2132	}
2133    } else {
2134	if ((obj = dlcheck(handle)) == NULL) {
2135	    rlock_release(rtld_bind_lock, lockstate);
2136	    return NULL;
2137	}
2138
2139	donelist_init(&donelist);
2140	if (obj->mainprog) {
2141	    /* Search main program and all libraries loaded by it. */
2142	    def = symlook_list(name, hash, &list_main, &defobj, ve, flags,
2143			       &donelist);
2144
2145	    /*
2146	     * We do not distinguish between 'main' object and global scope.
2147	     * If symbol is not defined by objects loaded at startup, continue
2148	     * search among dynamically loaded objects with RTLD_GLOBAL
2149	     * scope.
2150	     */
2151	    if (def == NULL)
2152		def = symlook_list(name, hash, &list_global, &defobj, ve,
2153		    		    flags, &donelist);
2154	} else {
2155	    Needed_Entry fake;
2156
2157	    /* Search the whole DAG rooted at the given object. */
2158	    fake.next = NULL;
2159	    fake.obj = (Obj_Entry *)obj;
2160	    fake.name = 0;
2161	    def = symlook_needed(name, hash, &fake, &defobj, ve, flags,
2162				 &donelist);
2163	}
2164    }
2165
2166    if (def != NULL) {
2167	rlock_release(rtld_bind_lock, lockstate);
2168
2169	/*
2170	 * The value required by the caller is derived from the value
2171	 * of the symbol. For the ia64 architecture, we need to
2172	 * construct a function descriptor which the caller can use to
2173	 * call the function with the right 'gp' value. For other
2174	 * architectures and for non-functions, the value is simply
2175	 * the relocated value of the symbol.
2176	 */
2177	if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
2178	    return make_function_pointer(def, defobj);
2179	else
2180	    return defobj->relocbase + def->st_value;
2181    }
2182
2183    _rtld_error("Undefined symbol \"%s\"", name);
2184    rlock_release(rtld_bind_lock, lockstate);
2185    return NULL;
2186}
2187
2188void *
2189dlsym(void *handle, const char *name)
2190{
2191	return do_dlsym(handle, name, __builtin_return_address(0), NULL,
2192	    SYMLOOK_DLSYM);
2193}
2194
2195dlfunc_t
2196dlfunc(void *handle, const char *name)
2197{
2198	union {
2199		void *d;
2200		dlfunc_t f;
2201	} rv;
2202
2203	rv.d = do_dlsym(handle, name, __builtin_return_address(0), NULL,
2204	    SYMLOOK_DLSYM);
2205	return (rv.f);
2206}
2207
2208void *
2209dlvsym(void *handle, const char *name, const char *version)
2210{
2211	Ver_Entry ventry;
2212
2213	ventry.name = version;
2214	ventry.file = NULL;
2215	ventry.hash = elf_hash(version);
2216	ventry.flags= 0;
2217	return do_dlsym(handle, name, __builtin_return_address(0), &ventry,
2218	    SYMLOOK_DLSYM);
2219}
2220
2221int
2222_rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info)
2223{
2224    const Obj_Entry *obj;
2225    int lockstate;
2226
2227    lockstate = rlock_acquire(rtld_bind_lock);
2228    obj = obj_from_addr(addr);
2229    if (obj == NULL) {
2230        _rtld_error("No shared object contains address");
2231	rlock_release(rtld_bind_lock, lockstate);
2232        return (0);
2233    }
2234    rtld_fill_dl_phdr_info(obj, phdr_info);
2235    rlock_release(rtld_bind_lock, lockstate);
2236    return (1);
2237}
2238
2239int
2240dladdr(const void *addr, Dl_info *info)
2241{
2242    const Obj_Entry *obj;
2243    const Elf_Sym *def;
2244    void *symbol_addr;
2245    unsigned long symoffset;
2246    int lockstate;
2247
2248    lockstate = rlock_acquire(rtld_bind_lock);
2249    obj = obj_from_addr(addr);
2250    if (obj == NULL) {
2251        _rtld_error("No shared object contains address");
2252	rlock_release(rtld_bind_lock, lockstate);
2253        return 0;
2254    }
2255    info->dli_fname = obj->path;
2256    info->dli_fbase = obj->mapbase;
2257    info->dli_saddr = (void *)0;
2258    info->dli_sname = NULL;
2259
2260    /*
2261     * Walk the symbol list looking for the symbol whose address is
2262     * closest to the address sent in.
2263     */
2264    for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
2265        def = obj->symtab + symoffset;
2266
2267        /*
2268         * For skip the symbol if st_shndx is either SHN_UNDEF or
2269         * SHN_COMMON.
2270         */
2271        if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
2272            continue;
2273
2274        /*
2275         * If the symbol is greater than the specified address, or if it
2276         * is further away from addr than the current nearest symbol,
2277         * then reject it.
2278         */
2279        symbol_addr = obj->relocbase + def->st_value;
2280        if (symbol_addr > addr || symbol_addr < info->dli_saddr)
2281            continue;
2282
2283        /* Update our idea of the nearest symbol. */
2284        info->dli_sname = obj->strtab + def->st_name;
2285        info->dli_saddr = symbol_addr;
2286
2287        /* Exact match? */
2288        if (info->dli_saddr == addr)
2289            break;
2290    }
2291    rlock_release(rtld_bind_lock, lockstate);
2292    return 1;
2293}
2294
2295int
2296dlinfo(void *handle, int request, void *p)
2297{
2298    const Obj_Entry *obj;
2299    int error, lockstate;
2300
2301    lockstate = rlock_acquire(rtld_bind_lock);
2302
2303    if (handle == NULL || handle == RTLD_SELF) {
2304	void *retaddr;
2305
2306	retaddr = __builtin_return_address(0);	/* __GNUC__ only */
2307	if ((obj = obj_from_addr(retaddr)) == NULL)
2308	    _rtld_error("Cannot determine caller's shared object");
2309    } else
2310	obj = dlcheck(handle);
2311
2312    if (obj == NULL) {
2313	rlock_release(rtld_bind_lock, lockstate);
2314	return (-1);
2315    }
2316
2317    error = 0;
2318    switch (request) {
2319    case RTLD_DI_LINKMAP:
2320	*((struct link_map const **)p) = &obj->linkmap;
2321	break;
2322    case RTLD_DI_ORIGIN:
2323	error = rtld_dirname(obj->path, p);
2324	break;
2325
2326    case RTLD_DI_SERINFOSIZE:
2327    case RTLD_DI_SERINFO:
2328	error = do_search_info(obj, request, (struct dl_serinfo *)p);
2329	break;
2330
2331    default:
2332	_rtld_error("Invalid request %d passed to dlinfo()", request);
2333	error = -1;
2334    }
2335
2336    rlock_release(rtld_bind_lock, lockstate);
2337
2338    return (error);
2339}
2340
2341static void
2342rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
2343{
2344
2345	phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
2346	phdr_info->dlpi_name = STAILQ_FIRST(&obj->names) ?
2347	    STAILQ_FIRST(&obj->names)->name : obj->path;
2348	phdr_info->dlpi_phdr = obj->phdr;
2349	phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
2350	phdr_info->dlpi_tls_modid = obj->tlsindex;
2351	phdr_info->dlpi_tls_data = obj->tlsinit;
2352	phdr_info->dlpi_adds = obj_loads;
2353	phdr_info->dlpi_subs = obj_loads - obj_count;
2354}
2355
2356int
2357dl_iterate_phdr(__dl_iterate_hdr_callback callback, void *param)
2358{
2359    struct dl_phdr_info phdr_info;
2360    const Obj_Entry *obj;
2361    int error, bind_lockstate, phdr_lockstate;
2362
2363    phdr_lockstate = wlock_acquire(rtld_phdr_lock);
2364    bind_lockstate = rlock_acquire(rtld_bind_lock);
2365
2366    error = 0;
2367
2368    for (obj = obj_list;  obj != NULL;  obj = obj->next) {
2369	rtld_fill_dl_phdr_info(obj, &phdr_info);
2370	if ((error = callback(&phdr_info, sizeof phdr_info, param)) != 0)
2371		break;
2372
2373    }
2374    rlock_release(rtld_bind_lock, bind_lockstate);
2375    wlock_release(rtld_phdr_lock, phdr_lockstate);
2376
2377    return (error);
2378}
2379
2380struct fill_search_info_args {
2381    int		 request;
2382    unsigned int flags;
2383    Dl_serinfo  *serinfo;
2384    Dl_serpath  *serpath;
2385    char	*strspace;
2386};
2387
2388static void *
2389fill_search_info(const char *dir, size_t dirlen, void *param)
2390{
2391    struct fill_search_info_args *arg;
2392
2393    arg = param;
2394
2395    if (arg->request == RTLD_DI_SERINFOSIZE) {
2396	arg->serinfo->dls_cnt ++;
2397	arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1;
2398    } else {
2399	struct dl_serpath *s_entry;
2400
2401	s_entry = arg->serpath;
2402	s_entry->dls_name  = arg->strspace;
2403	s_entry->dls_flags = arg->flags;
2404
2405	strncpy(arg->strspace, dir, dirlen);
2406	arg->strspace[dirlen] = '\0';
2407
2408	arg->strspace += dirlen + 1;
2409	arg->serpath++;
2410    }
2411
2412    return (NULL);
2413}
2414
2415static int
2416do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info)
2417{
2418    struct dl_serinfo _info;
2419    struct fill_search_info_args args;
2420
2421    args.request = RTLD_DI_SERINFOSIZE;
2422    args.serinfo = &_info;
2423
2424    _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath);
2425    _info.dls_cnt  = 0;
2426
2427    path_enumerate(ld_library_path, fill_search_info, &args);
2428    path_enumerate(obj->rpath, fill_search_info, &args);
2429    path_enumerate(gethints(), fill_search_info, &args);
2430    path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args);
2431
2432
2433    if (request == RTLD_DI_SERINFOSIZE) {
2434	info->dls_size = _info.dls_size;
2435	info->dls_cnt = _info.dls_cnt;
2436	return (0);
2437    }
2438
2439    if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) {
2440	_rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()");
2441	return (-1);
2442    }
2443
2444    args.request  = RTLD_DI_SERINFO;
2445    args.serinfo  = info;
2446    args.serpath  = &info->dls_serpath[0];
2447    args.strspace = (char *)&info->dls_serpath[_info.dls_cnt];
2448
2449    args.flags = LA_SER_LIBPATH;
2450    if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL)
2451	return (-1);
2452
2453    args.flags = LA_SER_RUNPATH;
2454    if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL)
2455	return (-1);
2456
2457    args.flags = LA_SER_CONFIG;
2458    if (path_enumerate(gethints(), fill_search_info, &args) != NULL)
2459	return (-1);
2460
2461    args.flags = LA_SER_DEFAULT;
2462    if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL)
2463	return (-1);
2464    return (0);
2465}
2466
2467static int
2468rtld_dirname(const char *path, char *bname)
2469{
2470    const char *endp;
2471
2472    /* Empty or NULL string gets treated as "." */
2473    if (path == NULL || *path == '\0') {
2474	bname[0] = '.';
2475	bname[1] = '\0';
2476	return (0);
2477    }
2478
2479    /* Strip trailing slashes */
2480    endp = path + strlen(path) - 1;
2481    while (endp > path && *endp == '/')
2482	endp--;
2483
2484    /* Find the start of the dir */
2485    while (endp > path && *endp != '/')
2486	endp--;
2487
2488    /* Either the dir is "/" or there are no slashes */
2489    if (endp == path) {
2490	bname[0] = *endp == '/' ? '/' : '.';
2491	bname[1] = '\0';
2492	return (0);
2493    } else {
2494	do {
2495	    endp--;
2496	} while (endp > path && *endp == '/');
2497    }
2498
2499    if (endp - path + 2 > PATH_MAX)
2500    {
2501	_rtld_error("Filename is too long: %s", path);
2502	return(-1);
2503    }
2504
2505    strncpy(bname, path, endp - path + 1);
2506    bname[endp - path + 1] = '\0';
2507    return (0);
2508}
2509
2510static int
2511rtld_dirname_abs(const char *path, char *base)
2512{
2513	char base_rel[PATH_MAX];
2514
2515	if (rtld_dirname(path, base) == -1)
2516		return (-1);
2517	if (base[0] == '/')
2518		return (0);
2519	if (getcwd(base_rel, sizeof(base_rel)) == NULL ||
2520	    strlcat(base_rel, "/", sizeof(base_rel)) >= sizeof(base_rel) ||
2521	    strlcat(base_rel, base, sizeof(base_rel)) >= sizeof(base_rel))
2522		return (-1);
2523	strcpy(base, base_rel);
2524	return (0);
2525}
2526
2527static void
2528linkmap_add(Obj_Entry *obj)
2529{
2530    struct link_map *l = &obj->linkmap;
2531    struct link_map *prev;
2532
2533    obj->linkmap.l_name = obj->path;
2534    obj->linkmap.l_addr = obj->mapbase;
2535    obj->linkmap.l_ld = obj->dynamic;
2536#ifdef __mips__
2537    /* GDB needs load offset on MIPS to use the symbols */
2538    obj->linkmap.l_offs = obj->relocbase;
2539#endif
2540
2541    if (r_debug.r_map == NULL) {
2542	r_debug.r_map = l;
2543	return;
2544    }
2545
2546    /*
2547     * Scan to the end of the list, but not past the entry for the
2548     * dynamic linker, which we want to keep at the very end.
2549     */
2550    for (prev = r_debug.r_map;
2551      prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap;
2552      prev = prev->l_next)
2553	;
2554
2555    /* Link in the new entry. */
2556    l->l_prev = prev;
2557    l->l_next = prev->l_next;
2558    if (l->l_next != NULL)
2559	l->l_next->l_prev = l;
2560    prev->l_next = l;
2561}
2562
2563static void
2564linkmap_delete(Obj_Entry *obj)
2565{
2566    struct link_map *l = &obj->linkmap;
2567
2568    if (l->l_prev == NULL) {
2569	if ((r_debug.r_map = l->l_next) != NULL)
2570	    l->l_next->l_prev = NULL;
2571	return;
2572    }
2573
2574    if ((l->l_prev->l_next = l->l_next) != NULL)
2575	l->l_next->l_prev = l->l_prev;
2576}
2577
2578/*
2579 * Function for the debugger to set a breakpoint on to gain control.
2580 *
2581 * The two parameters allow the debugger to easily find and determine
2582 * what the runtime loader is doing and to whom it is doing it.
2583 *
2584 * When the loadhook trap is hit (r_debug_state, set at program
2585 * initialization), the arguments can be found on the stack:
2586 *
2587 *  +8   struct link_map *m
2588 *  +4   struct r_debug  *rd
2589 *  +0   RetAddr
2590 */
2591void
2592r_debug_state(struct r_debug* rd, struct link_map *m)
2593{
2594}
2595
2596/*
2597 * Get address of the pointer variable in the main program.
2598 */
2599static const void **
2600get_program_var_addr(const char *name)
2601{
2602    const Obj_Entry *obj;
2603    unsigned long hash;
2604
2605    hash = elf_hash(name);
2606    for (obj = obj_main;  obj != NULL;  obj = obj->next) {
2607	const Elf_Sym *def;
2608
2609	if ((def = symlook_obj(name, hash, obj, NULL, 0)) != NULL) {
2610	    const void **addr;
2611
2612	    addr = (const void **)(obj->relocbase + def->st_value);
2613	    return addr;
2614	}
2615    }
2616    return NULL;
2617}
2618
2619/*
2620 * Set a pointer variable in the main program to the given value.  This
2621 * is used to set key variables such as "environ" before any of the
2622 * init functions are called.
2623 */
2624static void
2625set_program_var(const char *name, const void *value)
2626{
2627    const void **addr;
2628
2629    if ((addr = get_program_var_addr(name)) != NULL) {
2630	dbg("\"%s\": *%p <-- %p", name, addr, value);
2631	*addr = value;
2632    }
2633}
2634
2635/*
2636 * Given a symbol name in a referencing object, find the corresponding
2637 * definition of the symbol.  Returns a pointer to the symbol, or NULL if
2638 * no definition was found.  Returns a pointer to the Obj_Entry of the
2639 * defining object via the reference parameter DEFOBJ_OUT.
2640 */
2641static const Elf_Sym *
2642symlook_default(const char *name, unsigned long hash, const Obj_Entry *refobj,
2643    const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags)
2644{
2645    DoneList donelist;
2646    const Elf_Sym *def;
2647    const Elf_Sym *symp;
2648    const Obj_Entry *obj;
2649    const Obj_Entry *defobj;
2650    const Objlist_Entry *elm;
2651    def = NULL;
2652    defobj = NULL;
2653    donelist_init(&donelist);
2654
2655    /* Look first in the referencing object if linked symbolically. */
2656    if (refobj->symbolic && !donelist_check(&donelist, refobj)) {
2657	symp = symlook_obj(name, hash, refobj, ventry, flags);
2658	if (symp != NULL) {
2659	    def = symp;
2660	    defobj = refobj;
2661	}
2662    }
2663
2664    /* Search all objects loaded at program start up. */
2665    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2666	symp = symlook_list(name, hash, &list_main, &obj, ventry, flags,
2667	    &donelist);
2668	if (symp != NULL &&
2669	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2670	    def = symp;
2671	    defobj = obj;
2672	}
2673    }
2674
2675    /* Search all DAGs whose roots are RTLD_GLOBAL objects. */
2676    STAILQ_FOREACH(elm, &list_global, link) {
2677       if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2678           break;
2679       symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2680	   flags, &donelist);
2681	if (symp != NULL &&
2682	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2683	    def = symp;
2684	    defobj = obj;
2685	}
2686    }
2687
2688    /* Search all dlopened DAGs containing the referencing object. */
2689    STAILQ_FOREACH(elm, &refobj->dldags, link) {
2690	if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK)
2691	    break;
2692	symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, ventry,
2693	    flags, &donelist);
2694	if (symp != NULL &&
2695	  (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) {
2696	    def = symp;
2697	    defobj = obj;
2698	}
2699    }
2700
2701    /*
2702     * Search the dynamic linker itself, and possibly resolve the
2703     * symbol from there.  This is how the application links to
2704     * dynamic linker services such as dlopen.
2705     */
2706    if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) {
2707	symp = symlook_obj(name, hash, &obj_rtld, ventry, flags);
2708	if (symp != NULL) {
2709	    def = symp;
2710	    defobj = &obj_rtld;
2711	}
2712    }
2713
2714    if (def != NULL)
2715	*defobj_out = defobj;
2716    return def;
2717}
2718
2719static const Elf_Sym *
2720symlook_list(const char *name, unsigned long hash, const Objlist *objlist,
2721  const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2722  DoneList *dlp)
2723{
2724    const Elf_Sym *symp;
2725    const Elf_Sym *def;
2726    const Obj_Entry *defobj;
2727    const Objlist_Entry *elm;
2728
2729    def = NULL;
2730    defobj = NULL;
2731    STAILQ_FOREACH(elm, objlist, link) {
2732	if (donelist_check(dlp, elm->obj))
2733	    continue;
2734	if ((symp = symlook_obj(name, hash, elm->obj, ventry, flags)) != NULL) {
2735	    if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) {
2736		def = symp;
2737		defobj = elm->obj;
2738		if (ELF_ST_BIND(def->st_info) != STB_WEAK)
2739		    break;
2740	    }
2741	}
2742    }
2743    if (def != NULL)
2744	*defobj_out = defobj;
2745    return def;
2746}
2747
2748/*
2749 * Search the symbol table of a shared object and all objects needed
2750 * by it for a symbol of the given name.  Search order is
2751 * breadth-first.  Returns a pointer to the symbol, or NULL if no
2752 * definition was found.
2753 */
2754static const Elf_Sym *
2755symlook_needed(const char *name, unsigned long hash, const Needed_Entry *needed,
2756  const Obj_Entry **defobj_out, const Ver_Entry *ventry, int flags,
2757  DoneList *dlp)
2758{
2759    const Elf_Sym *def, *def_w;
2760    const Needed_Entry *n;
2761    const Obj_Entry *obj, *defobj, *defobj1;
2762
2763    def = def_w = NULL;
2764    defobj = NULL;
2765    for (n = needed; n != NULL; n = n->next) {
2766	if ((obj = n->obj) == NULL ||
2767	    donelist_check(dlp, obj) ||
2768	    (def = symlook_obj(name, hash, obj, ventry, flags)) == NULL)
2769	    continue;
2770	defobj = obj;
2771	if (ELF_ST_BIND(def->st_info) != STB_WEAK) {
2772	    *defobj_out = defobj;
2773	    return (def);
2774	}
2775    }
2776    /*
2777     * There we come when either symbol definition is not found in
2778     * directly needed objects, or found symbol is weak.
2779     */
2780    for (n = needed; n != NULL; n = n->next) {
2781	if ((obj = n->obj) == NULL)
2782	    continue;
2783	def_w = symlook_needed(name, hash, obj->needed, &defobj1,
2784			       ventry, flags, dlp);
2785	if (def_w == NULL)
2786	    continue;
2787	if (def == NULL || ELF_ST_BIND(def_w->st_info) != STB_WEAK) {
2788	    def = def_w;
2789	    defobj = defobj1;
2790	}
2791	if (ELF_ST_BIND(def_w->st_info) != STB_WEAK)
2792	    break;
2793    }
2794    if (def != NULL)
2795	*defobj_out = defobj;
2796    return (def);
2797}
2798
2799/*
2800 * Search the symbol table of a single shared object for a symbol of
2801 * the given name and version, if requested.  Returns a pointer to the
2802 * symbol, or NULL if no definition was found.
2803 *
2804 * The symbol's hash value is passed in for efficiency reasons; that
2805 * eliminates many recomputations of the hash value.
2806 */
2807const Elf_Sym *
2808symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj,
2809    const Ver_Entry *ventry, int flags)
2810{
2811    unsigned long symnum;
2812    const Elf_Sym *vsymp;
2813    Elf_Versym verndx;
2814    int vcount;
2815
2816    if (obj->buckets == NULL)
2817	return NULL;
2818
2819    vsymp = NULL;
2820    vcount = 0;
2821    symnum = obj->buckets[hash % obj->nbuckets];
2822
2823    for (; symnum != STN_UNDEF; symnum = obj->chains[symnum]) {
2824	const Elf_Sym *symp;
2825	const char *strp;
2826
2827	if (symnum >= obj->nchains)
2828		return NULL;	/* Bad object */
2829
2830	symp = obj->symtab + symnum;
2831	strp = obj->strtab + symp->st_name;
2832
2833	switch (ELF_ST_TYPE(symp->st_info)) {
2834	case STT_FUNC:
2835	case STT_NOTYPE:
2836	case STT_OBJECT:
2837	    if (symp->st_value == 0)
2838		continue;
2839		/* fallthrough */
2840	case STT_TLS:
2841	    if (symp->st_shndx != SHN_UNDEF)
2842		break;
2843#ifndef __mips__
2844	    else if (((flags & SYMLOOK_IN_PLT) == 0) &&
2845		 (ELF_ST_TYPE(symp->st_info) == STT_FUNC))
2846		break;
2847		/* fallthrough */
2848#endif
2849	default:
2850	    continue;
2851	}
2852	if (name[0] != strp[0] || strcmp(name, strp) != 0)
2853	    continue;
2854
2855	if (ventry == NULL) {
2856	    if (obj->versyms != NULL) {
2857		verndx = VER_NDX(obj->versyms[symnum]);
2858		if (verndx > obj->vernum) {
2859		    _rtld_error("%s: symbol %s references wrong version %d",
2860			obj->path, obj->strtab + symnum, verndx);
2861		    continue;
2862		}
2863		/*
2864		 * If we are not called from dlsym (i.e. this is a normal
2865		 * relocation from unversioned binary, accept the symbol
2866		 * immediately if it happens to have first version after
2867		 * this shared object became versioned. Otherwise, if
2868		 * symbol is versioned and not hidden, remember it. If it
2869		 * is the only symbol with this name exported by the
2870		 * shared object, it will be returned as a match at the
2871		 * end of the function. If symbol is global (verndx < 2)
2872		 * accept it unconditionally.
2873		 */
2874		if ((flags & SYMLOOK_DLSYM) == 0 && verndx == VER_NDX_GIVEN)
2875		    return symp;
2876	        else if (verndx >= VER_NDX_GIVEN) {
2877		    if ((obj->versyms[symnum] & VER_NDX_HIDDEN) == 0) {
2878			if (vsymp == NULL)
2879			    vsymp = symp;
2880			vcount ++;
2881		    }
2882		    continue;
2883		}
2884	    }
2885	    return symp;
2886	} else {
2887	    if (obj->versyms == NULL) {
2888		if (object_match_name(obj, ventry->name)) {
2889		    _rtld_error("%s: object %s should provide version %s for "
2890			"symbol %s", obj_rtld.path, obj->path, ventry->name,
2891			obj->strtab + symnum);
2892		    continue;
2893		}
2894	    } else {
2895		verndx = VER_NDX(obj->versyms[symnum]);
2896		if (verndx > obj->vernum) {
2897		    _rtld_error("%s: symbol %s references wrong version %d",
2898			obj->path, obj->strtab + symnum, verndx);
2899		    continue;
2900		}
2901		if (obj->vertab[verndx].hash != ventry->hash ||
2902		    strcmp(obj->vertab[verndx].name, ventry->name)) {
2903		    /*
2904		     * Version does not match. Look if this is a global symbol
2905		     * and if it is not hidden. If global symbol (verndx < 2)
2906		     * is available, use it. Do not return symbol if we are
2907		     * called by dlvsym, because dlvsym looks for a specific
2908		     * version and default one is not what dlvsym wants.
2909		     */
2910		    if ((flags & SYMLOOK_DLSYM) ||
2911			(obj->versyms[symnum] & VER_NDX_HIDDEN) ||
2912			(verndx >= VER_NDX_GIVEN))
2913			continue;
2914		}
2915	    }
2916	    return symp;
2917	}
2918    }
2919    return (vcount == 1) ? vsymp : NULL;
2920}
2921
2922static void
2923trace_loaded_objects(Obj_Entry *obj)
2924{
2925    char	*fmt1, *fmt2, *fmt, *main_local, *list_containers;
2926    int		c;
2927
2928    if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
2929	main_local = "";
2930
2931    if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL)
2932	fmt1 = "\t%o => %p (%x)\n";
2933
2934    if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL)
2935	fmt2 = "\t%o (%x)\n";
2936
2937    list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL");
2938
2939    for (; obj; obj = obj->next) {
2940	Needed_Entry		*needed;
2941	char			*name, *path;
2942	bool			is_lib;
2943
2944	if (list_containers && obj->needed != NULL)
2945	    printf("%s:\n", obj->path);
2946	for (needed = obj->needed; needed; needed = needed->next) {
2947	    if (needed->obj != NULL) {
2948		if (needed->obj->traced && !list_containers)
2949		    continue;
2950		needed->obj->traced = true;
2951		path = needed->obj->path;
2952	    } else
2953		path = "not found";
2954
2955	    name = (char *)obj->strtab + needed->name;
2956	    is_lib = strncmp(name, "lib", 3) == 0;	/* XXX - bogus */
2957
2958	    fmt = is_lib ? fmt1 : fmt2;
2959	    while ((c = *fmt++) != '\0') {
2960		switch (c) {
2961		default:
2962		    putchar(c);
2963		    continue;
2964		case '\\':
2965		    switch (c = *fmt) {
2966		    case '\0':
2967			continue;
2968		    case 'n':
2969			putchar('\n');
2970			break;
2971		    case 't':
2972			putchar('\t');
2973			break;
2974		    }
2975		    break;
2976		case '%':
2977		    switch (c = *fmt) {
2978		    case '\0':
2979			continue;
2980		    case '%':
2981		    default:
2982			putchar(c);
2983			break;
2984		    case 'A':
2985			printf("%s", main_local);
2986			break;
2987		    case 'a':
2988			printf("%s", obj_main->path);
2989			break;
2990		    case 'o':
2991			printf("%s", name);
2992			break;
2993#if 0
2994		    case 'm':
2995			printf("%d", sodp->sod_major);
2996			break;
2997		    case 'n':
2998			printf("%d", sodp->sod_minor);
2999			break;
3000#endif
3001		    case 'p':
3002			printf("%s", path);
3003			break;
3004		    case 'x':
3005			printf("%p", needed->obj ? needed->obj->mapbase : 0);
3006			break;
3007		    }
3008		    break;
3009		}
3010		++fmt;
3011	    }
3012	}
3013    }
3014}
3015
3016/*
3017 * Unload a dlopened object and its dependencies from memory and from
3018 * our data structures.  It is assumed that the DAG rooted in the
3019 * object has already been unreferenced, and that the object has a
3020 * reference count of 0.
3021 */
3022static void
3023unload_object(Obj_Entry *root)
3024{
3025    Obj_Entry *obj;
3026    Obj_Entry **linkp;
3027
3028    assert(root->refcount == 0);
3029
3030    /*
3031     * Pass over the DAG removing unreferenced objects from
3032     * appropriate lists.
3033     */
3034    unlink_object(root);
3035
3036    /* Unmap all objects that are no longer referenced. */
3037    linkp = &obj_list->next;
3038    while ((obj = *linkp) != NULL) {
3039	if (obj->refcount == 0) {
3040	    LD_UTRACE(UTRACE_UNLOAD_OBJECT, obj, obj->mapbase, obj->mapsize, 0,
3041		obj->path);
3042	    dbg("unloading \"%s\"", obj->path);
3043	    munmap(obj->mapbase, obj->mapsize);
3044	    linkmap_delete(obj);
3045	    *linkp = obj->next;
3046	    obj_count--;
3047	    obj_free(obj);
3048	} else
3049	    linkp = &obj->next;
3050    }
3051    obj_tail = linkp;
3052}
3053
3054static void
3055unlink_object(Obj_Entry *root)
3056{
3057    Objlist_Entry *elm;
3058
3059    if (root->refcount == 0) {
3060	/* Remove the object from the RTLD_GLOBAL list. */
3061	objlist_remove(&list_global, root);
3062
3063    	/* Remove the object from all objects' DAG lists. */
3064    	STAILQ_FOREACH(elm, &root->dagmembers, link) {
3065	    objlist_remove(&elm->obj->dldags, root);
3066	    if (elm->obj != root)
3067		unlink_object(elm->obj);
3068	}
3069    }
3070}
3071
3072static void
3073ref_dag(Obj_Entry *root)
3074{
3075    Objlist_Entry *elm;
3076
3077    STAILQ_FOREACH(elm, &root->dagmembers, link)
3078	elm->obj->refcount++;
3079}
3080
3081static void
3082unref_dag(Obj_Entry *root)
3083{
3084    Objlist_Entry *elm;
3085
3086    STAILQ_FOREACH(elm, &root->dagmembers, link)
3087	elm->obj->refcount--;
3088}
3089
3090/*
3091 * Common code for MD __tls_get_addr().
3092 */
3093void *
3094tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset)
3095{
3096    Elf_Addr* dtv = *dtvp;
3097    int lockstate;
3098
3099    /* Check dtv generation in case new modules have arrived */
3100    if (dtv[0] != tls_dtv_generation) {
3101	Elf_Addr* newdtv;
3102	int to_copy;
3103
3104	lockstate = wlock_acquire(rtld_bind_lock);
3105	newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3106	to_copy = dtv[1];
3107	if (to_copy > tls_max_index)
3108	    to_copy = tls_max_index;
3109	memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr));
3110	newdtv[0] = tls_dtv_generation;
3111	newdtv[1] = tls_max_index;
3112	free(dtv);
3113	wlock_release(rtld_bind_lock, lockstate);
3114	*dtvp = newdtv;
3115    }
3116
3117    /* Dynamically allocate module TLS if necessary */
3118    if (!dtv[index + 1]) {
3119	/* Signal safe, wlock will block out signals. */
3120	lockstate = wlock_acquire(rtld_bind_lock);
3121	if (!dtv[index + 1])
3122	    dtv[index + 1] = (Elf_Addr)allocate_module_tls(index);
3123	wlock_release(rtld_bind_lock, lockstate);
3124    }
3125    return (void*) (dtv[index + 1] + offset);
3126}
3127
3128/* XXX not sure what variants to use for arm. */
3129
3130#if defined(__ia64__) || defined(__powerpc__)
3131
3132/*
3133 * Allocate Static TLS using the Variant I method.
3134 */
3135void *
3136allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign)
3137{
3138    Obj_Entry *obj;
3139    char *tcb;
3140    Elf_Addr **tls;
3141    Elf_Addr *dtv;
3142    Elf_Addr addr;
3143    int i;
3144
3145    if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
3146	return (oldtcb);
3147
3148    assert(tcbsize >= TLS_TCB_SIZE);
3149    tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
3150    tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
3151
3152    if (oldtcb != NULL) {
3153	memcpy(tls, oldtcb, tls_static_space);
3154	free(oldtcb);
3155
3156	/* Adjust the DTV. */
3157	dtv = tls[0];
3158	for (i = 0; i < dtv[1]; i++) {
3159	    if (dtv[i+2] >= (Elf_Addr)oldtcb &&
3160		dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) {
3161		dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls;
3162	    }
3163	}
3164    } else {
3165	dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr));
3166	tls[0] = dtv;
3167	dtv[0] = tls_dtv_generation;
3168	dtv[1] = tls_max_index;
3169
3170	for (obj = objs; obj; obj = obj->next) {
3171	    if (obj->tlsoffset > 0) {
3172		addr = (Elf_Addr)tls + obj->tlsoffset;
3173		if (obj->tlsinitsize > 0)
3174		    memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3175		if (obj->tlssize > obj->tlsinitsize)
3176		    memset((void*) (addr + obj->tlsinitsize), 0,
3177			   obj->tlssize - obj->tlsinitsize);
3178		dtv[obj->tlsindex + 1] = addr;
3179	    }
3180	}
3181    }
3182
3183    return (tcb);
3184}
3185
3186void
3187free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3188{
3189    Elf_Addr *dtv;
3190    Elf_Addr tlsstart, tlsend;
3191    int dtvsize, i;
3192
3193    assert(tcbsize >= TLS_TCB_SIZE);
3194
3195    tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE;
3196    tlsend = tlsstart + tls_static_space;
3197
3198    dtv = *(Elf_Addr **)tlsstart;
3199    dtvsize = dtv[1];
3200    for (i = 0; i < dtvsize; i++) {
3201	if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) {
3202	    free((void*)dtv[i+2]);
3203	}
3204    }
3205    free(dtv);
3206    free(tcb);
3207}
3208
3209#endif
3210
3211#if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \
3212    defined(__arm__) || defined(__mips__)
3213
3214/*
3215 * Allocate Static TLS using the Variant II method.
3216 */
3217void *
3218allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign)
3219{
3220    Obj_Entry *obj;
3221    size_t size;
3222    char *tls;
3223    Elf_Addr *dtv, *olddtv;
3224    Elf_Addr segbase, oldsegbase, addr;
3225    int i;
3226
3227    size = round(tls_static_space, tcbalign);
3228
3229    assert(tcbsize >= 2*sizeof(Elf_Addr));
3230    tls = calloc(1, size + tcbsize);
3231    dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
3232
3233    segbase = (Elf_Addr)(tls + size);
3234    ((Elf_Addr*)segbase)[0] = segbase;
3235    ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv;
3236
3237    dtv[0] = tls_dtv_generation;
3238    dtv[1] = tls_max_index;
3239
3240    if (oldtls) {
3241	/*
3242	 * Copy the static TLS block over whole.
3243	 */
3244	oldsegbase = (Elf_Addr) oldtls;
3245	memcpy((void *)(segbase - tls_static_space),
3246	       (const void *)(oldsegbase - tls_static_space),
3247	       tls_static_space);
3248
3249	/*
3250	 * If any dynamic TLS blocks have been created tls_get_addr(),
3251	 * move them over.
3252	 */
3253	olddtv = ((Elf_Addr**)oldsegbase)[1];
3254	for (i = 0; i < olddtv[1]; i++) {
3255	    if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) {
3256		dtv[i+2] = olddtv[i+2];
3257		olddtv[i+2] = 0;
3258	    }
3259	}
3260
3261	/*
3262	 * We assume that this block was the one we created with
3263	 * allocate_initial_tls().
3264	 */
3265	free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr));
3266    } else {
3267	for (obj = objs; obj; obj = obj->next) {
3268	    if (obj->tlsoffset) {
3269		addr = segbase - obj->tlsoffset;
3270		memset((void*) (addr + obj->tlsinitsize),
3271		       0, obj->tlssize - obj->tlsinitsize);
3272		if (obj->tlsinit)
3273		    memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize);
3274		dtv[obj->tlsindex + 1] = addr;
3275	    }
3276	}
3277    }
3278
3279    return (void*) segbase;
3280}
3281
3282void
3283free_tls(void *tls, size_t tcbsize, size_t tcbalign)
3284{
3285    size_t size;
3286    Elf_Addr* dtv;
3287    int dtvsize, i;
3288    Elf_Addr tlsstart, tlsend;
3289
3290    /*
3291     * Figure out the size of the initial TLS block so that we can
3292     * find stuff which ___tls_get_addr() allocated dynamically.
3293     */
3294    size = round(tls_static_space, tcbalign);
3295
3296    dtv = ((Elf_Addr**)tls)[1];
3297    dtvsize = dtv[1];
3298    tlsend = (Elf_Addr) tls;
3299    tlsstart = tlsend - size;
3300    for (i = 0; i < dtvsize; i++) {
3301	if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) {
3302	    free((void*) dtv[i+2]);
3303	}
3304    }
3305
3306    free((void*) tlsstart);
3307    free((void*) dtv);
3308}
3309
3310#endif
3311
3312/*
3313 * Allocate TLS block for module with given index.
3314 */
3315void *
3316allocate_module_tls(int index)
3317{
3318    Obj_Entry* obj;
3319    char* p;
3320
3321    for (obj = obj_list; obj; obj = obj->next) {
3322	if (obj->tlsindex == index)
3323	    break;
3324    }
3325    if (!obj) {
3326	_rtld_error("Can't find module with TLS index %d", index);
3327	die();
3328    }
3329
3330    p = malloc(obj->tlssize);
3331    if (p == NULL) {
3332	_rtld_error("Cannot allocate TLS block for index %d", index);
3333	die();
3334    }
3335    memcpy(p, obj->tlsinit, obj->tlsinitsize);
3336    memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize);
3337
3338    return p;
3339}
3340
3341bool
3342allocate_tls_offset(Obj_Entry *obj)
3343{
3344    size_t off;
3345
3346    if (obj->tls_done)
3347	return true;
3348
3349    if (obj->tlssize == 0) {
3350	obj->tls_done = true;
3351	return true;
3352    }
3353
3354    if (obj->tlsindex == 1)
3355	off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign);
3356    else
3357	off = calculate_tls_offset(tls_last_offset, tls_last_size,
3358				   obj->tlssize, obj->tlsalign);
3359
3360    /*
3361     * If we have already fixed the size of the static TLS block, we
3362     * must stay within that size. When allocating the static TLS, we
3363     * leave a small amount of space spare to be used for dynamically
3364     * loading modules which use static TLS.
3365     */
3366    if (tls_static_space) {
3367	if (calculate_tls_end(off, obj->tlssize) > tls_static_space)
3368	    return false;
3369    }
3370
3371    tls_last_offset = obj->tlsoffset = off;
3372    tls_last_size = obj->tlssize;
3373    obj->tls_done = true;
3374
3375    return true;
3376}
3377
3378void
3379free_tls_offset(Obj_Entry *obj)
3380{
3381
3382    /*
3383     * If we were the last thing to allocate out of the static TLS
3384     * block, we give our space back to the 'allocator'. This is a
3385     * simplistic workaround to allow libGL.so.1 to be loaded and
3386     * unloaded multiple times.
3387     */
3388    if (calculate_tls_end(obj->tlsoffset, obj->tlssize)
3389	== calculate_tls_end(tls_last_offset, tls_last_size)) {
3390	tls_last_offset -= obj->tlssize;
3391	tls_last_size = 0;
3392    }
3393}
3394
3395void *
3396_rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign)
3397{
3398    void *ret;
3399    int lockstate;
3400
3401    lockstate = wlock_acquire(rtld_bind_lock);
3402    ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign);
3403    wlock_release(rtld_bind_lock, lockstate);
3404    return (ret);
3405}
3406
3407void
3408_rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign)
3409{
3410    int lockstate;
3411
3412    lockstate = wlock_acquire(rtld_bind_lock);
3413    free_tls(tcb, tcbsize, tcbalign);
3414    wlock_release(rtld_bind_lock, lockstate);
3415}
3416
3417static void
3418object_add_name(Obj_Entry *obj, const char *name)
3419{
3420    Name_Entry *entry;
3421    size_t len;
3422
3423    len = strlen(name);
3424    entry = malloc(sizeof(Name_Entry) + len);
3425
3426    if (entry != NULL) {
3427	strcpy(entry->name, name);
3428	STAILQ_INSERT_TAIL(&obj->names, entry, link);
3429    }
3430}
3431
3432static int
3433object_match_name(const Obj_Entry *obj, const char *name)
3434{
3435    Name_Entry *entry;
3436
3437    STAILQ_FOREACH(entry, &obj->names, link) {
3438	if (strcmp(name, entry->name) == 0)
3439	    return (1);
3440    }
3441    return (0);
3442}
3443
3444static Obj_Entry *
3445locate_dependency(const Obj_Entry *obj, const char *name)
3446{
3447    const Objlist_Entry *entry;
3448    const Needed_Entry *needed;
3449
3450    STAILQ_FOREACH(entry, &list_main, link) {
3451	if (object_match_name(entry->obj, name))
3452	    return entry->obj;
3453    }
3454
3455    for (needed = obj->needed;  needed != NULL;  needed = needed->next) {
3456	if (needed->obj == NULL)
3457	    continue;
3458	if (object_match_name(needed->obj, name))
3459	    return needed->obj;
3460    }
3461    _rtld_error("%s: Unexpected inconsistency: dependency %s not found",
3462	obj->path, name);
3463    die();
3464}
3465
3466static int
3467check_object_provided_version(Obj_Entry *refobj, const Obj_Entry *depobj,
3468    const Elf_Vernaux *vna)
3469{
3470    const Elf_Verdef *vd;
3471    const char *vername;
3472
3473    vername = refobj->strtab + vna->vna_name;
3474    vd = depobj->verdef;
3475    if (vd == NULL) {
3476	_rtld_error("%s: version %s required by %s not defined",
3477	    depobj->path, vername, refobj->path);
3478	return (-1);
3479    }
3480    for (;;) {
3481	if (vd->vd_version != VER_DEF_CURRENT) {
3482	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3483		depobj->path, vd->vd_version);
3484	    return (-1);
3485	}
3486	if (vna->vna_hash == vd->vd_hash) {
3487	    const Elf_Verdaux *aux = (const Elf_Verdaux *)
3488		((char *)vd + vd->vd_aux);
3489	    if (strcmp(vername, depobj->strtab + aux->vda_name) == 0)
3490		return (0);
3491	}
3492	if (vd->vd_next == 0)
3493	    break;
3494	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3495    }
3496    if (vna->vna_flags & VER_FLG_WEAK)
3497	return (0);
3498    _rtld_error("%s: version %s required by %s not found",
3499	depobj->path, vername, refobj->path);
3500    return (-1);
3501}
3502
3503static int
3504rtld_verify_object_versions(Obj_Entry *obj)
3505{
3506    const Elf_Verneed *vn;
3507    const Elf_Verdef  *vd;
3508    const Elf_Verdaux *vda;
3509    const Elf_Vernaux *vna;
3510    const Obj_Entry *depobj;
3511    int maxvernum, vernum;
3512
3513    maxvernum = 0;
3514    /*
3515     * Walk over defined and required version records and figure out
3516     * max index used by any of them. Do very basic sanity checking
3517     * while there.
3518     */
3519    vn = obj->verneed;
3520    while (vn != NULL) {
3521	if (vn->vn_version != VER_NEED_CURRENT) {
3522	    _rtld_error("%s: Unsupported version %d of Elf_Verneed entry",
3523		obj->path, vn->vn_version);
3524	    return (-1);
3525	}
3526	vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3527	for (;;) {
3528	    vernum = VER_NEED_IDX(vna->vna_other);
3529	    if (vernum > maxvernum)
3530		maxvernum = vernum;
3531	    if (vna->vna_next == 0)
3532		 break;
3533	    vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3534	}
3535	if (vn->vn_next == 0)
3536	    break;
3537	vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3538    }
3539
3540    vd = obj->verdef;
3541    while (vd != NULL) {
3542	if (vd->vd_version != VER_DEF_CURRENT) {
3543	    _rtld_error("%s: Unsupported version %d of Elf_Verdef entry",
3544		obj->path, vd->vd_version);
3545	    return (-1);
3546	}
3547	vernum = VER_DEF_IDX(vd->vd_ndx);
3548	if (vernum > maxvernum)
3549		maxvernum = vernum;
3550	if (vd->vd_next == 0)
3551	    break;
3552	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3553    }
3554
3555    if (maxvernum == 0)
3556	return (0);
3557
3558    /*
3559     * Store version information in array indexable by version index.
3560     * Verify that object version requirements are satisfied along the
3561     * way.
3562     */
3563    obj->vernum = maxvernum + 1;
3564    obj->vertab = calloc(obj->vernum, sizeof(Ver_Entry));
3565
3566    vd = obj->verdef;
3567    while (vd != NULL) {
3568	if ((vd->vd_flags & VER_FLG_BASE) == 0) {
3569	    vernum = VER_DEF_IDX(vd->vd_ndx);
3570	    assert(vernum <= maxvernum);
3571	    vda = (const Elf_Verdaux *)((char *)vd + vd->vd_aux);
3572	    obj->vertab[vernum].hash = vd->vd_hash;
3573	    obj->vertab[vernum].name = obj->strtab + vda->vda_name;
3574	    obj->vertab[vernum].file = NULL;
3575	    obj->vertab[vernum].flags = 0;
3576	}
3577	if (vd->vd_next == 0)
3578	    break;
3579	vd = (const Elf_Verdef *) ((char *)vd + vd->vd_next);
3580    }
3581
3582    vn = obj->verneed;
3583    while (vn != NULL) {
3584	depobj = locate_dependency(obj, obj->strtab + vn->vn_file);
3585	vna = (const Elf_Vernaux *) ((char *)vn + vn->vn_aux);
3586	for (;;) {
3587	    if (check_object_provided_version(obj, depobj, vna))
3588		return (-1);
3589	    vernum = VER_NEED_IDX(vna->vna_other);
3590	    assert(vernum <= maxvernum);
3591	    obj->vertab[vernum].hash = vna->vna_hash;
3592	    obj->vertab[vernum].name = obj->strtab + vna->vna_name;
3593	    obj->vertab[vernum].file = obj->strtab + vn->vn_file;
3594	    obj->vertab[vernum].flags = (vna->vna_other & VER_NEED_HIDDEN) ?
3595		VER_INFO_HIDDEN : 0;
3596	    if (vna->vna_next == 0)
3597		 break;
3598	    vna = (const Elf_Vernaux *) ((char *)vna + vna->vna_next);
3599	}
3600	if (vn->vn_next == 0)
3601	    break;
3602	vn = (const Elf_Verneed *) ((char *)vn + vn->vn_next);
3603    }
3604    return 0;
3605}
3606
3607static int
3608rtld_verify_versions(const Objlist *objlist)
3609{
3610    Objlist_Entry *entry;
3611    int rc;
3612
3613    rc = 0;
3614    STAILQ_FOREACH(entry, objlist, link) {
3615	/*
3616	 * Skip dummy objects or objects that have their version requirements
3617	 * already checked.
3618	 */
3619	if (entry->obj->strtab == NULL || entry->obj->vertab != NULL)
3620	    continue;
3621	if (rtld_verify_object_versions(entry->obj) == -1) {
3622	    rc = -1;
3623	    if (ld_tracing == NULL)
3624		break;
3625	}
3626    }
3627    if (rc == 0 || ld_tracing != NULL)
3628    	rc = rtld_verify_object_versions(&obj_rtld);
3629    return rc;
3630}
3631
3632const Ver_Entry *
3633fetch_ventry(const Obj_Entry *obj, unsigned long symnum)
3634{
3635    Elf_Versym vernum;
3636
3637    if (obj->vertab) {
3638	vernum = VER_NDX(obj->versyms[symnum]);
3639	if (vernum >= obj->vernum) {
3640	    _rtld_error("%s: symbol %s has wrong verneed value %d",
3641		obj->path, obj->strtab + symnum, vernum);
3642	} else if (obj->vertab[vernum].hash != 0) {
3643	    return &obj->vertab[vernum];
3644	}
3645    }
3646    return NULL;
3647}
3648
3649/*
3650 * Overrides for libc_pic-provided functions.
3651 */
3652
3653int
3654__getosreldate(void)
3655{
3656	size_t len;
3657	int oid[2];
3658	int error, osrel;
3659
3660	if (osreldate != 0)
3661		return (osreldate);
3662
3663	oid[0] = CTL_KERN;
3664	oid[1] = KERN_OSRELDATE;
3665	osrel = 0;
3666	len = sizeof(osrel);
3667	error = sysctl(oid, 2, &osrel, &len, NULL, 0);
3668	if (error == 0 && osrel > 0 && len == sizeof(osrel))
3669		osreldate = osrel;
3670	return (osreldate);
3671}
3672
3673/*
3674 * No unresolved symbols for rtld.
3675 */
3676void
3677__pthread_cxa_finalize(struct dl_phdr_info *a)
3678{
3679}
3680