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