Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.129
      1 /*	$NetBSD: rtld.c,v 1.129 2010/02/27 11:16:38 roy 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 <sys/cdefs.h>
     42 #ifndef lint
     43 __RCSID("$NetBSD: rtld.c,v 1.129 2010/02/27 11:16:38 roy Exp $");
     44 #endif /* not lint */
     45 
     46 #include <err.h>
     47 #include <errno.h>
     48 #include <fcntl.h>
     49 #include <stdarg.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <unistd.h>
     54 #include <sys/param.h>
     55 #include <sys/mman.h>
     56 #include <dirent.h>
     57 
     58 #include <ctype.h>
     59 
     60 #include <dlfcn.h>
     61 #include "debug.h"
     62 #include "rtld.h"
     63 
     64 #if !defined(lint)
     65 #include "sysident.h"
     66 #endif
     67 
     68 /*
     69  * Function declarations.
     70  */
     71 static void     _rtld_init(caddr_t, caddr_t, const char *);
     72 static void     _rtld_exit(void);
     73 
     74 Elf_Addr        _rtld(Elf_Addr *, Elf_Addr);
     75 
     76 
     77 /*
     78  * Data declarations.
     79  */
     80 static char    *error_message;	/* Message for dlopen(), or NULL */
     81 
     82 struct r_debug  _rtld_debug;	/* for GDB; */
     83 bool            _rtld_trust;	/* False for setuid and setgid programs */
     84 Obj_Entry      *_rtld_objlist;	/* Head of linked list of shared objects */
     85 Obj_Entry     **_rtld_objtail;	/* Link field of last object in list */
     86 int		_rtld_objcount;	/* Number of shared objects */
     87 Obj_Entry      *_rtld_objmain;	/* The main program shared object */
     88 Obj_Entry       _rtld_objself;	/* The dynamic linker shared object */
     89 const char	_rtld_path[] = _PATH_RTLD;
     90 
     91 /* Initialize a fake symbol for resolving undefined weak references. */
     92 Elf_Sym		_rtld_sym_zero = {
     93     .st_info	= ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
     94     .st_shndx	= SHN_ABS,
     95 };
     96 size_t	_rtld_pagesz;	/* Page size, as provided by kernel */
     97 
     98 Search_Path    *_rtld_default_paths;
     99 Search_Path    *_rtld_paths;
    100 
    101 Library_Xform  *_rtld_xforms;
    102 
    103 /*
    104  * Global declarations normally provided by crt0.
    105  */
    106 char           *__progname;
    107 char          **environ;
    108 
    109 #if defined(RTLD_DEBUG)
    110 #ifndef __sh__
    111 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
    112 #else  /* 32-bit SuperH */
    113 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
    114 #endif
    115 #endif /* RTLD_DEBUG */
    116 extern Elf_Dyn  _DYNAMIC;
    117 
    118 static void _rtld_call_fini_functions(int);
    119 static void _rtld_call_init_functions(void);
    120 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
    121 static void _rtld_initlist_tsort(Objlist *, int);
    122 static Obj_Entry *_rtld_dlcheck(void *);
    123 static void _rtld_init_dag(Obj_Entry *);
    124 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
    125 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
    126 static void _rtld_objlist_clear(Objlist *);
    127 static void _rtld_unload_object(Obj_Entry *, bool);
    128 static void _rtld_unref_dag(Obj_Entry *);
    129 static Obj_Entry *_rtld_obj_from_addr(const void *);
    130 
    131 static void
    132 _rtld_call_fini_functions(int force)
    133 {
    134 	Objlist_Entry *elm;
    135 	Objlist finilist;
    136 	Obj_Entry *obj;
    137 
    138 	dbg(("_rtld_call_fini_functions(%d)", force));
    139 
    140 	SIMPLEQ_INIT(&finilist);
    141 	_rtld_initlist_tsort(&finilist, 1);
    142 
    143 	/* First pass: objects _not_ marked with DF_1_INITFIRST. */
    144 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    145 		obj = elm->obj;
    146 		if (obj->refcount > 0 && !force) {
    147 			continue;
    148 		}
    149 		if (obj->fini == NULL || obj->fini_called || obj->initfirst) {
    150 		    	continue;
    151 		}
    152 		dbg (("calling fini function %s at %p",  obj->path,
    153 		    (void *)obj->fini));
    154 		obj->fini_called = 1;
    155 		(*obj->fini)();
    156 	}
    157 
    158 	/* Second pass: objects marked with DF_1_INITFIRST. */
    159 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    160 		obj = elm->obj;
    161 		if (obj->refcount > 0 && !force) {
    162 			continue;
    163 		}
    164 		if (obj->fini == NULL || obj->fini_called) {
    165 		    	continue;
    166 		}
    167 		dbg (("calling fini function %s at %p (DF_1_INITFIRST)",
    168 		    obj->path, (void *)obj->fini));
    169 		obj->fini_called = 1;
    170 		(*obj->fini)();
    171 	}
    172 
    173         _rtld_objlist_clear(&finilist);
    174 }
    175 
    176 static void
    177 _rtld_call_init_functions()
    178 {
    179 	Objlist_Entry *elm;
    180 	Objlist initlist;
    181 	Obj_Entry *obj;
    182 
    183 	dbg(("_rtld_call_init_functions()"));
    184 	SIMPLEQ_INIT(&initlist);
    185 	_rtld_initlist_tsort(&initlist, 0);
    186 
    187 	/* First pass: objects marked with DF_1_INITFIRST. */
    188 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    189 		obj = elm->obj;
    190 		if (obj->init == NULL || obj->init_called || !obj->initfirst) {
    191 			continue;
    192 		}
    193 		dbg (("calling init function %s at %p (DF_1_INITFIRST)",
    194 		    obj->path, (void *)obj->init));
    195 		obj->init_called = 1;
    196 		(*obj->init)();
    197 	}
    198 
    199 	/* Second pass: all other objects. */
    200 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    201 		obj = elm->obj;
    202 		if (obj->init == NULL || obj->init_called) {
    203 			continue;
    204 		}
    205 		dbg (("calling init function %s at %p",  obj->path,
    206 		    (void *)obj->init));
    207 		obj->init_called = 1;
    208 		(*obj->init)();
    209 	}
    210 
    211         _rtld_objlist_clear(&initlist);
    212 }
    213 
    214 /*
    215  * Initialize the dynamic linker.  The argument is the address at which
    216  * the dynamic linker has been mapped into memory.  The primary task of
    217  * this function is to create an Obj_Entry for the dynamic linker and
    218  * to resolve the PLT relocation for platforms that need it (those that
    219  * define __HAVE_FUNCTION_DESCRIPTORS
    220  */
    221 static void
    222 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
    223 {
    224 
    225 	/* Conjure up an Obj_Entry structure for the dynamic linker. */
    226 	_rtld_objself.path = __UNCONST(_rtld_path);
    227 	_rtld_objself.pathlen = sizeof(_rtld_path)-1;
    228 	_rtld_objself.rtld = true;
    229 	_rtld_objself.mapbase = mapbase;
    230 	_rtld_objself.relocbase = relocbase;
    231 	_rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
    232 	_rtld_objself.strtab = "_rtld_sym_zero";
    233 
    234 	/*
    235 	 * Set value to -relocbase so that
    236 	 *
    237 	 *     _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
    238 	 *
    239 	 * This allows unresolved references to weak symbols to be computed
    240 	 * to a value of 0.
    241 	 */
    242 	_rtld_sym_zero.st_value = -(uintptr_t)relocbase;
    243 
    244 	_rtld_digest_dynamic(_rtld_path, &_rtld_objself);
    245 	assert(!_rtld_objself.needed);
    246 #if !defined(__hppa__)
    247 	assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
    248 #else
    249 	_rtld_relocate_plt_objects(&_rtld_objself);
    250 #endif
    251 #if !defined(__mips__) && !defined(__hppa__)
    252 	assert(!_rtld_objself.pltgot);
    253 #endif
    254 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
    255 	/* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
    256 	assert(!_rtld_objself.textrel);
    257 #endif
    258 
    259 	_rtld_add_paths(execname, &_rtld_default_paths,
    260 	    RTLD_DEFAULT_LIBRARY_PATH);
    261 
    262 #ifdef RTLD_ARCH_SUBDIR
    263 	_rtld_add_paths(execname, &_rtld_default_paths,
    264 	    RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
    265 #endif
    266 
    267 	/*
    268 	 * Set up the _rtld_objlist pointer, so that rtld symbols can be found.
    269 	 */
    270 	_rtld_objlist = &_rtld_objself;
    271 
    272 	/* Make the object list empty again. */
    273 	_rtld_objlist = NULL;
    274 	_rtld_objtail = &_rtld_objlist;
    275 	_rtld_objcount = 0;
    276 
    277 	_rtld_debug.r_brk = _rtld_debug_state;
    278 	_rtld_debug.r_state = RT_CONSISTENT;
    279 }
    280 
    281 /*
    282  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    283  * before the process exits.
    284  */
    285 static void
    286 _rtld_exit(void)
    287 {
    288 	dbg(("rtld_exit()"));
    289 
    290 	_rtld_call_fini_functions(1);
    291 }
    292 
    293 /*
    294  * Main entry point for dynamic linking.  The argument is the stack
    295  * pointer.  The stack is expected to be laid out as described in the
    296  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    297  * the stack pointer points to a word containing ARGC.  Following that
    298  * in the stack is a null-terminated sequence of pointers to argument
    299  * strings.  Then comes a null-terminated sequence of pointers to
    300  * environment strings.  Finally, there is a sequence of "auxiliary
    301  * vector" entries.
    302  *
    303  * This function returns the entry point for the main program, the dynamic
    304  * linker's exit procedure in sp[0], and a pointer to the main object in
    305  * sp[1].
    306  */
    307 Elf_Addr
    308 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
    309 {
    310 	const AuxInfo  *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
    311 	               *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
    312 		       *pAUX_ruid, *pAUX_rgid;
    313 	const AuxInfo  *pAUX_pagesz;
    314 	char          **env;
    315 	const AuxInfo  *aux;
    316 	const AuxInfo  *auxp;
    317 	Elf_Addr       *const osp = sp;
    318 	bool            bind_now = 0;
    319 	const char     *ld_bind_now;
    320 	const char    **argv;
    321 	const char     *execname;
    322 	long		argc;
    323 	const char **real___progname;
    324 	const Obj_Entry **real___mainprog_obj;
    325 	char ***real_environ;
    326 #if defined(RTLD_DEBUG)
    327 	int i = 0;
    328 #endif
    329 
    330 	/*
    331          * On entry, the dynamic linker itself has not been relocated yet.
    332          * Be very careful not to reference any global data until after
    333          * _rtld_init has returned.  It is OK to reference file-scope statics
    334          * and string constants, and to call static and global functions.
    335          */
    336 	/* Find the auxiliary vector on the stack. */
    337 	/* first Elf_Word reserved to address of exit routine */
    338 #if defined(RTLD_DEBUG)
    339 	debug = 1;
    340 	dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
    341 	    (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
    342 	dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
    343 	    &_DYNAMIC));
    344 	dbg(("_ctype_ is %p", _ctype_));
    345 #endif
    346 
    347 	sp += 2;		/* skip over return argument space */
    348 	argv = (const char **) &sp[1];
    349 	argc = *(long *)sp;
    350 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
    351 				 * terminator */
    352 	env = (char **) sp;
    353 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    354 #if defined(RTLD_DEBUG)
    355 		dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
    356 #endif
    357 	}
    358 	aux = (const AuxInfo *) sp;
    359 
    360 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
    361 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
    362 	pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
    363 	pAUX_pagesz = NULL;
    364 
    365 	execname = NULL;
    366 
    367 	/* Digest the auxiliary vector. */
    368 	for (auxp = aux; auxp->a_type != AT_NULL; ++auxp) {
    369 		switch (auxp->a_type) {
    370 		case AT_BASE:
    371 			pAUX_base = auxp;
    372 			break;
    373 		case AT_ENTRY:
    374 			pAUX_entry = auxp;
    375 			break;
    376 		case AT_EXECFD:
    377 			pAUX_execfd = auxp;
    378 			break;
    379 		case AT_PHDR:
    380 			pAUX_phdr = auxp;
    381 			break;
    382 		case AT_PHENT:
    383 			pAUX_phent = auxp;
    384 			break;
    385 		case AT_PHNUM:
    386 			pAUX_phnum = auxp;
    387 			break;
    388 #ifdef AT_EUID
    389 		case AT_EUID:
    390 			pAUX_euid = auxp;
    391 			break;
    392 		case AT_RUID:
    393 			pAUX_ruid = auxp;
    394 			break;
    395 		case AT_EGID:
    396 			pAUX_egid = auxp;
    397 			break;
    398 		case AT_RGID:
    399 			pAUX_rgid = auxp;
    400 			break;
    401 #endif
    402 #ifdef AT_SUN_EXECNAME
    403 		case AT_SUN_EXECNAME:
    404 			execname = (const char *)(const void *)auxp->a_v;
    405 			break;
    406 #endif
    407 		case AT_PAGESZ:
    408 			pAUX_pagesz = auxp;
    409 			break;
    410 		}
    411 	}
    412 
    413 	/* Initialize and relocate ourselves. */
    414 	if (pAUX_base == NULL) {
    415 		_rtld_error("Bad pAUX_base");
    416 		_rtld_die();
    417 	}
    418 	assert(pAUX_pagesz != NULL);
    419 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
    420 	_rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
    421 
    422 	__progname = _rtld_objself.path;
    423 	environ = env;
    424 
    425 	_rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
    426 	    (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
    427 	    ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
    428 	    (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
    429 
    430 	ld_bind_now = getenv("LD_BIND_NOW");
    431 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
    432 		bind_now = true;
    433 	if (_rtld_trust) {
    434 #ifdef DEBUG
    435 		const char     *ld_debug = getenv("LD_DEBUG");
    436 #ifdef RTLD_DEBUG
    437 		debug = 0;
    438 #endif
    439 		if (ld_debug != NULL && *ld_debug != '\0')
    440 			debug = 1;
    441 #endif
    442 		_rtld_add_paths(execname, &_rtld_paths,
    443 		    getenv("LD_LIBRARY_PATH"));
    444 	} else {
    445 		execname = NULL;
    446 		if (unsetenv("LD_DEBUG") || unsetenv("LD_LIBRARY_PATH"))
    447 			_rtld_die();
    448 	}
    449 	_rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
    450 	    _PATH_LD_HINTS);
    451 	dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
    452 	     _rtld_objself.mapbase, _rtld_objself.relocbase));
    453 
    454 	/*
    455          * Load the main program, or process its program header if it is
    456          * already loaded.
    457          */
    458 	if (pAUX_execfd != NULL) {	/* Load the main program. */
    459 		int             fd = pAUX_execfd->a_v;
    460 		const char *obj_name = argv[0] ? argv[0] : "main program";
    461 		dbg(("loading main program"));
    462 		_rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
    463 		close(fd);
    464 		if (_rtld_objmain == NULL)
    465 			_rtld_die();
    466 	} else {		/* Main program already loaded. */
    467 		const Elf_Phdr *phdr;
    468 		int             phnum;
    469 		caddr_t         entry;
    470 
    471 		dbg(("processing main program's program header"));
    472 		assert(pAUX_phdr != NULL);
    473 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
    474 		assert(pAUX_phnum != NULL);
    475 		phnum = pAUX_phnum->a_v;
    476 		assert(pAUX_phent != NULL);
    477 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
    478 		assert(pAUX_entry != NULL);
    479 		entry = (caddr_t) pAUX_entry->a_v;
    480 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    481 		_rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
    482 		    "main program");
    483 		_rtld_objmain->pathlen = strlen(_rtld_objmain->path);
    484 	}
    485 
    486 	_rtld_objmain->mainprog = true;
    487 
    488 	/*
    489 	 * Get the actual dynamic linker pathname from the executable if
    490 	 * possible.  (It should always be possible.)  That ensures that
    491 	 * gdb will find the right dynamic linker even if a non-standard
    492 	 * one is being used.
    493 	 */
    494 	if (_rtld_objmain->interp != NULL &&
    495 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0)
    496 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
    497 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
    498 
    499 	_rtld_digest_dynamic(execname, _rtld_objmain);
    500 
    501 	/* Link the main program into the list of objects. */
    502 	*_rtld_objtail = _rtld_objmain;
    503 	_rtld_objtail = &_rtld_objmain->next;
    504 
    505 	_rtld_linkmap_add(_rtld_objmain);
    506 	_rtld_linkmap_add(&_rtld_objself);
    507 
    508 	++_rtld_objmain->refcount;
    509 	_rtld_objmain->mainref = 1;
    510 	_rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
    511 
    512 	if (_rtld_trust) {
    513 		/*
    514 		 * Pre-load user-specified objects after the main program
    515 		 * but before any shared object dependencies.
    516 		 */
    517 		dbg(("preloading objects"));
    518 		if (_rtld_preload(getenv("LD_PRELOAD")) == -1)
    519 			_rtld_die();
    520 	} else
    521 		if (unsetenv("LD_PRELOAD"))
    522 			_rtld_die();
    523 
    524 	dbg(("loading needed objects"));
    525 	if (_rtld_load_needed_objects(_rtld_objmain, RTLD_MAIN) == -1)
    526 		_rtld_die();
    527 
    528 	dbg(("relocating objects"));
    529 	if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
    530 		_rtld_die();
    531 
    532 	dbg(("doing copy relocations"));
    533 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
    534 		_rtld_die();
    535 
    536 	/*
    537 	 * Set the __progname,  environ and, __mainprog_obj before
    538 	 * calling anything that might use them.
    539 	 */
    540 	real___progname = _rtld_objmain_sym("__progname");
    541 	if (real___progname) {
    542 		if (argv[0] != NULL) {
    543 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
    544 				(*real___progname) = argv[0];
    545 			else
    546 				(*real___progname)++;
    547 		} else {
    548 			(*real___progname) = NULL;
    549 		}
    550 	}
    551 	real_environ = _rtld_objmain_sym("environ");
    552 	if (real_environ)
    553 		*real_environ = environ;
    554 	/*
    555 	 * Set __mainprog_obj for old binaries.
    556 	 */
    557 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
    558 	if (real___mainprog_obj)
    559 		*real___mainprog_obj = _rtld_objmain;
    560 
    561 	dbg(("calling _init functions"));
    562 	_rtld_call_init_functions();
    563 
    564 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
    565 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
    566 
    567 	/*
    568 	 * Return with the entry point and the exit procedure in at the top
    569 	 * of stack.
    570 	 */
    571 
    572 	_rtld_debug_state();	/* say hello to gdb! */
    573 
    574 	((void **) osp)[0] = _rtld_exit;
    575 	((void **) osp)[1] = _rtld_objmain;
    576 	return (Elf_Addr) _rtld_objmain->entry;
    577 }
    578 
    579 void
    580 _rtld_die(void)
    581 {
    582 	const char *msg = dlerror();
    583 
    584 	if (msg == NULL)
    585 		msg = "Fatal error";
    586 	xerrx(1, "%s", msg);
    587 }
    588 
    589 static Obj_Entry *
    590 _rtld_dlcheck(void *handle)
    591 {
    592 	Obj_Entry *obj;
    593 
    594 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    595 		if (obj == (Obj_Entry *) handle)
    596 			break;
    597 
    598 	if (obj == NULL || obj->dl_refcount == 0) {
    599 		xwarnx("Invalid shared object handle %p", handle);
    600 		return NULL;
    601 	}
    602 	return obj;
    603 }
    604 
    605 static void
    606 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
    607 {
    608 	Needed_Entry* elm;
    609 
    610 	/* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
    611 
    612 	if (obj->init_done)
    613 		return;
    614 	obj->init_done = 1;
    615 
    616 	for (elm = obj->needed; elm != NULL; elm = elm->next) {
    617 		if (elm->obj != NULL) {
    618 			_rtld_initlist_visit(list, elm->obj, rev);
    619 		}
    620 	}
    621 
    622 	if (rev) {
    623 		_rtld_objlist_push_head(list, obj);
    624 	} else {
    625 		_rtld_objlist_push_tail(list, obj);
    626 	}
    627 }
    628 
    629 static void
    630 _rtld_initlist_tsort(Objlist* list, int rev)
    631 {
    632 	dbg(("_rtld_initlist_tsort"));
    633 
    634 	Obj_Entry* obj;
    635 
    636 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    637 		obj->init_done = 0;
    638 	}
    639 
    640 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    641 		_rtld_initlist_visit(list, obj, rev);
    642 	}
    643 }
    644 
    645 static void
    646 _rtld_init_dag(Obj_Entry *root)
    647 {
    648 
    649 	_rtld_init_dag1(root, root);
    650 }
    651 
    652 static void
    653 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
    654 {
    655 	const Needed_Entry *needed;
    656 
    657 	if (!obj->mainref) {
    658 		if (_rtld_objlist_find(&obj->dldags, root))
    659 			return;
    660 		rdbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
    661 		    root->path));
    662 		_rtld_objlist_push_tail(&obj->dldags, root);
    663 		_rtld_objlist_push_tail(&root->dagmembers, obj);
    664 	}
    665 	for (needed = obj->needed; needed != NULL; needed = needed->next)
    666 		if (needed->obj != NULL)
    667 			_rtld_init_dag1(root, needed->obj);
    668 }
    669 
    670 /*
    671  * Note, this is called only for objects loaded by dlopen().
    672  */
    673 static void
    674 _rtld_unload_object(Obj_Entry *root, bool do_fini_funcs)
    675 {
    676 
    677 	_rtld_unref_dag(root);
    678 	if (root->refcount == 0) { /* We are finished with some objects. */
    679 		Obj_Entry *obj;
    680 		Obj_Entry **linkp;
    681 		Objlist_Entry *elm;
    682 
    683 		/* Finalize objects that are about to be unmapped. */
    684 		if (do_fini_funcs)
    685 			_rtld_call_fini_functions(0);
    686 
    687 		/* Remove the DAG from all objects' DAG lists. */
    688 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
    689 			_rtld_objlist_remove(&elm->obj->dldags, root);
    690 
    691 		/* Remove the DAG from the RTLD_GLOBAL list. */
    692 		if (root->globalref) {
    693 			root->globalref = 0;
    694 			_rtld_objlist_remove(&_rtld_list_global, root);
    695 		}
    696 
    697 		/* Unmap all objects that are no longer referenced. */
    698 		linkp = &_rtld_objlist->next;
    699 		while ((obj = *linkp) != NULL) {
    700 			if (obj->refcount == 0) {
    701 #ifdef RTLD_DEBUG
    702 				dbg(("unloading \"%s\"", obj->path));
    703 #endif
    704 				if (obj->ehdr != MAP_FAILED)
    705 					munmap(obj->ehdr, _rtld_pagesz);
    706 				munmap(obj->mapbase, obj->mapsize);
    707 				_rtld_objlist_remove(&_rtld_list_global, obj);
    708 				_rtld_linkmap_delete(obj);
    709 				*linkp = obj->next;
    710 				_rtld_objcount--;
    711 				_rtld_obj_free(obj);
    712 			} else
    713 				linkp = &obj->next;
    714 		}
    715 		_rtld_objtail = linkp;
    716 	}
    717 }
    718 
    719 static void
    720 _rtld_unref_dag(Obj_Entry *root)
    721 {
    722 
    723 	assert(root);
    724 	assert(root->refcount != 0);
    725 	--root->refcount;
    726 	if (root->refcount == 0) {
    727 		const Needed_Entry *needed;
    728 
    729 		for (needed = root->needed; needed != NULL;
    730 		     needed = needed->next) {
    731 			if (needed->obj != NULL)
    732 				_rtld_unref_dag(needed->obj);
    733 		}
    734 	}
    735 }
    736 
    737 __strong_alias(__dlclose,dlclose)
    738 int
    739 dlclose(void *handle)
    740 {
    741 	Obj_Entry *root = _rtld_dlcheck(handle);
    742 
    743 	if (root == NULL)
    744 		return -1;
    745 
    746 	_rtld_debug.r_state = RT_DELETE;
    747 	_rtld_debug_state();
    748 
    749 	--root->dl_refcount;
    750 	_rtld_unload_object(root, true);
    751 
    752 	_rtld_debug.r_state = RT_CONSISTENT;
    753 	_rtld_debug_state();
    754 
    755 	return 0;
    756 }
    757 
    758 __strong_alias(__dlerror,dlerror)
    759 char *
    760 dlerror(void)
    761 {
    762 	char *msg = error_message;
    763 
    764 	error_message = NULL;
    765 	return msg;
    766 }
    767 
    768 __strong_alias(__dlopen,dlopen)
    769 void *
    770 dlopen(const char *name, int mode)
    771 {
    772 	Obj_Entry **old_obj_tail = _rtld_objtail;
    773 	Obj_Entry *obj = NULL;
    774 
    775 	_rtld_debug.r_state = RT_ADD;
    776 	_rtld_debug_state();
    777 
    778 	if (name == NULL) {
    779 		obj = _rtld_objmain;
    780 		obj->refcount++;
    781 	} else
    782 		obj = _rtld_load_library(name, _rtld_objmain, mode);
    783 
    784 	if (obj != NULL) {
    785 		++obj->dl_refcount;
    786 		if (*old_obj_tail != NULL) {	/* We loaded something new. */
    787 			assert(*old_obj_tail == obj);
    788 
    789 			if (_rtld_load_needed_objects(obj, mode) == -1 ||
    790 			    (_rtld_init_dag(obj),
    791 			    _rtld_relocate_objects(obj,
    792 			    ((mode & 3) == RTLD_NOW))) == -1) {
    793 				_rtld_unload_object(obj, false);
    794 				obj->dl_refcount--;
    795 				obj = NULL;
    796 			} else {
    797 				_rtld_call_init_functions();
    798 			}
    799 		}
    800 	}
    801 	_rtld_debug.r_state = RT_CONSISTENT;
    802 	_rtld_debug_state();
    803 
    804 	return obj;
    805 }
    806 
    807 /*
    808  * Find a symbol in the main program.
    809  */
    810 void *
    811 _rtld_objmain_sym(const char *name)
    812 {
    813 	unsigned long hash;
    814 	const Elf_Sym *def;
    815 	const Obj_Entry *obj;
    816 	DoneList donelist;
    817 
    818 	hash = _rtld_elf_hash(name);
    819 	obj = _rtld_objmain;
    820 	_rtld_donelist_init(&donelist);
    821 
    822 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, false,
    823 	    &donelist);
    824 
    825 	_rtld_donelist_clear(&donelist);
    826 
    827 	if (def != NULL)
    828 		return obj->relocbase + def->st_value;
    829 	return(NULL);
    830 }
    831 
    832 #ifdef __powerpc__
    833 static void *
    834 hackish_return_address(void)
    835 {
    836 	return __builtin_return_address(1);
    837 }
    838 #endif
    839 
    840 __strong_alias(__dlsym,dlsym)
    841 void *
    842 dlsym(void *handle, const char *name)
    843 {
    844 	const Obj_Entry *obj;
    845 	unsigned long hash;
    846 	const Elf_Sym *def;
    847 	const Obj_Entry *defobj;
    848 	void *retaddr;
    849 	DoneList donelist;
    850 
    851 	hash = _rtld_elf_hash(name);
    852 	def = NULL;
    853 	defobj = NULL;
    854 
    855 	switch ((intptr_t)handle) {
    856 	case (intptr_t)NULL:
    857 	case (intptr_t)RTLD_NEXT:
    858 	case (intptr_t)RTLD_DEFAULT:
    859 	case (intptr_t)RTLD_SELF:
    860 #ifdef __powerpc__
    861 		retaddr = hackish_return_address();
    862 #else
    863 		retaddr = __builtin_return_address(0);
    864 #endif
    865 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
    866 			_rtld_error("Cannot determine caller's shared object");
    867 			return NULL;
    868 		}
    869 
    870 		switch ((intptr_t)handle) {
    871 		case (intptr_t)NULL:	 /* Just the caller's shared object. */
    872 			def = _rtld_symlook_obj(name, hash, obj, false);
    873 			defobj = obj;
    874 			break;
    875 
    876 		case (intptr_t)RTLD_NEXT:	/* Objects after callers */
    877 			obj = obj->next;
    878 			/*FALLTHROUGH*/
    879 
    880 		case (intptr_t)RTLD_SELF:	/* Caller included */
    881 			for (; obj; obj = obj->next) {
    882 				if ((def = _rtld_symlook_obj(name, hash, obj,
    883 				    false)) != NULL) {
    884 					defobj = obj;
    885 					break;
    886 				}
    887 			}
    888 			break;
    889 
    890 		case (intptr_t)RTLD_DEFAULT:
    891 			def = _rtld_symlook_default(name, hash, obj, &defobj,
    892 			    false);
    893 			break;
    894 
    895 		default:
    896 			abort();
    897 		}
    898 		break;
    899 
    900 	default:
    901 		if ((obj = _rtld_dlcheck(handle)) == NULL)
    902 			return NULL;
    903 
    904 		_rtld_donelist_init(&donelist);
    905 
    906 		if (obj->mainprog) {
    907 			/* Search main program and all libraries loaded by it */
    908 			def = _rtld_symlook_list(name, hash, &_rtld_list_main,
    909 			    &defobj, false, &donelist);
    910 		} else {
    911 			Needed_Entry fake;
    912 			DoneList depth;
    913 
    914 			/* Search the object and all the libraries loaded by it. */
    915 			fake.next = NULL;
    916 			fake.obj = __UNCONST(obj);
    917 			fake.name = 0;
    918 
    919 			_rtld_donelist_init(&depth);
    920 			def = _rtld_symlook_needed(name, hash, &fake, &defobj,
    921 			    false, &donelist, &depth);
    922 			_rtld_donelist_clear(&depth);
    923 		}
    924 
    925 		_rtld_donelist_clear(&donelist);
    926 		break;
    927 	}
    928 
    929 	if (def != NULL) {
    930 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    931 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC)
    932 			return (void *)_rtld_function_descriptor_alloc(defobj,
    933 			    def, 0);
    934 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    935 		return defobj->relocbase + def->st_value;
    936 	}
    937 
    938 	_rtld_error("Undefined symbol \"%s\"", name);
    939 	return NULL;
    940 }
    941 
    942 __strong_alias(__dladdr,dladdr)
    943 int
    944 dladdr(const void *addr, Dl_info *info)
    945 {
    946 	const Obj_Entry *obj;
    947 	const Elf_Sym *def, *best_def;
    948 	void *symbol_addr;
    949 	unsigned long symoffset;
    950 
    951 #ifdef __HAVE_FUNCTION_DESCRIPTORS
    952 	addr = _rtld_function_descriptor_function(addr);
    953 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
    954 
    955 	obj = _rtld_obj_from_addr(addr);
    956 	if (obj == NULL) {
    957 		_rtld_error("No shared object contains address");
    958 		return 0;
    959 	}
    960 	info->dli_fname = obj->path;
    961 	info->dli_fbase = obj->mapbase;
    962 	info->dli_saddr = (void *)0;
    963 	info->dli_sname = NULL;
    964 
    965 	/*
    966 	 * Walk the symbol list looking for the symbol whose address is
    967 	 * closest to the address sent in.
    968 	 */
    969 	best_def = NULL;
    970 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
    971 		def = obj->symtab + symoffset;
    972 
    973 		/*
    974 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
    975 		 * SHN_COMMON.
    976 		 */
    977 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
    978 			continue;
    979 
    980 		/*
    981 		 * If the symbol is greater than the specified address, or if it
    982 		 * is further away from addr than the current nearest symbol,
    983 		 * then reject it.
    984 		 */
    985 		symbol_addr = obj->relocbase + def->st_value;
    986 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
    987 			continue;
    988 
    989 		/* Update our idea of the nearest symbol. */
    990 		info->dli_sname = obj->strtab + def->st_name;
    991 		info->dli_saddr = symbol_addr;
    992 		best_def = def;
    993 
    994 		/* Exact match? */
    995 		if (info->dli_saddr == addr)
    996 			break;
    997 	}
    998 
    999 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1000 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
   1001 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
   1002 		    best_def, 0);
   1003 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   1004 
   1005 	return 1;
   1006 }
   1007 
   1008 __strong_alias(__dlinfo,dlinfo)
   1009 int
   1010 dlinfo(void *handle, int req, void *v)
   1011 {
   1012 	const Obj_Entry *obj;
   1013 	void *retaddr;
   1014 
   1015 	if (handle == RTLD_SELF) {
   1016 #ifdef __powerpc__
   1017 		retaddr = hackish_return_address();
   1018 #else
   1019 		retaddr = __builtin_return_address(0);
   1020 #endif
   1021 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   1022 			_rtld_error("Cannot determine caller's shared object");
   1023 			return -1;
   1024 		}
   1025 	} else {
   1026 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   1027 			_rtld_error("Invalid handle");
   1028 			return -1;
   1029 		}
   1030 	}
   1031 
   1032 	switch (req) {
   1033 	case RTLD_DI_LINKMAP:
   1034 		{
   1035 		const struct link_map **map = v;
   1036 
   1037 		*map = &obj->linkmap;
   1038 		break;
   1039 		}
   1040 
   1041 	default:
   1042 		_rtld_error("Invalid request");
   1043 		return -1;
   1044 	}
   1045 
   1046 	return 0;
   1047 }
   1048 
   1049 /*
   1050  * Error reporting function.  Use it like printf.  If formats the message
   1051  * into a buffer, and sets things up so that the next call to dlerror()
   1052  * will return the message.
   1053  */
   1054 void
   1055 _rtld_error(const char *fmt,...)
   1056 {
   1057 	static char     buf[512];
   1058 	va_list         ap;
   1059 
   1060 	va_start(ap, fmt);
   1061 	xvsnprintf(buf, sizeof buf, fmt, ap);
   1062 	error_message = buf;
   1063 	va_end(ap);
   1064 }
   1065 
   1066 void
   1067 _rtld_debug_state(void)
   1068 {
   1069 
   1070 	/* do nothing */
   1071 }
   1072 
   1073 void
   1074 _rtld_linkmap_add(Obj_Entry *obj)
   1075 {
   1076 	struct link_map *l = &obj->linkmap;
   1077 	struct link_map *prev;
   1078 
   1079 	obj->linkmap.l_name = obj->path;
   1080 	obj->linkmap.l_addr = obj->relocbase;
   1081 	obj->linkmap.l_ld = obj->dynamic;
   1082 #ifdef __mips__
   1083 	/* XXX This field is not standard and will be removed eventually. */
   1084 	obj->linkmap.l_offs = obj->relocbase;
   1085 #endif
   1086 
   1087 	if (_rtld_debug.r_map == NULL) {
   1088 		_rtld_debug.r_map = l;
   1089 		return;
   1090 	}
   1091 
   1092 	/*
   1093 	 * Scan to the end of the list, but not past the entry for the
   1094 	 * dynamic linker, which we want to keep at the very end.
   1095 	 */
   1096 	for (prev = _rtld_debug.r_map;
   1097 	    prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
   1098 	    prev = prev->l_next);
   1099 
   1100 	l->l_prev = prev;
   1101 	l->l_next = prev->l_next;
   1102 	if (l->l_next != NULL)
   1103 		l->l_next->l_prev = l;
   1104 	prev->l_next = l;
   1105 }
   1106 
   1107 void
   1108 _rtld_linkmap_delete(Obj_Entry *obj)
   1109 {
   1110 	struct link_map *l = &obj->linkmap;
   1111 
   1112 	if (l->l_prev == NULL) {
   1113 		if ((_rtld_debug.r_map = l->l_next) != NULL)
   1114 			l->l_next->l_prev = NULL;
   1115 		return;
   1116 	}
   1117 	if ((l->l_prev->l_next = l->l_next) != NULL)
   1118 		l->l_next->l_prev = l->l_prev;
   1119 }
   1120 
   1121 static Obj_Entry *
   1122 _rtld_obj_from_addr(const void *addr)
   1123 {
   1124 	Obj_Entry *obj;
   1125 
   1126 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   1127 		if (addr < (void *) obj->mapbase)
   1128 			continue;
   1129 		if (addr < (void *) (obj->mapbase + obj->mapsize))
   1130 			return obj;
   1131 	}
   1132 	return NULL;
   1133 }
   1134 
   1135 static void
   1136 _rtld_objlist_clear(Objlist *list)
   1137 {
   1138 	while (!SIMPLEQ_EMPTY(list)) {
   1139 		Objlist_Entry* elm = SIMPLEQ_FIRST(list);
   1140 		SIMPLEQ_REMOVE_HEAD(list, link);
   1141 		xfree(elm);
   1142 	}
   1143 }
   1144 
   1145 static void
   1146 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
   1147 {
   1148 	Objlist_Entry *elm;
   1149 
   1150 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
   1151 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
   1152 		xfree(elm);
   1153 	}
   1154 }
   1155