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