Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.93
      1 /*	$NetBSD: rtld.c,v 1.93 2003/05/30 15:43:33 christos Exp $	 */
      2 
      3 /*
      4  * Copyright 1996 John D. Polstra.
      5  * Copyright 1996 Matt Thomas <matt (at) 3am-software.com>
      6  * Copyright 2002 Charles M. Hannum <root (at) ihack.net>
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *      This product includes software developed by John Polstra.
     20  * 4. The name of the author may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Dynamic linker for ELF.
     37  *
     38  * John Polstra <jdp (at) polstra.com>.
     39  */
     40 
     41 #include <err.h>
     42 #include <errno.h>
     43 #include <fcntl.h>
     44 #include <stdarg.h>
     45 #include <stdio.h>
     46 #include <stdlib.h>
     47 #include <string.h>
     48 #include <unistd.h>
     49 #include <sys/param.h>
     50 #include <sys/mman.h>
     51 #include <dirent.h>
     52 
     53 #include <ctype.h>
     54 
     55 #include <dlfcn.h>
     56 #include "debug.h"
     57 #include "rtld.h"
     58 
     59 #if !defined(lint)
     60 #include "sysident.h"
     61 #endif
     62 
     63 /*
     64  * Function declarations.
     65  */
     66 static void     _rtld_init __P((caddr_t, caddr_t));
     67 static void     _rtld_exit __P((void));
     68 
     69 Elf_Addr        _rtld __P((Elf_Addr *, Elf_Addr));
     70 
     71 
     72 /*
     73  * Data declarations.
     74  */
     75 static char    *error_message;	/* Message for dlopen(), or NULL */
     76 
     77 struct r_debug  _rtld_debug;	/* for GDB; */
     78 bool            _rtld_trust;	/* False for setuid and setgid programs */
     79 Obj_Entry      *_rtld_objlist;	/* Head of linked list of shared objects */
     80 Obj_Entry     **_rtld_objtail;	/* Link field of last object in list */
     81 Obj_Entry      *_rtld_objmain;	/* The main program shared object */
     82 Obj_Entry       _rtld_objself;	/* The dynamic linker shared object */
     83 char           *_rtld_path = _PATH_RTLD;
     84 Elf_Sym         _rtld_sym_zero;	/* For resolving undefined weak refs. */
     85 int		_rtld_pagesz;	/* Page size, as provided by kernel */
     86 
     87 Search_Path    *_rtld_default_paths;
     88 Search_Path    *_rtld_paths;
     89 
     90 Library_Xform  *_rtld_xforms;
     91 
     92 /*
     93  * Global declarations normally provided by crt0.
     94  */
     95 char           *__progname;
     96 char          **environ;
     97 
     98 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
     99 extern Elf_Dyn  _DYNAMIC;
    100 
    101 static void _rtld_call_fini_functions __P((Obj_Entry *));
    102 static void _rtld_call_init_functions __P((Obj_Entry *));
    103 static Obj_Entry *_rtld_dlcheck __P((void *));
    104 static void _rtld_init_dag __P((Obj_Entry *));
    105 static void _rtld_init_dag1 __P((Obj_Entry *, Obj_Entry *));
    106 static void _rtld_objlist_remove __P((Objlist *, Obj_Entry *));
    107 static void _rtld_unload_object __P((Obj_Entry *, bool));
    108 static void _rtld_unref_dag __P((Obj_Entry *));
    109 static Obj_Entry *_rtld_obj_from_addr __P((const void *));
    110 
    111 static void
    112 _rtld_call_fini_functions(first)
    113 	Obj_Entry *first;
    114 {
    115 	Obj_Entry *obj;
    116 
    117 	for (obj = first; obj != NULL; obj = obj->next)
    118 		if (obj->fini != NULL)
    119 			(*obj->fini)();
    120 }
    121 
    122 static void
    123 _rtld_call_init_functions(first)
    124 	Obj_Entry *first;
    125 {
    126 	if (first != NULL) {
    127 		_rtld_call_init_functions(first->next);
    128 		if (first->init != NULL)
    129 			(*first->init)();
    130 	}
    131 }
    132 
    133 /*
    134  * Initialize the dynamic linker.  The argument is the address at which
    135  * the dynamic linker has been mapped into memory.  The primary task of
    136  * this function is to relocate the dynamic linker.
    137  */
    138 static void
    139 _rtld_init(mapbase, relocbase)
    140 	caddr_t mapbase, relocbase;
    141 {
    142 	/* Conjure up an Obj_Entry structure for the dynamic linker. */
    143 	_rtld_objself.path = _rtld_path;
    144 	_rtld_objself.pathlen = strlen(_rtld_path);
    145 	_rtld_objself.rtld = true;
    146 	_rtld_objself.mapbase = mapbase;
    147 	_rtld_objself.relocbase = relocbase;
    148 	_rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
    149 
    150 #ifdef RTLD_RELOCATE_SELF
    151 #error platform still uses RTLD_RELOCATE_SELF
    152 #endif
    153 
    154 	_rtld_digest_dynamic(&_rtld_objself);
    155 	assert(!_rtld_objself.needed && !_rtld_objself.pltrel &&
    156 	    !_rtld_objself.pltrela);
    157 #ifndef __mips__
    158 	/* MIPS has a bogus DT_TEXTREL. */
    159 	assert(!_rtld_objself.pltgot && !_rtld_objself.textrel);
    160 #endif
    161 
    162 	_rtld_add_paths(&_rtld_default_paths, RTLD_DEFAULT_LIBRARY_PATH);
    163 
    164 	/*
    165 	 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
    166 	 */
    167 	_rtld_objlist = &_rtld_objself;
    168 
    169 	/* Make the object list empty again. */
    170 	_rtld_objlist = NULL;
    171 	_rtld_objtail = &_rtld_objlist;
    172 
    173 	_rtld_debug.r_brk = _rtld_debug_state;
    174 	_rtld_debug.r_state = RT_CONSISTENT;
    175 }
    176 
    177 /*
    178  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    179  * before the process exits.
    180  */
    181 static void
    182 _rtld_exit()
    183 {
    184 	dbg(("rtld_exit()"));
    185 
    186 	_rtld_call_fini_functions(_rtld_objlist->next);
    187 }
    188 
    189 /*
    190  * Main entry point for dynamic linking.  The argument is the stack
    191  * pointer.  The stack is expected to be laid out as described in the
    192  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    193  * the stack pointer points to a word containing ARGC.  Following that
    194  * in the stack is a null-terminated sequence of pointers to argument
    195  * strings.  Then comes a null-terminated sequence of pointers to
    196  * environment strings.  Finally, there is a sequence of "auxiliary
    197  * vector" entries.
    198  *
    199  * This function returns the entry point for the main program, the dynamic
    200  * linker's exit procedure in sp[0], and a pointer to the main object in
    201  * sp[1].
    202  */
    203 Elf_Addr
    204 _rtld(sp, relocbase)
    205 	Elf_Addr *sp;
    206 	Elf_Addr relocbase;
    207 {
    208 	const AuxInfo  *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
    209 	               *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
    210 		       *pAUX_ruid, *pAUX_rgid;
    211 	const AuxInfo  *pAUX_pagesz;
    212 	char          **env;
    213 	const AuxInfo  *aux;
    214 	const AuxInfo  *auxp;
    215 	Elf_Addr       *const osp = sp;
    216 	bool            bind_now = 0;
    217 	const char     *ld_bind_now;
    218 	const char    **argv;
    219 	long		argc;
    220 	const char **real___progname;
    221 	const Obj_Entry **real___mainprog_obj;
    222 	char ***real_environ;
    223 #if defined(RTLD_DEBUG)
    224 	int             i = 0;
    225 #endif
    226 
    227 	/*
    228          * On entry, the dynamic linker itself has not been relocated yet.
    229          * Be very careful not to reference any global data until after
    230          * _rtld_init has returned.  It is OK to reference file-scope statics
    231          * and string constants, and to call static and global functions.
    232          */
    233 	/* Find the auxiliary vector on the stack. */
    234 	/* first Elf_Word reserved to address of exit routine */
    235 #if defined(RTLD_DEBUG)
    236 	debug = 1;
    237 	dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
    238 	    (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
    239 	dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
    240 	    &_DYNAMIC));
    241 	dbg(("_ctype_ is %p", _ctype_));
    242 #endif
    243 
    244 	sp += 2;		/* skip over return argument space */
    245 	argv = (const char **) &sp[1];
    246 	argc = *(long *)sp;
    247 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
    248 				 * terminator */
    249 	env = (char **) sp;
    250 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    251 #if defined(RTLD_DEBUG)
    252 		dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
    253 #endif
    254 	}
    255 	aux = (const AuxInfo *) sp;
    256 
    257 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
    258 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
    259 	pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
    260 	pAUX_pagesz = NULL;
    261 
    262 	/* Digest the auxiliary vector. */
    263 	for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
    264 		switch (auxp->a_type) {
    265 		case AT_BASE:
    266 			pAUX_base = auxp;
    267 			break;
    268 		case AT_ENTRY:
    269 			pAUX_entry = auxp;
    270 			break;
    271 		case AT_EXECFD:
    272 			pAUX_execfd = auxp;
    273 			break;
    274 		case AT_PHDR:
    275 			pAUX_phdr = auxp;
    276 			break;
    277 		case AT_PHENT:
    278 			pAUX_phent = auxp;
    279 			break;
    280 		case AT_PHNUM:
    281 			pAUX_phnum = auxp;
    282 			break;
    283 #ifdef AT_EUID
    284 		case AT_EUID:
    285 			pAUX_euid = auxp;
    286 			break;
    287 		case AT_RUID:
    288 			pAUX_ruid = auxp;
    289 			break;
    290 		case AT_EGID:
    291 			pAUX_egid = auxp;
    292 			break;
    293 		case AT_RGID:
    294 			pAUX_rgid = auxp;
    295 			break;
    296 #endif
    297 		case AT_PAGESZ:
    298 			pAUX_pagesz = auxp;
    299 			break;
    300 		}
    301 	}
    302 
    303 	/* Initialize and relocate ourselves. */
    304 	if (pAUX_base == NULL) {
    305 		_rtld_error("Bad pAUX_base");
    306 		_rtld_die();
    307 	}
    308 	assert(pAUX_pagesz != NULL);
    309 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
    310 	_rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase);
    311 
    312 	__progname = _rtld_objself.path;
    313 	environ = env;
    314 
    315 	_rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
    316 	    (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
    317 	    ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
    318 	    (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
    319 
    320 	ld_bind_now = getenv("LD_BIND_NOW");
    321 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
    322 		bind_now = true;
    323 	if (_rtld_trust) {
    324 #ifdef DEBUG
    325 		const char     *ld_debug = getenv("LD_DEBUG");
    326 #ifdef RTLD_DEBUG
    327 		debug = 0;
    328 #endif
    329 		if (ld_debug != NULL && *ld_debug != '\0')
    330 			debug = 1;
    331 #endif
    332 		_rtld_add_paths(&_rtld_paths, getenv("LD_LIBRARY_PATH"));
    333 	}
    334 	_rtld_process_hints(&_rtld_paths, &_rtld_xforms, _PATH_LD_HINTS);
    335 	dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
    336 	     _rtld_objself.mapbase, _rtld_objself.relocbase));
    337 
    338 	/*
    339          * Load the main program, or process its program header if it is
    340          * already loaded.
    341          */
    342 	if (pAUX_execfd != NULL) {	/* Load the main program. */
    343 		int             fd = pAUX_execfd->a_v;
    344 		dbg(("loading main program"));
    345 		_rtld_objmain = _rtld_map_object(xstrdup(argv[0] ? argv[0] :
    346 		    "main program"), fd, NULL);
    347 		close(fd);
    348 		if (_rtld_objmain == NULL)
    349 			_rtld_die();
    350 	} else {		/* Main program already loaded. */
    351 		const Elf_Phdr *phdr;
    352 		int             phnum;
    353 		caddr_t         entry;
    354 
    355 		dbg(("processing main program's program header"));
    356 		assert(pAUX_phdr != NULL);
    357 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
    358 		assert(pAUX_phnum != NULL);
    359 		phnum = pAUX_phnum->a_v;
    360 		assert(pAUX_phent != NULL);
    361 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
    362 		assert(pAUX_entry != NULL);
    363 		entry = (caddr_t) pAUX_entry->a_v;
    364 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    365 		_rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
    366 		    "main program");
    367 		_rtld_objmain->pathlen = strlen(_rtld_objmain->path);
    368 	}
    369 
    370 	_rtld_objmain->mainprog = true;
    371 
    372 	/*
    373 	 * Get the actual dynamic linker pathname from the executable if
    374 	 * possible.  (It should always be possible.)  That ensures that
    375 	 * gdb will find the right dynamic linker even if a non-standard
    376 	 * one is being used.
    377 	 */
    378 	if (_rtld_objmain->interp != NULL &&
    379 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
    380 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
    381 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
    382 
    383 	_rtld_digest_dynamic(_rtld_objmain);
    384 
    385 	/* Link the main program into the list of objects. */
    386 	*_rtld_objtail = _rtld_objmain;
    387 	_rtld_objtail = &_rtld_objmain->next;
    388 
    389 	_rtld_linkmap_add(_rtld_objmain);
    390 	_rtld_linkmap_add(&_rtld_objself);
    391 
    392 	++_rtld_objmain->refcount;
    393 	_rtld_objmain->mainref = 1;
    394 	_rtld_objlist_add(&_rtld_list_main, _rtld_objmain);
    395 
    396 	/* Initialize a fake symbol for resolving undefined weak references. */
    397 	_rtld_sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
    398 	_rtld_sym_zero.st_shndx = SHN_ABS;
    399 
    400 	/*
    401 	 * Pre-load user-specified objects after the main program but before
    402 	 * any shared object dependencies.
    403 	 */
    404 	dbg(("preloading objects"));
    405 	if (_rtld_trust && _rtld_preload(getenv("LD_PRELOAD")) == -1)
    406 		_rtld_die();
    407 
    408 	dbg(("loading needed objects"));
    409 	if (_rtld_load_needed_objects(_rtld_objmain, RTLD_MAIN) == -1)
    410 		_rtld_die();
    411 
    412 	dbg(("relocating objects"));
    413 	if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
    414 		_rtld_die();
    415 
    416 	dbg(("doing copy relocations"));
    417 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
    418 		_rtld_die();
    419 
    420 	/*
    421 	 * Set the __progname,  environ and, __mainprog_obj before
    422 	 * calling anything that might use them.
    423 	 */
    424 	real___progname = _rtld_objmain_sym("__progname");
    425 	if (real___progname) {
    426 		if (argv[0] != NULL) {
    427 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
    428 				(*real___progname) = argv[0];
    429 			else
    430 				(*real___progname)++;
    431 		} else {
    432 			(*real___progname) = NULL;
    433 		}
    434 	}
    435 	real_environ = _rtld_objmain_sym("environ");
    436 	if (real_environ)
    437 		*real_environ = environ;
    438 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
    439 	if (real___mainprog_obj)
    440 		*real___mainprog_obj = _rtld_objmain;
    441 
    442 	dbg(("calling _init functions"));
    443 	_rtld_call_init_functions(_rtld_objmain->next);
    444 
    445 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
    446 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
    447 
    448 	/*
    449 	 * Return with the entry point and the exit procedure in at the top
    450 	 * of stack.
    451 	 */
    452 
    453 	_rtld_debug_state();	/* say hello to gdb! */
    454 
    455 	((void **) osp)[0] = _rtld_exit;
    456 	((void **) osp)[1] = _rtld_objmain;
    457 	return (Elf_Addr) _rtld_objmain->entry;
    458 }
    459 
    460 void
    461 _rtld_die()
    462 {
    463 	const char *msg = _rtld_dlerror();
    464 
    465 	if (msg == NULL)
    466 		msg = "Fatal error";
    467 	xerrx(1, "%s", msg);
    468 }
    469 
    470 static Obj_Entry *
    471 _rtld_dlcheck(handle)
    472 	void *handle;
    473 {
    474 	Obj_Entry *obj;
    475 
    476 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    477 		if (obj == (Obj_Entry *) handle)
    478 			break;
    479 
    480 	if (obj == NULL || obj->dl_refcount == 0) {
    481 		xwarnx("Invalid shared object handle %p", handle);
    482 		return NULL;
    483 	}
    484 	return obj;
    485 }
    486 
    487 static void
    488 _rtld_init_dag(root)
    489 	Obj_Entry *root;
    490 {
    491 	_rtld_init_dag1(root, root);
    492 }
    493 
    494 static void
    495 _rtld_init_dag1(root, obj)
    496 	Obj_Entry *root;
    497 	Obj_Entry *obj;
    498 {
    499 	const Needed_Entry *needed;
    500 
    501 	if (!obj->mainref) {
    502 		if (_rtld_objlist_find(&obj->dldags, root))
    503 			return;
    504 		rdbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
    505 		    root->path));
    506 		_rtld_objlist_add(&obj->dldags, root);
    507 		_rtld_objlist_add(&root->dagmembers, obj);
    508 	}
    509 	for (needed = obj->needed; needed != NULL; needed = needed->next)
    510 		if (needed->obj != NULL)
    511 			_rtld_init_dag1(root, needed->obj);
    512 }
    513 
    514 /*
    515  * Note, this is called only for objects loaded by dlopen().
    516  */
    517 static void
    518 _rtld_unload_object(root, do_fini_funcs)
    519 	Obj_Entry *root;
    520 	bool do_fini_funcs;
    521 {
    522 	_rtld_unref_dag(root);
    523 	if (root->refcount == 0) { /* We are finished with some objects. */
    524 		Obj_Entry *obj;
    525 		Obj_Entry **linkp;
    526 		Objlist_Entry *elm;
    527 
    528 		/* Finalize objects that are about to be unmapped. */
    529 		if (do_fini_funcs)
    530 			for (obj = _rtld_objlist->next;  obj != NULL;  obj = obj->next)
    531 				if (obj->refcount == 0 && obj->fini != NULL)
    532 					(*obj->fini)();
    533 
    534 		/* Remove the DAG from all objects' DAG lists. */
    535 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
    536 			_rtld_objlist_remove(&elm->obj->dldags, root);
    537 
    538 		/* Remove the DAG from the RTLD_GLOBAL list. */
    539 		if (root->globalref) {
    540 			root->globalref = 0;
    541 			_rtld_objlist_remove(&_rtld_list_global, root);
    542 		}
    543 
    544 		/* Unmap all objects that are no longer referenced. */
    545 		linkp = &_rtld_objlist->next;
    546 		while ((obj = *linkp) != NULL) {
    547 			if (obj->refcount == 0) {
    548 #ifdef RTLD_DEBUG
    549 				dbg(("unloading \"%s\"", obj->path));
    550 #endif
    551 				munmap(obj->mapbase, obj->mapsize);
    552 				_rtld_objlist_remove(&_rtld_list_global, obj);
    553 				_rtld_linkmap_delete(obj);
    554 				*linkp = obj->next;
    555 				_rtld_obj_free(obj);
    556 			} else
    557 				linkp = &obj->next;
    558 		}
    559 		_rtld_objtail = linkp;
    560 	}
    561 }
    562 
    563 static void
    564 _rtld_unref_dag(root)
    565 	Obj_Entry *root;
    566 {
    567 	assert(root);
    568 	assert(root->refcount != 0);
    569 	--root->refcount;
    570 	if (root->refcount == 0) {
    571 		const Needed_Entry *needed;
    572 
    573 		for (needed = root->needed; needed != NULL;
    574 		     needed = needed->next) {
    575 			if (needed->obj != NULL)
    576 				_rtld_unref_dag(needed->obj);
    577 		}
    578 	}
    579 }
    580 
    581 int
    582 _rtld_dlclose(handle)
    583 	void *handle;
    584 {
    585 	Obj_Entry *root = _rtld_dlcheck(handle);
    586 
    587 	if (root == NULL)
    588 		return -1;
    589 
    590 	_rtld_debug.r_state = RT_DELETE;
    591 	_rtld_debug_state();
    592 
    593 	--root->dl_refcount;
    594 	_rtld_unload_object(root, true);
    595 
    596 	_rtld_debug.r_state = RT_CONSISTENT;
    597 	_rtld_debug_state();
    598 
    599 	return 0;
    600 }
    601 
    602 char *
    603 _rtld_dlerror()
    604 {
    605 	char *msg = error_message;
    606 	error_message = NULL;
    607 	return msg;
    608 }
    609 
    610 void *
    611 _rtld_dlopen(name, mode)
    612 	const char *name;
    613 	int mode;
    614 {
    615 	Obj_Entry **old_obj_tail = _rtld_objtail;
    616 	Obj_Entry *obj = NULL;
    617 
    618 	_rtld_debug.r_state = RT_ADD;
    619 	_rtld_debug_state();
    620 
    621 	if (name == NULL) {
    622 		obj = _rtld_objmain;
    623 		obj->refcount++;
    624 	} else
    625 		obj = _rtld_load_library(name, _rtld_objmain, mode);
    626 
    627 	if (obj != NULL) {
    628 		++obj->dl_refcount;
    629 		if (*old_obj_tail != NULL) {	/* We loaded something new. */
    630 			assert(*old_obj_tail == obj);
    631 
    632 			if (_rtld_load_needed_objects(obj, mode) == -1 ||
    633 			    (_rtld_init_dag(obj),
    634 			    _rtld_relocate_objects(obj,
    635 			    ((mode & 3) == RTLD_NOW))) == -1) {
    636 				_rtld_unload_object(obj, false);
    637 				obj->dl_refcount--;
    638 				obj = NULL;
    639 			} else
    640 				_rtld_call_init_functions(obj);
    641 		}
    642 	}
    643 	_rtld_debug.r_state = RT_CONSISTENT;
    644 	_rtld_debug_state();
    645 
    646 	return obj;
    647 }
    648 
    649 /*
    650  * Find a symbol in the main program.
    651  */
    652 void *
    653 _rtld_objmain_sym(name)
    654 	const char *name;
    655 {
    656 	unsigned long hash;
    657 	const Elf_Sym *def;
    658 	const Obj_Entry *obj;
    659 
    660 	hash = _rtld_elf_hash(name);
    661 	obj = _rtld_objmain;
    662 
    663 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false);
    664 
    665 	if (def != NULL)
    666 		return obj->relocbase + def->st_value;
    667 	return(NULL);
    668 }
    669 
    670 void *
    671 _rtld_dlsym(handle, name)
    672 	void *handle;
    673 	const char *name;
    674 {
    675 	const Obj_Entry *obj;
    676 	unsigned long hash;
    677 	const Elf_Sym *def;
    678 	const Obj_Entry *defobj;
    679 	void *retaddr;
    680 
    681 	hash = _rtld_elf_hash(name);
    682 	def = NULL;
    683 	defobj = NULL;
    684 
    685 	switch ((intptr_t)handle) {
    686 	case (intptr_t)NULL:
    687 	case (intptr_t)RTLD_NEXT:
    688 	case (intptr_t)RTLD_DEFAULT:
    689 	case (intptr_t)RTLD_SELF:
    690 		retaddr = __builtin_return_address(0); /* __GNUC__ only */
    691 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
    692 			_rtld_error("Cannot determine caller's shared object");
    693 			return NULL;
    694 		}
    695 
    696 		switch ((intptr_t)handle) {
    697 		case (intptr_t)NULL:	 /* Just the caller's shared object. */
    698 			def = _rtld_symlook_obj(name, hash, obj, false);
    699 			defobj = obj;
    700 			break;
    701 
    702 		case (intptr_t)RTLD_NEXT:	/* Objects after callers */
    703 			obj = obj->next;
    704 			/*FALLTHROUGH*/
    705 
    706 		case (intptr_t)RTLD_SELF:	/* Caller included */
    707 			for (; obj; obj = obj->next) {
    708 				if ((def = _rtld_symlook_obj(name, hash, obj,
    709 				    false)) != NULL) {
    710 					defobj = obj;
    711 					break;
    712 				}
    713 			}
    714 			break;
    715 
    716 		case (intptr_t)RTLD_DEFAULT:
    717 			def = _rtld_symlook_default(name, hash, obj, &defobj,
    718 			    true);
    719 			break;
    720 
    721 		default:
    722 			abort();
    723 		}
    724 		break;
    725 
    726 	default:
    727 		if ((obj = _rtld_dlcheck(handle)) == NULL)
    728 			return NULL;
    729 
    730 		if (obj->mainprog) {
    731 			/* Search main program and all libraries loaded by it */
    732 			def = _rtld_symlook_list(name, hash, &_rtld_list_main,
    733 			    &defobj, false);
    734 		} else {
    735 			/*
    736 			 * XXX - This isn't correct.  The search should include
    737 			 * the whole DAG rooted at the given object.
    738 			 */
    739 			def = _rtld_symlook_obj(name, hash, obj, false);
    740 			defobj = obj;
    741 		}
    742 		break;
    743 	}
    744 
    745 	if (def != NULL) {
    746 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    747 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
    748 			return (void *)_rtld_function_descriptor_alloc(defobj,
    749 			    def, 0);
    750 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    751 		return defobj->relocbase + def->st_value;
    752 	}
    753 
    754 	_rtld_error("Undefined symbol \"%s\"", name);
    755 	return NULL;
    756 }
    757 
    758 int
    759 _rtld_dladdr(addr, info)
    760 	const void *addr;
    761 	Dl_info *info;
    762 {
    763 	const Obj_Entry *obj;
    764 	const Elf_Sym *def, *best_def;
    765 	void *symbol_addr;
    766 	unsigned long symoffset;
    767 
    768 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    769 	addr = _rtld_function_descriptor_function(addr);
    770 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    771 
    772 	obj = _rtld_obj_from_addr(addr);
    773 	if (obj == NULL) {
    774 		_rtld_error("No shared object contains address");
    775 		return 0;
    776 	}
    777 	info->dli_fname = obj->path;
    778 	info->dli_fbase = obj->mapbase;
    779 	info->dli_saddr = (void *)0;
    780 	info->dli_sname = NULL;
    781 
    782 	/*
    783 	 * Walk the symbol list looking for the symbol whose address is
    784 	 * closest to the address sent in.
    785 	 */
    786 	best_def = NULL;
    787 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
    788 		def = obj->symtab + symoffset;
    789 
    790 		/*
    791 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
    792 		 * SHN_COMMON.
    793 		 */
    794 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
    795 			continue;
    796 
    797 		/*
    798 		 * If the symbol is greater than the specified address, or if it
    799 		 * is further away from addr than the current nearest symbol,
    800 		 * then reject it.
    801 		 */
    802 		symbol_addr = obj->relocbase + def->st_value;
    803 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
    804 			continue;
    805 
    806 		/* Update our idea of the nearest symbol. */
    807 		info->dli_sname = obj->strtab + def->st_name;
    808 		info->dli_saddr = symbol_addr;
    809 		best_def = def;
    810 
    811 		/* Exact match? */
    812 		if (info->dli_saddr == addr)
    813 			break;
    814 	}
    815 
    816 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    817 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
    818 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
    819 		    best_def, 0);
    820 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    821 
    822 	return 1;
    823 }
    824 
    825 /*
    826  * Error reporting function.  Use it like printf.  If formats the message
    827  * into a buffer, and sets things up so that the next call to dlerror()
    828  * will return the message.
    829  */
    830 void
    831 _rtld_error(const char *fmt,...)
    832 {
    833 	static char     buf[512];
    834 	va_list         ap;
    835 
    836 	va_start(ap, fmt);
    837 	xvsnprintf(buf, sizeof buf, fmt, ap);
    838 	error_message = buf;
    839 	va_end(ap);
    840 }
    841 
    842 void
    843 _rtld_debug_state()
    844 {
    845 	/* do nothing */
    846 }
    847 
    848 void
    849 _rtld_linkmap_add(obj)
    850 	Obj_Entry *obj;
    851 {
    852 	struct link_map *l = &obj->linkmap;
    853 	struct link_map *prev;
    854 
    855 	obj->linkmap.l_name = obj->path;
    856 	obj->linkmap.l_addr = obj->relocbase;
    857 	obj->linkmap.l_ld = obj->dynamic;
    858 #ifdef __mips__
    859 	/* XXX This field is not standard and will be removed eventually. */
    860 	obj->linkmap.l_offs = obj->relocbase;
    861 #endif
    862 
    863 	if (_rtld_debug.r_map == NULL) {
    864 		_rtld_debug.r_map = l;
    865 		return;
    866 	}
    867 	for (prev = _rtld_debug.r_map; prev->l_next != NULL; prev = prev->l_next);
    868 	l->l_prev = prev;
    869 	prev->l_next = l;
    870 	l->l_next = NULL;
    871 }
    872 
    873 void
    874 _rtld_linkmap_delete(obj)
    875 	Obj_Entry *obj;
    876 {
    877 	struct link_map *l = &obj->linkmap;
    878 
    879 	if (l->l_prev == NULL) {
    880 		if ((_rtld_debug.r_map = l->l_next) != NULL)
    881 			l->l_next->l_prev = NULL;
    882 		return;
    883 	}
    884 	if ((l->l_prev->l_next = l->l_next) != NULL)
    885 		l->l_next->l_prev = l->l_prev;
    886 }
    887 
    888 static Obj_Entry *
    889 _rtld_obj_from_addr(const void *addr)
    890 {
    891 	Obj_Entry *obj;
    892 
    893 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
    894 		if (addr < (void *) obj->mapbase)
    895 			continue;
    896 		if (addr < (void *) (obj->mapbase + obj->mapsize))
    897 			return obj;
    898 	}
    899 	return NULL;
    900 }
    901 
    902 static void
    903 _rtld_objlist_remove(list, obj)
    904 	Objlist *list;
    905 	Obj_Entry *obj;
    906 {
    907 	Objlist_Entry *elm;
    908 
    909 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
    910 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
    911 		free(elm);
    912 	}
    913 }
    914