Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.123.8.1
      1 /*	$NetBSD: rtld.c,v 1.123.8.1 2010/04/21 05:26:10 matt 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.123.8.1 2010/04/21 05:26:10 matt 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 int		_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 -relocabase so that
    235 	 * _rtld_objself.relocbase + _rtld_smy_zero.st_value == 0
    236 	 * This allows unresolved references to weak symbols to be computed
    237 	 * to value a value of 0.
    238 	 */
    239 	_rtld_sym_zero.st_value = -(uintptr_t)relocbase;
    240 
    241 	_rtld_digest_dynamic(_rtld_path, &_rtld_objself);
    242 	assert(!_rtld_objself.needed);
    243 #if !defined(__hppa__)
    244 	assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
    245 #else
    246 	_rtld_relocate_plt_objects(&_rtld_objself);
    247 #endif
    248 #if !defined(__mips__) && !defined(__hppa__)
    249 	assert(!_rtld_objself.pltgot);
    250 #endif
    251 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
    252 	/* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
    253 	assert(!_rtld_objself.textrel);
    254 #endif
    255 
    256 	_rtld_add_paths(execname, &_rtld_default_paths,
    257 	    RTLD_DEFAULT_LIBRARY_PATH);
    258 
    259 #ifdef RTLD_ARCH_SUBDIR
    260 	_rtld_add_paths(execname, &_rtld_default_paths,
    261 	    RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
    262 #endif
    263 
    264 	/*
    265 	 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
    266 	 */
    267 	_rtld_objlist = &_rtld_objself;
    268 
    269 	/* Make the object list empty again. */
    270 	_rtld_objlist = NULL;
    271 	_rtld_objtail = &_rtld_objlist;
    272 
    273 	_rtld_debug.r_brk = _rtld_debug_state;
    274 	_rtld_debug.r_state = RT_CONSISTENT;
    275 }
    276 
    277 /*
    278  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    279  * before the process exits.
    280  */
    281 static void
    282 _rtld_exit(void)
    283 {
    284 	dbg(("rtld_exit()"));
    285 
    286 	_rtld_call_fini_functions(1);
    287 }
    288 
    289 /*
    290  * Main entry point for dynamic linking.  The argument is the stack
    291  * pointer.  The stack is expected to be laid out as described in the
    292  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    293  * the stack pointer points to a word containing ARGC.  Following that
    294  * in the stack is a null-terminated sequence of pointers to argument
    295  * strings.  Then comes a null-terminated sequence of pointers to
    296  * environment strings.  Finally, there is a sequence of "auxiliary
    297  * vector" entries.
    298  *
    299  * This function returns the entry point for the main program, the dynamic
    300  * linker's exit procedure in sp[0], and a pointer to the main object in
    301  * sp[1].
    302  */
    303 Elf_Addr
    304 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
    305 {
    306 	const AuxInfo  *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
    307 	               *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
    308 		       *pAUX_ruid, *pAUX_rgid;
    309 	const AuxInfo  *pAUX_pagesz;
    310 	char          **env;
    311 	const AuxInfo  *aux;
    312 	const AuxInfo  *auxp;
    313 	Elf_Addr       *const osp = sp;
    314 	bool            bind_now = 0;
    315 	const char     *ld_bind_now;
    316 	const char    **argv;
    317 	const char     *execname;
    318 	long		argc;
    319 	const char **real___progname;
    320 	const Obj_Entry **real___mainprog_obj;
    321 	char ***real_environ;
    322 #if defined(RTLD_DEBUG)
    323 	int i = 0;
    324 #endif
    325 
    326 	/*
    327          * On entry, the dynamic linker itself has not been relocated yet.
    328          * Be very careful not to reference any global data until after
    329          * _rtld_init has returned.  It is OK to reference file-scope statics
    330          * and string constants, and to call static and global functions.
    331          */
    332 	/* Find the auxiliary vector on the stack. */
    333 	/* first Elf_Word reserved to address of exit routine */
    334 #if defined(RTLD_DEBUG)
    335 	debug = 1;
    336 	dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
    337 	    (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
    338 	dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
    339 	    &_DYNAMIC));
    340 	dbg(("_ctype_ is %p", _ctype_));
    341 #endif
    342 
    343 	sp += 2;		/* skip over return argument space */
    344 	argv = (const char **) &sp[1];
    345 	argc = *(long *)sp;
    346 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
    347 				 * terminator */
    348 	env = (char **) sp;
    349 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    350 #if defined(RTLD_DEBUG)
    351 		dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
    352 #endif
    353 	}
    354 	aux = (const AuxInfo *) sp;
    355 
    356 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
    357 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
    358 	pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
    359 	pAUX_pagesz = NULL;
    360 
    361 	execname = NULL;
    362 
    363 	/* Digest the auxiliary vector. */
    364 	for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
    365 		switch (auxp->a_type) {
    366 		case AT_BASE:
    367 			pAUX_base = auxp;
    368 			break;
    369 		case AT_ENTRY:
    370 			pAUX_entry = auxp;
    371 			break;
    372 		case AT_EXECFD:
    373 			pAUX_execfd = auxp;
    374 			break;
    375 		case AT_PHDR:
    376 			pAUX_phdr = auxp;
    377 			break;
    378 		case AT_PHENT:
    379 			pAUX_phent = auxp;
    380 			break;
    381 		case AT_PHNUM:
    382 			pAUX_phnum = auxp;
    383 			break;
    384 #ifdef AT_EUID
    385 		case AT_EUID:
    386 			pAUX_euid = auxp;
    387 			break;
    388 		case AT_RUID:
    389 			pAUX_ruid = auxp;
    390 			break;
    391 		case AT_EGID:
    392 			pAUX_egid = auxp;
    393 			break;
    394 		case AT_RGID:
    395 			pAUX_rgid = auxp;
    396 			break;
    397 #endif
    398 #ifdef AT_SUN_EXECNAME
    399 		case AT_SUN_EXECNAME:
    400 			execname = (const char *)(const void *)auxp->a_v;
    401 			break;
    402 #endif
    403 		case AT_PAGESZ:
    404 			pAUX_pagesz = auxp;
    405 			break;
    406 		}
    407 	}
    408 
    409 	/* Initialize and relocate ourselves. */
    410 	if (pAUX_base == NULL) {
    411 		_rtld_error("Bad pAUX_base");
    412 		_rtld_die();
    413 	}
    414 	assert(pAUX_pagesz != NULL);
    415 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
    416 	_rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
    417 
    418 	__progname = _rtld_objself.path;
    419 	environ = env;
    420 
    421 	_rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
    422 	    (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
    423 	    ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
    424 	    (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
    425 
    426 	ld_bind_now = getenv("LD_BIND_NOW");
    427 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
    428 		bind_now = true;
    429 	if (_rtld_trust) {
    430 #ifdef DEBUG
    431 		const char     *ld_debug = getenv("LD_DEBUG");
    432 #ifdef RTLD_DEBUG
    433 		debug = 0;
    434 #endif
    435 		if (ld_debug != NULL && *ld_debug != '\0')
    436 			debug = 1;
    437 #endif
    438 		_rtld_add_paths(execname, &_rtld_paths,
    439 		    getenv("LD_LIBRARY_PATH"));
    440 	} else {
    441 		execname = NULL;
    442 		if (unsetenv("LD_DEBUG") || unsetenv("LD_LIBRARY_PATH"))
    443 			_rtld_die();
    444 	}
    445 	_rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
    446 	    _PATH_LD_HINTS);
    447 	dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
    448 	     _rtld_objself.mapbase, _rtld_objself.relocbase));
    449 
    450 	/*
    451          * Load the main program, or process its program header if it is
    452          * already loaded.
    453          */
    454 	if (pAUX_execfd != NULL) {	/* Load the main program. */
    455 		int             fd = pAUX_execfd->a_v;
    456 		const char *obj_name = argv[0] ? argv[0] : "main program";
    457 		dbg(("loading main program"));
    458 		_rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
    459 		close(fd);
    460 		if (_rtld_objmain == NULL)
    461 			_rtld_die();
    462 	} else {		/* Main program already loaded. */
    463 		const Elf_Phdr *phdr;
    464 		int             phnum;
    465 		caddr_t         entry;
    466 
    467 		dbg(("processing main program's program header"));
    468 		assert(pAUX_phdr != NULL);
    469 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
    470 		assert(pAUX_phnum != NULL);
    471 		phnum = pAUX_phnum->a_v;
    472 		assert(pAUX_phent != NULL);
    473 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
    474 		assert(pAUX_entry != NULL);
    475 		entry = (caddr_t) pAUX_entry->a_v;
    476 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    477 		_rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
    478 		    "main program");
    479 		_rtld_objmain->pathlen = strlen(_rtld_objmain->path);
    480 	}
    481 
    482 	_rtld_objmain->mainprog = true;
    483 
    484 	/*
    485 	 * Get the actual dynamic linker pathname from the executable if
    486 	 * possible.  (It should always be possible.)  That ensures that
    487 	 * gdb will find the right dynamic linker even if a non-standard
    488 	 * one is being used.
    489 	 */
    490 	if (_rtld_objmain->interp != NULL &&
    491 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
    492 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
    493 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
    494 
    495 	_rtld_digest_dynamic(execname, _rtld_objmain);
    496 
    497 	/* Link the main program into the list of objects. */
    498 	*_rtld_objtail = _rtld_objmain;
    499 	_rtld_objtail = &_rtld_objmain->next;
    500 
    501 	_rtld_linkmap_add(_rtld_objmain);
    502 	_rtld_linkmap_add(&_rtld_objself);
    503 
    504 	++_rtld_objmain->refcount;
    505 	_rtld_objmain->mainref = 1;
    506 	_rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
    507 
    508 	if (_rtld_trust) {
    509 		/*
    510 		 * Pre-load user-specified objects after the main program
    511 		 * but before any shared object dependencies.
    512 		 */
    513 		dbg(("preloading objects"));
    514 		if (_rtld_preload(getenv("LD_PRELOAD")) == -1)
    515 			_rtld_die();
    516 	} else
    517 		if (unsetenv("LD_PRELOAD"))
    518 			_rtld_die();
    519 
    520 	dbg(("loading needed objects"));
    521 	if (_rtld_load_needed_objects(_rtld_objmain, RTLD_MAIN) == -1)
    522 		_rtld_die();
    523 
    524 	dbg(("relocating objects"));
    525 	if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
    526 		_rtld_die();
    527 
    528 	dbg(("doing copy relocations"));
    529 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
    530 		_rtld_die();
    531 
    532 	/*
    533 	 * Set the __progname,  environ and, __mainprog_obj before
    534 	 * calling anything that might use them.
    535 	 */
    536 	real___progname = _rtld_objmain_sym("__progname");
    537 	if (real___progname) {
    538 		if (argv[0] != NULL) {
    539 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
    540 				(*real___progname) = argv[0];
    541 			else
    542 				(*real___progname)++;
    543 		} else {
    544 			(*real___progname) = NULL;
    545 		}
    546 	}
    547 	real_environ = _rtld_objmain_sym("environ");
    548 	if (real_environ)
    549 		*real_environ = environ;
    550 	/*
    551 	 * Set __mainprog_obj for old binaries.
    552 	 */
    553 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
    554 	if (real___mainprog_obj)
    555 		*real___mainprog_obj = _rtld_objmain;
    556 
    557 	dbg(("calling _init functions"));
    558 	_rtld_call_init_functions();
    559 
    560 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
    561 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
    562 
    563 	/*
    564 	 * Return with the entry point and the exit procedure in at the top
    565 	 * of stack.
    566 	 */
    567 
    568 	_rtld_debug_state();	/* say hello to gdb! */
    569 
    570 	((void **) osp)[0] = _rtld_exit;
    571 	((void **) osp)[1] = _rtld_objmain;
    572 	return (Elf_Addr) _rtld_objmain->entry;
    573 }
    574 
    575 void
    576 _rtld_die(void)
    577 {
    578 	const char *msg = dlerror();
    579 
    580 	if (msg == NULL)
    581 		msg = "Fatal error";
    582 	xerrx(1, "%s", msg);
    583 }
    584 
    585 static Obj_Entry *
    586 _rtld_dlcheck(void *handle)
    587 {
    588 	Obj_Entry *obj;
    589 
    590 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    591 		if (obj == (Obj_Entry *) handle)
    592 			break;
    593 
    594 	if (obj == NULL || obj->dl_refcount == 0) {
    595 		xwarnx("Invalid shared object handle %p", handle);
    596 		return NULL;
    597 	}
    598 	return obj;
    599 }
    600 
    601 static void
    602 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
    603 {
    604 	Needed_Entry* elm;
    605 
    606 	/* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
    607 
    608 	if (obj->init_done)
    609 		return;
    610 	obj->init_done = 1;
    611 
    612 	for (elm = obj->needed; elm != NULL; elm = elm->next) {
    613 		if (elm->obj != NULL) {
    614 			_rtld_initlist_visit(list, elm->obj, rev);
    615 		}
    616 	}
    617 
    618 	if (rev) {
    619 		_rtld_objlist_push_head(list, obj);
    620 	} else {
    621 		_rtld_objlist_push_tail(list, obj);
    622 	}
    623 }
    624 
    625 static void
    626 _rtld_initlist_tsort(Objlist* list, int rev)
    627 {
    628 	dbg(("_rtld_initlist_tsort"));
    629 
    630 	Obj_Entry* obj;
    631 
    632 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    633 		obj->init_done = 0;
    634 	}
    635 
    636 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    637 		_rtld_initlist_visit(list, obj, rev);
    638 	}
    639 }
    640 
    641 static void
    642 _rtld_init_dag(Obj_Entry *root)
    643 {
    644 
    645 	_rtld_init_dag1(root, root);
    646 }
    647 
    648 static void
    649 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
    650 {
    651 	const Needed_Entry *needed;
    652 
    653 	if (!obj->mainref) {
    654 		if (_rtld_objlist_find(&obj->dldags, root))
    655 			return;
    656 		rdbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
    657 		    root->path));
    658 		_rtld_objlist_push_tail(&obj->dldags, root);
    659 		_rtld_objlist_push_tail(&root->dagmembers, obj);
    660 	}
    661 	for (needed = obj->needed; needed != NULL; needed = needed->next)
    662 		if (needed->obj != NULL)
    663 			_rtld_init_dag1(root, needed->obj);
    664 }
    665 
    666 /*
    667  * Note, this is called only for objects loaded by dlopen().
    668  */
    669 static void
    670 _rtld_unload_object(Obj_Entry *root, bool do_fini_funcs)
    671 {
    672 
    673 	_rtld_unref_dag(root);
    674 	if (root->refcount == 0) { /* We are finished with some objects. */
    675 		Obj_Entry *obj;
    676 		Obj_Entry **linkp;
    677 		Objlist_Entry *elm;
    678 
    679 		/* Finalize objects that are about to be unmapped. */
    680 		if (do_fini_funcs)
    681 			_rtld_call_fini_functions(0);
    682 
    683 		/* Remove the DAG from all objects' DAG lists. */
    684 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
    685 			_rtld_objlist_remove(&elm->obj->dldags, root);
    686 
    687 		/* Remove the DAG from the RTLD_GLOBAL list. */
    688 		if (root->globalref) {
    689 			root->globalref = 0;
    690 			_rtld_objlist_remove(&_rtld_list_global, root);
    691 		}
    692 
    693 		/* Unmap all objects that are no longer referenced. */
    694 		linkp = &_rtld_objlist->next;
    695 		while ((obj = *linkp) != NULL) {
    696 			if (obj->refcount == 0) {
    697 #ifdef RTLD_DEBUG
    698 				dbg(("unloading \"%s\"", obj->path));
    699 #endif
    700 				if (obj->ehdr != MAP_FAILED)
    701 					munmap(obj->ehdr, _rtld_pagesz);
    702 				munmap(obj->mapbase, obj->mapsize);
    703 				_rtld_objlist_remove(&_rtld_list_global, obj);
    704 				_rtld_linkmap_delete(obj);
    705 				*linkp = obj->next;
    706 				_rtld_obj_free(obj);
    707 			} else
    708 				linkp = &obj->next;
    709 		}
    710 		_rtld_objtail = linkp;
    711 	}
    712 }
    713 
    714 static void
    715 _rtld_unref_dag(Obj_Entry *root)
    716 {
    717 
    718 	assert(root);
    719 	assert(root->refcount != 0);
    720 	--root->refcount;
    721 	if (root->refcount == 0) {
    722 		const Needed_Entry *needed;
    723 
    724 		for (needed = root->needed; needed != NULL;
    725 		     needed = needed->next) {
    726 			if (needed->obj != NULL)
    727 				_rtld_unref_dag(needed->obj);
    728 		}
    729 	}
    730 }
    731 
    732 __strong_alias(__dlclose,dlclose)
    733 int
    734 dlclose(void *handle)
    735 {
    736 	Obj_Entry *root = _rtld_dlcheck(handle);
    737 
    738 	if (root == NULL)
    739 		return -1;
    740 
    741 	_rtld_debug.r_state = RT_DELETE;
    742 	_rtld_debug_state();
    743 
    744 	--root->dl_refcount;
    745 	_rtld_unload_object(root, true);
    746 
    747 	_rtld_debug.r_state = RT_CONSISTENT;
    748 	_rtld_debug_state();
    749 
    750 	return 0;
    751 }
    752 
    753 __strong_alias(__dlerror,dlerror)
    754 char *
    755 dlerror(void)
    756 {
    757 	char *msg = error_message;
    758 
    759 	error_message = NULL;
    760 	return msg;
    761 }
    762 
    763 __strong_alias(__dlopen,dlopen)
    764 void *
    765 dlopen(const char *name, int mode)
    766 {
    767 	Obj_Entry **old_obj_tail = _rtld_objtail;
    768 	Obj_Entry *obj = NULL;
    769 
    770 	_rtld_debug.r_state = RT_ADD;
    771 	_rtld_debug_state();
    772 
    773 	if (name == NULL) {
    774 		obj = _rtld_objmain;
    775 		obj->refcount++;
    776 	} else
    777 		obj = _rtld_load_library(name, _rtld_objmain, mode);
    778 
    779 	if (obj != NULL) {
    780 		++obj->dl_refcount;
    781 		if (*old_obj_tail != NULL) {	/* We loaded something new. */
    782 			assert(*old_obj_tail == obj);
    783 
    784 			if (_rtld_load_needed_objects(obj, mode) == -1 ||
    785 			    (_rtld_init_dag(obj),
    786 			    _rtld_relocate_objects(obj,
    787 			    ((mode & 3) == RTLD_NOW))) == -1) {
    788 				_rtld_unload_object(obj, false);
    789 				obj->dl_refcount--;
    790 				obj = NULL;
    791 			} else {
    792 				_rtld_call_init_functions();
    793 			}
    794 		}
    795 	}
    796 	_rtld_debug.r_state = RT_CONSISTENT;
    797 	_rtld_debug_state();
    798 
    799 	return obj;
    800 }
    801 
    802 /*
    803  * Find a symbol in the main program.
    804  */
    805 void *
    806 _rtld_objmain_sym(const char *name)
    807 {
    808 	unsigned long hash;
    809 	const Elf_Sym *def;
    810 	const Obj_Entry *obj;
    811 
    812 	hash = _rtld_elf_hash(name);
    813 	obj = _rtld_objmain;
    814 
    815 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false);
    816 
    817 	if (def != NULL)
    818 		return obj->relocbase + def->st_value;
    819 	return(NULL);
    820 }
    821 
    822 #ifdef __powerpc__
    823 static void *
    824 hackish_return_address(void)
    825 {
    826 	return __builtin_return_address(1);
    827 }
    828 #endif
    829 
    830 __strong_alias(__dlsym,dlsym)
    831 void *
    832 dlsym(void *handle, const char *name)
    833 {
    834 	const Obj_Entry *obj;
    835 	unsigned long hash;
    836 	const Elf_Sym *def;
    837 	const Obj_Entry *defobj;
    838 	void *retaddr;
    839 
    840 	hash = _rtld_elf_hash(name);
    841 	def = NULL;
    842 	defobj = NULL;
    843 
    844 	switch ((intptr_t)handle) {
    845 	case (intptr_t)NULL:
    846 	case (intptr_t)RTLD_NEXT:
    847 	case (intptr_t)RTLD_DEFAULT:
    848 	case (intptr_t)RTLD_SELF:
    849 #ifdef __powerpc__
    850 		retaddr = hackish_return_address();
    851 #else
    852 		retaddr = __builtin_return_address(0);
    853 #endif
    854 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
    855 			_rtld_error("Cannot determine caller's shared object");
    856 			return NULL;
    857 		}
    858 
    859 		switch ((intptr_t)handle) {
    860 		case (intptr_t)NULL:	 /* Just the caller's shared object. */
    861 			def = _rtld_symlook_obj(name, hash, obj, false);
    862 			defobj = obj;
    863 			break;
    864 
    865 		case (intptr_t)RTLD_NEXT:	/* Objects after callers */
    866 			obj = obj->next;
    867 			/*FALLTHROUGH*/
    868 
    869 		case (intptr_t)RTLD_SELF:	/* Caller included */
    870 			for (; obj; obj = obj->next) {
    871 				if ((def = _rtld_symlook_obj(name, hash, obj,
    872 				    false)) != NULL) {
    873 					defobj = obj;
    874 					break;
    875 				}
    876 			}
    877 			break;
    878 
    879 		case (intptr_t)RTLD_DEFAULT:
    880 			def = _rtld_symlook_default(name, hash, obj, &defobj,
    881 			    false);
    882 			break;
    883 
    884 		default:
    885 			abort();
    886 		}
    887 		break;
    888 
    889 	default:
    890 		if ((obj = _rtld_dlcheck(handle)) == NULL)
    891 			return NULL;
    892 
    893 		if (obj->mainprog) {
    894 			/* Search main program and all libraries loaded by it */
    895 			def = _rtld_symlook_list(name, hash, &_rtld_list_main,
    896 			    &defobj, false);
    897 		} else {
    898 			Needed_Entry fake;
    899 
    900 			/* Search the object and all the libraries loaded by it. */
    901 			fake.next = NULL;
    902 			fake.obj = (Obj_Entry *)obj;
    903 			fake.name = 0;
    904 			def = _rtld_symlook_needed(name, hash, &fake, &defobj,
    905 			    false);
    906 		}
    907 		break;
    908 	}
    909 
    910 	if (def != NULL) {
    911 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    912 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
    913 			return (void *)_rtld_function_descriptor_alloc(defobj,
    914 			    def, 0);
    915 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    916 		return defobj->relocbase + def->st_value;
    917 	}
    918 
    919 	_rtld_error("Undefined symbol \"%s\"", name);
    920 	return NULL;
    921 }
    922 
    923 __strong_alias(__dladdr,dladdr)
    924 int
    925 dladdr(const void *addr, Dl_info *info)
    926 {
    927 	const Obj_Entry *obj;
    928 	const Elf_Sym *def, *best_def;
    929 	void *symbol_addr;
    930 	unsigned long symoffset;
    931 
    932 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    933 	addr = _rtld_function_descriptor_function(addr);
    934 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    935 
    936 	obj = _rtld_obj_from_addr(addr);
    937 	if (obj == NULL) {
    938 		_rtld_error("No shared object contains address");
    939 		return 0;
    940 	}
    941 	info->dli_fname = obj->path;
    942 	info->dli_fbase = obj->mapbase;
    943 	info->dli_saddr = (void *)0;
    944 	info->dli_sname = NULL;
    945 
    946 	/*
    947 	 * Walk the symbol list looking for the symbol whose address is
    948 	 * closest to the address sent in.
    949 	 */
    950 	best_def = NULL;
    951 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
    952 		def = obj->symtab + symoffset;
    953 
    954 		/*
    955 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
    956 		 * SHN_COMMON.
    957 		 */
    958 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
    959 			continue;
    960 
    961 		/*
    962 		 * If the symbol is greater than the specified address, or if it
    963 		 * is further away from addr than the current nearest symbol,
    964 		 * then reject it.
    965 		 */
    966 		symbol_addr = obj->relocbase + def->st_value;
    967 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
    968 			continue;
    969 
    970 		/* Update our idea of the nearest symbol. */
    971 		info->dli_sname = obj->strtab + def->st_name;
    972 		info->dli_saddr = symbol_addr;
    973 		best_def = def;
    974 
    975 		/* Exact match? */
    976 		if (info->dli_saddr == addr)
    977 			break;
    978 	}
    979 
    980 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    981 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
    982 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
    983 		    best_def, 0);
    984 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    985 
    986 	return 1;
    987 }
    988 
    989 __strong_alias(__dlinfo,dlinfo)
    990 int
    991 dlinfo(void *handle, int req, void *v)
    992 {
    993 	const Obj_Entry *obj;
    994 	void *retaddr;
    995 
    996 	if (handle == RTLD_SELF) {
    997 #ifdef __powerpc__
    998 		retaddr = hackish_return_address();
    999 #else
   1000 		retaddr = __builtin_return_address(0);
   1001 #endif
   1002 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   1003 			_rtld_error("Cannot determine caller's shared object");
   1004 			return -1;
   1005 		}
   1006 	} else {
   1007 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   1008 			_rtld_error("Invalid handle");
   1009 			return -1;
   1010 		}
   1011 	}
   1012 
   1013 	switch (req) {
   1014 	case RTLD_DI_LINKMAP:
   1015 		{
   1016 		const struct link_map **map = v;
   1017 
   1018 		*map = &obj->linkmap;
   1019 		break;
   1020 		}
   1021 
   1022 	default:
   1023 		_rtld_error("Invalid request");
   1024 		return -1;
   1025 	}
   1026 
   1027 	return 0;
   1028 }
   1029 
   1030 /*
   1031  * Error reporting function.  Use it like printf.  If formats the message
   1032  * into a buffer, and sets things up so that the next call to dlerror()
   1033  * will return the message.
   1034  */
   1035 void
   1036 _rtld_error(const char *fmt,...)
   1037 {
   1038 	static char     buf[512];
   1039 	va_list         ap;
   1040 
   1041 	va_start(ap, fmt);
   1042 	xvsnprintf(buf, sizeof buf, fmt, ap);
   1043 	error_message = buf;
   1044 	va_end(ap);
   1045 }
   1046 
   1047 void
   1048 _rtld_debug_state(void)
   1049 {
   1050 
   1051 	/* do nothing */
   1052 }
   1053 
   1054 void
   1055 _rtld_linkmap_add(Obj_Entry *obj)
   1056 {
   1057 	struct link_map *l = &obj->linkmap;
   1058 	struct link_map *prev;
   1059 
   1060 	obj->linkmap.l_name = obj->path;
   1061 	obj->linkmap.l_addr = obj->relocbase;
   1062 	obj->linkmap.l_ld = obj->dynamic;
   1063 #ifdef __mips__
   1064 	/* XXX This field is not standard and will be removed eventually. */
   1065 	obj->linkmap.l_offs = obj->relocbase;
   1066 #endif
   1067 
   1068 	if (_rtld_debug.r_map == NULL) {
   1069 		_rtld_debug.r_map = l;
   1070 		return;
   1071 	}
   1072 
   1073 	/*
   1074 	 * Scan to the end of the list, but not past the entry for the
   1075 	 * dynamic linker, which we want to keep at the very end.
   1076 	 */
   1077 	for (prev = _rtld_debug.r_map;
   1078 	    prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
   1079 	    prev = prev->l_next);
   1080 
   1081 	l->l_prev = prev;
   1082 	l->l_next = prev->l_next;
   1083 	if (l->l_next != NULL)
   1084 		l->l_next->l_prev = l;
   1085 	prev->l_next = l;
   1086 }
   1087 
   1088 void
   1089 _rtld_linkmap_delete(Obj_Entry *obj)
   1090 {
   1091 	struct link_map *l = &obj->linkmap;
   1092 
   1093 	if (l->l_prev == NULL) {
   1094 		if ((_rtld_debug.r_map = l->l_next) != NULL)
   1095 			l->l_next->l_prev = NULL;
   1096 		return;
   1097 	}
   1098 	if ((l->l_prev->l_next = l->l_next) != NULL)
   1099 		l->l_next->l_prev = l->l_prev;
   1100 }
   1101 
   1102 static Obj_Entry *
   1103 _rtld_obj_from_addr(const void *addr)
   1104 {
   1105 	Obj_Entry *obj;
   1106 
   1107 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   1108 		if (addr < (void *) obj->mapbase)
   1109 			continue;
   1110 		if (addr < (void *) (obj->mapbase + obj->mapsize))
   1111 			return obj;
   1112 	}
   1113 	return NULL;
   1114 }
   1115 
   1116 static void
   1117 _rtld_objlist_clear(Objlist *list)
   1118 {
   1119 	while (!SIMPLEQ_EMPTY(list)) {
   1120 		Objlist_Entry* elm = SIMPLEQ_FIRST(list);
   1121 		SIMPLEQ_REMOVE_HEAD(list, link);
   1122 		xfree(elm);
   1123 	}
   1124 }
   1125 
   1126 static void
   1127 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
   1128 {
   1129 	Objlist_Entry *elm;
   1130 
   1131 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
   1132 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
   1133 		xfree(elm);
   1134 	}
   1135 }
   1136