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