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