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