Home | History | Annotate | Line # | Download | only in ld.elf_so
      1 /*	$NetBSD: rtld.c,v 1.228 2026/07/19 19:56:06 riastradh 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.228 2026/07/19 19:56:06 riastradh 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 
     64 #include "debug.h"
     65 #include "hash.h"
     66 #include "rtld.h"
     67 
     68 #if !defined(lint)
     69 #include "sysident.h"
     70 #endif
     71 
     72 /*
     73  * Hidden function from common/lib/libc/atomic - nop on machines
     74  * with enough atomic ops. Need to explicitly call it early.
     75  * libc has the same symbol and will initialize itself, but not our copy.
     76  */
     77 void __libc_atomic_init(void);
     78 
     79 /*
     80  * Function declarations.
     81  */
     82 static void     _rtld_init(caddr_t, caddr_t, const char *);
     83 static void     _rtld_exit(void);
     84 
     85 Elf_Addr        _rtld(Elf_Addr *, Elf_Addr);
     86 
     87 
     88 /*
     89  * Data declarations.
     90  */
     91 static char    *error_message;	/* Message for dlopen(), or NULL */
     92 
     93 struct r_debug  _rtld_debug;	/* The SVR4 interface for the debugger */
     94 bool            _rtld_trust;	/* False for setuid and setgid programs */
     95 Obj_Entry      *_rtld_objlist;	/* Head of linked list of shared objects */
     96 Obj_Entry     **_rtld_objtail;	/* Link field of last object in list */
     97 Obj_Entry      *_rtld_objmain;	/* The main program shared object */
     98 Obj_Entry       _rtld_objself;	/* The dynamic linker shared object */
     99 u_int		_rtld_objcount;	/* Number of objects in _rtld_objlist */
    100 u_int		_rtld_objrelocpending = 1; /* Number of objects pending reloc */
    101 u_int		_rtld_objloads;	/* Number of objects loaded in _rtld_objlist */
    102 u_int		_rtld_objgen;	/* Generation count for _rtld_objlist */
    103 const char	_rtld_path[] = _PATH_RTLD;
    104 
    105 /* Initialize a fake symbol for resolving undefined weak references. */
    106 Elf_Sym		_rtld_sym_zero = {
    107     .st_info	= ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
    108     .st_shndx	= SHN_ABS,
    109 };
    110 size_t	_rtld_pagesz;	/* Page size, as provided by kernel */
    111 
    112 Search_Path    *_rtld_default_paths;
    113 Search_Path    *_rtld_paths;
    114 
    115 Library_Xform  *_rtld_xforms;
    116 static void    *auxinfo;
    117 
    118 /*
    119  * Global declarations normally provided by crt0.
    120  */
    121 char           *__progname;
    122 char          **environ;
    123 
    124 static volatile bool _rtld_mutex_may_recurse;
    125 
    126 #if defined(RTLD_DEBUG)
    127 #ifndef __sh__
    128 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
    129 #else  /* 32-bit SuperH */
    130 register Elf_Addr *_GLOBAL_OFFSET_TABLE_ asm("r12");
    131 #endif
    132 #endif /* RTLD_DEBUG */
    133 extern Elf_Dyn  _DYNAMIC;
    134 
    135 static void _rtld_call_fini_functions(Obj_Entry *, sigset_t *, int);
    136 static void _rtld_call_init_functions(Obj_Entry *, sigset_t *);
    137 static void _rtld_call_preinit_functions(sigset_t *);
    138 static bool _rtld_initlist_visit(Objlist *, Obj_Entry *, int);
    139 static void _rtld_initlist_tsort(Objlist *, int, Obj_Entry *);
    140 static Obj_Entry *_rtld_dlcheck(void *);
    141 static void _rtld_init_dag(Obj_Entry *);
    142 static void _rtld_init_dag1(Obj_Entry *, Obj_Entry *);
    143 static void _rtld_objlist_remove(Objlist *, Obj_Entry *);
    144 static void _rtld_objlist_clear(Objlist *);
    145 static void _rtld_unload_object(sigset_t *, Obj_Entry *, bool);
    146 static void _rtld_unref_dag(Obj_Entry *);
    147 static Obj_Entry *_rtld_obj_from_addr(const void *);
    148 static void _rtld_fill_dl_phdr_info(const Obj_Entry *, struct dl_phdr_info *);
    149 
    150 /*
    151  * _rtld_load_needed_enter(obj)
    152  *
    153  *	Mark obj as busy loading its dependencies.  Multiple threads
    154  *	may be working on a single thread's dependencies concurrently;
    155  *	dlclose will wait until they are all done.  Caller must follow
    156  *	this by _rtld_load_needed_enter.
    157  *
    158  *	Non-reentrant: a thread must not call this again until it has
    159  *	called _rtld_load_needed_exit.
    160  *
    161  *	Caller must hold the rtld exclusive lock.  obj must have
    162  *	positive refcount; if it is already slated for destruction,
    163  *	this is not useful.
    164  */
    165 void
    166 _rtld_load_needed_enter(Obj_Entry *obj)
    167 {
    168 
    169 	assert(obj->refcount > 0);
    170 	assert(obj->neededrefcount < INT_MAX);
    171 	obj->neededrefcount++;
    172 }
    173 
    174 /*
    175  * _rtld_load_needed_exit(obj)
    176  *
    177  *	Mark obj as no longer busy loading its dependencies after
    178  *	_rtld_load_needed_enter.
    179  *
    180  *	Caller must hold the rtld exclusive lock.  Will not release or
    181  *	reacquire it.
    182  *
    183  *	Caller must have previously called
    184  *	_rtld_loadingneeded_enter(obj, ...) in the same thread.
    185  */
    186 void
    187 _rtld_load_needed_exit(Obj_Entry *obj)
    188 {
    189 
    190 	assert(obj->neededrefcount > 0);
    191 
    192 	if (__predict_false(--obj->neededrefcount))
    193 		return;
    194 	if (__predict_true(obj->neededwaiter == 0))
    195 		return;
    196 	assert(obj->refcount == 0);
    197 	_lwp_unpark(obj->neededwaiter, &obj->neededrefcount);
    198 	obj->neededwaiter = 0;
    199 }
    200 
    201 /*
    202  * _rtld_wait_for_load_needed(&obj, mask)
    203  *
    204  *	If another thread is concurrently loading obj's dependencies,
    205  *	release the rtld exclusive lock, wait until it is done,
    206  *	reacquire the rtld exclusive lock, and return true.  On
    207  *	return, obj is nulled out.
    208  *
    209  *	Otherwise, if there is no thread concurrently loading obj's
    210  *	dependencies, leave it intact and return false without
    211  *	releasing and reacquiring the rtld exclusive lock -- obj is
    212  *	safe to free now.
    213  *
    214  *	Caller must hold the rtld exclusive lock.  May release and
    215  *	reacquire the rtld exclusive lock.  obj must have refcount zero
    216  *	already; this is only for when we are preparing to free obj.
    217  */
    218 static bool
    219 _rtld_wait_for_load_needed(Obj_Entry **objp, sigset_t *mask)
    220 {
    221 	Obj_Entry *obj = *objp;
    222 	lwpid_t next;
    223 
    224 	/*
    225 	 * This is only useful when obj is already marked for
    226 	 * destruction.
    227 	 */
    228 	assert(obj->refcount == 0);
    229 
    230 	/*
    231 	 * If there are no threads concurrently loading obj's
    232 	 * dependencies, nothing to do.
    233 	 */
    234 	if (__predict_true(obj->neededrefcount == 0))
    235 		return false;
    236 
    237 	/*
    238 	 * Queue ourselves up to be notified when all threads are done
    239 	 * loading obj's dependencies, and remember the next thread to
    240 	 * be notified.
    241 	 */
    242 	next = obj->neededwaiter;
    243 	obj->neededwaiter = _lwp_self();
    244 
    245 	/*
    246 	 * Release the rtld exclusive lock to wait and reacquire it
    247 	 * when done.  After we release the lock, we can't dereference
    248 	 * obj -- it may be concurrently freed by dlclose.
    249 	 */
    250 	_rtld_exclusive_exit(mask);
    251 	*objp = NULL;
    252 	_lwp_park(CLOCK_REALTIME, 0, NULL, 0, &obj->neededrefcount, NULL);
    253 	_rtld_exclusive_enter(mask);
    254 
    255 	/*
    256 	 * If another thread was waiting too, notify that thread.
    257 	 */
    258 	if (next)
    259 		_lwp_unpark(next, &obj->neededrefcount);
    260 
    261 	/*
    262 	 * Notify the caller that we released/reacquired the rtld
    263 	 * exclusive lock to wait for a state change so they must start
    264 	 * over from the top.
    265 	 */
    266 	return true;
    267 }
    268 
    269 /*
    270  * _rtld_initfini_enter(&obj, mask)
    271  *
    272  *	Prepare to call an init/fini routine and return true if the
    273  *	caller should do it and then call _rtld_initfini_exit, or false
    274  *	if we waited for a state change and the caller must start over
    275  *	from the top.
    276  *
    277  *	If another thread is concurrently running an init/fini routine
    278  *	for the same object, release the rtld exclusive lock, wait
    279  *	until it's done (or a spurious wakeup), reacquire the rtld
    280  *	exclusive lock, null out obj, and return false.  Returning
    281  *	false does _not_ imply the init/fini is done -- it only implies
    282  *	that it _may_ be done but the caller must reassess the rtld
    283  *	state and start over from the top.
    284  *
    285  *	Otherwise, mark obj as running an init/fini routine in this
    286  *	thread and return true, without releasing and reacquiring the
    287  *	rtld exclusive lock.
    288  *
    289  *	Caller must hold the rtld exclusive lock.  May release and
    290  *	reacquire the rtld exclusive lock.
    291  */
    292 static bool
    293 _rtld_initfini_enter(Obj_Entry **objp, sigset_t *mask)
    294 {
    295 	Obj_Entry *obj = *objp;
    296 	lwpid_t next;
    297 
    298 	/*
    299 	 * If no other thread is concurrently running an init/fini
    300 	 * routine for this object, claim the object for this thread
    301 	 * and return true without releasing or reacquiring the rtld
    302 	 * exclusive lock.
    303 	 *
    304 	 * Recursive entry here should not be possible: the topological
    305 	 * sort detects when a constructor or destructor is already
    306 	 * running for an object, and excludes that object and anything
    307 	 * needing that object from the sorted list.
    308 	 */
    309 	if (__predict_true(obj->initfinilock == 0)) {
    310 		obj->initfinilock = _lwp_self();
    311 		return true;
    312 	}
    313 	assert(obj->initfinilock != _lwp_self());
    314 
    315 	/*
    316 	 * Remember whether anyone else is waiting for the lock, and
    317 	 * record ourselves as waiting.
    318 	 */
    319 	next = obj->initfinilockwaiter;
    320 	obj->initfinilockwaiter = _lwp_self();
    321 
    322 	/*
    323 	 * Release the rtld exclusive lock, wait for a state change,
    324 	 * and reacquire the rtld exclusive lock.  Must not touch obj
    325 	 * after releasing the rtld exclusive lock -- it may be
    326 	 * concurrently freed by dlclose.
    327 	 */
    328 	_rtld_exclusive_exit(mask);
    329 	*objp = NULL;
    330 	_lwp_park(CLOCK_REALTIME, 0, NULL, 0, &obj->initfinilock, NULL);
    331 	_rtld_exclusive_enter(mask);
    332 
    333 	/*
    334 	 * If anyone else was waiting for the lock, wake them too.
    335 	 */
    336 	if (next)
    337 		_lwp_unpark(next, &obj->initfinilock);
    338 
    339 	/*
    340 	 * Notify the caller we failed to claim the object and
    341 	 * released/reacquired the lock to wait for a state change so
    342 	 * they must start over from the top.
    343 	 */
    344 	return false;
    345 }
    346 
    347 /*
    348  * _rtld_initfini_exit(obj)
    349  *
    350  *	Mark obj as no longer running an init/fini routine in this
    351  *	thread, and wake any threads waiting for _rtld_initfini_enter
    352  *	on it.
    353  *
    354  *	Caller must hold the rtld exclusive lock.  Will not release or
    355  *	reacquire it.
    356  *
    357  *	Caller must have previously called _rtld_initfini_enter(&obj,
    358  *	...) in the same thread, and it must have returned true.
    359  */
    360 static void
    361 _rtld_initfini_exit(Obj_Entry *obj)
    362 {
    363 
    364 	/*
    365 	 * We had better have claimed this object.  Relinquish our
    366 	 * claim.
    367 	 */
    368 	assert(obj->initfinilock == _lwp_self());
    369 	obj->initfinilock = 0;
    370 
    371 	/*
    372 	 * If there's anyone waiting for the lock, wake them.  This may
    373 	 * provoke a thundering herd but it's unlikely that there will
    374 	 * be much contention on dlopen/dlclose in the real world.
    375 	 */
    376 	if (__predict_true(obj->initfinilockwaiter == 0))
    377 		return;
    378 	_lwp_unpark(obj->initfinilockwaiter, &obj->initfinilock);
    379 	obj->initfinilockwaiter = 0;
    380 }
    381 
    382 /*
    383  * _rtld_fini_done(obj)
    384  *
    385  *	Mark obj as done running destructors.  Wake any waiters in
    386  *	_rtld_wait_for_fini(&obj, ...).
    387  *
    388  *	Caller must hold the rtld exclusive lock.  Will not release or
    389  *	reacquire it.
    390  */
    391 static void
    392 _rtld_fini_done(Obj_Entry *obj)
    393 {
    394 
    395 	assert(obj->refcount == 0);
    396 	if (__predict_true(obj->finiwaiter == 0))
    397 		return;
    398 	_lwp_unpark(obj->finiwaiter, &obj->refcount);
    399 	obj->finiwaiter = 0;
    400 }
    401 
    402 /*
    403  * _rtld_wait_for_fini(&obj, mask)
    404  *
    405  *	If another thread is concurrently running destructors for obj,
    406  *	release the rtld exclusive lock, wait for that to complete,
    407  *	reacquire the rtld exclusive lock, and return true.  On return,
    408  *	obj is nulled out -- it was in the process of being destroyed
    409  *	when we started and it may be completely gone by the time we
    410  *	return.
    411  *
    412  *	Otherwise, if there is no thread concurrently running
    413  *	destructors for obj, leave it intact and return false without
    414  *	releasing and reacquiring the rtld exclusive lock -- obj is
    415  *	safe to use.
    416  *
    417  *	Caller must either hold the rtld exclusive lock, or be
    418  *	single-threaded; if single-threaded, this is guaranteed to
    419  *	return false, and mask may be null.
    420  */
    421 bool
    422 _rtld_wait_for_fini(Obj_Entry **objp, sigset_t *mask)
    423 {
    424 	Obj_Entry *obj = *objp;
    425 	lwpid_t next;
    426 
    427 	/*
    428 	 * If the object is still referenced, it can't be in the
    429 	 * process of destruction, so nothing to do -- notify the
    430 	 * caller we didn't wait.
    431 	 */
    432 	if (__predict_true(obj->refcount > 0))
    433 		return false;
    434 
    435 	/*
    436 	 * We can only reach this point if there are threads running
    437 	 * dlopen or dlclose concurrently.  This can't happen during
    438 	 * initial program load -- pthread_create is not available for
    439 	 * use in a constructor -- so initial program load can skip
    440 	 * taking the rtld exclusive lock.
    441 	 */
    442 	assert(mask != NULL);
    443 
    444 	/*
    445 	 * Queue ourselves up to be notified when concurrent fini is
    446 	 * done, and remember the next thread to be notified.
    447 	 */
    448 	next = obj->finiwaiter;
    449 	obj->finiwaiter = _lwp_self();
    450 
    451 	/*
    452 	 * Release the rtld exclusive lock to wait and reacquire it
    453 	 * when done.  After we release the lock, we can't dereference
    454 	 * obj -- it may be concurrently freed by dlclose.
    455 	 */
    456 	_rtld_exclusive_exit(mask);
    457 	*objp = NULL;
    458 	_lwp_park(CLOCK_REALTIME, 0, NULL, 0, &obj->refcount, NULL);
    459 	_rtld_exclusive_enter(mask);
    460 
    461 	/*
    462 	 * If another thread was waiting too, notify that thread.
    463 	 */
    464 	if (next)
    465 		_lwp_unpark(next, &obj->refcount);
    466 
    467 	/*
    468 	 * Notify the caller that we released/reacquired the rtld
    469 	 * exclusive lock to wait for a state change so they must start
    470 	 * over from the top.
    471 	 */
    472 	return true;
    473 }
    474 
    475 static inline void
    476 _rtld_call_initfini_function(fptr_t func, sigset_t *mask)
    477 {
    478 	_rtld_exclusive_exit(mask);
    479 	(*func)();
    480 	_rtld_exclusive_enter(mask);
    481 }
    482 
    483 static void
    484 _rtld_call_fini_function(Obj_Entry *obj, sigset_t *mask, u_int cur_objgen)
    485 {
    486 	if (obj->fini_arraysz == 0 && (obj->fini == NULL || obj->fini_called))
    487 		return;
    488 
    489 	if (obj->fini != NULL && !obj->fini_called) {
    490 		dbg (("calling fini function %s at %p%s", obj->path,
    491 		    (void *)obj->fini,
    492 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    493 		obj->fini_called = 1;
    494 		_rtld_call_initfini_function(obj->fini, mask);
    495 	}
    496 #ifdef HAVE_INITFINI_ARRAY
    497 	/*
    498 	 * Now process the fini_array if it exists.  Simply go from
    499 	 * start to end.  We need to make restartable so just advance
    500 	 * the array pointer and decrement the size each time through
    501 	 * the loop.
    502 	 *
    503 	 * Paranoia: avoid touching obj if the generation has changed.
    504 	 */
    505 	while (__predict_true(_rtld_objgen == cur_objgen) &&
    506 	    obj->fini_arraysz > 0) {
    507 		fptr_t fini = *obj->fini_array++;
    508 		obj->fini_arraysz--;
    509 		dbg (("calling fini array function %s at %p%s", obj->path,
    510 		    (void *)fini,
    511 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    512 		_rtld_call_initfini_function(fini, mask);
    513 	}
    514 #endif /* HAVE_INITFINI_ARRAY */
    515 }
    516 
    517 static void
    518 _rtld_call_fini_functions(Obj_Entry *dlobj, sigset_t *mask, int force)
    519 {
    520 	Objlist_Entry *elm;
    521 	Objlist finilist;
    522 	u_int cur_objgen;
    523 
    524 	dbg(("_rtld_call_fini_functions(%d)", force));
    525 
    526 restart:
    527 	cur_objgen = _rtld_objgen;
    528 	SIMPLEQ_INIT(&finilist);
    529 	_rtld_initlist_tsort(&finilist, 1, dlobj);
    530 
    531 	/* First pass: objects _not_ marked with DF_1_INITFIRST. */
    532 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    533 		Obj_Entry *obj = elm->obj;
    534 		if (!obj->z_initfirst) {
    535 			if (obj->refcount > 0 && !force) {
    536 				continue;
    537 			}
    538 			if (!_rtld_initfini_enter(&obj, mask)) {
    539 				_rtld_objlist_clear(&finilist);
    540 				goto restart;
    541 			}
    542 			assert(obj->relocstate == OBJRELOC_DONE);
    543 			_rtld_call_fini_function(obj, mask, cur_objgen);
    544 			_rtld_initfini_exit(obj);
    545 			if (_rtld_objgen != cur_objgen) {
    546 				dbg(("restarting fini iteration"));
    547 				_rtld_objlist_clear(&finilist);
    548 				goto restart;
    549 			}
    550 		}
    551 	}
    552 
    553 	/* Second pass: objects marked with DF_1_INITFIRST. */
    554 	SIMPLEQ_FOREACH(elm, &finilist, link) {
    555 		Obj_Entry *obj = elm->obj;
    556 		if (obj->refcount > 0 && !force) {
    557 			continue;
    558 		}
    559 		if (!_rtld_initfini_enter(&obj, mask)) {
    560 			_rtld_objlist_clear(&finilist);
    561 			goto restart;
    562 		}
    563 		assert(obj->relocstate == OBJRELOC_DONE);
    564 		_rtld_call_fini_function(obj, mask, cur_objgen);
    565 		_rtld_initfini_exit(obj);
    566 		if (_rtld_objgen != cur_objgen) {
    567 			dbg(("restarting fini iteration"));
    568 			_rtld_objlist_clear(&finilist);
    569 			goto restart;
    570 		}
    571 	}
    572 
    573         _rtld_objlist_clear(&finilist);
    574 }
    575 
    576 static void
    577 _rtld_call_init_function(Obj_Entry *obj, sigset_t *mask, u_int cur_objgen)
    578 {
    579 	if (obj->init_arraysz == 0 && (obj->init_called || obj->init == NULL))
    580 		return;
    581 
    582 	if (!obj->init_called && obj->init != NULL) {
    583 		dbg (("calling init function %s at %p%s",
    584 		    obj->path, (void *)obj->init,
    585 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    586 		obj->init_called = 1;
    587 		_rtld_call_initfini_function(obj->init, mask);
    588 	}
    589 
    590 #ifdef HAVE_INITFINI_ARRAY
    591 	/*
    592 	 * Now process the init_array if it exists.  Simply go from
    593 	 * start to end.  We need to make restartable so just advance
    594 	 * the array pointer and decrement the size each time through
    595 	 * the loop.
    596 	 */
    597 	while (obj->init_arraysz > 0 && _rtld_objgen == cur_objgen) {
    598 		fptr_t init = *obj->init_array++;
    599 		obj->init_arraysz--;
    600 		dbg (("calling init_array function %s at %p%s",
    601 		    obj->path, (void *)init,
    602 		    obj->z_initfirst ? " (DF_1_INITFIRST)" : ""));
    603 		_rtld_call_initfini_function(init, mask);
    604 	}
    605 #endif /* HAVE_INITFINI_ARRAY */
    606 }
    607 
    608 static bool
    609 _rtld_call_ifunc_functions(sigset_t *mask, Obj_Entry *obj, u_int cur_objgen)
    610 {
    611 	if (!_rtld_initfini_enter(&obj, mask))
    612 		return true;
    613 	assert(obj->relocstate == OBJRELOC_DONE);
    614 	if (obj->ifunc_remaining
    615 #if defined(IFUNC_NONPLT)
    616 	    || obj->ifunc_remaining_nonplt
    617 #endif
    618 	) {
    619 		_rtld_call_ifunc(obj, mask, cur_objgen);
    620 		if (_rtld_objgen != cur_objgen) {
    621 			_rtld_initfini_exit(obj);
    622 			return true;
    623 		}
    624 	}
    625 	_rtld_initfini_exit(obj);
    626 	return false;
    627 }
    628 
    629 static void
    630 _rtld_call_preinit_functions(sigset_t *mask)
    631 {
    632 #ifdef HAVE_INITFINI_ARRAY
    633 	Obj_Entry      *obj = _rtld_objmain;
    634 
    635 	/*
    636 	 * Process the init_array if it exists.  Simply go from  start
    637 	 * to end.
    638 	 */
    639 	for (size_t i = 0; i < obj->preinit_arraysz; i++) {
    640 		fptr_t preinit = obj->preinit_array[i];
    641 		dbg (("calling preinit_array function %s at %p",
    642 		    obj->path, (void *)preinit));
    643 		_rtld_call_initfini_function(preinit, mask);
    644 	}
    645 #endif /* HAVE_INITFINI_ARRAY */
    646 }
    647 
    648 static void
    649 _rtld_call_init_functions(Obj_Entry *dlobj, sigset_t *mask)
    650 {
    651 	Objlist_Entry *elm;
    652 	Objlist initlist;
    653 	u_int cur_objgen;
    654 
    655 	dbg(("_rtld_call_init_functions()"));
    656 
    657 restart:
    658 	cur_objgen = _rtld_objgen;
    659 	SIMPLEQ_INIT(&initlist);
    660 	_rtld_initlist_tsort(&initlist, 0, dlobj);
    661 
    662 	/* First pass: objects with IRELATIVE relocations. */
    663 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    664 		Obj_Entry *obj = elm->obj;
    665 		if (__predict_false(_rtld_wait_for_fini(&obj, mask))) {
    666 			_rtld_objlist_clear(&initlist);
    667 			goto restart;
    668 		}
    669 		if (_rtld_call_ifunc_functions(mask, obj, cur_objgen)) {
    670 			dbg(("restarting init iteration"));
    671 			_rtld_objlist_clear(&initlist);
    672 			goto restart;
    673 		}
    674 	}
    675 	/*
    676 	 * XXX: For historic reasons, init/fini of the main object are called
    677 	 * from crt0. Don't introduce that mistake for ifunc, so look at
    678 	 * the head of _rtld_objlist that _rtld_initlist_tsort skipped.
    679 	 */
    680 	assert(_rtld_objlist->refcount != 0);
    681 	assert(_rtld_objlist->initfinilock != _lwp_self());
    682 	if (_rtld_call_ifunc_functions(mask, _rtld_objlist, cur_objgen)) {
    683 		dbg(("restarting init iteration"));
    684 		_rtld_objlist_clear(&initlist);
    685 		goto restart;
    686 	}
    687 
    688 	/* Second pass: objects marked with DF_1_INITFIRST. */
    689 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    690 		Obj_Entry *obj = elm->obj;
    691 		if (__predict_false(_rtld_wait_for_fini(&obj, mask))) {
    692 			_rtld_objlist_clear(&initlist);
    693 			goto restart;
    694 		}
    695 		if (obj->z_initfirst) {
    696 			if (!_rtld_initfini_enter(&obj, mask)) {
    697 				_rtld_objlist_clear(&initlist);
    698 				goto restart;
    699 			}
    700 			assert(obj->relocstate == OBJRELOC_DONE);
    701 			_rtld_call_init_function(obj, mask, cur_objgen);
    702 			_rtld_initfini_exit(obj);
    703 			if (_rtld_objgen != cur_objgen) {
    704 				dbg(("restarting init iteration"));
    705 				_rtld_objlist_clear(&initlist);
    706 				goto restart;
    707 			}
    708 		}
    709 	}
    710 
    711 	/* Third pass: all other objects. */
    712 	SIMPLEQ_FOREACH(elm, &initlist, link) {
    713 		Obj_Entry *obj = elm->obj;
    714 		if (__predict_false(_rtld_wait_for_fini(&obj, mask))) {
    715 			_rtld_objlist_clear(&initlist);
    716 			goto restart;
    717 		}
    718 		if (!_rtld_initfini_enter(&obj, mask)) {
    719 			_rtld_objlist_clear(&initlist);
    720 			goto restart;
    721 		}
    722 		assert(obj->relocstate == OBJRELOC_DONE);
    723 		_rtld_call_init_function(obj, mask, cur_objgen);
    724 		_rtld_initfini_exit(obj);
    725 		if (_rtld_objgen != cur_objgen) {
    726 			dbg(("restarting init iteration"));
    727 			_rtld_objlist_clear(&initlist);
    728 			goto restart;
    729 		}
    730 	}
    731 
    732         _rtld_objlist_clear(&initlist);
    733 }
    734 
    735 /*
    736  * Initialize the dynamic linker.  The argument is the address at which
    737  * the dynamic linker has been mapped into memory.  The primary task of
    738  * this function is to create an Obj_Entry for the dynamic linker and
    739  * to resolve the PLT relocation for platforms that need it (those that
    740  * define __HAVE_FUNCTION_DESCRIPTORS
    741  */
    742 static void
    743 _rtld_init(caddr_t mapbase, caddr_t relocbase, const char *execname)
    744 {
    745 	const Elf_Ehdr *ehdr;
    746 
    747 	/* Conjure up an Obj_Entry structure for the dynamic linker. */
    748 	_rtld_objself.path = __UNCONST(_rtld_path);
    749 	_rtld_objself.pathlen = sizeof(_rtld_path)-1;
    750 	_rtld_objself.rtld = true;
    751 	_rtld_objself.mapbase = mapbase;
    752 	_rtld_objself.relocbase = relocbase;
    753 	_rtld_objself.dynamic = (Elf_Dyn *) &_DYNAMIC;
    754 	_rtld_objself.strtab = "_rtld_sym_zero";
    755 	_rtld_objself.refcount = 1;
    756 
    757 	/*
    758 	 * Set value to -relocbase so that
    759 	 *
    760 	 *     _rtld_objself.relocbase + _rtld_sym_zero.st_value == 0
    761 	 *
    762 	 * This allows unresolved references to weak symbols to be computed
    763 	 * to a value of 0.
    764 	 */
    765 	_rtld_sym_zero.st_value = -(uintptr_t)relocbase;
    766 
    767 	_rtld_digest_dynamic(_rtld_path, &_rtld_objself);
    768 	assert(!_rtld_objself.needed);
    769 #if !defined(__hppa__)
    770 	assert(!_rtld_objself.pltrel && !_rtld_objself.pltrela);
    771 #else
    772 	_rtld_relocate_plt_objects(&_rtld_objself);
    773 #endif
    774 #if !defined(__mips__) && !defined(__hppa__)
    775 	assert(!_rtld_objself.pltgot);
    776 #endif
    777 #if !defined(__arm__) && !defined(__mips__) && !defined(__sh__)
    778 	/* ARM, MIPS and SH{3,5} have a bogus DT_TEXTREL. */
    779 	assert(!_rtld_objself.textrel);
    780 #endif
    781 
    782 	_rtld_add_paths(execname, &_rtld_default_paths,
    783 	    RTLD_DEFAULT_LIBRARY_PATH);
    784 
    785 #ifdef RTLD_ARCH_SUBDIR
    786 	_rtld_add_paths(execname, &_rtld_default_paths,
    787 	    RTLD_DEFAULT_LIBRARY_PATH "/" RTLD_ARCH_SUBDIR);
    788 #endif
    789 
    790 	/* Make the object list empty. */
    791 	_rtld_objlist = NULL;
    792 	_rtld_objtail = &_rtld_objlist;
    793 	_rtld_objcount = 0;
    794 
    795 	_rtld_debug.r_version = R_DEBUG_VERSION;
    796 	_rtld_debug.r_brk = _rtld_debug_state;
    797 	_rtld_debug.r_state = RT_CONSISTENT;
    798 	_rtld_debug.r_ldbase = _rtld_objself.relocbase;
    799 
    800 	ehdr = (Elf_Ehdr *)mapbase;
    801 	_rtld_objself.phdr = (Elf_Phdr *)((char *)mapbase + ehdr->e_phoff);
    802 	_rtld_objself.phsize = ehdr->e_phnum * sizeof(_rtld_objself.phdr[0]);
    803 
    804 	__libc_atomic_init();
    805 }
    806 
    807 /*
    808  * Cleanup procedure.  It will be called (by the atexit() mechanism) just
    809  * before the process exits.
    810  */
    811 static void
    812 _rtld_exit(void)
    813 {
    814 	sigset_t mask;
    815 
    816 	dbg(("rtld_exit()"));
    817 
    818 	_rtld_exclusive_enter(&mask);
    819 
    820 	_rtld_call_fini_functions(NULL, &mask, 1);
    821 
    822 	_rtld_exclusive_exit(&mask);
    823 }
    824 
    825 __dso_public void *
    826 _dlauxinfo(void)
    827 {
    828 	return auxinfo;
    829 }
    830 
    831 /*
    832  * Main entry point for dynamic linking.  The argument is the stack
    833  * pointer.  The stack is expected to be laid out as described in the
    834  * SVR4 ABI specification, Intel 386 Processor Supplement.  Specifically,
    835  * the stack pointer points to a word containing ARGC.  Following that
    836  * in the stack is a null-terminated sequence of pointers to argument
    837  * strings.  Then comes a null-terminated sequence of pointers to
    838  * environment strings.  Finally, there is a sequence of "auxiliary
    839  * vector" entries.
    840  *
    841  * This function returns the entry point for the main program, the dynamic
    842  * linker's exit procedure in sp[0], and a pointer to the main object in
    843  * sp[1].
    844  */
    845 Elf_Addr
    846 _rtld(Elf_Addr *sp, Elf_Addr relocbase)
    847 {
    848 	const AuxInfo  *pAUX_base, *pAUX_entry, *pAUX_execfd, *pAUX_phdr,
    849 	               *pAUX_phent, *pAUX_phnum, *pAUX_euid, *pAUX_egid,
    850 		       *pAUX_ruid, *pAUX_rgid;
    851 	const AuxInfo  *pAUX_pagesz;
    852 	char          **env, **oenvp;
    853 	const AuxInfo  *auxp;
    854 	Obj_Entry      *obj;
    855 	Elf_Addr       *const osp = sp;
    856 	bool            bind_now = 0;
    857 	const char     *ld_bind_now, *ld_preload, *ld_library_path;
    858 	const char    **argv;
    859 	const char     *execname, *objmain_name;
    860 	long		argc;
    861 	const char **real___progname;
    862 	const Obj_Entry **real___mainprog_obj;
    863 	char ***real_environ;
    864 	sigset_t        mask;
    865 #ifdef DEBUG
    866 	const char     *ld_debug;
    867 #endif
    868 #ifdef RTLD_DEBUG
    869 	int i = 0;
    870 #endif
    871 
    872 	/*
    873          * On entry, the dynamic linker itself has not been relocated yet.
    874          * Be very careful not to reference any global data until after
    875          * _rtld_init has returned.  It is OK to reference file-scope statics
    876          * and string constants, and to call static and global functions.
    877          */
    878 	/* Find the auxiliary vector on the stack. */
    879 	/* first Elf_Word reserved to address of exit routine */
    880 #if defined(RTLD_DEBUG)
    881 	debug = 1;
    882 	dbg(("sp = %p, argc = %ld, argv = %p <%s> relocbase %p", sp,
    883 	    (long)sp[2], &sp[3], (char *) sp[3], (void *)relocbase));
    884 #ifndef __x86_64__
    885 	dbg(("got is at %p, dynamic is at %p", _GLOBAL_OFFSET_TABLE_,
    886 	    &_DYNAMIC));
    887 #endif
    888 #endif
    889 
    890 	sp += 2;		/* skip over return argument space */
    891 	argv = (const char **) &sp[1];
    892 	argc = *(long *)sp;
    893 	sp += 2 + argc;		/* Skip over argc, arguments, and NULL
    894 				 * terminator */
    895 	env = (char **) sp;
    896 	while (*sp++ != 0) {	/* Skip over environment, and NULL terminator */
    897 #if defined(RTLD_DEBUG)
    898 		dbg(("env[%d] = %p %s", i++, (void *)sp[-1], (char *)sp[-1]));
    899 #endif
    900 	}
    901 	auxinfo = (AuxInfo *) sp;
    902 
    903 	pAUX_base = pAUX_entry = pAUX_execfd = NULL;
    904 	pAUX_phdr = pAUX_phent = pAUX_phnum = NULL;
    905 	pAUX_euid = pAUX_ruid = pAUX_egid = pAUX_rgid = NULL;
    906 	pAUX_pagesz = NULL;
    907 
    908 	execname = NULL;
    909 
    910 	/* Digest the auxiliary vector. */
    911 	for (auxp = auxinfo; auxp->a_type != AT_NULL; ++auxp) {
    912 		switch (auxp->a_type) {
    913 		case AT_BASE:
    914 			pAUX_base = auxp;
    915 			break;
    916 		case AT_ENTRY:
    917 			pAUX_entry = auxp;
    918 			break;
    919 		case AT_EXECFD:
    920 			pAUX_execfd = auxp;
    921 			break;
    922 		case AT_PHDR:
    923 			pAUX_phdr = auxp;
    924 			break;
    925 		case AT_PHENT:
    926 			pAUX_phent = auxp;
    927 			break;
    928 		case AT_PHNUM:
    929 			pAUX_phnum = auxp;
    930 			break;
    931 #ifdef AT_EUID
    932 		case AT_EUID:
    933 			pAUX_euid = auxp;
    934 			break;
    935 		case AT_RUID:
    936 			pAUX_ruid = auxp;
    937 			break;
    938 		case AT_EGID:
    939 			pAUX_egid = auxp;
    940 			break;
    941 		case AT_RGID:
    942 			pAUX_rgid = auxp;
    943 			break;
    944 #endif
    945 #ifdef AT_SUN_EXECNAME
    946 		case AT_SUN_EXECNAME:
    947 			execname = (const char *)(const void *)auxp->a_v;
    948 			break;
    949 #endif
    950 		case AT_PAGESZ:
    951 			pAUX_pagesz = auxp;
    952 			break;
    953 		}
    954 	}
    955 
    956 	/* Initialize and relocate ourselves. */
    957 	if (pAUX_base == NULL) {
    958 		_rtld_error("Bad pAUX_base");
    959 		_rtld_die();
    960 	}
    961 	assert(pAUX_pagesz != NULL);
    962 	_rtld_pagesz = (int)pAUX_pagesz->a_v;
    963 	_rtld_init((caddr_t)pAUX_base->a_v, (caddr_t)relocbase, execname);
    964 
    965 	__progname = _rtld_objself.path;
    966 	environ = env;
    967 
    968 	_rtld_trust = ((pAUX_euid ? (uid_t)pAUX_euid->a_v : geteuid()) ==
    969 	    (pAUX_ruid ? (uid_t)pAUX_ruid->a_v : getuid())) &&
    970 	    ((pAUX_egid ? (gid_t)pAUX_egid->a_v : getegid()) ==
    971 	    (pAUX_rgid ? (gid_t)pAUX_rgid->a_v : getgid()));
    972 
    973 #ifdef DEBUG
    974 	ld_debug = NULL;
    975 #endif
    976 	ld_bind_now = NULL;
    977 	ld_library_path = NULL;
    978 	ld_preload = NULL;
    979 	/*
    980 	 * Inline avoid using normal getenv/unsetenv here as the libc
    981 	 * code is quite a bit more complicated.
    982 	 */
    983 	for (oenvp = env; *env != NULL; ++env) {
    984 		static const char bind_var[] = "LD_BIND_NOW=";
    985 		static const char debug_var[] =  "LD_DEBUG=";
    986 		static const char path_var[] = "LD_LIBRARY_PATH=";
    987 		static const char preload_var[] = "LD_PRELOAD=";
    988 #define LEN(x)	(sizeof(x) - 1)
    989 
    990 		if ((*env)[0] != 'L' || (*env)[1] != 'D') {
    991 			/*
    992 			 * Special case to skip most entries without
    993 			 * the more expensive calls to strncmp.
    994 			 */
    995 			*oenvp++ = *env;
    996 		} else if (strncmp(*env, debug_var, LEN(debug_var)) == 0) {
    997 			if (_rtld_trust) {
    998 #ifdef DEBUG
    999 				ld_debug = *env + LEN(debug_var);
   1000 #endif
   1001 				*oenvp++ = *env;
   1002 			}
   1003 		} else if (strncmp(*env, bind_var, LEN(bind_var)) == 0) {
   1004 			if (_rtld_trust) {
   1005 				ld_bind_now = *env + LEN(bind_var);
   1006 				*oenvp++ = *env;
   1007 			}
   1008 		} else if (strncmp(*env, path_var, LEN(path_var)) == 0) {
   1009 			if (_rtld_trust) {
   1010 				ld_library_path = *env + LEN(path_var);
   1011 				*oenvp++ = *env;
   1012 			}
   1013 		} else if (strncmp(*env, preload_var, LEN(preload_var)) == 0) {
   1014 			if (_rtld_trust) {
   1015 				ld_preload = *env + LEN(preload_var);
   1016 				*oenvp++ = *env;
   1017 			}
   1018 		} else {
   1019 			*oenvp++ = *env;
   1020 		}
   1021 #undef LEN
   1022 	}
   1023 	*oenvp++ = NULL;
   1024 
   1025 	/*
   1026 	 * Set the main name. Prefer the name passed by the kernel first,
   1027 	 * then the argument vector, and fall back to "main program"
   1028 	 * This way the name will be an absolute path if available.
   1029 	 */
   1030 	objmain_name = execname ? execname :
   1031 	    (argv[0] ? argv[0] : "main program");
   1032 
   1033 	if (ld_bind_now != NULL && *ld_bind_now != '\0')
   1034 		bind_now = true;
   1035 	if (_rtld_trust) {
   1036 #ifdef DEBUG
   1037 #ifdef RTLD_DEBUG
   1038 		debug = 0;
   1039 #endif
   1040 		if (ld_debug != NULL && *ld_debug != '\0')
   1041 			debug = 1;
   1042 #endif
   1043 		_rtld_add_paths(execname, &_rtld_paths, ld_library_path);
   1044 	} else {
   1045 		// Prevent $ORIGIN expansion
   1046 		execname = NULL;
   1047 	}
   1048 	_rtld_process_hints(execname, &_rtld_paths, &_rtld_xforms,
   1049 	    _PATH_LD_HINTS);
   1050 	dbg(("dynamic linker is initialized, mapbase=%p, relocbase=%p",
   1051 	     _rtld_objself.mapbase, _rtld_objself.relocbase));
   1052 
   1053 	/*
   1054          * Load the main program, or process its program header if it is
   1055          * already loaded.
   1056          */
   1057 	if (pAUX_execfd != NULL) {	/* Load the main program. */
   1058 		int             fd = pAUX_execfd->a_v;
   1059 		dbg(("loading main program"));
   1060 		_rtld_objmain = _rtld_map_object(objmain_name, fd, NULL);
   1061 		close(fd);
   1062 		if (_rtld_objmain == NULL)
   1063 			_rtld_die();
   1064 	} else {		/* Main program already loaded. */
   1065 		const Elf_Phdr *phdr;
   1066 		int             phnum;
   1067 		caddr_t         entry;
   1068 
   1069 		dbg(("processing main program's program header"));
   1070 		assert(pAUX_phdr != NULL);
   1071 		phdr = (const Elf_Phdr *) pAUX_phdr->a_v;
   1072 		assert(pAUX_phnum != NULL);
   1073 		phnum = pAUX_phnum->a_v;
   1074 		assert(pAUX_phent != NULL);
   1075 		assert(pAUX_phent->a_v == sizeof(Elf_Phdr));
   1076 		assert(pAUX_entry != NULL);
   1077 		entry = (caddr_t) pAUX_entry->a_v;
   1078 		_rtld_objmain = _rtld_digest_phdr(phdr, phnum, entry);
   1079 		_rtld_objmain->path = xstrdup(objmain_name);
   1080 		_rtld_objmain->pathlen = strlen(_rtld_objmain->path);
   1081 	}
   1082 
   1083 	_rtld_objmain->mainprog = true;
   1084 
   1085 	/*
   1086 	 * Get the actual dynamic linker pathname from the executable if
   1087 	 * possible.  (It should always be possible.)  That ensures that
   1088 	 * the debugger will find the right dynamic linker even if a
   1089 	 * non-standard one is being used.
   1090 	 */
   1091 	if (_rtld_objmain->interp != NULL &&
   1092 	    strcmp(_rtld_objmain->interp, _rtld_objself.path) != 0) {
   1093 		_rtld_objself.path = xstrdup(_rtld_objmain->interp);
   1094 		_rtld_objself.pathlen = strlen(_rtld_objself.path);
   1095 	}
   1096 	dbg(("actual dynamic linker is %s", _rtld_objself.path));
   1097 
   1098 	_rtld_digest_dynamic(execname, _rtld_objmain);
   1099 
   1100 	/* Link the main program into the list of objects. */
   1101 	*_rtld_objtail = _rtld_objmain;
   1102 	_rtld_objtail = &_rtld_objmain->next;
   1103 	_rtld_objcount++;
   1104 	_rtld_objloads++;
   1105 
   1106 	_rtld_linkmap_add(_rtld_objmain);
   1107 	_rtld_objself.path = xstrdup(_rtld_objself.path);
   1108 	_rtld_linkmap_add(&_rtld_objself);
   1109 
   1110 	++_rtld_objmain->refcount;
   1111 	_rtld_objmain->mainref = 1;
   1112 	_rtld_objlist_push_tail(&_rtld_list_main, _rtld_objmain);
   1113 
   1114 	if (ld_preload) {
   1115 		/*
   1116 		 * Pre-load user-specified objects after the main program
   1117 		 * but before any shared object dependencies.
   1118 		 */
   1119 		dbg(("preloading objects"));
   1120 		if (_rtld_preload(ld_preload, NULL) == -1)
   1121 			_rtld_die();
   1122 	}
   1123 
   1124 	dbg(("loading needed objects"));
   1125 	if (_rtld_load_needed_objects(_rtld_objmain, _RTLD_MAIN, NULL) == -1)
   1126 		_rtld_die();
   1127 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
   1128 		assert(obj->relocstate == OBJRELOC_NOTYET);
   1129 		obj->relocstate = OBJRELOC_READY;
   1130 	}
   1131 
   1132 	dbg(("checking for required versions"));
   1133 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next) {
   1134 		if (_rtld_verify_object_versions(obj) == -1)
   1135 			_rtld_die();
   1136 	}
   1137 
   1138 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
   1139 	dbg(("initializing initial Thread Local Storage offsets"));
   1140 	/*
   1141 	 * All initial objects get the TLS space from the static block.
   1142 	 */
   1143 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
   1144 		_rtld_tls_offset_allocate(obj);
   1145 #endif
   1146 
   1147 	dbg(("relocating objects"));
   1148 	if (_rtld_relocate_objects(_rtld_objmain, bind_now) == -1)
   1149 		_rtld_die();
   1150 
   1151 	dbg(("doing copy relocations"));
   1152 	if (_rtld_do_copy_relocations(_rtld_objmain) == -1)
   1153 		_rtld_die();
   1154 
   1155 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
   1156 	dbg(("initializing Thread Local Storage for main thread"));
   1157 	/*
   1158 	 * Set up TLS area for the main thread.
   1159 	 * This has to be done after all relocations are processed,
   1160 	 * since .tdata may contain relocations.
   1161 	 */
   1162 	_rtld_tls_initial_allocation();
   1163 #endif
   1164 
   1165 	/*
   1166 	 * Set the __progname,  environ and, __mainprog_obj before
   1167 	 * calling anything that might use them.
   1168 	 */
   1169 	real___progname = _rtld_objmain_sym("__progname");
   1170 	if (real___progname) {
   1171 		if (argv[0] != NULL) {
   1172 			if ((*real___progname = strrchr(argv[0], '/')) == NULL)
   1173 				(*real___progname) = argv[0];
   1174 			else
   1175 				(*real___progname)++;
   1176 		} else {
   1177 			(*real___progname) = NULL;
   1178 		}
   1179 	}
   1180 	real_environ = _rtld_objmain_sym("environ");
   1181 	if (real_environ)
   1182 		*real_environ = environ;
   1183 	/*
   1184 	 * Set __mainprog_obj for old binaries.
   1185 	 */
   1186 	real___mainprog_obj = _rtld_objmain_sym("__mainprog_obj");
   1187 	if (real___mainprog_obj)
   1188 		*real___mainprog_obj = _rtld_objmain;
   1189 
   1190 	_rtld_debug_state();	/* say hello to the debugger! */
   1191 
   1192 	_rtld_exclusive_enter(&mask);
   1193 
   1194 	dbg(("calling main preinit array functions"));
   1195 	_rtld_call_preinit_functions(&mask);
   1196 
   1197 	dbg(("calling _init functions"));
   1198 	_rtld_call_init_functions(NULL, &mask);
   1199 
   1200 	dbg(("control at program entry point = %p, obj = %p, exit = %p",
   1201 	     _rtld_objmain->entry, _rtld_objmain, _rtld_exit));
   1202 
   1203 	_rtld_exclusive_exit(&mask);
   1204 
   1205 #ifdef GNU_RELRO
   1206 	/*
   1207 	 * If the main program is lazily bound (default -- whether or
   1208 	 * not LD_BINDNOW is set in the calling environment), its RELRO
   1209 	 * region has already been mapped read-only in
   1210 	 * _rtld_do_copy_relocations.  The ifunc resolutions lie
   1211 	 * outside this region, so future lazy ifunc resolution is
   1212 	 * unaffected by the RELRO region's being read-only.
   1213 	 *
   1214 	 * If the main program is eagerly bound (i.e., the object has
   1215 	 * DF_1_NOW set in DT_FLAGS_1, whether or not LD_BIND_NOW is
   1216 	 * set in the calling environment), we deferred that from
   1217 	 * _rtld_do_copy_relocations so that the ifunc resolution, we
   1218 	 * have now resolved all ifuncs in it, so we can commit the
   1219 	 * RELRO region to be read-only -- and that means ifunc
   1220 	 * resolutions are read-only too.
   1221 	 */
   1222 	if (_rtld_objmain->z_now && _rtld_relro(_rtld_objmain, true) == -1)
   1223 		_rtld_die();
   1224 #endif
   1225 
   1226 	/*
   1227 	 * Return with the entry point and the exit procedure in at the top
   1228 	 * of stack.
   1229 	 */
   1230 
   1231 	((void **) osp)[0] = _rtld_exit;
   1232 	((void **) osp)[1] = __UNCONST(_rtld_compat_obj);
   1233 	return (Elf_Addr) _rtld_objmain->entry;
   1234 }
   1235 
   1236 void
   1237 _rtld_die(void)
   1238 {
   1239 	const char *msg = dlerror();
   1240 
   1241 	if (msg == NULL)
   1242 		msg = "Fatal error";
   1243 	xerrx(1, "%s", msg);
   1244 }
   1245 
   1246 static Obj_Entry *
   1247 _rtld_dlcheck(void *handle)
   1248 {
   1249 	Obj_Entry *obj;
   1250 
   1251 	for (obj = _rtld_objlist; obj != NULL; obj = obj->next)
   1252 		if (obj == (Obj_Entry *) handle)
   1253 			break;
   1254 
   1255 	if (obj == NULL || obj->dl_refcount == 0) {
   1256 		_rtld_error("Invalid shared object handle %p", handle);
   1257 		return NULL;
   1258 	}
   1259 	return obj;
   1260 }
   1261 
   1262 /*
   1263  * _rtld_initlist_visit(list, obj, rev)
   1264  *
   1265  *	Visit obj in a depth-first search for a topological ordering of
   1266  *	objects by DT_NEEDED relations.  Recursively traverse all its
   1267  *	DT_NEEDED objects, and add it to list if appropriate, at the
   1268  *	end if rev is 0 or the beginning if rev is 1.  Returns true if
   1269  *	the current object is blocked because we're currently in its
   1270  *	constructor/destructor, or in the constructor/destructor of an
   1271  *	object this one needs.
   1272  *
   1273  *	Objects which have not yet been relocated are skipped: they may
   1274  *	appear in the list during a concurrent dlopen in
   1275  *	_rtld_load_needed_objects, before that call to dlopen has run
   1276  *	_rtld_relocate_objects.  They can't be relevant to the
   1277  *	constructor or destructor order of the object currently being
   1278  *	dlopened or dlclosed.
   1279  *
   1280  *	Objects which are currently being initialized or finalized by
   1281  *	_this thread_, i.e., objects whose constructors or destructors
   1282  *	call dlopen/dlclose, can't be initialized or finalized.
   1283  *	Neither can any objects that depend on objects currently being
   1284  *	initialized or finalized, until this dlopen/dlclose call has
   1285  *	returned (at which point rtld will notice the object list has
   1286  *	changed, tsort afresh, and pick up where it left off).  So
   1287  *	_rtld_initlist_visit returns a boolean flag indicating whether
   1288  *	initialization/finalization for this object is blocked (true)
   1289  *	or not (false).  Blocked objects are not included in the
   1290  *	topologically sorted list at all.
   1291  */
   1292 static bool
   1293 _rtld_initlist_visit(Objlist *list, Obj_Entry *obj, int rev)
   1294 {
   1295 	Needed_Entry *elm;
   1296 	bool blocked = false;
   1297 
   1298 	/* dbg(("_rtld_initlist_visit(%s)", obj->path)); */
   1299 
   1300 	/*
   1301 	 * If the object hasn't been relocated yet, we have nothing to
   1302 	 * do -- another thread is running dlopen, and will get to it
   1303 	 * eventually, but it isn't ordered with respect to any
   1304 	 * initializers we have to run.
   1305 	 */
   1306 	switch (obj->relocstate) {
   1307 	case OBJRELOC_NOTYET:
   1308 	case OBJRELOC_READY:
   1309 		/*
   1310 		 * Not blocked but also not relevant -- don't put it in
   1311 		 * the list.
   1312 		 */
   1313 		return false;
   1314 	case OBJRELOC_DONE:
   1315 	case OBJRELOC_FAILED:
   1316 		break;
   1317 	}
   1318 
   1319 	/*
   1320 	 * If the object has already been visited, we have nothing to
   1321 	 * do, so skip it.  Note: This is reset at the beginning of
   1322 	 * _rtld_initlist_topsort; it does not reflect whether the
   1323 	 * initializers have actually run yet.
   1324 	 */
   1325 	if (obj->init_done)
   1326 		return obj->init_blocked;
   1327 	obj->init_done = 1;
   1328 	assert(obj->initfinilock != _lwp_self());
   1329 
   1330 	for (elm = obj->needed; elm != NULL; elm = elm->next) {
   1331 		if (elm->obj != NULL) {
   1332 			if (_rtld_initlist_visit(list, elm->obj, rev)) {
   1333 				blocked = true;
   1334 			}
   1335 		}
   1336 	}
   1337 
   1338 	obj->init_blocked = blocked;
   1339 	if (blocked) {
   1340 		return true;
   1341 	}
   1342 
   1343 	if (rev) {
   1344 		_rtld_objlist_push_head(list, obj);
   1345 	} else {
   1346 		_rtld_objlist_push_tail(list, obj);
   1347 	}
   1348 	return false;
   1349 }
   1350 
   1351 /*
   1352  * _rtld_initlist_tsort(list, rev, dlobj)
   1353  *
   1354  *	Compute a topological sort of objects by DT_NEEDED
   1355  *	dependencies.
   1356  *
   1357  *	If rev (reverse) is false, object A comes before object B if B
   1358  *	has a DT_NEEDED entry for A, i.e., dependencies come before
   1359  *	objects that depend on them, for initialization.  If rev is
   1360  *	true, the order is reversed.
   1361  *
   1362  *	If we are currently dlopening or dlclosing an object (dlobj),
   1363  *	and we detect that we are currently running a constructor or
   1364  *	destructor for some object, then that object and anything that
   1365  *	depends on it is excluded from the topological sort results.
   1366  */
   1367 static void
   1368 _rtld_initlist_tsort(Objlist *list, int rev, Obj_Entry *dlobj)
   1369 {
   1370 	dbg(("_rtld_initlist_tsort"));
   1371 
   1372 	Obj_Entry *obj;
   1373 
   1374 	/*
   1375 	 * We don't include objmain here (starting from next)
   1376 	 * because csu handles it
   1377 	 */
   1378 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
   1379 		obj->init_done = 0;
   1380 		obj->init_blocked = 0;
   1381 	}
   1382 
   1383 	/*
   1384 	 * Consider:
   1385 	 *
   1386 	 *	libB.so has NEEDED libA.so
   1387 	 *	libY.so has NEEDED libX.so
   1388 	 *	libA.so's constructor dlopens libY.so
   1389 	 *
   1390 	 * In other words, we have the following ordering constraints:
   1391 	 *
   1392 	 *	A -> B
   1393 	 *	X -> Y
   1394 	 *
   1395 	 * plus, _while A's constructor is running_, we discover that
   1396 	 * we need Y.  We must not include A or B in the result,
   1397 	 * because A's constructor is still running until after dlopen
   1398 	 * returns, and B's constructor can't run until A's constructor
   1399 	 * has finished.  We block the sort at A, as well as anything
   1400 	 * else that needs it.  Once the constructor returns, it will
   1401 	 * notice that the objects have changed, tsort afresh, and run
   1402 	 * the downstream constructors as needed.
   1403 	 */
   1404 	if (dlobj) {
   1405 		for (obj = _rtld_objlist->next; obj; obj = obj->next) {
   1406 			if (__predict_false(obj->initfinilock ==
   1407 				_lwp_self())) {
   1408 				obj->init_done = 1;
   1409 				obj->init_blocked = 1;
   1410 			}
   1411 		}
   1412 	}
   1413 	for (obj = _rtld_objlist->next; obj; obj = obj->next) {
   1414 		(void)_rtld_initlist_visit(list, obj, rev);
   1415 	}
   1416 }
   1417 
   1418 static void
   1419 _rtld_init_dag(Obj_Entry *root)
   1420 {
   1421 
   1422 	_rtld_init_dag1(root, root);
   1423 }
   1424 
   1425 static void
   1426 _rtld_init_dag1(Obj_Entry *root, Obj_Entry *obj)
   1427 {
   1428 	const Needed_Entry *needed;
   1429 
   1430 	/*
   1431 	 * Now that all objects reachable from root have been loaded,
   1432 	 * they are ready to be relocated.  Before they were all
   1433 	 * loaded, a concurrent thread relocating objects might fail to
   1434 	 * symbols.
   1435 	 *
   1436 	 * That's not quite right: they are actually not ready yet
   1437 	 * until all the dldags lists have been updated.  But we hold
   1438 	 * the rtld exclusive lock and won't drop it or attempt symbol
   1439 	 * lookups until after _rtld_init_dag has traversed the DAG.
   1440 	 */
   1441 	if (obj->relocstate == OBJRELOC_NOTYET) {
   1442 		obj->relocstate = OBJRELOC_READY;
   1443 	}
   1444 
   1445 	if (!obj->mainref) {
   1446 		if (_rtld_objlist_find(&obj->dldags, root))
   1447 			return;
   1448 		dbg(("add %p (%s) to %p (%s) DAG", obj, obj->path, root,
   1449 		    root->path));
   1450 		_rtld_objlist_push_tail(&obj->dldags, root);
   1451 		_rtld_objlist_push_tail(&root->dagmembers, obj);
   1452 	}
   1453 	for (needed = obj->needed; needed != NULL; needed = needed->next) {
   1454 		if (needed->obj != NULL) {
   1455 			assert(needed->obj->refcount > 0);
   1456 			_rtld_init_dag1(root, needed->obj);
   1457 		}
   1458 	}
   1459 }
   1460 
   1461 /*
   1462  * Note, this is called only for objects loaded by dlopen().
   1463  */
   1464 static void
   1465 _rtld_unload_object(sigset_t *mask, Obj_Entry *root, bool do_fini_funcs)
   1466 {
   1467 
   1468 	_rtld_unref_dag(root);
   1469 	if (root->refcount == 0) { /* We are finished with some objects. */
   1470 		Obj_Entry *obj;
   1471 		Obj_Entry **linkp;
   1472 		Objlist_Entry *elm;
   1473 
   1474 		assert(root->dl_refcount == 0);
   1475 		assert(!root->z_nodelete);
   1476 		assert(!root->ref_nodel);
   1477 
   1478 		/*
   1479 		 * Set root->dlclosing to notify other threads that we
   1480 		 * are busy dlclosing root, so they don't pull the rug
   1481 		 * out from under us while we wait for various things.
   1482 		 */
   1483 		root->dlclosing++;
   1484 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link) {
   1485 			elm->obj->dlclosing++;
   1486 		}
   1487 
   1488 		/*
   1489 		 * A concurrent dlopen of some other library might have
   1490 		 * picked up this object while loading needed entries.
   1491 		 * Wait for that to complete.  The root can't go away
   1492 		 * at this point: we have set root->dlclosing.
   1493 		 */
   1494 		obj = root;
   1495 		(void)_rtld_wait_for_load_needed(&obj, mask);
   1496 		assert(root->dlclosing);
   1497 		assert(root->refcount == 0);
   1498 		assert(root->dl_refcount == 0);
   1499 		assert(!root->z_nodelete);
   1500 		assert(!root->ref_nodel);
   1501 
   1502 		/*
   1503 		 * Finalize objects that are about to be unmapped.
   1504 		 * Since we set root->dlclosing above, concurrent
   1505 		 * dlclose calls, which can run while the rtld
   1506 		 * exclusive lock is dropped across fini calls, will
   1507 		 * skip this when garbage-collecting the object list.
   1508 		 */
   1509 		if (do_fini_funcs) {
   1510 			_rtld_call_fini_functions(root, mask, 0);
   1511 			assert(root->dlclosing);
   1512 			assert(root->refcount == 0);
   1513 			assert(root->dl_refcount == 0);
   1514 		}
   1515 
   1516 		/* Remove the DAG from all objects' DAG lists. */
   1517 		SIMPLEQ_FOREACH(elm, &root->dagmembers, link) {
   1518 			assert(elm->obj->dlclosing);
   1519 			_rtld_objlist_remove(&elm->obj->dldags, root);
   1520 			elm->obj->dlclosing--;
   1521 		}
   1522 
   1523 		/* Remove the DAG from the RTLD_GLOBAL list. */
   1524 		if (root->globalref) {
   1525 			root->globalref = 0;
   1526 			_rtld_objlist_remove(&_rtld_list_global, root);
   1527 		}
   1528 
   1529 		/*
   1530 		 * We are done closing root.  Allow it to be
   1531 		 * garbage-collected -- probably by this thread, but
   1532 		 * possibly by another thread if we have to drop the
   1533 		 * lock to wait before freeing an object in the GC loop
   1534 		 * below.  Further direct references to root are now
   1535 		 * forbidden.
   1536 		 */
   1537 		assert(root->dlclosing);
   1538 		root->dlclosing--;
   1539 
   1540 		/*
   1541 		 * Unmap all objects that are no longer referenced.
   1542 		 *
   1543 		 * Objects that are unreferenced but have dlclosing or
   1544 		 * initfinilock set must be in use in a concurrent call
   1545 		 * to _rtld_unload_object, which will go through the
   1546 		 * list of objects to unmap when it is done, so we skip
   1547 		 * them -- this avoids pulling the rug out from under
   1548 		 * the concurrent call, and won't leak.
   1549 		 *
   1550 		 * For objects that are still having their dependencies
   1551 		 * loaded, we have to wait until the loading is done --
   1552 		 * and while we're waiting, another thread might free
   1553 		 * it, so we have to start over from the top.
   1554 		 */
   1555 restart:
   1556 		linkp = &_rtld_objlist->next;
   1557 		while ((obj = *linkp) != NULL) {
   1558 			if (obj->refcount == 0 &&
   1559 			    !obj->dlclosing &&
   1560 			    obj->initfinilock == 0) {
   1561 				if (__predict_false(
   1562 				    _rtld_wait_for_load_needed(&obj, mask)))
   1563 					goto restart;
   1564 				dbg(("unloading \"%s\"", obj->path));
   1565 				if (obj->ehdr != MAP_FAILED)
   1566 					munmap(obj->ehdr, _rtld_pagesz);
   1567 				munmap(obj->mapbase, obj->mapsize);
   1568 				_rtld_objlist_remove(&_rtld_list_global, obj);
   1569 				_rtld_linkmap_delete(obj);
   1570 				*linkp = obj->next;
   1571 				_rtld_objcount--;
   1572 				_rtld_fini_done(obj);
   1573 				_rtld_obj_free(obj);
   1574 			} else
   1575 				linkp = &obj->next;
   1576 		}
   1577 		_rtld_objtail = linkp;
   1578 		_rtld_objgen++;
   1579 	}
   1580 }
   1581 
   1582 void
   1583 _rtld_ref_dag(Obj_Entry *root)
   1584 {
   1585 	const Needed_Entry *needed;
   1586 
   1587 	assert(root);
   1588 	assert(root->refcount > 0);
   1589 
   1590 	++root->refcount;
   1591 
   1592 	dbg(("incremented reference on \"%s\" (%d)", root->path,
   1593 	    root->refcount));
   1594 	for (needed = root->needed; needed != NULL;
   1595 	     needed = needed->next) {
   1596 		if (needed->obj != NULL)
   1597 			_rtld_ref_dag(needed->obj);
   1598 	}
   1599 }
   1600 
   1601 static void
   1602 _rtld_unref_dag(Obj_Entry *root)
   1603 {
   1604 
   1605 	assert(root);
   1606 	assert(root->refcount != 0);
   1607 
   1608 	--root->refcount;
   1609 	dbg(("decremented reference on \"%s\" (%d)", root->path,
   1610 	    root->refcount));
   1611 
   1612 	if (root->refcount == 0) {
   1613 		const Needed_Entry *needed;
   1614 
   1615 		for (needed = root->needed; needed != NULL;
   1616 		     needed = needed->next) {
   1617 			if (needed->obj != NULL)
   1618 				_rtld_unref_dag(needed->obj);
   1619 		}
   1620 	}
   1621 }
   1622 
   1623 __strong_alias(__dlclose,dlclose)
   1624 int
   1625 dlclose(void *handle)
   1626 {
   1627 	Obj_Entry *root;
   1628 	sigset_t mask;
   1629 
   1630 	dbg(("dlclose of %p", handle));
   1631 
   1632 	_rtld_exclusive_enter(&mask);
   1633 
   1634 	root = _rtld_dlcheck(handle);
   1635 
   1636 	if (root == NULL) {
   1637 		_rtld_exclusive_exit(&mask);
   1638 		return -1;
   1639 	}
   1640 	assert(root->refcount != 0);
   1641 	assert(root->dl_refcount != 0);
   1642 
   1643 	_rtld_debug.r_state = RT_DELETE;
   1644 	_rtld_debug_state();
   1645 
   1646 	--root->dl_refcount;
   1647 	assert(root->refcount != 0);
   1648 	_rtld_unload_object(&mask, root, true);
   1649 
   1650 	_rtld_debug.r_state = RT_CONSISTENT;
   1651 	_rtld_debug_state();
   1652 
   1653 	_rtld_exclusive_exit(&mask);
   1654 
   1655 	return 0;
   1656 }
   1657 
   1658 __strong_alias(__dlerror,dlerror)
   1659 char *
   1660 dlerror(void)
   1661 {
   1662 	char *msg = error_message;
   1663 
   1664 	error_message = NULL;
   1665 	return msg;
   1666 }
   1667 
   1668 __strong_alias(__dlopen,dlopen)
   1669 void *
   1670 dlopen(const char *name, int mode)
   1671 {
   1672 	Obj_Entry *obj = NULL;
   1673 	int flags = _RTLD_DLOPEN;
   1674 	bool nodelete;
   1675 	bool now;
   1676 	sigset_t mask;
   1677 	int result;
   1678 
   1679 	dbg(("dlopen of %s 0x%x", name, mode));
   1680 
   1681 	_rtld_exclusive_enter(&mask);
   1682 
   1683 	flags |= (mode & RTLD_GLOBAL) ? _RTLD_GLOBAL : 0;
   1684 	flags |= (mode & RTLD_NOLOAD) ? _RTLD_NOLOAD : 0;
   1685 
   1686 	nodelete = (mode & RTLD_NODELETE) ? true : false;
   1687 	now = ((mode & RTLD_MODEMASK) == RTLD_NOW) ? true : false;
   1688 
   1689 	_rtld_debug.r_state = RT_ADD;
   1690 	_rtld_debug_state();
   1691 
   1692 	if (name == NULL) {
   1693 		obj = _rtld_objmain;
   1694 		assert(obj->refcount > 0);
   1695 		obj->refcount++;
   1696 	} else
   1697 		obj = _rtld_load_library(name, _rtld_objmain, flags, &mask);
   1698 
   1699 	if (obj != NULL) {
   1700 		assert(obj->refcount > 0);
   1701 		++obj->dl_refcount;
   1702 		if (_rtld_objrelocpending) {	/* We loaded something new. */
   1703 			result = _rtld_load_needed_objects(obj, flags, &mask);
   1704 			if (result != -1) {
   1705 				Objlist_Entry *entry;
   1706 				_rtld_init_dag(obj);
   1707 				SIMPLEQ_FOREACH(entry, &obj->dagmembers, link) {
   1708 					result = _rtld_verify_object_versions(entry->obj);
   1709 					if (result == -1)
   1710 						break;
   1711 				}
   1712 			}
   1713 			if (result == -1 || _rtld_relocate_objects(_rtld_objlist,
   1714 			    (now || obj->z_now)) == -1) {
   1715 				obj->dl_refcount--;
   1716 				_rtld_unload_object(&mask, obj, false);
   1717 				obj = NULL;
   1718 			} else {
   1719 				_rtld_call_init_functions(obj, &mask);
   1720 			}
   1721 		}
   1722 		if (obj != NULL) {
   1723 			if ((nodelete || obj->z_nodelete) && !obj->ref_nodel) {
   1724 				dbg(("dlopen obj %s nodelete", obj->path));
   1725 				_rtld_ref_dag(obj);
   1726 				obj->z_nodelete = obj->ref_nodel = true;
   1727 			}
   1728 		}
   1729 	}
   1730 	_rtld_debug.r_state = RT_CONSISTENT;
   1731 	_rtld_debug_state();
   1732 
   1733 	dbg(("dlopen of %s 0x%x returned %p%s%s%s", name, mode, obj,
   1734 	    obj ? "" : " (", obj ? "" : error_message, obj ? "" : ")"));
   1735 
   1736 	_rtld_exclusive_exit(&mask);
   1737 
   1738 	return obj;
   1739 }
   1740 
   1741 /*
   1742  * Find a symbol in the main program.
   1743  */
   1744 _Pragma("GCC diagnostic push")	/* _rtld_donelist_init: -Wno-stack-protector */
   1745 _Pragma("GCC diagnostic ignored \"-Wstack-protector\"")
   1746 void *
   1747 _rtld_objmain_sym(const char *name)
   1748 {
   1749 	Elf_Hash hash;
   1750 	const Elf_Sym *def;
   1751 	const Obj_Entry *obj;
   1752 	DoneList donelist;
   1753 
   1754 	hash.sysv = _rtld_sysv_hash(name);
   1755 	hash.gnu = _rtld_gnu_hash(name);
   1756 	obj = _rtld_objmain;
   1757 	_rtld_donelist_init(&donelist);
   1758 
   1759 	def = _rtld_symlook_list(name, &hash, &_rtld_list_main, &obj, 0,
   1760 	    NULL, &donelist);
   1761 
   1762 	if (def != NULL)
   1763 		return obj->relocbase + def->st_value;
   1764 	return NULL;
   1765 }
   1766 _Pragma("GCC diagnostic pop")
   1767 
   1768 #if defined(__powerpc__) && !defined(__clang__)
   1769 static __noinline void *
   1770 hackish_return_address(void)
   1771 {
   1772 #if __GNUC_PREREQ__(6,0)
   1773 #pragma GCC diagnostic push
   1774 #pragma GCC diagnostic ignored "-Wframe-address"
   1775 #endif
   1776 	return __builtin_return_address(1);
   1777 #if __GNUC_PREREQ__(6,0)
   1778 #pragma GCC diagnostic pop
   1779 #endif
   1780 }
   1781 #endif
   1782 
   1783 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1784 #define	lookup_mutex_enter()	_rtld_exclusive_enter(&mask)
   1785 #define	lookup_mutex_exit()	_rtld_exclusive_exit(&mask)
   1786 #else
   1787 #define	lookup_mutex_enter()	_rtld_shared_enter()
   1788 #define	lookup_mutex_exit()	_rtld_shared_exit()
   1789 #endif
   1790 
   1791 _Pragma("GCC diagnostic push")	/* _rtld_donelist_init: -Wno-stack-protector */
   1792 _Pragma("GCC diagnostic ignored \"-Wstack-protector\"")
   1793 static void *
   1794 do_dlsym(void *handle, const char *name, const Ver_Entry *ventry, void *retaddr)
   1795 {
   1796 	const Obj_Entry *obj;
   1797 	Elf_Hash hash;
   1798 	const Elf_Sym *def;
   1799 	const Obj_Entry *defobj;
   1800 	DoneList donelist;
   1801 	const u_int flags = SYMLOOK_DLSYM | SYMLOOK_IN_PLT;
   1802 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1803 	sigset_t mask;
   1804 #endif
   1805 
   1806 	lookup_mutex_enter();
   1807 
   1808 	hash.sysv = _rtld_sysv_hash(name);
   1809 	hash.gnu = _rtld_gnu_hash(name);
   1810 	def = NULL;
   1811 	defobj = NULL;
   1812 
   1813 	switch ((intptr_t)handle) {
   1814 	case (intptr_t)NULL:
   1815 	case (intptr_t)RTLD_NEXT:
   1816 	case (intptr_t)RTLD_DEFAULT:
   1817 	case (intptr_t)RTLD_SELF:
   1818 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   1819 			_rtld_error("Cannot determine caller's shared object");
   1820 			lookup_mutex_exit();
   1821 			return NULL;
   1822 		}
   1823 
   1824 		switch ((intptr_t)handle) {
   1825 		case (intptr_t)NULL:	 /* Just the caller's shared object. */
   1826 			def = _rtld_symlook_obj(name, &hash, obj, flags, ventry);
   1827 			defobj = obj;
   1828 			break;
   1829 
   1830 		case (intptr_t)RTLD_NEXT:	/* Objects after callers */
   1831 			obj = obj->next;
   1832 			/*FALLTHROUGH*/
   1833 
   1834 		case (intptr_t)RTLD_SELF:	/* Caller included */
   1835 			for (; obj; obj = obj->next) {
   1836 				if ((def = _rtld_symlook_obj(name, &hash, obj,
   1837 				    flags, ventry)) != NULL) {
   1838 					defobj = obj;
   1839 					break;
   1840 				}
   1841 			}
   1842 			/*
   1843 			 * Search the dynamic linker itself, and possibly
   1844 			 * resolve the symbol from there if it is not defined
   1845 			 * already or weak. This is how the application links
   1846 			 * to dynamic linker services such as dlopen.
   1847 			 */
   1848 			if (!def || ELF_ST_BIND(def->st_info) == STB_WEAK) {
   1849 				const Elf_Sym *symp = _rtld_symlook_obj(name,
   1850 				    &hash, &_rtld_objself, flags, ventry);
   1851 				if (symp != NULL) {
   1852 					def = symp;
   1853 					defobj = &_rtld_objself;
   1854 				}
   1855 			}
   1856 			break;
   1857 
   1858 		case (intptr_t)RTLD_DEFAULT:
   1859 			def = _rtld_symlook_default(name, &hash, obj, &defobj,
   1860 			    flags, ventry);
   1861 			break;
   1862 
   1863 		default:
   1864 			abort();
   1865 		}
   1866 		break;
   1867 
   1868 	default:
   1869 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   1870 			lookup_mutex_exit();
   1871 			return NULL;
   1872 		}
   1873 
   1874 		_rtld_donelist_init(&donelist);
   1875 
   1876 		if (obj->mainprog) {
   1877 			/* Search main program and all libraries loaded by it */
   1878 			def = _rtld_symlook_list(name, &hash, &_rtld_list_main,
   1879 			    &defobj, flags, ventry, &donelist);
   1880 		} else {
   1881 			Needed_Entry fake;
   1882 			DoneList depth;
   1883 
   1884 			/* Search the object and all the libraries loaded by it. */
   1885 			fake.next = NULL;
   1886 			fake.obj = __UNCONST(obj);
   1887 			fake.name = 0;
   1888 
   1889 			_rtld_donelist_init(&depth);
   1890 			def = _rtld_symlook_needed(name, &hash, &fake, &defobj,
   1891 			    flags, ventry, &donelist, &depth);
   1892 		}
   1893 
   1894 		break;
   1895 	}
   1896 
   1897 	if (def != NULL) {
   1898 		void *p;
   1899 
   1900 		if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) {
   1901 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1902 			lookup_mutex_exit();
   1903 			_rtld_shared_enter();
   1904 #endif
   1905 			p = (void *)_rtld_resolve_ifunc(defobj, def);
   1906 			_rtld_shared_exit();
   1907 			return p;
   1908 		}
   1909 
   1910 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1911 		if (ELF_ST_TYPE(def->st_info) == STT_FUNC) {
   1912 			p = (void *)_rtld_function_descriptor_alloc(defobj,
   1913 			    def, 0);
   1914 			lookup_mutex_exit();
   1915 			return p;
   1916 		}
   1917 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   1918 		p = defobj->relocbase + def->st_value;
   1919 		lookup_mutex_exit();
   1920 		return p;
   1921 	}
   1922 
   1923 	_rtld_error("Undefined symbol \"%s\"", name);
   1924 	lookup_mutex_exit();
   1925 	return NULL;
   1926 }
   1927 _Pragma("GCC diagnostic pop")
   1928 
   1929 __strong_alias(__dlsym,dlsym)
   1930 void *
   1931 dlsym(void *handle, const char *name)
   1932 {
   1933 	void *retaddr;
   1934 
   1935 	dbg(("dlsym of %s in %p", name, handle));
   1936 
   1937 #if defined(__powerpc__) && !defined(__clang__)
   1938 	retaddr = hackish_return_address();
   1939 #else
   1940 	retaddr = __builtin_return_address(0);
   1941 #endif
   1942 	return do_dlsym(handle, name, NULL, retaddr);
   1943 }
   1944 
   1945 __strong_alias(__dlvsym,dlvsym)
   1946 void *
   1947 dlvsym(void *handle, const char *name, const char *version)
   1948 {
   1949 	Ver_Entry *ventry = NULL;
   1950 	Ver_Entry ver_entry;
   1951 	void *retaddr;
   1952 
   1953 	dbg(("dlvsym of %s@%s in %p", name, version ? version : NULL, handle));
   1954 
   1955 	if (version != NULL) {
   1956 		ver_entry.name = version;
   1957 		ver_entry.file = NULL;
   1958 		ver_entry.hash = _rtld_sysv_hash(version);
   1959 		ver_entry.flags = 0;
   1960 		ventry = &ver_entry;
   1961 	}
   1962 #if defined(__powerpc__) && !defined(__clang__)
   1963 	retaddr = hackish_return_address();
   1964 #else
   1965 	retaddr = __builtin_return_address(0);
   1966 #endif
   1967 	return do_dlsym(handle, name, ventry, retaddr);
   1968 }
   1969 
   1970 __strong_alias(__dladdr,dladdr)
   1971 int
   1972 dladdr(const void *addr, Dl_info *info)
   1973 {
   1974 	const Obj_Entry *obj;
   1975 	const Elf_Sym *def, *best_def;
   1976 	void *symbol_addr;
   1977 	unsigned long symoffset;
   1978 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1979 	sigset_t mask;
   1980 #endif
   1981 
   1982 	dbg(("dladdr of %p", addr));
   1983 
   1984 	lookup_mutex_enter();
   1985 
   1986 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   1987 	addr = _rtld_function_descriptor_function(addr);
   1988 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   1989 
   1990 	obj = _rtld_obj_from_addr(addr);
   1991 	if (obj == NULL) {
   1992 		_rtld_error("No shared object contains address");
   1993 		lookup_mutex_exit();
   1994 		return 0;
   1995 	}
   1996 	info->dli_fname = obj->path;
   1997 	info->dli_fbase = obj->mapbase;
   1998 	info->dli_saddr = (void *)0;
   1999 	info->dli_sname = NULL;
   2000 
   2001 	/*
   2002 	 * Walk the symbol list looking for the symbol whose address is
   2003 	 * closest to the address sent in.
   2004 	 */
   2005 	best_def = NULL;
   2006 	for (symoffset = 0; symoffset < obj->nchains; symoffset++) {
   2007 		def = obj->symtab + symoffset;
   2008 
   2009 		/*
   2010 		 * For skip the symbol if st_shndx is either SHN_UNDEF or
   2011 		 * SHN_COMMON.
   2012 		 */
   2013 		if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON)
   2014 			continue;
   2015 
   2016 		/*
   2017 		 * If the symbol is greater than the specified address, or if it
   2018 		 * is further away from addr than the current nearest symbol,
   2019 		 * then reject it.
   2020 		 */
   2021 		symbol_addr = obj->relocbase + def->st_value;
   2022 		if (symbol_addr > addr || symbol_addr < info->dli_saddr)
   2023 			continue;
   2024 
   2025 		/* Update our idea of the nearest symbol. */
   2026 		info->dli_sname = obj->strtab + def->st_name;
   2027 		info->dli_saddr = symbol_addr;
   2028 		best_def = def;
   2029 
   2030 
   2031 		/* Exact match? */
   2032 		if (info->dli_saddr == addr)
   2033 			break;
   2034 	}
   2035 
   2036 #ifdef __HAVE_FUNCTION_DESCRIPTORS
   2037 	if (best_def != NULL && ELF_ST_TYPE(best_def->st_info) == STT_FUNC)
   2038 		info->dli_saddr = (void *)_rtld_function_descriptor_alloc(obj,
   2039 		    best_def, 0);
   2040 #else
   2041 	__USE(best_def);
   2042 #endif /* __HAVE_FUNCTION_DESCRIPTORS */
   2043 
   2044 	lookup_mutex_exit();
   2045 	return 1;
   2046 }
   2047 
   2048 __strong_alias(__dlinfo,dlinfo)
   2049 int
   2050 dlinfo(void *handle, int req, void *v)
   2051 {
   2052 	const Obj_Entry *obj;
   2053 	void *retaddr;
   2054 
   2055 	dbg(("dlinfo for %p %d", handle, req));
   2056 
   2057 	_rtld_shared_enter();
   2058 
   2059 	if (handle == RTLD_SELF) {
   2060 #if defined(__powerpc__) && !defined(__clang__)
   2061 		retaddr = hackish_return_address();
   2062 #else
   2063 		retaddr = __builtin_return_address(0);
   2064 #endif
   2065 		if ((obj = _rtld_obj_from_addr(retaddr)) == NULL) {
   2066 			_rtld_error("Cannot determine caller's shared object");
   2067 			_rtld_shared_exit();
   2068 			return -1;
   2069 		}
   2070 	} else {
   2071 		if ((obj = _rtld_dlcheck(handle)) == NULL) {
   2072 			_rtld_shared_exit();
   2073 			return -1;
   2074 		}
   2075 	}
   2076 
   2077 	switch (req) {
   2078 	case RTLD_DI_LINKMAP:
   2079 		{
   2080 		const struct link_map **map = v;
   2081 
   2082 		*map = &obj->linkmap;
   2083 		break;
   2084 		}
   2085 
   2086 	default:
   2087 		_rtld_error("Invalid request");
   2088 		_rtld_shared_exit();
   2089 		return -1;
   2090 	}
   2091 
   2092 	_rtld_shared_exit();
   2093 	return 0;
   2094 }
   2095 
   2096 static void
   2097 _rtld_fill_dl_phdr_info(const Obj_Entry *obj, struct dl_phdr_info *phdr_info)
   2098 {
   2099 
   2100 	phdr_info->dlpi_addr = (Elf_Addr)obj->relocbase;
   2101 	/* XXX: wrong but not fixing it yet */
   2102 	phdr_info->dlpi_name = obj->path;
   2103 	phdr_info->dlpi_phdr = obj->phdr;
   2104 	phdr_info->dlpi_phnum = obj->phsize / sizeof(obj->phdr[0]);
   2105 #if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
   2106 	phdr_info->dlpi_tls_modid = obj->tlsindex;
   2107 	phdr_info->dlpi_tls_data = obj->tlsinit;
   2108 #else
   2109 	phdr_info->dlpi_tls_modid = 0;
   2110 	phdr_info->dlpi_tls_data = 0;
   2111 #endif
   2112 	phdr_info->dlpi_adds = _rtld_objloads;
   2113 	phdr_info->dlpi_subs = _rtld_objloads - _rtld_objcount;
   2114 }
   2115 
   2116 __strong_alias(__dl_iterate_phdr,dl_iterate_phdr);
   2117 int
   2118 dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *param)
   2119 {
   2120 	struct dl_phdr_info phdr_info;
   2121 	const Obj_Entry *obj;
   2122 	int error = 0;
   2123 
   2124 	dbg(("dl_iterate_phdr"));
   2125 
   2126 	_rtld_shared_enter();
   2127 
   2128 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   2129 		_rtld_fill_dl_phdr_info(obj, &phdr_info);
   2130 
   2131 		/* XXXlocking: exit point */
   2132 		error = callback(&phdr_info, sizeof(phdr_info), param);
   2133 		if (error)
   2134 			break;
   2135 	}
   2136 
   2137 	if (error == 0) {
   2138 		_rtld_fill_dl_phdr_info(&_rtld_objself, &phdr_info);
   2139 
   2140 		/* XXXlocking: exit point */
   2141 		error = callback(&phdr_info, sizeof(phdr_info), param);
   2142 	}
   2143 
   2144 	_rtld_shared_exit();
   2145 	return error;
   2146 }
   2147 
   2148 void
   2149 __dl_cxa_refcount(void *addr, ssize_t delta)
   2150 {
   2151 	sigset_t mask;
   2152 	Obj_Entry *obj;
   2153 
   2154 	if (delta == 0)
   2155 		return;
   2156 
   2157 	dbg(("__dl_cxa_refcount of %p with %zd", addr, delta));
   2158 
   2159 	_rtld_exclusive_enter(&mask);
   2160 	obj = _rtld_obj_from_addr(addr);
   2161 
   2162 	if (obj == NULL) {
   2163 		dbg(("__dl_cxa_refcont: address not found"));
   2164 		_rtld_error("No shared object contains address");
   2165 		_rtld_exclusive_exit(&mask);
   2166 		return;
   2167 	}
   2168 	if (delta > 0 && obj->cxa_refcount > SIZE_MAX - delta)
   2169 		_rtld_error("Reference count overflow");
   2170 	else if (delta < 0 && obj->cxa_refcount < -1 + (size_t)-(delta + 1))
   2171 		_rtld_error("Reference count underflow");
   2172 	else {
   2173 		if (obj->cxa_refcount == 0) {
   2174 			assert(obj->refcount > 0);
   2175 			++obj->refcount;
   2176 		}
   2177 		obj->cxa_refcount += delta;
   2178 		dbg(("new reference count: %zu", obj->cxa_refcount));
   2179 		if (obj->cxa_refcount == 0) {
   2180 			--obj->refcount;
   2181 			if (obj->refcount == 0)
   2182 				_rtld_unload_object(&mask, obj, true);
   2183 		}
   2184 	}
   2185 
   2186 	_rtld_exclusive_exit(&mask);
   2187 }
   2188 
   2189 __dso_public pid_t
   2190 __locked_fork(int *my_errno)
   2191 {
   2192 	pid_t result;
   2193 
   2194 	_rtld_shared_enter();
   2195 	result = __fork();
   2196 	if (result == -1)
   2197 		*my_errno = errno;
   2198 	_rtld_shared_exit();
   2199 
   2200 	return result;
   2201 }
   2202 
   2203 /*
   2204  * Error reporting function.  Use it like printf.  If formats the message
   2205  * into a buffer, and sets things up so that the next call to dlerror()
   2206  * will return the message.
   2207  */
   2208 void
   2209 _rtld_error(const char *fmt,...)
   2210 {
   2211 	static char     buf[512];
   2212 	va_list         ap;
   2213 
   2214 	va_start(ap, fmt);
   2215 	xvsnprintf(buf, sizeof buf, fmt, ap);
   2216 	dbg(("%s: %s", __func__, buf));
   2217 	error_message = buf;
   2218 	va_end(ap);
   2219 }
   2220 
   2221 void
   2222 _rtld_debug_state(void)
   2223 {
   2224 #if defined(__hppa__)
   2225 	__asm volatile("nop" ::: "memory");
   2226 #endif
   2227 
   2228 	/* Prevent optimizer from removing calls to this function */
   2229 	__insn_barrier();
   2230 }
   2231 
   2232 void
   2233 _rtld_linkmap_add(Obj_Entry *obj)
   2234 {
   2235 	struct link_map *l = &obj->linkmap;
   2236 	struct link_map *prev;
   2237 
   2238 	obj->linkmap.l_name = obj->path;
   2239 	obj->linkmap.l_addr = obj->relocbase;
   2240 	obj->linkmap.l_ld = obj->dynamic;
   2241 #ifdef __mips__
   2242 	/* XXX This field is not standard and will be removed eventually. */
   2243 	obj->linkmap.l_offs = obj->relocbase;
   2244 #endif
   2245 
   2246 	if (_rtld_debug.r_map == NULL) {
   2247 		_rtld_debug.r_map = l;
   2248 		return;
   2249 	}
   2250 
   2251 	/*
   2252 	 * Scan to the end of the list, but not past the entry for the
   2253 	 * dynamic linker, which we want to keep at the very end.
   2254 	 */
   2255 	for (prev = _rtld_debug.r_map;
   2256 	    prev->l_next != NULL && prev->l_next != &_rtld_objself.linkmap;
   2257 	    prev = prev->l_next);
   2258 
   2259 	l->l_prev = prev;
   2260 	l->l_next = prev->l_next;
   2261 	if (l->l_next != NULL)
   2262 		l->l_next->l_prev = l;
   2263 	prev->l_next = l;
   2264 }
   2265 
   2266 void
   2267 _rtld_linkmap_delete(Obj_Entry *obj)
   2268 {
   2269 	struct link_map *l = &obj->linkmap;
   2270 
   2271 	if (l->l_prev == NULL) {
   2272 		if ((_rtld_debug.r_map = l->l_next) != NULL)
   2273 			l->l_next->l_prev = NULL;
   2274 		return;
   2275 	}
   2276 	if ((l->l_prev->l_next = l->l_next) != NULL)
   2277 		l->l_next->l_prev = l->l_prev;
   2278 }
   2279 
   2280 static Obj_Entry *
   2281 _rtld_obj_from_addr(const void *addr)
   2282 {
   2283 	Obj_Entry *obj;
   2284 
   2285 	for (obj = _rtld_objlist;  obj != NULL;  obj = obj->next) {
   2286 		if (addr < (void *) obj->mapbase)
   2287 			continue;
   2288 		if (addr < (void *) (obj->mapbase + obj->mapsize))
   2289 			return obj;
   2290 	}
   2291 	return NULL;
   2292 }
   2293 
   2294 static void
   2295 _rtld_objlist_clear(Objlist *list)
   2296 {
   2297 	while (!SIMPLEQ_EMPTY(list)) {
   2298 		Objlist_Entry* elm = SIMPLEQ_FIRST(list);
   2299 		SIMPLEQ_REMOVE_HEAD(list, link);
   2300 		xfree(elm);
   2301 	}
   2302 }
   2303 
   2304 static void
   2305 _rtld_objlist_remove(Objlist *list, Obj_Entry *obj)
   2306 {
   2307 	Objlist_Entry *elm;
   2308 
   2309 	if ((elm = _rtld_objlist_find(list, obj)) != NULL) {
   2310 		SIMPLEQ_REMOVE(list, elm, Struct_Objlist_Entry, link);
   2311 		xfree(elm);
   2312 	}
   2313 }
   2314 
   2315 #define	RTLD_EXCLUSIVE_MASK	0x80000000U
   2316 static volatile unsigned int _rtld_mutex;
   2317 static volatile unsigned int _rtld_waiter_exclusive;
   2318 static volatile unsigned int _rtld_waiter_shared;
   2319 
   2320 void
   2321 _rtld_shared_enter(void)
   2322 {
   2323 	unsigned int cur;
   2324 	lwpid_t waiter, self = 0;
   2325 
   2326 	for (;;) {
   2327 		cur = _rtld_mutex;
   2328 		/*
   2329 		 * First check if we are currently not exclusively locked.
   2330 		 */
   2331 		if ((cur & RTLD_EXCLUSIVE_MASK) == 0) {
   2332 			/* Yes, so increment use counter */
   2333 			if (atomic_cas_uint(&_rtld_mutex, cur, cur + 1) != cur)
   2334 				continue;
   2335 			membar_acquire();
   2336 			return;
   2337 		}
   2338 		/*
   2339 		 * Someone has an exclusive lock.  Puts us on the waiter list.
   2340 		 */
   2341 		if (!self)
   2342 			self = _lwp_self();
   2343 		if (cur == (self | RTLD_EXCLUSIVE_MASK)) {
   2344 			if (_rtld_mutex_may_recurse)
   2345 				return;
   2346 			_rtld_error("%s: dead lock detected", __func__);
   2347 			_rtld_die();
   2348 		}
   2349 		waiter = atomic_swap_uint(&_rtld_waiter_shared, self);
   2350 		/*
   2351 		 * Check for race against _rtld_exclusive_exit before sleeping.
   2352 		 */
   2353 		membar_sync();
   2354 		if ((_rtld_mutex & RTLD_EXCLUSIVE_MASK) ||
   2355 		    _rtld_waiter_exclusive)
   2356 			_lwp_park(CLOCK_REALTIME, 0, NULL, 0,
   2357 			    __UNVOLATILE(&_rtld_mutex), NULL);
   2358 		/* Try to remove us from the waiter list. */
   2359 		atomic_cas_uint(&_rtld_waiter_shared, self, 0);
   2360 		if (waiter)
   2361 			_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   2362 	}
   2363 }
   2364 
   2365 void
   2366 _rtld_shared_exit(void)
   2367 {
   2368 	lwpid_t waiter;
   2369 
   2370 	/*
   2371 	 * Shared lock taken after an exclusive lock.
   2372 	 * Just assume this is a partial recursion.
   2373 	 */
   2374 	if (_rtld_mutex & RTLD_EXCLUSIVE_MASK)
   2375 		return;
   2376 
   2377 	/*
   2378 	 * Wakeup LWPs waiting for an exclusive lock if this is the last
   2379 	 * LWP on the shared lock.
   2380 	 */
   2381 	membar_release();
   2382 	if (atomic_dec_uint_nv(&_rtld_mutex))
   2383 		return;
   2384 	membar_sync();
   2385 	if ((waiter = _rtld_waiter_exclusive) != 0)
   2386 		_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   2387 }
   2388 
   2389 void
   2390 _rtld_exclusive_enter(sigset_t *mask)
   2391 {
   2392 	lwpid_t waiter, self = _lwp_self();
   2393 	unsigned int locked_value = (unsigned int)self | RTLD_EXCLUSIVE_MASK;
   2394 	unsigned int cur;
   2395 	sigset_t blockmask;
   2396 
   2397 	sigfillset(&blockmask);
   2398 	sigdelset(&blockmask, SIGTRAP);	/* Allow the debugger */
   2399 	sigprocmask(SIG_BLOCK, &blockmask, mask);
   2400 
   2401 	for (;;) {
   2402 		if (atomic_cas_uint(&_rtld_mutex, 0, locked_value) == 0) {
   2403 			membar_acquire();
   2404 			break;
   2405 		}
   2406 		waiter = atomic_swap_uint(&_rtld_waiter_exclusive, self);
   2407 		membar_sync();
   2408 		cur = _rtld_mutex;
   2409 		if (cur == locked_value) {
   2410 			_rtld_error("%s: dead lock detected", __func__);
   2411 			_rtld_die();
   2412 		}
   2413 		if (cur)
   2414 			_lwp_park(CLOCK_REALTIME, 0, NULL, 0,
   2415 			    __UNVOLATILE(&_rtld_mutex), NULL);
   2416 		atomic_cas_uint(&_rtld_waiter_exclusive, self, 0);
   2417 		if (waiter)
   2418 			_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   2419 	}
   2420 }
   2421 
   2422 void
   2423 _rtld_exclusive_exit(sigset_t *mask)
   2424 {
   2425 	lwpid_t waiter;
   2426 
   2427 	membar_release();
   2428 	_rtld_mutex = 0;
   2429 	membar_sync();
   2430 	if ((waiter = _rtld_waiter_exclusive) != 0)
   2431 		_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   2432 
   2433 	if ((waiter = _rtld_waiter_shared) != 0)
   2434 		_lwp_unpark(waiter, __UNVOLATILE(&_rtld_mutex));
   2435 
   2436 	sigprocmask(SIG_SETMASK, mask, NULL);
   2437 }
   2438 
   2439 int
   2440 _rtld_relro(const Obj_Entry *obj, bool wantmain)
   2441 {
   2442 #ifdef GNU_RELRO
   2443 	/*
   2444 	 * If our VM page size is larger than the page size used by the
   2445 	 * linker when laying out the object, we could end up making data
   2446 	 * read-only that is unintended.  Detect and avoid this situation.
   2447 	 * It may mean we are unable to protect everything we'd like, but
   2448 	 * it's better than crashing.
   2449 	 */
   2450 	uintptr_t relro_end = (uintptr_t)obj->relro_page + obj->relro_size;
   2451 	uintptr_t relro_start = round_down((uintptr_t)obj->relro_page);
   2452 	assert(relro_end >= relro_start);
   2453 	size_t relro_size = round_down(relro_end) - relro_start;
   2454 
   2455 	if (relro_size == 0)
   2456 		return 0;
   2457 	if (wantmain != (obj ==_rtld_objmain))
   2458 		return 0;
   2459 
   2460 	dbg(("RELRO %s %p %zx", obj->path, (void *)relro_start, relro_size));
   2461 	if (mprotect((void *)relro_start, relro_size, PROT_READ) == -1) {
   2462 		_rtld_error("%s: Cannot enforce relro " "protection: %s",
   2463 		    obj->path, xstrerror(errno));
   2464 		return -1;
   2465 	}
   2466 #endif
   2467 	return 0;
   2468 }
   2469