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