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