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