Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.67
      1 /*	$NetBSD: rtld.c,v 1.67 2002/09/23 23:56:48 mycroft 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] ? xstrdup(argv[0]) :
    422 		    xstrdup("main program"), fd, NULL);
    423 		close(fd);
    424 		if (_rtld_objmain == NULL)
    425 			_rtld_die();
    426 	} else {		/* Main program already loaded. */
    427 		const Elf_Phdr *phdr;
    428 		int             phnum;
    429 		caddr_t         entry;
    430 
    431 		dbg(("processing main program's program header"));
    432 		assert(pAUX_phdr != NULL);
    433 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
    434 		assert(pAUX_phnum != NULL);
    435 		phnum = pAUX_phnum->a_v;
    436 		assert(pAUX_phent != NULL);
    437 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
    438 		assert(pAUX_entry != NULL);
    439 		entry = (caddr_t) pAUX_entry->a_v;
    440 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    441 	}
    442 
    443 	_rtld_objmain->mainprog = true;
    444 
    445 	/*
    446 	 * Get the actual dynamic linker pathname from the executable if
    447 	 * possible.  (It should always be possible.)  That ensures that
    448 	 * gdb will find the right dynamic linker even if a non-standard
    449 	 * one is being used.
    450 	 */
    451 	if (_rtld_objmain->interp != NULL &&
    452 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0) {
    453 		free(_rtld_objself.path);
    454 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
    455 	}
    456 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
    457 
    458 	_rtld_digest_dynamic(_rtld_objmain);
    459 
    460 	_rtld_linkmap_add(_rtld_objmain);
    461 	_rtld_linkmap_add(&_rtld_objself);
    462 
    463 	/* Link the main program into the list of objects. */
    464 	*_rtld_objtail = _rtld_objmain;
    465 	_rtld_objtail = &_rtld_objmain->next;
    466 	++_rtld_objmain->refcount;
    467 
    468 	/* Initialize a fake symbol for resolving undefined weak references. */
    469 	_rtld_sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
    470 	_rtld_sym_zero.st_shndx = SHN_ABS;
    471 
    472 	/*
    473 	 * Pre-load user-specified objects after the main program but before
    474 	 * any shared object dependencies.
    475 	 */
    476 	dbg(("preloading objects"));
    477 	if (_rtld_trust && _rtld_preload(getenv("LD_PRELOAD")) == -1)
    478 		_rtld_die();
    479 
    480 	dbg(("loading needed objects"));
    481 	if (_rtld_load_needed_objects(_rtld_objmain, RTLD_GLOBAL) == -1)
    482 		_rtld_die();
    483 
    484 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next)
    485 		_rtld_objlist_add(&_rtld_list_main, obj);
    486 
    487 	dbg(("relocating objects"));
    488 	if (_rtld_relocate_objects(_rtld_objmain, bind_now, false) == -1)
    489 		_rtld_die();
    490 
    491 	dbg(("doing copy relocations"));
    492 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
    493 		_rtld_die();
    494 
    495 	/*
    496 	 * Set the __progname,  environ and, __mainprog_obj before
    497 	 * calling anything that might use them.
    498 	 */
    499 	real___progname = _rtld_objmain_sym("__progname");
    500 	if (real___progname) {
    501 		if (argv[0] != NULL) {
    502 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
    503 				(*real___progname) = argv[0];
    504 			else
    505 				(*real___progname)++;
    506 		} else {
    507 			(*real___progname) = NULL;
    508 		}
    509 	}
    510 	real_environ = _rtld_objmain_sym("environ");
    511 	if (real_environ)
    512 		*real_environ = environ;
    513 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
    514 	if (real___mainprog_obj)
    515 		*real___mainprog_obj = _rtld_objmain;
    516 
    517 	dbg(("calling _init functions"));
    518 	_rtld_call_init_functions(_rtld_objmain->next);
    519 
    520 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
    521 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
    522 
    523 	/*
    524 	 * Return with the entry point and the exit procedure in at the top
    525 	 * of stack.
    526 	 */
    527 
    528 	_rtld_debug_state();	/* say hello to gdb! */
    529 
    530 	((void **) osp)[0] = _rtld_exit;
    531 	((void **) osp)[1] = _rtld_objmain;
    532 	return (Elf_Addr) _rtld_objmain->entry;
    533 }
    534 
    535 void
    536 _rtld_die()
    537 {
    538 	const char *msg = _rtld_dlerror();
    539 
    540 	if (msg == NULL)
    541 		msg = "Fatal error";
    542 	xerrx(1, "%s", msg);
    543 }
    544 
    545 static Obj_Entry *
    546 _rtld_dlcheck(handle)
    547 	void *handle;
    548 {
    549 	Obj_Entry *obj;
    550 
    551 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    552 		if (obj == (Obj_Entry *) handle)
    553 			break;
    554 
    555 	if (obj == NULL || obj->dl_refcount == 0) {
    556 		xwarnx("Invalid shared object handle %p", handle);
    557 		return NULL;
    558 	}
    559 	return obj;
    560 }
    561 
    562 static void
    563 _rtld_init_dag(root)
    564 	Obj_Entry *root;
    565 {
    566 	_rtld_init_dag1(root, root);
    567 }
    568 
    569 static void
    570 _rtld_init_dag1(root, obj)
    571 	Obj_Entry *root;
    572 	Obj_Entry *obj;
    573 {
    574 	const Needed_Entry *needed;
    575 
    576 	_rtld_objlist_add(&obj->dldags, root);
    577 	_rtld_objlist_add(&root->dagmembers, obj);
    578 	for (needed = obj->needed; needed != NULL; needed = needed->next)
    579 		if (needed->obj != NULL)
    580 			_rtld_init_dag1(root, needed->obj);
    581 }
    582 
    583 /*
    584  * Note, this is called only for objects loaded by dlopen().
    585  */
    586 static void
    587 _rtld_unload_object(root, do_fini_funcs)
    588 	Obj_Entry *root;
    589 	bool do_fini_funcs;
    590 {
    591 	_rtld_unref_dag(root);
    592 	if (root->refcount == 0) { /* We are finished with some objects. */
    593 		Obj_Entry *obj;
    594 		Obj_Entry **linkp;
    595 		Objlist_Entry *elm;
    596 
    597 		/* Finalize objects that are about to be unmapped. */
    598 		if (do_fini_funcs)
    599 			for (obj = _rtld_objlist->next;  obj != NULL;  obj = obj->next)
    600 				if (obj->refcount == 0 && obj->fini != NULL)
    601 					(*obj->fini)();
    602 
    603 		/* Remove the DAG from all objects' DAG lists. */
    604 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
    605 			_rtld_objlist_remove(&elm->obj->dldags, root);
    606 
    607 		/* Remove the DAG from the RTLD_GLOBAL list. */
    608 		_rtld_objlist_remove(&_rtld_list_global, root);
    609 
    610 		/* Unmap all objects that are no longer referenced. */
    611 		linkp = &_rtld_objlist->next;
    612 		while ((obj = *linkp) != NULL) {
    613 			if (obj->refcount == 0) {
    614 #ifdef RTLD_DEBUG
    615 				dbg(("unloading \"%s\"", obj->path));
    616 #endif
    617 				munmap(obj->mapbase, obj->mapsize);
    618 				_rtld_objlist_remove(&_rtld_list_global, obj);
    619 				_rtld_linkmap_delete(obj);
    620 				*linkp = obj->next;
    621 				_rtld_obj_free(obj);
    622 			} else
    623 				linkp = &obj->next;
    624 		}
    625 		_rtld_objtail = linkp;
    626 	}
    627 }
    628 
    629 static void
    630 _rtld_unref_dag(root)
    631 	Obj_Entry *root;
    632 {
    633 	assert(root);
    634 	assert(root->refcount != 0);
    635 	--root->refcount;
    636 	if (root->refcount == 0) {
    637 		const Needed_Entry *needed;
    638 
    639 		for (needed = root->needed; needed != NULL;
    640 		     needed = needed->next) {
    641 			if (needed->obj != NULL)
    642 				_rtld_unref_dag(needed->obj);
    643 		}
    644 	}
    645 }
    646 
    647 int
    648 _rtld_dlclose(handle)
    649 	void *handle;
    650 {
    651 	Obj_Entry *root = _rtld_dlcheck(handle);
    652 
    653 	if (root == NULL)
    654 		return -1;
    655 
    656 	_rtld_debug.r_state = RT_DELETE;
    657 	_rtld_debug_state();
    658 
    659 	--root->dl_refcount;
    660 	_rtld_unload_object(root, true);
    661 
    662 	_rtld_debug.r_state = RT_CONSISTENT;
    663 	_rtld_debug_state();
    664 
    665 	return 0;
    666 }
    667 
    668 char *
    669 _rtld_dlerror()
    670 {
    671 	char *msg = error_message;
    672 	error_message = NULL;
    673 	return msg;
    674 }
    675 
    676 void *
    677 _rtld_dlopen(name, mode)
    678 	const char *name;
    679 	int mode;
    680 {
    681 	Obj_Entry **old_obj_tail = _rtld_objtail;
    682 	Obj_Entry *obj = NULL;
    683 
    684 	_rtld_debug.r_state = RT_ADD;
    685 	_rtld_debug_state();
    686 
    687 	if (name == NULL) {
    688 		obj = _rtld_objmain;
    689 		obj->refcount++;
    690 	} else
    691 		obj = _rtld_load_library(name, _rtld_objmain, mode);
    692 
    693 	if (obj != NULL) {
    694 		++obj->dl_refcount;
    695 		if (*old_obj_tail != NULL) {	/* We loaded something new. */
    696 			assert(*old_obj_tail == obj);
    697 
    698 			if (_rtld_load_needed_objects(obj, mode) == -1 ||
    699 			    (_rtld_init_dag(obj),
    700 			    _rtld_relocate_objects(obj,
    701 			    ((mode & 3) == RTLD_NOW), false)) == -1) {
    702 				_rtld_unload_object(obj, false);
    703 				obj->dl_refcount--;
    704 				obj = NULL;
    705 			} else
    706 				_rtld_call_init_functions(obj);
    707 		}
    708 	}
    709 	_rtld_debug.r_state = RT_CONSISTENT;
    710 	_rtld_debug_state();
    711 
    712 	return obj;
    713 }
    714 
    715 /*
    716  * Find a symbol in the main program.
    717  */
    718 void *
    719 _rtld_objmain_sym(name)
    720 	const char *name;
    721 {
    722 	unsigned long hash;
    723 	const Elf_Sym *def;
    724 	const Obj_Entry *obj;
    725 
    726 	hash = _rtld_elf_hash(name);
    727 	obj = _rtld_objmain;
    728 
    729 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj);
    730 
    731 	if (def != NULL)
    732 		return obj->relocbase + def->st_value;
    733 	return(NULL);
    734 }
    735 
    736 void *
    737 _rtld_dlsym(handle, name)
    738 	void *handle;
    739 	const char *name;
    740 {
    741 	const Obj_Entry *obj;
    742 	unsigned long hash;
    743 	const Elf_Sym *def;
    744 	const Obj_Entry *defobj;
    745 
    746 	hash = _rtld_elf_hash(name);
    747 	def = NULL;
    748 	defobj = NULL;
    749 
    750 	if (handle == NULL
    751 #if 0
    752 	    || handle == RTLD_NEXT
    753 #endif
    754 	) {
    755 		void *retaddr;
    756 
    757 		retaddr = __builtin_return_address(0); /* __GNUC__ only */
    758 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
    759 			_rtld_error("Cannot determine caller's shared object");
    760 			return NULL;
    761 		}
    762 		if (handle == NULL) { /* Just the caller's shared object. */
    763 			def = _rtld_symlook_obj(name, hash, obj);
    764 			defobj = obj;
    765 		} else { /* All the shared objects after the caller's */
    766 			while ((obj = obj->next) != NULL) {
    767 				if ((def = _rtld_symlook_obj(name, hash, obj)) != NULL) {
    768 					defobj = obj;
    769 					break;
    770 				}
    771 			}
    772 		}
    773 	} else {
    774 		if ((obj = _rtld_dlcheck(handle)) == NULL)
    775 			return NULL;
    776 
    777 		if (obj->mainprog) {
    778 			/* Search main program and all libraries loaded by it. */
    779 			def = _rtld_symlook_list(name, hash, &_rtld_list_main, &defobj);
    780 		} else {
    781 			/*
    782 			 * XXX - This isn't correct.  The search should include the whole
    783 			 * DAG rooted at the given object.
    784 			 */
    785 			def = _rtld_symlook_obj(name, hash, obj);
    786 			defobj = obj;
    787 		}
    788 	}
    789 
    790 	if (def != NULL) {
    791 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    792 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
    793 			return (void *)_rtld_function_descriptor_alloc(defobj,
    794 			    def, 0);
    795 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    796 		return defobj->relocbase + def->st_value;
    797 	}
    798 
    799 	_rtld_error("Undefined symbol \"%s\"", name);
    800 	return NULL;
    801 }
    802 
    803 int
    804 _rtld_dladdr(addr, info)
    805 	const void *addr;
    806 	Dl_info *info;
    807 {
    808 	const Obj_Entry *obj;
    809 	const Elf_Sym *def, *best_def;
    810 	void *symbol_addr;
    811 	unsigned long symoffset;
    812 
    813 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    814 	addr = _rtld_function_descriptor_function(addr);
    815 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    816 
    817 	obj = _rtld_obj_from_addr(addr);
    818 	if (obj == NULL) {
    819 		_rtld_error("No shared object contains address");
    820 		return 0;
    821 	}
    822 	info->dli_fname = obj->path;
    823 	info->dli_fbase = obj->mapbase;
    824 	info->dli_saddr = (void *)0;
    825 	info->dli_sname = NULL;
    826 
    827 	/*
    828 	 * Walk the symbol list looking for the symbol whose address is
    829 	 * closest to the address sent in.
    830 	 */
    831 	best_def = NULL;
    832 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
    833 		def = obj->symtab + symoffset;
    834 
    835 		/*
    836 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
    837 		 * SHN_COMMON.
    838 		 */
    839 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
    840 			continue;
    841 
    842 		/*
    843 		 * If the symbol is greater than the specified address, or if it
    844 		 * is further away from addr than the current nearest symbol,
    845 		 * then reject it.
    846 		 */
    847 		symbol_addr = obj->relocbase + def->st_value;
    848 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
    849 			continue;
    850 
    851 		/* Update our idea of the nearest symbol. */
    852 		info->dli_sname = obj->strtab + def->st_name;
    853 		info->dli_saddr = symbol_addr;
    854 		best_def = def;
    855 
    856 		/* Exact match? */
    857 		if (info->dli_saddr == addr)
    858 			break;
    859 	}
    860 
    861 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    862 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
    863 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
    864 		    best_def, 0);
    865 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    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 _rtld_error(const char *fmt,...)
    877 {
    878 	static char     buf[512];
    879 	va_list         ap;
    880 
    881 	va_start(ap, fmt);
    882 	xvsnprintf(buf, sizeof buf, fmt, ap);
    883 	error_message = buf;
    884 	va_end(ap);
    885 }
    886 
    887 void
    888 _rtld_debug_state()
    889 {
    890 	/* do nothing */
    891 }
    892 
    893 void
    894 _rtld_linkmap_add(obj)
    895 	Obj_Entry *obj;
    896 {
    897 	struct link_map *l = &obj->linkmap;
    898 	struct link_map *prev;
    899 
    900 	obj->linkmap.l_name = obj->path;
    901 	obj->linkmap.l_addr = obj->mapbase;
    902 	obj->linkmap.l_ld = obj->dynamic;
    903 #ifdef __mips__
    904 	/* GDB needs load offset on MIPS to use the symbols */
    905 	obj->linkmap.l_offs = obj->relocbase;
    906 #endif
    907 #ifdef __vax__
    908 	/* VAX shared libaries don't start at a vaddr of 0 */
    909 	obj->linkmap.l_addr -= obj->vaddrbase;
    910 #endif
    911 
    912 	if (_rtld_debug.r_map == NULL) {
    913 		_rtld_debug.r_map = l;
    914 		return;
    915 	}
    916 	for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next);
    917 	l->l_prev = prev;
    918 	prev->l_next = l;
    919 	l->l_next = NULL;
    920 }
    921 
    922 void
    923 _rtld_linkmap_delete(obj)
    924 	Obj_Entry *obj;
    925 {
    926 	struct link_map *l = &obj->linkmap;
    927 
    928 	if (l->l_prev == NULL) {
    929 		if ((_rtld_debug.r_map = l->l_next) != NULL)
    930 			l->l_next->l_prev = NULL;
    931 		return;
    932 	}
    933 	if ((l->l_prev->l_next = l->l_next) != NULL)
    934 		l->l_next->l_prev = l->l_prev;
    935 }
    936 
    937 static Obj_Entry *
    938 _rtld_obj_from_addr(const void *addr)
    939 {
    940 	Obj_Entry *obj;
    941 
    942 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
    943 		if (addr < (void *) obj->mapbase)
    944 			continue;
    945 		if (addr < (void *) (obj->mapbase + obj->mapsize))
    946 			return obj;
    947 	}
    948 	return NULL;
    949 }
    950 
    951 static void
    952 _rtld_objlist_remove(list, obj)
    953 	Objlist *list;
    954 	Obj_Entry *obj;
    955 {
    956 	Objlist_Entry *elm;
    957 
    958 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
    959 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
    960 		free(elm);
    961 	}
    962 }
    963