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