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