Home | History | Annotate | Line # | Download | only in ld.elf_so
rtld.c revision 1.198
      1 /*	$NetBSD: rtld.c,v 1.198 2019/09/15 13:40:46 kamil 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.198 2019/09/15 13:40:46 kamil Exp $");
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/atomic.h>
     48 #include <sys/mman.h>
     49 #include <err.h>
     50 #include <errno.h>
     51 #include <fcntl.h>
     52 #include <lwp.h>
     53 #include <stdarg.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <unistd.h>
     58 #include <dirent.h>
     59 
     60 #include <ctype.h>
     61 
     62 #include <dlfcn.h>
     63 #include "debug.h"
     64 #include "rtld.h"
     65 
     66 #if !defined(lint)
     67 #include "sysident.h"
     68 #endif
     69 
     70 /*
     71  * Function declarations.
     72  */
     73 static void     _rtld_init(caddr_t, caddr_t, const char *);
     74 static void     _rtld_exit(void);
     75 
     76 Elf_Addr        _rtld(Elf_Addr *, Elf_Addr);
     77 
     78 
     79 /*
     80  * Data declarations.
     81  */
     82 static char    *error_message;	/* Message for dlopen(), or NULL */
     83 
     84 struct r_debug  _rtld_debug;	/* for GDB; */
     85 bool            _rtld_trust;	/* False for setuid and setgid programs */
     86 Obj_Entry      *_rtld_objlist;	/* Head of linked list of shared objects */
     87 Obj_Entry     **_rtld_objtail;	/* Link field of last object in list */
     88 Obj_Entry      *_rtld_objmain;	/* The main program shared object */
     89 Obj_Entry       _rtld_objself;	/* The dynamic linker shared object */
     90 u_int		_rtld_objcount;	/* Number of objects in _rtld_objlist */
     91 u_int		_rtld_objloads;	/* Number of objects loaded in _rtld_objlist */
     92 u_int		_rtld_objgen;	/* Generation count for _rtld_objlist */
     93 const char	_rtld_path[] = _PATH_RTLD;
     94 
     95 /* Initialize a fake symbol for resolving undefined weak references. */
     96 Elf_Sym		_rtld_sym_zero = {
     97     .st_info	= ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
     98     .st_shndx	= SHN_ABS,
     99 };
    100 size_t	_rtld_pagesz;	/* Page size, as provided by kernel */
    101 
    102 Search_Path    *_rtld_default_paths;
    103 Search_Path    *_rtld_paths;
    104 
    105 Library_Xform  *_rtld_xforms;
    106 static void    *auxinfo;
    107 
    108 /*
    109  * Global declarations normally provided by crt0.
    110  */
    111 char           *__progname;
    112 char          **environ;
    113 
    114 static volatile bool _rtld_mutex_may_recurse;
    115 
    116 #if defined(RTLD_DEBUG)
    117 #ifndef __sh__
    118 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
    119 #else  /* 32-bit SuperH */
    120 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
    121 #endif
    122 #endif /* RTLD_DEBUG */
    123 extern Elf_Dyn  _DYNAMIC;
    124 
    125 static void _rtld_call_fini_functions(sigset_t *, int);
    126 static void _rtld_call_init_functions(sigset_t *);
    127 static void _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
    128 static void _rtld_initlist_tsort(Objlist *, int);
    129 static Obj_Entry *_rtld_dlcheck(void *);
    130 static void _rtld_init_dag(Obj_Entry *);
    131 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
    132 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
    133 static void _rtld_objlist_clear(Objlist *);
    134 static void _rtld_unload_object(sigset_t *, Obj_Entry *, bool);
    135 static void _rtld_unref_dag(Obj_Entry *);
    136 static Obj_Entry *_rtld_obj_from_addr(const void *);
    137 static void _rtld_fill_dl_phdr_info(const Obj_Entry *, struct dl_phdr_info *);
    138 
    139 static inline void
    140 _rtld_call_initfini_function(const Obj_Entry *obj, Elf_Addr func, sigset_t *mask)
    141 {
    142 	_rtld_exclusive_exit(mask);
    143 	_rtld_call_function_void(obj, func);
    144 	_rtld_exclusive_enter(mask);
    145 }
    146 
    147 static void
    148 _rtld_call_fini_function(Obj_Entry *obj, sigset_t *mask, u_int cur_objgen)
    149 {
    150 	if (obj->fini_arraysz == 0 && (obj->fini == 0 || obj->fini_called))
    151 		return;
    152 
    153 	if (obj->fini != 0 && !obj->fini_called) {
    154 		dbg (("calling fini function %s at %p%s", obj->path,
    155 		    (void *)obj->fini,
    156 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    157 		obj->fini_called = 1;
    158 		_rtld_call_initfini_function(obj, obj->fini, mask);
    159 	}
    160 #ifdef HAVE_INITFINI_ARRAY
    161 	/*
    162 	 * Now process the fini_array if it exists.  Simply go from
    163 	 * start to end.  We need to make restartable so just advance
    164 	 * the array pointer and decrement the size each time through
    165 	 * the loop.
    166 	 */
    167 	while (obj->fini_arraysz > 0 && _rtld_objgen == cur_objgen) {
    168 		Elf_Addr fini = *obj->fini_array++;
    169 		obj->fini_arraysz--;
    170 		dbg (("calling fini array function %s at %p%s", obj->path,
    171 		    (void *)fini,
    172 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    173 		_rtld_call_initfini_function(obj, fini, mask);
    174 	}
    175 #endif /* HAVE_INITFINI_ARRAY */
    176 }
    177 
    178 static void
    179 _rtld_call_fini_functions(sigset_t *mask, int force)
    180 {
    181 	Objlist_Entry *elm;
    182 	Objlist finilist;
    183 	u_int cur_objgen;
    184 
    185 	dbg(("_rtld_call_fini_functions(%d)", force));
    186 
    187 restart:
    188 	cur_objgen = ++_rtld_objgen;
    189 	SIMPLEQ_INIT(&finilist);
    190 	_rtld_initlist_tsort(&finilist, 1);
    191 
    192 	/* First pass: objects _not_ marked with DF_1_INITFIRST. */
    193 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    194 		Obj_Entry * const obj = elm->obj;
    195 		if (!obj->z_initfirst) {
    196 			if (obj->refcount > 0 && !force) {
    197 				continue;
    198 			}
    199 			/*
    200 			 * XXX This can race against a concurrent dlclose().
    201 			 * XXX In that case, the object could be unmapped before
    202 			 * XXX the fini() call or the fini_array has completed.
    203 			 */
    204 			_rtld_call_fini_function(obj, mask, cur_objgen);
    205 			if (_rtld_objgen != cur_objgen) {
    206 				dbg(("restarting fini iteration"));
    207 				_rtld_objlist_clear(&finilist);
    208 				goto restart;
    209 		}
    210 		}
    211 	}
    212 
    213 	/* Second pass: objects marked with DF_1_INITFIRST. */
    214 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    215 		Obj_Entry * const obj = elm->obj;
    216 		if (obj->refcount > 0 && !force) {
    217 			continue;
    218 		}
    219 		/* XXX See above for the race condition here */
    220 		_rtld_call_fini_function(obj, mask, cur_objgen);
    221 		if (_rtld_objgen != cur_objgen) {
    222 			dbg(("restarting fini iteration"));
    223 			_rtld_objlist_clear(&finilist);
    224 			goto restart;
    225 		}
    226 	}
    227 
    228         _rtld_objlist_clear(&finilist);
    229 }
    230 
    231 static void
    232 _rtld_call_init_function(Obj_Entry *obj, sigset_t *mask, u_int cur_objgen)
    233 {
    234 	if (obj->init_arraysz == 0 && (obj->init_called || obj->init == 0))
    235 		return;
    236 
    237 	if (!obj->init_called && obj->init != 0) {
    238 		dbg (("calling init function %s at %p%s",
    239 		    obj->path, (void *)obj->init,
    240 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    241 		obj->init_called = 1;
    242 		_rtld_call_initfini_function(obj, obj->init, mask);
    243 	}
    244 
    245 #ifdef HAVE_INITFINI_ARRAY
    246 	/*
    247 	 * Now process the init_array if it exists.  Simply go from
    248 	 * start to end.  We need to make restartable so just advance
    249 	 * the array pointer and decrement the size each time through
    250 	 * the loop.
    251 	 */
    252 	while (obj->init_arraysz > 0 && _rtld_objgen == cur_objgen) {
    253 		Elf_Addr init = *obj->init_array++;
    254 		obj->init_arraysz--;
    255 		dbg (("calling init_array function %s at %p%s",
    256 		    obj->path, (void *)init,
    257 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    258 		_rtld_call_initfini_function(obj, init, mask);
    259 	}
    260 #endif /* HAVE_INITFINI_ARRAY */
    261 }
    262 
    263 static bool
    264 _rtld_call_ifunc_functions(sigset_t *mask, Obj_Entry *obj, u_int cur_objgen)
    265 {
    266 	if (obj->ifunc_remaining
    267 #if defined(IFUNC_NONPLT)
    268 	    || obj->ifunc_remaining_nonplt
    269 #endif
    270 	) {
    271 		_rtld_call_ifunc(obj, mask, cur_objgen);
    272 		if (_rtld_objgen != cur_objgen) {
    273 			return true;
    274 		}
    275 	}
    276 	return false;
    277 }
    278 
    279 static void
    280 _rtld_call_init_functions(sigset_t *mask)
    281 {
    282 	Objlist_Entry *elm;
    283 	Objlist initlist;
    284 	u_int cur_objgen;
    285 
    286 	dbg(("_rtld_call_init_functions()"));
    287 
    288 restart:
    289 	cur_objgen = ++_rtld_objgen;
    290 	SIMPLEQ_INIT(&initlist);
    291 	_rtld_initlist_tsort(&initlist, 0);
    292 
    293 	/* First pass: objects with IRELATIVE relocations. */
    294 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    295 		if (_rtld_call_ifunc_functions(mask, elm->obj, cur_objgen)) {
    296 			dbg(("restarting init iteration"));
    297 			_rtld_objlist_clear(&initlist);
    298 			goto restart;
    299 		}
    300 	}
    301 	/*
    302 	 * XXX: For historic reasons, init/fini of the main object are called
    303 	 * from crt0. Don't introduce that mistake for ifunc, so look at
    304 	 * the head of _rtld_objlist that _rtld_initlist_tsort skipped.
    305 	 */
    306 	if (_rtld_call_ifunc_functions(mask, _rtld_objlist, cur_objgen)) {
    307 		dbg(("restarting init iteration"));
    308 		_rtld_objlist_clear(&initlist);
    309 		goto restart;
    310 	}
    311 
    312 	/* Second pass: objects marked with DF_1_INITFIRST. */
    313 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    314 		Obj_Entry * const obj = elm->obj;
    315 		if (obj->z_initfirst) {
    316 			_rtld_call_init_function(obj, mask, cur_objgen);
    317 			if (_rtld_objgen != cur_objgen) {
    318 				dbg(("restarting init iteration"));
    319 				_rtld_objlist_clear(&initlist);
    320 				goto restart;
    321 			}
    322 		}
    323 	}
    324 
    325 	/* Third pass: all other objects. */
    326 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    327 		_rtld_call_init_function(elm->obj, mask, cur_objgen);
    328 		if (_rtld_objgen != cur_objgen) {
    329 			dbg(("restarting init iteration"));
    330 			_rtld_objlist_clear(&initlist);
    331 			goto restart;
    332 		}
    333 	}
    334 
    335         _rtld_objlist_clear(&initlist);
    336 }
    337 
    338 /*
    339  * Initialize the dynamic linker.  The argument is the address at which
    340  * the dynamic linker has been mapped into memory.  The primary task of
    341  * this function is to create an Obj_Entry for the dynamic linker and
    342  * to resolve the PLT relocation for platforms that need it (those that
    343  * define __HAVE_FUNCTION_DESCRIPTORS
    344  */
    345 static void
    346 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
    347 {
    348 	const Elf_Ehdr *ehdr;
    349 
    350 	/* Conjure up an Obj_Entry structure for the dynamic linker. */
    351 	_rtld_objself.path = __UNCONST(_rtld_path);
    352 	_rtld_objself.pathlen = sizeof(_rtld_path)-1;
    353 	_rtld_objself.rtld = true;
    354 	_rtld_objself.mapbase = mapbase;
    355 	_rtld_objself.relocbase = relocbase;
    356 	_rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
    357 	_rtld_objself.strtab = "_rtld_sym_zero";
    358 
    359 	/*
    360 	 * Set value to -relocbase so that
    361 	 *
    362 	 *     _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
    363 	 *
    364 	 * This allows unresolved references to weak symbols to be computed
    365 	 * to a value of 0.
    366 	 */
    367 	_rtld_sym_zero.st_value = -(uintptr_t)relocbase;
    368 
    369 	_rtld_digest_dynamic(_rtld_path, &_rtld_objself);
    370 	assert(!_rtld_objself.needed);
    371 #if !defined(__hppa__)
    372 	assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
    373 #else
    374 	_rtld_relocate_plt_objects(&_rtld_objself);
    375 #endif
    376 #if !defined(__mips__) && !defined(__hppa__)
    377 	assert(!_rtld_objself.pltgot);
    378 #endif
    379 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
    380 	/* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
    381 	assert(!_rtld_objself.textrel);
    382 #endif
    383 
    384 	_rtld_add_paths(execname, &_rtld_default_paths,
    385 	    RTLD_DEFAULT_LIBRARY_PATH);
    386 
    387 #ifdef RTLD_ARCH_SUBDIR
    388 	_rtld_add_paths(execname, &_rtld_default_paths,
    389 	    RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
    390 #endif
    391 
    392 	/* Make the object list empty. */
    393 	_rtld_objlist = NULL;
    394 	_rtld_objtail = &_rtld_objlist;
    395 	_rtld_objcount = 0;
    396 
    397 	_rtld_debug.r_brk = _rtld_debug_state;
    398 	_rtld_debug.r_state = RT_CONSISTENT;
    399 
    400 	ehdr = (Elf_Ehdr *)mapbase;
    401 	_rtld_objself.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
    402 	_rtld_objself.phsize = ehdr->e_phnum * sizeof(_rtld_objself.phdr[0]);
    403 }
    404 
    405 /*
    406  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    407  * before the process exits.
    408  */
    409 static void
    410 _rtld_exit(void)
    411 {
    412 	sigset_t mask;
    413 
    414 	dbg(("rtld_exit()"));
    415 
    416 	_rtld_exclusive_enter(&mask);
    417 
    418 	_rtld_call_fini_functions(&mask, 1);
    419 
    420 	_rtld_exclusive_exit(&mask);
    421 }
    422 
    423 __dso_public void *
    424 _dlauxinfo(void)
    425 {
    426 	return auxinfo;
    427 }
    428 
    429 /*
    430  * Main entry point for dynamic linking.  The argument is the stack
    431  * pointer.  The stack is expected to be laid out as described in the
    432  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    433  * the stack pointer points to a word containing ARGC.  Following that
    434  * in the stack is a null-terminated sequence of pointers to argument
    435  * strings.  Then comes a null-terminated sequence of pointers to
    436  * environment strings.  Finally, there is a sequence of "auxiliary
    437  * vector" entries.
    438  *
    439  * This function returns the entry point for the main program, the dynamic
    440  * linker's exit procedure in sp[0], and a pointer to the main object in
    441  * sp[1].
    442  */
    443 Elf_Addr
    444 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
    445 {
    446 	const AuxInfo  *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
    447 	               *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
    448 		       *pAUX_ruid, *pAUX_rgid;
    449 	const AuxInfo  *pAUX_pagesz;
    450 	char          **env, **oenvp;
    451 	const AuxInfo  *auxp;
    452 	Obj_Entry      *obj;
    453 	Elf_Addr       *const osp = sp;
    454 	bool            bind_now = 0;
    455 	const char     *ld_bind_now, *ld_preload, *ld_library_path;
    456 	const char    **argv;
    457 	const char     *execname;
    458 	long		argc;
    459 	const char **real___progname;
    460 	const Obj_Entry **real___mainprog_obj;
    461 	char ***real_environ;
    462 	sigset_t        mask;
    463 #ifdef DEBUG
    464 	const char     *ld_debug;
    465 #endif
    466 #ifdef RTLD_DEBUG
    467 	int i = 0;
    468 #endif
    469 
    470 	/*
    471          * On entry, the dynamic linker itself has not been relocated yet.
    472          * Be very careful not to reference any global data until after
    473          * _rtld_init has returned.  It is OK to reference file-scope statics
    474          * and string constants, and to call static and global functions.
    475          */
    476 	/* Find the auxiliary vector on the stack. */
    477 	/* first Elf_Word reserved to address of exit routine */
    478 #if defined(RTLD_DEBUG)
    479 	debug = 1;
    480 	dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
    481 	    (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
    482 #ifndef __x86_64__
    483 	dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
    484 	    &_DYNAMIC));
    485 #endif
    486 #endif
    487 
    488 	sp += 2;		/* skip over return argument space */
    489 	argv = (const char **) &sp[1];
    490 	argc = *(long *)sp;
    491 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
    492 				 * terminator */
    493 	env = (char **) sp;
    494 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    495 #if defined(RTLD_DEBUG)
    496 		dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
    497 #endif
    498 	}
    499 	auxinfo = (AuxInfo *) sp;
    500 
    501 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
    502 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
    503 	pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
    504 	pAUX_pagesz = NULL;
    505 
    506 	execname = NULL;
    507 
    508 	/* Digest the auxiliary vector. */
    509 	for (auxp = auxinfo; auxp->a_type != AT_NULL; ++auxp) {
    510 		switch (auxp->a_type) {
    511 		case AT_BASE:
    512 			pAUX_base = auxp;
    513 			break;
    514 		case AT_ENTRY:
    515 			pAUX_entry = auxp;
    516 			break;
    517 		case AT_EXECFD:
    518 			pAUX_execfd = auxp;
    519 			break;
    520 		case AT_PHDR:
    521 			pAUX_phdr = auxp;
    522 			break;
    523 		case AT_PHENT:
    524 			pAUX_phent = auxp;
    525 			break;
    526 		case AT_PHNUM:
    527 			pAUX_phnum = auxp;
    528 			break;
    529 #ifdef AT_EUID
    530 		case AT_EUID:
    531 			pAUX_euid = auxp;
    532 			break;
    533 		case AT_RUID:
    534 			pAUX_ruid = auxp;
    535 			break;
    536 		case AT_EGID:
    537 			pAUX_egid = auxp;
    538 			break;
    539 		case AT_RGID:
    540 			pAUX_rgid = auxp;
    541 			break;
    542 #endif
    543 #ifdef AT_SUN_EXECNAME
    544 		case AT_SUN_EXECNAME:
    545 			execname = (const char *)(const void *)auxp->a_v;
    546 			break;
    547 #endif
    548 		case AT_PAGESZ:
    549 			pAUX_pagesz = auxp;
    550 			break;
    551 		}
    552 	}
    553 
    554 	/* Initialize and relocate ourselves. */
    555 	if (pAUX_base == NULL) {
    556 		_rtld_error("Bad pAUX_base");
    557 		_rtld_die();
    558 	}
    559 	assert(pAUX_pagesz != NULL);
    560 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
    561 	_rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
    562 
    563 	__progname = _rtld_objself.path;
    564 	environ = env;
    565 
    566 	_rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
    567 	    (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
    568 	    ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
    569 	    (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
    570 
    571 #ifdef DEBUG
    572 	ld_debug = NULL;
    573 #endif
    574 	ld_bind_now = NULL;
    575 	ld_library_path = NULL;
    576 	ld_preload = NULL;
    577 	/*
    578 	 * Inline avoid using normal getenv/unsetenv here as the libc
    579 	 * code is quite a bit more complicated.
    580 	 */
    581 	for (oenvp = env; *env != NULL; ++env) {
    582 		static const char bind_var[] = "LD_BIND_NOW=";
    583 		static const char debug_var[] =  "LD_DEBUG=";
    584 		static const char path_var[] = "LD_LIBRARY_PATH=";
    585 		static const char preload_var[] = "LD_PRELOAD=";
    586 #define LEN(x)	(sizeof(x) - 1)
    587 
    588 		if ((*env)[0] != 'L' || (*env)[1] != 'D') {
    589 			/*
    590 			 * Special case to skip most entries without
    591 			 * the more expensive calls to strncmp.
    592 			 */
    593 			*oenvp++ = *env;
    594 		} else if (strncmp(*env, debug_var, LEN(debug_var)) == 0) {
    595 			if (_rtld_trust) {
    596 #ifdef DEBUG
    597 				ld_debug = *env + LEN(debug_var);
    598 #endif
    599 				*oenvp++ = *env;
    600 			}
    601 		} else if (strncmp(*env, bind_var, LEN(bind_var)) == 0) {
    602 			if (_rtld_trust) {
    603 				ld_bind_now = *env + LEN(bind_var);
    604 				*oenvp++ = *env;
    605 			}
    606 		} else if (strncmp(*env, path_var, LEN(path_var)) == 0) {
    607 			if (_rtld_trust) {
    608 				ld_library_path = *env + LEN(path_var);
    609 				*oenvp++ = *env;
    610 			}
    611 		} else if (strncmp(*env, preload_var, LEN(preload_var)) == 0) {
    612 			if (_rtld_trust) {
    613 				ld_preload = *env + LEN(preload_var);
    614 				*oenvp++ = *env;
    615 			}
    616 		} else {
    617 			*oenvp++ = *env;
    618 		}
    619 #undef LEN
    620 	}
    621 	*oenvp++ = NULL;
    622 
    623 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
    624 		bind_now = true;
    625 	if (_rtld_trust) {
    626 #ifdef DEBUG
    627 #ifdef RTLD_DEBUG
    628 		debug = 0;
    629 #endif
    630 		if (ld_debug != NULL && *ld_debug != '\0')
    631 			debug = 1;
    632 #endif
    633 		_rtld_add_paths(execname, &_rtld_paths, ld_library_path);
    634 	} else {
    635 		execname = NULL;
    636 	}
    637 	_rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
    638 	    _PATH_LD_HINTS);
    639 	dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
    640 	     _rtld_objself.mapbase, _rtld_objself.relocbase));
    641 
    642 	/*
    643          * Load the main program, or process its program header if it is
    644          * already loaded.
    645          */
    646 	if (pAUX_execfd != NULL) {	/* Load the main program. */
    647 		int             fd = pAUX_execfd->a_v;
    648 		const char *obj_name = argv[0] ? argv[0] : "main program";
    649 		dbg(("loading main program"));
    650 		_rtld_objmain = _rtld_map_object(obj_name, fd, NULL);
    651 		close(fd);
    652 		if (_rtld_objmain == NULL)
    653 			_rtld_die();
    654 	} else {		/* Main program already loaded. */
    655 		const Elf_Phdr *phdr;
    656 		int             phnum;
    657 		caddr_t         entry;
    658 
    659 		dbg(("processing main program's program header"));
    660 		assert(pAUX_phdr != NULL);
    661 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
    662 		assert(pAUX_phnum != NULL);
    663 		phnum = pAUX_phnum->a_v;
    664 		assert(pAUX_phent != NULL);
    665 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
    666 		assert(pAUX_entry != NULL);
    667 		entry = (caddr_t) pAUX_entry->a_v;
    668 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
    669 		_rtld_objmain->path = xstrdup(argv[0] ? argv[0] :
    670 		    "main program");
    671 		_rtld_objmain->pathlen = strlen(_rtld_objmain->path);
    672 	}
    673 
    674 	_rtld_objmain->mainprog = true;
    675 
    676 	/*
    677 	 * Get the actual dynamic linker pathname from the executable if
    678 	 * possible.  (It should always be possible.)  That ensures that
    679 	 * gdb will find the right dynamic linker even if a non-standard
    680 	 * one is being used.
    681 	 */
    682 	if (_rtld_objmain->interp != NULL &&
    683 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0) {
    684 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
    685 		_rtld_objself.pathlen = strlen(_rtld_objself.path);
    686 	}
    687 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
    688 
    689 	_rtld_digest_dynamic(execname, _rtld_objmain);
    690 
    691 	/* Link the main program into the list of objects. */
    692 	*_rtld_objtail = _rtld_objmain;
    693 	_rtld_objtail = &_rtld_objmain->next;
    694 	_rtld_objcount++;
    695 	_rtld_objloads++;
    696 
    697 	_rtld_linkmap_add(_rtld_objmain);
    698 	_rtld_objself.path = xstrdup(_rtld_objself.path);
    699 	_rtld_linkmap_add(&_rtld_objself);
    700 
    701 	++_rtld_objmain->refcount;
    702 	_rtld_objmain->mainref = 1;
    703 	_rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
    704 
    705 	if (ld_preload) {
    706 		/*
    707 		 * Pre-load user-specified objects after the main program
    708 		 * but before any shared object dependencies.
    709 		 */
    710 		dbg(("preloading objects"));
    711 		if (_rtld_preload(ld_preload) == -1)
    712 			_rtld_die();
    713 	}
    714 
    715 	dbg(("loading needed objects"));
    716 	if (_rtld_load_needed_objects(_rtld_objmain, _RTLD_MAIN) == -1)
    717 		_rtld_die();
    718 
    719 	dbg(("checking for required versions"));
    720 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
    721 		if (_rtld_verify_object_versions(obj) == -1)
    722 			_rtld_die();
    723 	}
    724 
    725 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
    726 	dbg(("initializing initial Thread Local Storage offsets"));
    727 	/*
    728 	 * All initial objects get the TLS space from the static block.
    729 	 */
    730 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    731 		_rtld_tls_offset_allocate(obj);
    732 #endif
    733 
    734 	dbg(("relocating objects"));
    735 	if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
    736 		_rtld_die();
    737 
    738 	dbg(("doing copy relocations"));
    739 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
    740 		_rtld_die();
    741 
    742 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
    743 	dbg(("initializing Thread Local Storage for main thread"));
    744 	/*
    745 	 * Set up TLS area for the main thread.
    746 	 * This has to be done after all relocations are processed,
    747 	 * since .tdata may contain relocations.
    748 	 */
    749 	_rtld_tls_initial_allocation();
    750 #endif
    751 
    752 	/*
    753 	 * Set the __progname,  environ and, __mainprog_obj before
    754 	 * calling anything that might use them.
    755 	 */
    756 	real___progname = _rtld_objmain_sym("__progname");
    757 	if (real___progname) {
    758 		if (argv[0] != NULL) {
    759 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
    760 				(*real___progname) = argv[0];
    761 			else
    762 				(*real___progname)++;
    763 		} else {
    764 			(*real___progname) = NULL;
    765 		}
    766 	}
    767 	real_environ = _rtld_objmain_sym("environ");
    768 	if (real_environ)
    769 		*real_environ = environ;
    770 	/*
    771 	 * Set __mainprog_obj for old binaries.
    772 	 */
    773 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
    774 	if (real___mainprog_obj)
    775 		*real___mainprog_obj = _rtld_objmain;
    776 
    777 	_rtld_debug_state();	/* say hello to gdb! */
    778 
    779 	_rtld_exclusive_enter(&mask);
    780 
    781 	dbg(("calling _init functions"));
    782 	_rtld_call_init_functions(&mask);
    783 
    784 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
    785 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
    786 
    787 	_rtld_exclusive_exit(&mask);
    788 
    789 	/*
    790 	 * Return with the entry point and the exit procedure in at the top
    791 	 * of stack.
    792 	 */
    793 
    794 	((void **) osp)[0] = _rtld_exit;
    795 	((void **) osp)[1] = __UNCONST(_rtld_compat_obj);
    796 	return (Elf_Addr) _rtld_objmain->entry;
    797 }
    798 
    799 void
    800 _rtld_die(void)
    801 {
    802 	const char *msg = dlerror();
    803 
    804 	if (msg == NULL)
    805 		msg = "Fatal error";
    806 	xerrx(1, "%s", msg);
    807 }
    808 
    809 static Obj_Entry *
    810 _rtld_dlcheck(void *handle)
    811 {
    812 	Obj_Entry *obj;
    813 
    814 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
    815 		if (obj == (Obj_Entry *) handle)
    816 			break;
    817 
    818 	if (obj == NULL || obj->dl_refcount == 0) {
    819 		_rtld_error("Invalid shared object handle %p", handle);
    820 		return NULL;
    821 	}
    822 	return obj;
    823 }
    824 
    825 static void
    826 _rtld_initlist_visit(Objlist* list, Obj_Entry *obj, int rev)
    827 {
    828 	Needed_Entry* elm;
    829 
    830 	/* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
    831 
    832 	if (obj->init_done)
    833 		return;
    834 	obj->init_done = 1;
    835 
    836 	for (elm = obj->needed; elm != NULL; elm = elm->next) {
    837 		if (elm->obj != NULL) {
    838 			_rtld_initlist_visit(list, elm->obj, rev);
    839 		}
    840 	}
    841 
    842 	if (rev) {
    843 		_rtld_objlist_push_head(list, obj);
    844 	} else {
    845 		_rtld_objlist_push_tail(list, obj);
    846 	}
    847 }
    848 
    849 static void
    850 _rtld_initlist_tsort(Objlist* list, int rev)
    851 {
    852 	dbg(("_rtld_initlist_tsort"));
    853 
    854 	Obj_Entry* obj;
    855 
    856 	/*
    857 	 * We don't include objmain here (starting from next)
    858 	 * because csu handles it
    859 	 */
    860 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    861 		obj->init_done = 0;
    862 	}
    863 
    864 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
    865 		_rtld_initlist_visit(list, obj, rev);
    866 	}
    867 }
    868 
    869 static void
    870 _rtld_init_dag(Obj_Entry *root)
    871 {
    872 
    873 	_rtld_init_dag1(root, root);
    874 }
    875 
    876 static void
    877 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
    878 {
    879 	const Needed_Entry *needed;
    880 
    881 	if (!obj->mainref) {
    882 		if (_rtld_objlist_find(&obj->dldags, root))
    883 			return;
    884 		dbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
    885 		    root->path));
    886 		_rtld_objlist_push_tail(&obj->dldags, root);
    887 		_rtld_objlist_push_tail(&root->dagmembers, obj);
    888 	}
    889 	for (needed = obj->needed; needed != NULL; needed = needed->next)
    890 		if (needed->obj != NULL)
    891 			_rtld_init_dag1(root, needed->obj);
    892 }
    893 
    894 /*
    895  * Note, this is called only for objects loaded by dlopen().
    896  */
    897 static void
    898 _rtld_unload_object(sigset_t *mask, Obj_Entry *root, bool do_fini_funcs)
    899 {
    900 
    901 	_rtld_unref_dag(root);
    902 	if (root->refcount == 0) { /* We are finished with some objects. */
    903 		Obj_Entry *obj;
    904 		Obj_Entry **linkp;
    905 		Objlist_Entry *elm;
    906 
    907 		/* Finalize objects that are about to be unmapped. */
    908 		if (do_fini_funcs)
    909 			_rtld_call_fini_functions(mask, 0);
    910 
    911 		/* Remove the DAG from all objects' DAG lists. */
    912 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link)
    913 			_rtld_objlist_remove(&elm->obj->dldags, root);
    914 
    915 		/* Remove the DAG from the RTLD_GLOBAL list. */
    916 		if (root->globalref) {
    917 			root->globalref = 0;
    918 			_rtld_objlist_remove(&_rtld_list_global, root);
    919 		}
    920 
    921 		/* Unmap all objects that are no longer referenced. */
    922 		linkp = &_rtld_objlist->next;
    923 		while ((obj = *linkp) != NULL) {
    924 			if (obj->refcount == 0) {
    925 				dbg(("unloading \"%s\"", obj->path));
    926 				if (obj->ehdr != MAP_FAILED)
    927 					munmap(obj->ehdr, _rtld_pagesz);
    928 				munmap(obj->mapbase, obj->mapsize);
    929 				_rtld_objlist_remove(&_rtld_list_global, obj);
    930 				_rtld_linkmap_delete(obj);
    931 				*linkp = obj->next;
    932 				_rtld_objcount--;
    933 				_rtld_obj_free(obj);
    934 			} else
    935 				linkp = &obj->next;
    936 		}
    937 		_rtld_objtail = linkp;
    938 	}
    939 }
    940 
    941 void
    942 _rtld_ref_dag(Obj_Entry *root)
    943 {
    944 	const Needed_Entry *needed;
    945 
    946 	assert(root);
    947 
    948 	++root->refcount;
    949 
    950 	dbg(("incremented reference on \"%s\" (%d)", root->path,
    951 	    root->refcount));
    952 	for (needed = root->needed; needed != NULL;
    953 	     needed = needed->next) {
    954 		if (needed->obj != NULL)
    955 			_rtld_ref_dag(needed->obj);
    956 	}
    957 }
    958 
    959 static void
    960 _rtld_unref_dag(Obj_Entry *root)
    961 {
    962 
    963 	assert(root);
    964 	assert(root->refcount != 0);
    965 
    966 	--root->refcount;
    967 	dbg(("decremented reference on \"%s\" (%d)", root->path,
    968 	    root->refcount));
    969 
    970 	if (root->refcount == 0) {
    971 		const Needed_Entry *needed;
    972 
    973 		for (needed = root->needed; needed != NULL;
    974 		     needed = needed->next) {
    975 			if (needed->obj != NULL)
    976 				_rtld_unref_dag(needed->obj);
    977 		}
    978 	}
    979 }
    980 
    981 __strong_alias(__dlclose,dlclose)
    982 int
    983 dlclose(void *handle)
    984 {
    985 	Obj_Entry *root;
    986 	sigset_t mask;
    987 
    988 	dbg(("dlclose of %p", handle));
    989 
    990 	_rtld_exclusive_enter(&mask);
    991 
    992 	root = _rtld_dlcheck(handle);
    993 
    994 	if (root == NULL) {
    995 		_rtld_exclusive_exit(&mask);
    996 		return -1;
    997 	}
    998 
    999 	_rtld_debug.r_state = RT_DELETE;
   1000 	_rtld_debug_state();
   1001 
   1002 	--root->dl_refcount;
   1003 	_rtld_unload_object(&mask, root, true);
   1004 
   1005 	_rtld_debug.r_state = RT_CONSISTENT;
   1006 	_rtld_debug_state();
   1007 
   1008 	_rtld_exclusive_exit(&mask);
   1009 
   1010 	return 0;
   1011 }
   1012 
   1013 __strong_alias(__dlerror,dlerror)
   1014 char *
   1015 dlerror(void)
   1016 {
   1017 	char *msg = error_message;
   1018 
   1019 	error_message = NULL;
   1020 	return msg;
   1021 }
   1022 
   1023 __strong_alias(__dlopen,dlopen)
   1024 void *
   1025 dlopen(const char *name, int mode)
   1026 {
   1027 	Obj_Entry **old_obj_tail = _rtld_objtail;
   1028 	Obj_Entry *obj = NULL;
   1029 	int flags = _RTLD_DLOPEN;
   1030 	bool nodelete;
   1031 	bool now;
   1032 	sigset_t mask;
   1033 	int result;
   1034 
   1035 	dbg(("dlopen of %s %d", name, mode));
   1036 
   1037 	_rtld_exclusive_enter(&mask);
   1038 
   1039 	flags |= (mode & RTLD_GLOBAL) ? _RTLD_GLOBAL : 0;
   1040 	flags |= (mode & RTLD_NOLOAD) ? _RTLD_NOLOAD : 0;
   1041 
   1042 	nodelete = (mode & RTLD_NODELETE) ? true : false;
   1043 	now = ((mode & RTLD_MODEMASK) == RTLD_NOW) ? true : false;
   1044 
   1045 	_rtld_debug.r_state = RT_ADD;
   1046 	_rtld_debug_state();
   1047 
   1048 	if (name == NULL) {
   1049 		obj = _rtld_objmain;
   1050 		obj->refcount++;
   1051 	} else
   1052 		obj = _rtld_load_library(name, _rtld_objmain, flags);
   1053 
   1054 
   1055 	if (obj != NULL) {
   1056 		++obj->dl_refcount;
   1057 		if (*old_obj_tail != NULL) {	/* We loaded something new. */
   1058 			assert(*old_obj_tail == obj);
   1059 
   1060 			result = _rtld_load_needed_objects(obj, flags);
   1061 			if (result != -1) {
   1062 				Objlist_Entry *entry;
   1063 				_rtld_init_dag(obj);
   1064 				SIMPLEQ_FOREACH(entry, &obj->dagmembers, link) {
   1065 					result = _rtld_verify_object_versions(entry->obj);
   1066 					if (result == -1)
   1067 						break;
   1068 				}
   1069 			}
   1070 			if (result == -1 || _rtld_relocate_objects(obj,
   1071 			    (now || obj->z_now)) == -1) {
   1072 				_rtld_unload_object(&mask, obj, false);
   1073 				obj->dl_refcount--;
   1074 				obj = NULL;
   1075 			} else {
   1076 				_rtld_call_init_functions(&mask);
   1077 			}
   1078 		}
   1079 		if (obj != NULL) {
   1080 			if ((nodelete || obj->z_nodelete) && !obj->ref_nodel) {
   1081 				dbg(("dlopen obj %s nodelete", obj->path));
   1082 				_rtld_ref_dag(obj);
   1083 				obj->z_nodelete = obj->ref_nodel = true;
   1084 			}
   1085 		}
   1086 	}
   1087 	_rtld_debug.r_state = RT_CONSISTENT;
   1088 	_rtld_debug_state();
   1089 
   1090 	_rtld_exclusive_exit(&mask);
   1091 
   1092 	return obj;
   1093 }
   1094 
   1095 /*
   1096  * Find a symbol in the main program.
   1097  */
   1098 void *
   1099 _rtld_objmain_sym(const char *name)
   1100 {
   1101 	unsigned long hash;
   1102 	const Elf_Sym *def;
   1103 	const Obj_Entry *obj;
   1104 	DoneList donelist;
   1105 
   1106 	hash = _rtld_elf_hash(name);
   1107 	obj = _rtld_objmain;
   1108 	_rtld_donelist_init(&donelist);
   1109 
   1110 	def = _rtld_symlook_list(name, hash, &_rtld_list_main, &obj, 0,
   1111 	    NULL, &donelist);
   1112 
   1113 	if (def != NULL)
   1114 		return obj->relocbase + def->st_value;
   1115 	return NULL;
   1116 }
   1117 
   1118 #ifdef __powerpc__
   1119 static __noinline void *
   1120 hackish_return_address(void)
   1121 {
   1122 #if __GNUC_PREREQ__(6,0)
   1123 #pragma GCC diagnostic push
   1124 #pragma GCC diagnostic ignored "-Wframe-address"
   1125 #endif
   1126 	return __builtin_return_address(1);
   1127 #if __GNUC_PREREQ__(6,0)
   1128 #pragma GCC diagnostic pop
   1129 #endif
   1130 }
   1131 #endif
   1132 
   1133 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1134 #define	lookup_mutex_enter()	_rtld_exclusive_enter(&mask)
   1135 #define	lookup_mutex_exit()	_rtld_exclusive_exit(&mask)
   1136 #else
   1137 #define	lookup_mutex_enter()	_rtld_shared_enter()
   1138 #define	lookup_mutex_exit()	_rtld_shared_exit()
   1139 #endif
   1140 
   1141 static void *
   1142 do_dlsym(void *handle, const char *name, const Ver_Entry *ventry, void *retaddr)
   1143 {
   1144 	const Obj_Entry *obj;
   1145 	unsigned long hash;
   1146 	const Elf_Sym *def;
   1147 	const Obj_Entry *defobj;
   1148 	DoneList donelist;
   1149 	const u_int flags = SYMLOOK_DLSYM | SYMLOOK_IN_PLT;
   1150 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1151 	sigset_t mask;
   1152 #endif
   1153 
   1154 	lookup_mutex_enter();
   1155 
   1156 	hash = _rtld_elf_hash(name);
   1157 	def = NULL;
   1158 	defobj = NULL;
   1159 
   1160 	switch ((intptr_t)handle) {
   1161 	case (intptr_t)NULL:
   1162 	case (intptr_t)RTLD_NEXT:
   1163 	case (intptr_t)RTLD_DEFAULT:
   1164 	case (intptr_t)RTLD_SELF:
   1165 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   1166 			_rtld_error("Cannot determine caller's shared object");
   1167 			lookup_mutex_exit();
   1168 			return NULL;
   1169 		}
   1170 
   1171 		switch ((intptr_t)handle) {
   1172 		case (intptr_t)NULL:	 /* Just the caller's shared object. */
   1173 			def = _rtld_symlook_obj(name, hash, obj, flags, ventry);
   1174 			defobj = obj;
   1175 			break;
   1176 
   1177 		case (intptr_t)RTLD_NEXT:	/* Objects after callers */
   1178 			obj = obj->next;
   1179 			/*FALLTHROUGH*/
   1180 
   1181 		case (intptr_t)RTLD_SELF:	/* Caller included */
   1182 			for (; obj; obj = obj->next) {
   1183 				if ((def = _rtld_symlook_obj(name, hash, obj,
   1184 				    flags, ventry)) != NULL) {
   1185 					defobj = obj;
   1186 					break;
   1187 				}
   1188 			}
   1189 			/*
   1190 			 * Search the dynamic linker itself, and possibly
   1191 			 * resolve the symbol from there if it is not defined
   1192 			 * already or weak. This is how the application links
   1193 			 * to dynamic linker services such as dlopen.
   1194 			 */
   1195 			if (!def || ELF_ST_BIND(def->st_info) == STB_WEAK) {
   1196 				const Elf_Sym *symp = _rtld_symlook_obj(name,
   1197 				    hash, &_rtld_objself, flags, ventry);
   1198 				if (symp != NULL) {
   1199 					def = symp;
   1200 					defobj = &_rtld_objself;
   1201 				}
   1202 			}
   1203 			break;
   1204 
   1205 		case (intptr_t)RTLD_DEFAULT:
   1206 			def = _rtld_symlook_default(name, hash, obj, &defobj,
   1207 			    flags, ventry);
   1208 			break;
   1209 
   1210 		default:
   1211 			abort();
   1212 		}
   1213 		break;
   1214 
   1215 	default:
   1216 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   1217 			lookup_mutex_exit();
   1218 			return NULL;
   1219 		}
   1220 
   1221 		_rtld_donelist_init(&donelist);
   1222 
   1223 		if (obj->mainprog) {
   1224 			/* Search main program and all libraries loaded by it */
   1225 			def = _rtld_symlook_list(name, hash, &_rtld_list_main,
   1226 			    &defobj, flags, ventry, &donelist);
   1227 		} else {
   1228 			Needed_Entry fake;
   1229 			DoneList depth;
   1230 
   1231 			/* Search the object and all the libraries loaded by it. */
   1232 			fake.next = NULL;
   1233 			fake.obj = __UNCONST(obj);
   1234 			fake.name = 0;
   1235 
   1236 			_rtld_donelist_init(&depth);
   1237 			def = _rtld_symlook_needed(name, hash, &fake, &defobj,
   1238 			    flags, ventry, &donelist, &depth);
   1239 		}
   1240 
   1241 		break;
   1242 	}
   1243 
   1244 	if (def != NULL) {
   1245 		void *p;
   1246 
   1247 		if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) {
   1248 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1249 			lookup_mutex_exit();
   1250 			_rtld_shared_enter();
   1251 #endif
   1252 			p = (void *)_rtld_resolve_ifunc(defobj, def);
   1253 			_rtld_shared_exit();
   1254 			return p;
   1255 		}
   1256 
   1257 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1258 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC) {
   1259 			p = (void *)_rtld_function_descriptor_alloc(defobj,
   1260 			    def, 0);
   1261 			lookup_mutex_exit();
   1262 			return p;
   1263 		}
   1264 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   1265 		p = defobj->relocbase + def->st_value;
   1266 		lookup_mutex_exit();
   1267 		return p;
   1268 	}
   1269 
   1270 	_rtld_error("Undefined symbol \"%s\"", name);
   1271 	lookup_mutex_exit();
   1272 	return NULL;
   1273 }
   1274 
   1275 __strong_alias(__dlsym,dlsym)
   1276 void *
   1277 dlsym(void *handle, const char *name)
   1278 {
   1279 	void *retaddr;
   1280 
   1281 	dbg(("dlsym of %s in %p", name, handle));
   1282 
   1283 #ifdef __powerpc__
   1284 	retaddr = hackish_return_address();
   1285 #else
   1286 	retaddr = __builtin_return_address(0);
   1287 #endif
   1288 	return do_dlsym(handle, name, NULL, retaddr);
   1289 }
   1290 
   1291 __strong_alias(__dlvsym,dlvsym)
   1292 void *
   1293 dlvsym(void *handle, const char *name, const char *version)
   1294 {
   1295 	Ver_Entry *ventry = NULL;
   1296 	Ver_Entry ver_entry;
   1297 	void *retaddr;
   1298 
   1299 	dbg(("dlvsym of %s@%s in %p", name, version ? version : NULL, handle));
   1300 
   1301 	if (version != NULL) {
   1302 		ver_entry.name = version;
   1303 		ver_entry.file = NULL;
   1304 		ver_entry.hash = _rtld_elf_hash(version);
   1305 		ver_entry.flags = 0;
   1306 		ventry = &ver_entry;
   1307 	}
   1308 #ifdef __powerpc__
   1309 	retaddr = hackish_return_address();
   1310 #else
   1311 	retaddr = __builtin_return_address(0);
   1312 #endif
   1313 	return do_dlsym(handle, name, ventry, retaddr);
   1314 }
   1315 
   1316 __strong_alias(__dladdr,dladdr)
   1317 int
   1318 dladdr(const void *addr, Dl_info *info)
   1319 {
   1320 	const Obj_Entry *obj;
   1321 	const Elf_Sym *def, *best_def;
   1322 	void *symbol_addr;
   1323 	unsigned long symoffset;
   1324 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1325 	sigset_t mask;
   1326 #endif
   1327 
   1328 	dbg(("dladdr of %p", addr));
   1329 
   1330 	lookup_mutex_enter();
   1331 
   1332 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1333 	addr = _rtld_function_descriptor_function(addr);
   1334 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   1335 
   1336 	obj = _rtld_obj_from_addr(addr);
   1337 	if (obj == NULL) {
   1338 		_rtld_error("No shared object contains address");
   1339 		lookup_mutex_exit();
   1340 		return 0;
   1341 	}
   1342 	info->dli_fname = obj->path;
   1343 	info->dli_fbase = obj->mapbase;
   1344 	info->dli_saddr = (void *)0;
   1345 	info->dli_sname = NULL;
   1346 
   1347 	/*
   1348 	 * Walk the symbol list looking for the symbol whose address is
   1349 	 * closest to the address sent in.
   1350 	 */
   1351 	best_def = NULL;
   1352 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
   1353 		def = obj->symtab + symoffset;
   1354 
   1355 		/*
   1356 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
   1357 		 * SHN_COMMON.
   1358 		 */
   1359 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
   1360 			continue;
   1361 
   1362 		/*
   1363 		 * If the symbol is greater than the specified address, or if it
   1364 		 * is further away from addr than the current nearest symbol,
   1365 		 * then reject it.
   1366 		 */
   1367 		symbol_addr = obj->relocbase + def->st_value;
   1368 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
   1369 			continue;
   1370 
   1371 		/* Update our idea of the nearest symbol. */
   1372 		info->dli_sname = obj->strtab + def->st_name;
   1373 		info->dli_saddr = symbol_addr;
   1374 		best_def = def;
   1375 
   1376 
   1377 		/* Exact match? */
   1378 		if (info->dli_saddr == addr)
   1379 			break;
   1380 	}
   1381 
   1382 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1383 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
   1384 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
   1385 		    best_def, 0);
   1386 #else
   1387 	__USE(best_def);
   1388 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   1389 
   1390 	lookup_mutex_exit();
   1391 	return 1;
   1392 }
   1393 
   1394 __strong_alias(__dlinfo,dlinfo)
   1395 int
   1396 dlinfo(void *handle, int req, void *v)
   1397 {
   1398 	const Obj_Entry *obj;
   1399 	void *retaddr;
   1400 
   1401 	dbg(("dlinfo for %p %d", handle, req));
   1402 
   1403 	_rtld_shared_enter();
   1404 
   1405 	if (handle == RTLD_SELF) {
   1406 #ifdef __powerpc__
   1407 		retaddr = hackish_return_address();
   1408 #else
   1409 		retaddr = __builtin_return_address(0);
   1410 #endif
   1411 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   1412 			_rtld_error("Cannot determine caller's shared object");
   1413 			_rtld_shared_exit();
   1414 			return -1;
   1415 		}
   1416 	} else {
   1417 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   1418 			_rtld_shared_exit();
   1419 			return -1;
   1420 		}
   1421 	}
   1422 
   1423 	switch (req) {
   1424 	case RTLD_DI_LINKMAP:
   1425 		{
   1426 		const struct link_map **map = v;
   1427 
   1428 		*map = &obj->linkmap;
   1429 		break;
   1430 		}
   1431 
   1432 	default:
   1433 		_rtld_error("Invalid request");
   1434 		_rtld_shared_exit();
   1435 		return -1;
   1436 	}
   1437 
   1438 	_rtld_shared_exit();
   1439 	return 0;
   1440 }
   1441 
   1442 static void
   1443 _rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
   1444 {
   1445 
   1446 	phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
   1447 	/* XXX: wrong but not fixing it yet */
   1448 	phdr_info->dlpi_name = obj->path;
   1449 	phdr_info->dlpi_phdr = obj->phdr;
   1450 	phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
   1451 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
   1452 	phdr_info->dlpi_tls_modid = obj->tlsindex;
   1453 	phdr_info->dlpi_tls_data = obj->tlsinit;
   1454 #else
   1455 	phdr_info->dlpi_tls_modid = 0;
   1456 	phdr_info->dlpi_tls_data = 0;
   1457 #endif
   1458 	phdr_info->dlpi_adds = _rtld_objloads;
   1459 	phdr_info->dlpi_subs = _rtld_objloads - _rtld_objcount;
   1460 }
   1461 
   1462 __strong_alias(__dl_iterate_phdr,dl_iterate_phdr);
   1463 int
   1464 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *param)
   1465 {
   1466 	struct dl_phdr_info phdr_info;
   1467 	const Obj_Entry *obj;
   1468 	int error = 0;
   1469 
   1470 	dbg(("dl_iterate_phdr"));
   1471 
   1472 	_rtld_shared_enter();
   1473 
   1474 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   1475 		_rtld_fill_dl_phdr_info(obj, &phdr_info);
   1476 
   1477 		/* XXXlocking: exit point */
   1478 		error = callback(&phdr_info, sizeof(phdr_info), param);
   1479 		if (error)
   1480 			break;
   1481 	}
   1482 
   1483 	if (error == 0) {
   1484 		_rtld_fill_dl_phdr_info(&_rtld_objself, &phdr_info);
   1485 
   1486 		/* XXXlocking: exit point */
   1487 		error = callback(&phdr_info, sizeof(phdr_info), param);
   1488 	}
   1489 
   1490 	_rtld_shared_exit();
   1491 	return error;
   1492 }
   1493 
   1494 void
   1495 __dl_cxa_refcount(void *addr, ssize_t delta)
   1496 {
   1497 	sigset_t mask;
   1498 	Obj_Entry *obj;
   1499 
   1500 	if (delta == 0)
   1501 		return;
   1502 
   1503 	dbg(("__dl_cxa_refcount of %p with %zd", addr, delta));
   1504 
   1505 	_rtld_exclusive_enter(&mask);
   1506 	obj = _rtld_obj_from_addr(addr);
   1507 
   1508 	if (obj == NULL) {
   1509 		dbg(("__dl_cxa_refcont: address not found"));
   1510 		_rtld_error("No shared object contains address");
   1511 		_rtld_exclusive_exit(&mask);
   1512 		return;
   1513 	}
   1514 	if (delta > 0 && obj->cxa_refcount > SIZE_MAX - delta)
   1515 		_rtld_error("Reference count overflow");
   1516 	else if (delta < 0 && obj->cxa_refcount < -1 + (size_t)-(delta + 1))
   1517 		_rtld_error("Reference count underflow");
   1518 	else {
   1519 		if (obj->cxa_refcount == 0)
   1520 			++obj->refcount;
   1521 		obj->cxa_refcount += delta;
   1522 		dbg(("new reference count: %zu", obj->cxa_refcount));
   1523 		if (obj->cxa_refcount == 0) {
   1524 			--obj->refcount;
   1525 			if (obj->refcount == 0)
   1526 				_rtld_unload_object(&mask, obj, true);
   1527 		}
   1528 	}
   1529 
   1530 	_rtld_exclusive_exit(&mask);
   1531 }
   1532 
   1533 /*
   1534  * Error reporting function.  Use it like printf.  If formats the message
   1535  * into a buffer, and sets things up so that the next call to dlerror()
   1536  * will return the message.
   1537  */
   1538 void
   1539 _rtld_error(const char *fmt,...)
   1540 {
   1541 	static char     buf[512];
   1542 	va_list         ap;
   1543 
   1544 	va_start(ap, fmt);
   1545 	xvsnprintf(buf, sizeof buf, fmt, ap);
   1546 	error_message = buf;
   1547 	va_end(ap);
   1548 }
   1549 
   1550 void
   1551 _rtld_debug_state(void)
   1552 {
   1553 #if defined(__hppa__)
   1554 	__asm volatile("nop" ::: "memory");
   1555 #endif
   1556 
   1557 	/* Prevent optimizer from removing calls to this function */
   1558 	__insn_barrier();
   1559 }
   1560 
   1561 void
   1562 _rtld_linkmap_add(Obj_Entry *obj)
   1563 {
   1564 	struct link_map *l = &obj->linkmap;
   1565 	struct link_map *prev;
   1566 
   1567 	obj->linkmap.l_name = obj->path;
   1568 	obj->linkmap.l_addr = obj->relocbase;
   1569 	obj->linkmap.l_ld = obj->dynamic;
   1570 #ifdef __mips__
   1571 	/* XXX This field is not standard and will be removed eventually. */
   1572 	obj->linkmap.l_offs = obj->relocbase;
   1573 #endif
   1574 
   1575 	if (_rtld_debug.r_map == NULL) {
   1576 		_rtld_debug.r_map = l;
   1577 		return;
   1578 	}
   1579 
   1580 	/*
   1581 	 * Scan to the end of the list, but not past the entry for the
   1582 	 * dynamic linker, which we want to keep at the very end.
   1583 	 */
   1584 	for (prev = _rtld_debug.r_map;
   1585 	    prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
   1586 	    prev = prev->l_next);
   1587 
   1588 	l->l_prev = prev;
   1589 	l->l_next = prev->l_next;
   1590 	if (l->l_next != NULL)
   1591 		l->l_next->l_prev = l;
   1592 	prev->l_next = l;
   1593 }
   1594 
   1595 void
   1596 _rtld_linkmap_delete(Obj_Entry *obj)
   1597 {
   1598 	struct link_map *l = &obj->linkmap;
   1599 
   1600 	if (l->l_prev == NULL) {
   1601 		if ((_rtld_debug.r_map = l->l_next) != NULL)
   1602 			l->l_next->l_prev = NULL;
   1603 		return;
   1604 	}
   1605 	if ((l->l_prev->l_next = l->l_next) != NULL)
   1606 		l->l_next->l_prev = l->l_prev;
   1607 }
   1608 
   1609 static Obj_Entry *
   1610 _rtld_obj_from_addr(const void *addr)
   1611 {
   1612 	Obj_Entry *obj;
   1613 
   1614 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   1615 		if (addr < (void *) obj->mapbase)
   1616 			continue;
   1617 		if (addr < (void *) (obj->mapbase + obj->mapsize))
   1618 			return obj;
   1619 	}
   1620 	return NULL;
   1621 }
   1622 
   1623 static void
   1624 _rtld_objlist_clear(Objlist *list)
   1625 {
   1626 	while (!SIMPLEQ_EMPTY(list)) {
   1627 		Objlist_Entry* elm = SIMPLEQ_FIRST(list);
   1628 		SIMPLEQ_REMOVE_HEAD(list, link);
   1629 		xfree(elm);
   1630 	}
   1631 }
   1632 
   1633 static void
   1634 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
   1635 {
   1636 	Objlist_Entry *elm;
   1637 
   1638 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
   1639 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
   1640 		xfree(elm);
   1641 	}
   1642 }
   1643 
   1644 #define	RTLD_EXCLUSIVE_MASK	0x80000000U
   1645 static volatile unsigned int _rtld_mutex;
   1646 static volatile unsigned int _rtld_waiter_exclusive;
   1647 static volatile unsigned int _rtld_waiter_shared;
   1648 
   1649 void
   1650 _rtld_shared_enter(void)
   1651 {
   1652 	unsigned int cur;
   1653 	lwpid_t waiter, self = 0;
   1654 
   1655 	membar_enter();
   1656 
   1657 	for (;;) {
   1658 		cur = _rtld_mutex;
   1659 		/*
   1660 		 * First check if we are currently not exclusively locked.
   1661 		 */
   1662 		if ((cur & RTLD_EXCLUSIVE_MASK) == 0) {
   1663 			/* Yes, so increment use counter */
   1664 			if (atomic_cas_uint(&_rtld_mutex, cur, cur + 1) != cur)
   1665 				continue;
   1666 			membar_enter();
   1667 			return;
   1668 		}
   1669 		/*
   1670 		 * Someone has an exclusive lock.  Puts us on the waiter list.
   1671 		 */
   1672 		if (!self)
   1673 			self = _lwp_self();
   1674 		if (cur == (self | RTLD_EXCLUSIVE_MASK)) {
   1675 			if (_rtld_mutex_may_recurse)
   1676 				return;
   1677 			_rtld_error("dead lock detected");
   1678 			_rtld_die();
   1679 		}
   1680 		waiter = atomic_swap_uint(&_rtld_waiter_shared, self);
   1681 		/*
   1682 		 * Check for race against _rtld_exclusive_exit before sleeping.
   1683 		 */
   1684 		membar_sync();
   1685 		if ((_rtld_mutex & RTLD_EXCLUSIVE_MASK) ||
   1686 		    _rtld_waiter_exclusive)
   1687 			_lwp_park(CLOCK_REALTIME, 0, NULL, 0,
   1688 			    __UNVOLATILE(&_rtld_mutex), NULL);
   1689 		/* Try to remove us from the waiter list. */
   1690 		atomic_cas_uint(&_rtld_waiter_shared, self, 0);
   1691 		if (waiter)
   1692 			_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   1693 	}
   1694 }
   1695 
   1696 void
   1697 _rtld_shared_exit(void)
   1698 {
   1699 	lwpid_t waiter;
   1700 
   1701 	/*
   1702 	 * Shared lock taken after an exclusive lock.
   1703 	 * Just assume this is a partial recursion.
   1704 	 */
   1705 	if (_rtld_mutex & RTLD_EXCLUSIVE_MASK)
   1706 		return;
   1707 
   1708 	/*
   1709 	 * Wakeup LWPs waiting for an exclusive lock if this is the last
   1710 	 * LWP on the shared lock.
   1711 	 */
   1712 	membar_exit();
   1713 	if (atomic_dec_uint_nv(&_rtld_mutex))
   1714 		return;
   1715 	membar_sync();
   1716 	if ((waiter = _rtld_waiter_exclusive) != 0)
   1717 		_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   1718 }
   1719 
   1720 void
   1721 _rtld_exclusive_enter(sigset_t *mask)
   1722 {
   1723 	lwpid_t waiter, self = _lwp_self();
   1724 	unsigned int locked_value = (unsigned int)self | RTLD_EXCLUSIVE_MASK;
   1725 	unsigned int cur;
   1726 	sigset_t blockmask;
   1727 
   1728 	sigfillset(&blockmask);
   1729 	sigdelset(&blockmask, SIGTRAP);	/* Allow the debugger */
   1730 	sigprocmask(SIG_BLOCK, &blockmask, mask);
   1731 
   1732 	for (;;) {
   1733 		if (atomic_cas_uint(&_rtld_mutex, 0, locked_value) == 0) {
   1734 			membar_enter();
   1735 			break;
   1736 		}
   1737 		waiter = atomic_swap_uint(&_rtld_waiter_exclusive, self);
   1738 		membar_sync();
   1739 		cur = _rtld_mutex;
   1740 		if (cur == locked_value) {
   1741 			_rtld_error("dead lock detected");
   1742 			_rtld_die();
   1743 		}
   1744 		if (cur)
   1745 			_lwp_park(CLOCK_REALTIME, 0, NULL, 0,
   1746 			    __UNVOLATILE(&_rtld_mutex), NULL);
   1747 		atomic_cas_uint(&_rtld_waiter_exclusive, self, 0);
   1748 		if (waiter)
   1749 			_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   1750 	}
   1751 }
   1752 
   1753 void
   1754 _rtld_exclusive_exit(sigset_t *mask)
   1755 {
   1756 	lwpid_t waiter;
   1757 
   1758 	membar_exit();
   1759 	_rtld_mutex = 0;
   1760 	membar_sync();
   1761 	if ((waiter = _rtld_waiter_exclusive) != 0)
   1762 		_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   1763 
   1764 	if ((waiter = _rtld_waiter_shared) != 0)
   1765 		_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   1766 
   1767 	sigprocmask(SIG_SETMASK, mask, NULL);
   1768 }
   1769 
   1770 int
   1771 _rtld_relro(const Obj_Entry *obj, bool wantmain)
   1772 {
   1773 #ifdef GNU_RELRO
   1774 	if (obj->relro_size == 0)
   1775 		return 0;
   1776 	if (wantmain != (obj ==_rtld_objmain))
   1777 		return 0;
   1778 
   1779 	dbg(("RELRO %s %p %lx\n", obj->path, obj->relro_page, obj->relro_size));
   1780 	if (mprotect(obj->relro_page, obj->relro_size, PROT_READ) == -1) {
   1781 		_rtld_error("%s: Cannot enforce relro " "protection: %s",
   1782 		    obj->path, xstrerror(errno));
   1783 		return -1;
   1784 	}
   1785 #endif
   1786 	return 0;
   1787 }
   1788