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