Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.128
      1 /*	$NetBSD: rtld.c,v 1.128 2010/01/10 06:37:32 skrll Exp $	 */
      2 
      3 /*
      4  * Copyright 1996 John D. Polstra.
      5  * Copyright 1996 Matt Thomas <matt (at) 3am-software.com>
      6  * Copyright 2002 Charles M. Hannum <root (at) ihack.net>
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *      This product includes software developed by John Polstra.
     20  * 4. The name of the author may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Dynamic linker for ELF.
     37  *
     38  * John Polstra <jdp (at) polstra.com>.
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 #ifndef lint
     43 __RCSID("$NetBSD: rtld.c,v 1.128 2010/01/10 06:37:32 skrll Exp $");
     44 #endif /* not lint */
     45 
     46 #include <err.h>
     47 #include <errno.h>
     48 #include <fcntl.h>
     49 #include <stdarg.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <unistd.h>
     54 #include <sys/param.h>
     55 #include <sys/mman.h>
     56 #include <dirent.h>
     57 
     58 #include <ctype.h>
     59 
     60 #include <dlfcn.h>
     61 #include "debug.h"
     62 #include "rtld.h"
     63 
     64 #if !defined(lint)
     65 #include "sysident.h"
     66 #endif
     67 
     68 /*
     69  * Function declarations.
     70  */
     71 static void     _rtld_init(caddr_t, caddr_t, const char *);
     72 static void     _rtld_exit(void);
     73 
     74 Elf_Addr        _rtld(Elf_Addr *, Elf_Addr);
     75 
     76 
     77 /*
     78  * Data declarations.
     79  */
     80 static char    *error_message;	/* Message for dlopen(), or NULL */
     81 
     82 struct r_debug  _rtld_debug;	/* for GDB; */
     83 bool            _rtld_trust;	/* False for setuid and setgid programs */
     84 Obj_Entry      *_rtld_objlist;	/* Head of linked list of shared objects */
     85 Obj_Entry     **_rtld_objtail;	/* Link field of last object in list */
     86 Obj_Entry      *_rtld_objmain;	/* The main program shared object */
     87 Obj_Entry       _rtld_objself;	/* The dynamic linker shared object */
     88 const char	_rtld_path[] = _PATH_RTLD;
     89 
     90 /* Initialize a fake symbol for resolving undefined weak references. */
     91 Elf_Sym		_rtld_sym_zero = {
     92     .st_info	= ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
     93     .st_shndx	= SHN_ABS,
     94 };
     95 size_t	_rtld_pagesz;	/* Page size, as provided by kernel */
     96 
     97 Search_Path    *_rtld_default_paths;
     98 Search_Path    *_rtld_paths;
     99 
    100 Library_Xform  *_rtld_xforms;
    101 
    102 /*
    103  * Global declarations normally provided by crt0.
    104  */
    105 char           *__progname;
    106 char          **environ;
    107 
    108 #if defined(RTLD_DEBUG)
    109 #ifndef __sh__
    110 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
    111 #else  /* 32-bit SuperH */
    112 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
    113 #endif
    114 #endif /* RTLD_DEBUG */
    115 extern Elf_Dyn  _DYNAMIC;
    116 
    117 static void _rtld_call_fini_functions(int);
    118 static void _rtld_call_init_functions(void);
    119 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
    120 static void _rtld_initlist_tsort(Objlist *, int);
    121 static Obj_Entry *_rtld_dlcheck(void *);
    122 static void _rtld_init_dag(Obj_Entry *);
    123 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
    124 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
    125 static void _rtld_objlist_clear(Objlist *);
    126 static void _rtld_unload_object(Obj_Entry *, bool);
    127 static void _rtld_unref_dag(Obj_Entry *);
    128 static Obj_Entry *_rtld_obj_from_addr(const void *);
    129 
    130 static void
    131 _rtld_call_fini_functions(int force)
    132 {
    133 	Objlist_Entry *elm;
    134 	Objlist finilist;
    135 	Obj_Entry *obj;
    136 
    137 	dbg(("_rtld_call_fini_functions(%d)", force));
    138 
    139 	SIMPLEQ_INIT(&finilist);
    140 	_rtld_initlist_tsort(&finilist, 1);
    141 
    142 	/* First pass: objects _not_ marked with DF_1_INITFIRST. */
    143 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    144 		obj = elm->obj;
    145 		if (obj->refcount > 0 && !force) {
    146 			continue;
    147 		}
    148 		if (obj->fini == NULL || obj->fini_called || obj->initfirst) {
    149 		    	continue;
    150 		}
    151 		dbg (("calling fini function %s at %p",  obj->path,
    152 		    (void *)obj->fini));
    153 		obj->fini_called = 1;
    154 		(*obj->fini)();
    155 	}
    156 
    157 	/* Second pass: objects marked with DF_1_INITFIRST. */
    158 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    159 		obj = elm->obj;
    160 		if (obj->refcount > 0 && !force) {
    161 			continue;
    162 		}
    163 		if (obj->fini == NULL || obj->fini_called) {
    164 		    	continue;
    165 		}
    166 		dbg (("calling fini function %s at %p (DF_1_INITFIRST)",
    167 		    obj->path, (void *)obj->fini));
    168 		obj->fini_called = 1;
    169 		(*obj->fini)();
    170 	}
    171 
    172         _rtld_objlist_clear(&finilist);
    173 }
    174 
    175 static void
    176 _rtld_call_init_functions()
    177 {
    178 	Objlist_Entry *elm;
    179 	Objlist initlist;
    180 	Obj_Entry *obj;
    181 
    182 	dbg(("_rtld_call_init_functions()"));
    183 	SIMPLEQ_INIT(&initlist);
    184 	_rtld_initlist_tsort(&initlist, 0);
    185 
    186 	/* First pass: objects marked with DF_1_INITFIRST. */
    187 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    188 		obj = elm->obj;
    189 		if (obj->init == NULL || obj->init_called || !obj->initfirst) {
    190 			continue;
    191 		}
    192 		dbg (("calling init function %s at %p (DF_1_INITFIRST)",
    193 		    obj->path, (void *)obj->init));
    194 		obj->init_called = 1;
    195 		(*obj->init)();
    196 	}
    197 
    198 	/* Second pass: all other objects. */
    199 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    200 		obj = elm->obj;
    201 		if (obj->init == NULL || obj->init_called) {
    202 			continue;
    203 		}
    204 		dbg (("calling init function %s at %p",  obj->path,
    205 		    (void *)obj->init));
    206 		obj->init_called = 1;
    207 		(*obj->init)();
    208 	}
    209 
    210         _rtld_objlist_clear(&initlist);
    211 }
    212 
    213 /*
    214  * Initialize the dynamic linker.  The argument is the address at which
    215  * the dynamic linker has been mapped into memory.  The primary task of
    216  * this function is to create an Obj_Entry for the dynamic linker and
    217  * to resolve the PLT relocation for platforms that need it (those that
    218  * define __HAVE_FUNCTION_DESCRIPTORS
    219  */
    220 static void
    221 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
    222 {
    223 
    224 	/* Conjure up an Obj_Entry structure for the dynamic linker. */
    225 	_rtld_objself.path = __UNCONST(_rtld_path);
    226 	_rtld_objself.pathlen = sizeof(_rtld_path)-1;
    227 	_rtld_objself.rtld = true;
    228 	_rtld_objself.mapbase = mapbase;
    229 	_rtld_objself.relocbase = relocbase;
    230 	_rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
    231 	_rtld_objself.strtab = "_rtld_sym_zero";
    232 
    233 	/*
    234 	 * Set value to -relocbase so that
    235 	 *
    236 	 *     _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
    237 	 *
    238 	 * This allows unresolved references to weak symbols to be computed
    239 	 * to a value of 0.
    240 	 */
    241 	_rtld_sym_zero.st_value = -(uintptr_t)relocbase;
    242 
    243 	_rtld_digest_dynamic(_rtld_path, &_rtld_objself);
    244 	assert(!_rtld_objself.needed);
    245 #if !defined(__hppa__)
    246 	assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
    247 #else
    248 	_rtld_relocate_plt_objects(&_rtld_objself);
    249 #endif
    250 #if !defined(__mips__) && !defined(__hppa__)
    251 	assert(!_rtld_objself.pltgot);
    252 #endif
    253 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
    254 	/* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
    255 	assert(!_rtld_objself.textrel);
    256 #endif
    257 
    258 	_rtld_add_paths(execname, &_rtld_default_paths,
    259 	    RTLD_DEFAULT_LIBRARY_PATH);
    260 
    261 #ifdef RTLD_ARCH_SUBDIR
    262 	_rtld_add_paths(execname, &_rtld_default_paths,
    263 	    RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
    264 #endif
    265 
    266 	/*
    267 	 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
    268 	 */
    269 	_rtld_objlist = &_rtld_objself;
    270 
    271 	/* Make the object list empty again. */
    272 	_rtld_objlist = NULL;
    273 	_rtld_objtail = &_rtld_objlist;
    274 
    275 	_rtld_debug.r_brk = _rtld_debug_state;
    276 	_rtld_debug.r_state = RT_CONSISTENT;
    277 }
    278 
    279 /*
    280  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    281  * before the process exits.
    282  */
    283 static void
    284 _rtld_exit(void)
    285 {
    286 	dbg(("rtld_exit()"));
    287 
    288 	_rtld_call_fini_functions(1);
    289 }
    290 
    291 /*
    292  * Main entry point for dynamic linking.  The argument is the stack
    293  * pointer.  The stack is expected to be laid out as described in the
    294  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    295  * the stack pointer points to a word containing ARGC.  Following that
    296  * in the stack is a null-terminated sequence of pointers to argument
    297  * strings.  Then comes a null-terminated sequence of pointers to
    298  * environment strings.  Finally, there is a sequence of "auxiliary
    299  * vector" entries.
    300  *
    301  * This function returns the entry point for the main program, the dynamic
    302  * linker's exit procedure in sp[0], and a pointer to the main object in
    303  * sp[1].
    304  */
    305 Elf_Addr
    306 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
    307 {
    308 	const AuxInfo  *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
    309 	               *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
    310 		       *pAUX_ruid, *pAUX_rgid;
    311 	const AuxInfo  *pAUX_pagesz;
    312 	char          **env;
    313 	const AuxInfo  *aux;
    314 	const AuxInfo  *auxp;
    315 	Elf_Addr       *const osp = sp;
    316 	bool            bind_now = 0;
    317 	const char     *ld_bind_now;
    318 	const char    **argv;
    319 	const char     *execname;
    320 	long		argc;
    321 	const char **real___progname;
    322 	const Obj_Entry **real___mainprog_obj;
    323 	char ***real_environ;
    324 #if defined(RTLD_DEBUG)
    325 	int i = 0;
    326 #endif
    327 
    328 	/*
    329          * On entry, the dynamic linker itself has not been relocated yet.
    330          * Be very careful not to reference any global data until after
    331          * _rtld_init has returned.  It is OK to reference file-scope statics
    332          * and string constants, and to call static and global functions.
    333          */
    334 	/* Find the auxiliary vector on the stack. */
    335 	/* first Elf_Word reserved to address of exit routine */
    336 #if defined(RTLD_DEBUG)
    337 	debug = 1;
    338 	dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
    339 	    (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
    340 	dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
    341 	    &_DYNAMIC));
    342 	dbg(("_ctype_ is %p", _ctype_));
    343 #endif
    344 
    345 	sp += 2;		/* skip over return argument space */
    346 	argv = (const char **) &sp[1];
    347 	argc = *(long *)sp;
    348 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
    349 				 * terminator */
    350 	env = (char **) sp;
    351 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    352 #if defined(RTLD_DEBUG)
    353 		dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
    354 #endif
    355 	}
    356 	aux = (const AuxInfo *) sp;
    357 
    358 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
    359 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
    360 	pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
    361 	pAUX_pagesz = NULL;
    362 
    363 	execname = NULL;
    364 
    365 	/* Digest the auxiliary vector. */
    366 	for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
    367 		switch (auxp->a_type) {
    368 		case AT_BASE:
    369 			pAUX_base = auxp;
    370 			break;
    371 		case AT_ENTRY:
    372 			pAUX_entry = auxp;
    373 			break;
    374 		case AT_EXECFD:
    375 			pAUX_execfd = auxp;
    376 			break;
    377 		case AT_PHDR:
    378 			pAUX_phdr = auxp;
    379 			break;
    380 		case AT_PHENT:
    381 			pAUX_phent = auxp;
    382 			break;
    383 		case AT_PHNUM:
    384 			pAUX_phnum = auxp;
    385 			break;
    386 #ifdef AT_EUID
    387 		case AT_EUID:
    388 			pAUX_euid = auxp;
    389 			break;
    390 		case AT_RUID:
    391 			pAUX_ruid = auxp;
    392 			break;
    393 		case AT_EGID:
    394 			pAUX_egid = auxp;
    395 			break;
    396 		case AT_RGID:
    397 			pAUX_rgid = auxp;
    398 			break;
    399 #endif
    400 #ifdef AT_SUN_EXECNAME
    401 		case AT_SUN_EXECNAME:
    402 			execname = (const char *)(const void *)auxp->a_v;
    403 			break;
    404 #endif
    405 		case AT_PAGESZ:
    406 			pAUX_pagesz = auxp;
    407 			break;
    408 		}
    409 	}
    410 
    411 	/* Initialize and relocate ourselves. */
    412 	if (pAUX_base == NULL) {
    413 		_rtld_error("Bad pAUX_base");
    414 		_rtld_die();
    415 	}
    416 	assert(pAUX_pagesz != NULL);
    417 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
    418 	_rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
    419 
    420 	__progname = _rtld_objself.path;
    421 	environ = env;
    422 
    423 	_rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
    424 	    (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
    425 	    ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
    426 	    (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
    427 
    428 	ld_bind_now = getenv("LD_BIND_NOW");
    429 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
    430 		bind_now = true;
    431 	if (_rtld_trust) {
    432 #ifdef DEBUG
    433 		const char     *ld_debug = getenv("LD_DEBUG");
    434 #ifdef RTLD_DEBUG
    435 		debug = 0;
    436 #endif
    437 		if (ld_debug != NULL && *ld_debug != '\0')
    438 			debug = 1;
    439 #endif
    440 		_rtld_add_paths(execname, &_rtld_paths,
    441 		    getenv("LD_LIBRARY_PATH"));
    442 	} else {
    443 		execname = NULL;
    444 		if (unsetenv("LD_DEBUG") || unsetenv("LD_LIBRARY_PATH"))
    445 			_rtld_die();
    446 	}
    447 	_rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
    448 	    _PATH_LD_HINTS);
    449 	dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
    450 	     _rtld_objself.mapbase, _rtld_objself.relocbase));
    451 
    452 	/*
    453          * Load the main program, or process its program header if it is
    454          * already loaded.
    455          */
    456 	if (pAUX_execfd != NULL) {	/* Load the main program. */
    457 		int             fd = pAUX_execfd->a_v;
    458 		const char *obj_name = argv[0] ? argv[0] : "main program";
    459 		dbg(("loading main program"));
    460 		_rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
    461 		close(fd);
    462 		if (_rtld_objmain == NULL)
    463 			_rtld_die();
    464 	} else {		/* Main program already loaded. */
    465 		const Elf_Phdr *phdr;
    466 		int             phnum;
    467 		caddr_t         entry;
    468 
    469 		dbg(("processing main program's program header"));
    470 		assert(pAUX_phdr != NULL);
    471 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
    472 		assert(pAUX_phnum != NULL);
    473 		phnum = pAUX_phnum->a_v;
    474 		assert(pAUX_phent != NULL);
    475 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
    476 		assert(pAUX_entry != NULL);
    477 		entry = (caddr_t) pAUX_entry->a_v;
    478 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    479 		_rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
    480 		    "main program");
    481 		_rtld_objmain->pathlen = strlen(_rtld_objmain->path);
    482 	}
    483 
    484 	_rtld_objmain->mainprog = true;
    485 
    486 	/*
    487 	 * Get the actual dynamic linker pathname from the executable if
    488 	 * possible.  (It should always be possible.)  That ensures that
    489 	 * gdb will find the right dynamic linker even if a non-standard
    490 	 * one is being used.
    491 	 */
    492 	if (_rtld_objmain->interp != NULL &&
    493 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
    494 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
    495 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
    496 
    497 	_rtld_digest_dynamic(execname, _rtld_objmain);
    498 
    499 	/* Link the main program into the list of objects. */
    500 	*_rtld_objtail = _rtld_objmain;
    501 	_rtld_objtail = &_rtld_objmain->next;
    502 
    503 	_rtld_linkmap_add(_rtld_objmain);
    504 	_rtld_linkmap_add(&_rtld_objself);
    505 
    506 	++_rtld_objmain->refcount;
    507 	_rtld_objmain->mainref = 1;
    508 	_rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
    509 
    510 	if (_rtld_trust) {
    511 		/*
    512 		 * Pre-load user-specified objects after the main program
    513 		 * but before any shared object dependencies.
    514 		 */
    515 		dbg(("preloading objects"));
    516 		if (_rtld_preload(getenv("LD_PRELOAD")) == -1)
    517 			_rtld_die();
    518 	} else
    519 		if (unsetenv("LD_PRELOAD"))
    520 			_rtld_die();
    521 
    522 	dbg(("loading needed objects"));
    523 	if (_rtld_load_needed_objects(_rtld_objmain, RTLD_MAIN) == -1)
    524 		_rtld_die();
    525 
    526 	dbg(("relocating objects"));
    527 	if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
    528 		_rtld_die();
    529 
    530 	dbg(("doing copy relocations"));
    531 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
    532 		_rtld_die();
    533 
    534 	/*
    535 	 * Set the __progname,  environ and, __mainprog_obj before
    536 	 * calling anything that might use them.
    537 	 */
    538 	real___progname = _rtld_objmain_sym("__progname");
    539 	if (real___progname) {
    540 		if (argv[0] != NULL) {
    541 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
    542 				(*real___progname) = argv[0];
    543 			else
    544 				(*real___progname)++;
    545 		} else {
    546 			(*real___progname) = NULL;
    547 		}
    548 	}
    549 	real_environ = _rtld_objmain_sym("environ");
    550 	if (real_environ)
    551 		*real_environ = environ;
    552 	/*
    553 	 * Set __mainprog_obj for old binaries.
    554 	 */
    555 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
    556 	if (real___mainprog_obj)
    557 		*real___mainprog_obj = _rtld_objmain;
    558 
    559 	dbg(("calling _init functions"));
    560 	_rtld_call_init_functions();
    561 
    562 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
    563 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
    564 
    565 	/*
    566 	 * Return with the entry point and the exit procedure in at the top
    567 	 * of stack.
    568 	 */
    569 
    570 	_rtld_debug_state();	/* say hello to gdb! */
    571 
    572 	((void **) osp)[0] = _rtld_exit;
    573 	((void **) osp)[1] = _rtld_objmain;
    574 	return (Elf_Addr) _rtld_objmain->entry;
    575 }
    576 
    577 void
    578 _rtld_die(void)
    579 {
    580 	const char *msg = dlerror();
    581 
    582 	if (msg == NULL)
    583 		msg = "Fatal error";
    584 	xerrx(1, "%s", msg);
    585 }
    586 
    587 static Obj_Entry *
    588 _rtld_dlcheck(void *handle)
    589 {
    590 	Obj_Entry *obj;
    591 
    592 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    593 		if (obj == (Obj_Entry *) handle)
    594 			break;
    595 
    596 	if (obj == NULL || obj->dl_refcount == 0) {
    597 		xwarnx("Invalid shared object handle %p", handle);
    598 		return NULL;
    599 	}
    600 	return obj;
    601 }
    602 
    603 static void
    604 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
    605 {
    606 	Needed_Entry* elm;
    607 
    608 	/* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
    609 
    610 	if (obj->init_done)
    611 		return;
    612 	obj->init_done = 1;
    613 
    614 	for (elm = obj->needed; elm != NULL; elm = elm->next) {
    615 		if (elm->obj != NULL) {
    616 			_rtld_initlist_visit(list, elm->obj, rev);
    617 		}
    618 	}
    619 
    620 	if (rev) {
    621 		_rtld_objlist_push_head(list, obj);
    622 	} else {
    623 		_rtld_objlist_push_tail(list, obj);
    624 	}
    625 }
    626 
    627 static void
    628 _rtld_initlist_tsort(Objlist* list, int rev)
    629 {
    630 	dbg(("_rtld_initlist_tsort"));
    631 
    632 	Obj_Entry* obj;
    633 
    634 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    635 		obj->init_done = 0;
    636 	}
    637 
    638 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    639 		_rtld_initlist_visit(list, obj, rev);
    640 	}
    641 }
    642 
    643 static void
    644 _rtld_init_dag(Obj_Entry *root)
    645 {
    646 
    647 	_rtld_init_dag1(root, root);
    648 }
    649 
    650 static void
    651 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
    652 {
    653 	const Needed_Entry *needed;
    654 
    655 	if (!obj->mainref) {
    656 		if (_rtld_objlist_find(&obj->dldags, root))
    657 			return;
    658 		rdbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
    659 		    root->path));
    660 		_rtld_objlist_push_tail(&obj->dldags, root);
    661 		_rtld_objlist_push_tail(&root->dagmembers, obj);
    662 	}
    663 	for (needed = obj->needed; needed != NULL; needed = needed->next)
    664 		if (needed->obj != NULL)
    665 			_rtld_init_dag1(root, needed->obj);
    666 }
    667 
    668 /*
    669  * Note, this is called only for objects loaded by dlopen().
    670  */
    671 static void
    672 _rtld_unload_object(Obj_Entry *root, bool do_fini_funcs)
    673 {
    674 
    675 	_rtld_unref_dag(root);
    676 	if (root->refcount == 0) { /* We are finished with some objects. */
    677 		Obj_Entry *obj;
    678 		Obj_Entry **linkp;
    679 		Objlist_Entry *elm;
    680 
    681 		/* Finalize objects that are about to be unmapped. */
    682 		if (do_fini_funcs)
    683 			_rtld_call_fini_functions(0);
    684 
    685 		/* Remove the DAG from all objects' DAG lists. */
    686 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
    687 			_rtld_objlist_remove(&elm->obj->dldags, root);
    688 
    689 		/* Remove the DAG from the RTLD_GLOBAL list. */
    690 		if (root->globalref) {
    691 			root->globalref = 0;
    692 			_rtld_objlist_remove(&_rtld_list_global, root);
    693 		}
    694 
    695 		/* Unmap all objects that are no longer referenced. */
    696 		linkp = &_rtld_objlist->next;
    697 		while ((obj = *linkp) != NULL) {
    698 			if (obj->refcount == 0) {
    699 #ifdef RTLD_DEBUG
    700 				dbg(("unloading \"%s\"", obj->path));
    701 #endif
    702 				if (obj->ehdr != MAP_FAILED)
    703 					munmap(obj->ehdr, _rtld_pagesz);
    704 				munmap(obj->mapbase, obj->mapsize);
    705 				_rtld_objlist_remove(&_rtld_list_global, obj);
    706 				_rtld_linkmap_delete(obj);
    707 				*linkp = obj->next;
    708 				_rtld_obj_free(obj);
    709 			} else
    710 				linkp = &obj->next;
    711 		}
    712 		_rtld_objtail = linkp;
    713 	}
    714 }
    715 
    716 static void
    717 _rtld_unref_dag(Obj_Entry *root)
    718 {
    719 
    720 	assert(root);
    721 	assert(root->refcount != 0);
    722 	--root->refcount;
    723 	if (root->refcount == 0) {
    724 		const Needed_Entry *needed;
    725 
    726 		for (needed = root->needed; needed != NULL;
    727 		     needed = needed->next) {
    728 			if (needed->obj != NULL)
    729 				_rtld_unref_dag(needed->obj);
    730 		}
    731 	}
    732 }
    733 
    734 __strong_alias(__dlclose,dlclose)
    735 int
    736 dlclose(void *handle)
    737 {
    738 	Obj_Entry *root = _rtld_dlcheck(handle);
    739 
    740 	if (root == NULL)
    741 		return -1;
    742 
    743 	_rtld_debug.r_state = RT_DELETE;
    744 	_rtld_debug_state();
    745 
    746 	--root->dl_refcount;
    747 	_rtld_unload_object(root, true);
    748 
    749 	_rtld_debug.r_state = RT_CONSISTENT;
    750 	_rtld_debug_state();
    751 
    752 	return 0;
    753 }
    754 
    755 __strong_alias(__dlerror,dlerror)
    756 char *
    757 dlerror(void)
    758 {
    759 	char *msg = error_message;
    760 
    761 	error_message = NULL;
    762 	return msg;
    763 }
    764 
    765 __strong_alias(__dlopen,dlopen)
    766 void *
    767 dlopen(const char *name, int mode)
    768 {
    769 	Obj_Entry **old_obj_tail = _rtld_objtail;
    770 	Obj_Entry *obj = NULL;
    771 
    772 	_rtld_debug.r_state = RT_ADD;
    773 	_rtld_debug_state();
    774 
    775 	if (name == NULL) {
    776 		obj = _rtld_objmain;
    777 		obj->refcount++;
    778 	} else
    779 		obj = _rtld_load_library(name, _rtld_objmain, mode);
    780 
    781 	if (obj != NULL) {
    782 		++obj->dl_refcount;
    783 		if (*old_obj_tail != NULL) {	/* We loaded something new. */
    784 			assert(*old_obj_tail == obj);
    785 
    786 			if (_rtld_load_needed_objects(obj, mode) == -1 ||
    787 			    (_rtld_init_dag(obj),
    788 			    _rtld_relocate_objects(obj,
    789 			    ((mode & 3) == RTLD_NOW))) == -1) {
    790 				_rtld_unload_object(obj, false);
    791 				obj->dl_refcount--;
    792 				obj = NULL;
    793 			} else {
    794 				_rtld_call_init_functions();
    795 			}
    796 		}
    797 	}
    798 	_rtld_debug.r_state = RT_CONSISTENT;
    799 	_rtld_debug_state();
    800 
    801 	return obj;
    802 }
    803 
    804 /*
    805  * Find a symbol in the main program.
    806  */
    807 void *
    808 _rtld_objmain_sym(const char *name)
    809 {
    810 	unsigned long hash;
    811 	const Elf_Sym *def;
    812 	const Obj_Entry *obj;
    813 
    814 	hash = _rtld_elf_hash(name);
    815 	obj = _rtld_objmain;
    816 
    817 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false);
    818 
    819 	if (def != NULL)
    820 		return obj->relocbase + def->st_value;
    821 	return(NULL);
    822 }
    823 
    824 #ifdef __powerpc__
    825 static void *
    826 hackish_return_address(void)
    827 {
    828 	return __builtin_return_address(1);
    829 }
    830 #endif
    831 
    832 __strong_alias(__dlsym,dlsym)
    833 void *
    834 dlsym(void *handle, const char *name)
    835 {
    836 	const Obj_Entry *obj;
    837 	unsigned long hash;
    838 	const Elf_Sym *def;
    839 	const Obj_Entry *defobj;
    840 	void *retaddr;
    841 
    842 	hash = _rtld_elf_hash(name);
    843 	def = NULL;
    844 	defobj = NULL;
    845 
    846 	switch ((intptr_t)handle) {
    847 	case (intptr_t)NULL:
    848 	case (intptr_t)RTLD_NEXT:
    849 	case (intptr_t)RTLD_DEFAULT:
    850 	case (intptr_t)RTLD_SELF:
    851 #ifdef __powerpc__
    852 		retaddr = hackish_return_address();
    853 #else
    854 		retaddr = __builtin_return_address(0);
    855 #endif
    856 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
    857 			_rtld_error("Cannot determine caller's shared object");
    858 			return NULL;
    859 		}
    860 
    861 		switch ((intptr_t)handle) {
    862 		case (intptr_t)NULL:	 /* Just the caller's shared object. */
    863 			def = _rtld_symlook_obj(name, hash, obj, false);
    864 			defobj = obj;
    865 			break;
    866 
    867 		case (intptr_t)RTLD_NEXT:	/* Objects after callers */
    868 			obj = obj->next;
    869 			/*FALLTHROUGH*/
    870 
    871 		case (intptr_t)RTLD_SELF:	/* Caller included */
    872 			for (; obj; obj = obj->next) {
    873 				if ((def = _rtld_symlook_obj(name, hash, obj,
    874 				    false)) != NULL) {
    875 					defobj = obj;
    876 					break;
    877 				}
    878 			}
    879 			break;
    880 
    881 		case (intptr_t)RTLD_DEFAULT:
    882 			def = _rtld_symlook_default(name, hash, obj, &defobj,
    883 			    false);
    884 			break;
    885 
    886 		default:
    887 			abort();
    888 		}
    889 		break;
    890 
    891 	default:
    892 		if ((obj = _rtld_dlcheck(handle)) == NULL)
    893 			return NULL;
    894 
    895 		if (obj->mainprog) {
    896 			/* Search main program and all libraries loaded by it */
    897 			def = _rtld_symlook_list(name, hash, &_rtld_list_main,
    898 			    &defobj, false);
    899 		} else {
    900 			Needed_Entry fake;
    901 
    902 			/* Search the object and all the libraries loaded by it. */
    903 			fake.next = NULL;
    904 			fake.obj = __UNCONST(obj);
    905 			fake.name = 0;
    906 			def = _rtld_symlook_needed(name, hash, &fake, &defobj,
    907 			    false);
    908 		}
    909 		break;
    910 	}
    911 
    912 	if (def != NULL) {
    913 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    914 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
    915 			return (void *)_rtld_function_descriptor_alloc(defobj,
    916 			    def, 0);
    917 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    918 		return defobj->relocbase + def->st_value;
    919 	}
    920 
    921 	_rtld_error("Undefined symbol \"%s\"", name);
    922 	return NULL;
    923 }
    924 
    925 __strong_alias(__dladdr,dladdr)
    926 int
    927 dladdr(const void *addr, Dl_info *info)
    928 {
    929 	const Obj_Entry *obj;
    930 	const Elf_Sym *def, *best_def;
    931 	void *symbol_addr;
    932 	unsigned long symoffset;
    933 
    934 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    935 	addr = _rtld_function_descriptor_function(addr);
    936 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    937 
    938 	obj = _rtld_obj_from_addr(addr);
    939 	if (obj == NULL) {
    940 		_rtld_error("No shared object contains address");
    941 		return 0;
    942 	}
    943 	info->dli_fname = obj->path;
    944 	info->dli_fbase = obj->mapbase;
    945 	info->dli_saddr = (void *)0;
    946 	info->dli_sname = NULL;
    947 
    948 	/*
    949 	 * Walk the symbol list looking for the symbol whose address is
    950 	 * closest to the address sent in.
    951 	 */
    952 	best_def = NULL;
    953 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
    954 		def = obj->symtab + symoffset;
    955 
    956 		/*
    957 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
    958 		 * SHN_COMMON.
    959 		 */
    960 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
    961 			continue;
    962 
    963 		/*
    964 		 * If the symbol is greater than the specified address, or if it
    965 		 * is further away from addr than the current nearest symbol,
    966 		 * then reject it.
    967 		 */
    968 		symbol_addr = obj->relocbase + def->st_value;
    969 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
    970 			continue;
    971 
    972 		/* Update our idea of the nearest symbol. */
    973 		info->dli_sname = obj->strtab + def->st_name;
    974 		info->dli_saddr = symbol_addr;
    975 		best_def = def;
    976 
    977 		/* Exact match? */
    978 		if (info->dli_saddr == addr)
    979 			break;
    980 	}
    981 
    982 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    983 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
    984 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
    985 		    best_def, 0);
    986 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    987 
    988 	return 1;
    989 }
    990 
    991 __strong_alias(__dlinfo,dlinfo)
    992 int
    993 dlinfo(void *handle, int req, void *v)
    994 {
    995 	const Obj_Entry *obj;
    996 	void *retaddr;
    997 
    998 	if (handle == RTLD_SELF) {
    999 #ifdef __powerpc__
   1000 		retaddr = hackish_return_address();
   1001 #else
   1002 		retaddr = __builtin_return_address(0);
   1003 #endif
   1004 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   1005 			_rtld_error("Cannot determine caller's shared object");
   1006 			return -1;
   1007 		}
   1008 	} else {
   1009 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   1010 			_rtld_error("Invalid handle");
   1011 			return -1;
   1012 		}
   1013 	}
   1014 
   1015 	switch (req) {
   1016 	case RTLD_DI_LINKMAP:
   1017 		{
   1018 		const struct link_map **map = v;
   1019 
   1020 		*map = &obj->linkmap;
   1021 		break;
   1022 		}
   1023 
   1024 	default:
   1025 		_rtld_error("Invalid request");
   1026 		return -1;
   1027 	}
   1028 
   1029 	return 0;
   1030 }
   1031 
   1032 /*
   1033  * Error reporting function.  Use it like printf.  If formats the message
   1034  * into a buffer, and sets things up so that the next call to dlerror()
   1035  * will return the message.
   1036  */
   1037 void
   1038 _rtld_error(const char *fmt,...)
   1039 {
   1040 	static char     buf[512];
   1041 	va_list         ap;
   1042 
   1043 	va_start(ap, fmt);
   1044 	xvsnprintf(buf, sizeof buf, fmt, ap);
   1045 	error_message = buf;
   1046 	va_end(ap);
   1047 }
   1048 
   1049 void
   1050 _rtld_debug_state(void)
   1051 {
   1052 
   1053 	/* do nothing */
   1054 }
   1055 
   1056 void
   1057 _rtld_linkmap_add(Obj_Entry *obj)
   1058 {
   1059 	struct link_map *l = &obj->linkmap;
   1060 	struct link_map *prev;
   1061 
   1062 	obj->linkmap.l_name = obj->path;
   1063 	obj->linkmap.l_addr = obj->relocbase;
   1064 	obj->linkmap.l_ld = obj->dynamic;
   1065 #ifdef __mips__
   1066 	/* XXX This field is not standard and will be removed eventually. */
   1067 	obj->linkmap.l_offs = obj->relocbase;
   1068 #endif
   1069 
   1070 	if (_rtld_debug.r_map == NULL) {
   1071 		_rtld_debug.r_map = l;
   1072 		return;
   1073 	}
   1074 
   1075 	/*
   1076 	 * Scan to the end of the list, but not past the entry for the
   1077 	 * dynamic linker, which we want to keep at the very end.
   1078 	 */
   1079 	for (prev = _rtld_debug.r_map;
   1080 	    prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
   1081 	    prev = prev->l_next);
   1082 
   1083 	l->l_prev = prev;
   1084 	l->l_next = prev->l_next;
   1085 	if (l->l_next != NULL)
   1086 		l->l_next->l_prev = l;
   1087 	prev->l_next = l;
   1088 }
   1089 
   1090 void
   1091 _rtld_linkmap_delete(Obj_Entry *obj)
   1092 {
   1093 	struct link_map *l = &obj->linkmap;
   1094 
   1095 	if (l->l_prev == NULL) {
   1096 		if ((_rtld_debug.r_map = l->l_next) != NULL)
   1097 			l->l_next->l_prev = NULL;
   1098 		return;
   1099 	}
   1100 	if ((l->l_prev->l_next = l->l_next) != NULL)
   1101 		l->l_next->l_prev = l->l_prev;
   1102 }
   1103 
   1104 static Obj_Entry *
   1105 _rtld_obj_from_addr(const void *addr)
   1106 {
   1107 	Obj_Entry *obj;
   1108 
   1109 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   1110 		if (addr < (void *) obj->mapbase)
   1111 			continue;
   1112 		if (addr < (void *) (obj->mapbase + obj->mapsize))
   1113 			return obj;
   1114 	}
   1115 	return NULL;
   1116 }
   1117 
   1118 static void
   1119 _rtld_objlist_clear(Objlist *list)
   1120 {
   1121 	while (!SIMPLEQ_EMPTY(list)) {
   1122 		Objlist_Entry* elm = SIMPLEQ_FIRST(list);
   1123 		SIMPLEQ_REMOVE_HEAD(list, link);
   1124 		xfree(elm);
   1125 	}
   1126 }
   1127 
   1128 static void
   1129 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
   1130 {
   1131 	Objlist_Entry *elm;
   1132 
   1133 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
   1134 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
   1135 		xfree(elm);
   1136 	}
   1137 }
   1138