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