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