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