xref: /titanic_52/usr/src/cmd/sgs/rtld/common/util.c (revision b9bd317cda1afb3a01f4812de73e8cec888cbbd7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  *	Copyright (c) 1988 AT&T
29  *	  All Rights Reserved
30  */
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 /*
35  * Utility routines for run-time linker.  some are duplicated here from libc
36  * (with different names) to avoid name space collisions.
37  */
38 #include	<stdio.h>
39 #include	<sys/types.h>
40 #include	<sys/mman.h>
41 #include	<sys/lwp.h>
42 #include	<sys/debug.h>
43 #include	<stdarg.h>
44 #include	<fcntl.h>
45 #include	<string.h>
46 #include	<ctype.h>
47 #include	<dlfcn.h>
48 #include	<unistd.h>
49 #include	<stdlib.h>
50 #include	<sys/auxv.h>
51 #include	<debug.h>
52 #include	<conv.h>
53 #include	"_rtld.h"
54 #include	"_audit.h"
55 #include	"_elf.h"
56 #include	"msg.h"
57 
58 static int ld_flags_env(const char *, Word *, Word *, uint_t, int);
59 
60 /*
61  * All error messages go through eprintf().  During process initialization these
62  * messages should be directed to the standard error, however once control has
63  * been passed to the applications code these messages should be stored in an
64  * internal buffer for use with dlerror().  Note, fatal error conditions that
65  * may occur while running the application will still cause a standard error
66  * message, see rtldexit() in this file for details.
67  * The `application' flag serves to indicate the transition between process
68  * initialization and when the applications code is running.
69  */
70 
71 /*
72  * Null function used as place where a debugger can set a breakpoint.
73  */
74 void
75 rtld_db_dlactivity(Lm_list *lml)
76 {
77 	DBG_CALL(Dbg_util_dbnotify(lml, r_debug.rtd_rdebug.r_rdevent,
78 	    r_debug.rtd_rdebug.r_state));
79 }
80 
81 /*
82  * Null function used as place where debugger can set a pre .init
83  * processing breakpoint.
84  */
85 void
86 rtld_db_preinit(Lm_list *lml)
87 {
88 	DBG_CALL(Dbg_util_dbnotify(lml, r_debug.rtd_rdebug.r_rdevent,
89 	    r_debug.rtd_rdebug.r_state));
90 }
91 
92 /*
93  * Null function used as place where debugger can set a post .init
94  * processing breakpoint.
95  */
96 void
97 rtld_db_postinit(Lm_list *lml)
98 {
99 	DBG_CALL(Dbg_util_dbnotify(lml, r_debug.rtd_rdebug.r_rdevent,
100 	    r_debug.rtd_rdebug.r_state));
101 }
102 
103 /*
104  * Debugger Event Notification
105  *
106  * This function centralizes all debugger event notification (ala rtld_db).
107  *
108  * There's a simple intent, focused on insuring the primary link-map control
109  * list (or each link-map list) is consistent, and the indication that objects
110  * have been added or deleted from this list.  Although an RD_ADD and RD_DELETE
111  * event are posted for each of these, most debuggers don't care, as their
112  * view is that these events simply convey an "inconsistent" state.
113  *
114  * We also don't want to trigger multiple RD_ADD/RD_DELETE events any time we
115  * enter ld.so.1.
116  *
117  * With auditors, we may be in the process of relocating a collection of
118  * objects, and will leave() ld.so.1 to call the auditor.  At this point we
119  * must indicate an RD_CONSISTENT event, but librtld_db will not report an
120  * object to the debuggers until relocation processing has been completed on it.
121  * To allow for the collection of these objects that are pending relocation, an
122  * RD_ADD event is set after completing a series of relocations on the primary
123  * link-map control list.
124  *
125  * Set an RD_ADD/RD_DELETE event and indicate that an RD_CONSISTENT event is
126  * required later (LML_FLG_DBNOTIF):
127  *
128  *  i	the first time we add or delete an object to the primary link-map
129  *	control list.
130  *  ii	the first time we move a secondary link-map control list to the primary
131  *	link-map control list (effectively, this is like adding a group of
132  *	objects to the primary link-map control list).
133  *
134  * Set an RD_CONSISTENT event when it is required (LML_FLG_DBNOTIF is set) and
135  *
136  *  i	each time we leave the runtime linker.
137  */
138 void
139 rd_event(Lm_list *lml, rd_event_e event, r_state_e state)
140 {
141 	void	(*fptr)(Lm_list *);
142 
143 	switch (event) {
144 	case RD_PREINIT:
145 		fptr = rtld_db_preinit;
146 		break;
147 	case RD_POSTINIT:
148 		fptr = rtld_db_postinit;
149 		break;
150 	case RD_DLACTIVITY:
151 		switch (state) {
152 		case RT_CONSISTENT:
153 			lml->lm_flags &= ~LML_FLG_DBNOTIF;
154 
155 			/*
156 			 * Do we need to send a notification?
157 			 */
158 			if ((rtld_flags & RT_FL_DBNOTIF) == 0)
159 				return;
160 			rtld_flags &= ~RT_FL_DBNOTIF;
161 			break;
162 		case RT_ADD:
163 		case RT_DELETE:
164 			lml->lm_flags |= LML_FLG_DBNOTIF;
165 
166 			/*
167 			 * If we are already in an inconsistent state, no
168 			 * notification is required.
169 			 */
170 			if (rtld_flags & RT_FL_DBNOTIF)
171 				return;
172 			rtld_flags |= RT_FL_DBNOTIF;
173 			break;
174 		};
175 		fptr = rtld_db_dlactivity;
176 		break;
177 	default:
178 		/*
179 		 * RD_NONE - do nothing
180 		 */
181 		break;
182 	};
183 
184 	/*
185 	 * Set event state and call 'notification' function.
186 	 *
187 	 * The debugging clients have previously been told about these
188 	 * notification functions and have set breakpoints on them if they
189 	 * are interested in the notification.
190 	 */
191 	r_debug.rtd_rdebug.r_state = state;
192 	r_debug.rtd_rdebug.r_rdevent = event;
193 	fptr(lml);
194 	r_debug.rtd_rdebug.r_rdevent = RD_NONE;
195 }
196 
197 #if	defined(__sparc) || defined(__x86)
198 /*
199  * Stack Cleanup.
200  *
201  * This function is invoked to 'remove' arguments that were passed in on the
202  * stack.  This is most likely if ld.so.1 was invoked directly.  In that case
203  * we want to remove ld.so.1 as well as it's arguments from the argv[] array.
204  * Which means we then need to slide everything above it on the stack down
205  * accordingly.
206  *
207  * While the stack layout is platform specific - it just so happens that __x86,
208  * and __sparc platforms share the following initial stack layout.
209  *
210  *	!_______________________!  high addresses
211  *	!			!
212  *	!	Information	!
213  *	!	Block		!
214  *	!	(size varies)	!
215  *	!_______________________!
216  *	!	0 word		!
217  *	!_______________________!
218  *	!	Auxiliary	!
219  *	!	vector		!
220  *	!	2 word entries	!
221  *	!			!
222  *	!_______________________!
223  *	!	0 word		!
224  *	!_______________________!
225  *	!	Environment	!
226  *	!	pointers	!
227  *	!	...		!
228  *	!	(one word each)	!
229  *	!_______________________!
230  *	!	0 word		!
231  *	!_______________________!
232  *	!	Argument	! low addresses
233  *	!	pointers	!
234  *	!	Argc words	!
235  *	!_______________________!
236  *	!			!
237  *	!	Argc		!
238  *	!_______________________!
239  *	!	...		!
240  *
241  */
242 static void
243 stack_cleanup(char **argv, char ***envp, auxv_t **auxv, int rmcnt)
244 {
245 	int		ndx;
246 	long		*argc;
247 	char		**oargv, **nargv;
248 	char		**oenvp, **nenvp;
249 	auxv_t		*oauxv, *nauxv;
250 
251 	/*
252 	 * Slide ARGV[] and update argc.  The argv pointer remains the same,
253 	 * however slide the applications arguments over the arguments to
254 	 * ld.so.1.
255 	 */
256 	nargv = &argv[0];
257 	oargv = &argv[rmcnt];
258 
259 	for (ndx = 0; oargv[ndx]; ndx++)
260 		nargv[ndx] = oargv[ndx];
261 	nargv[ndx] = oargv[ndx];
262 
263 	argc = (long *)((uintptr_t)argv - sizeof (long *));
264 	*argc -= rmcnt;
265 
266 	/*
267 	 * Slide ENVP[], and update the environment array pointer.
268 	 */
269 	ndx++;
270 	nenvp = &nargv[ndx];
271 	oenvp = &oargv[ndx];
272 	*envp = nenvp;
273 
274 	for (ndx = 0; oenvp[ndx]; ndx++)
275 		nenvp[ndx] = oenvp[ndx];
276 	nenvp[ndx] = oenvp[ndx];
277 
278 	/*
279 	 * Slide AUXV[], and update the aux vector pointer.
280 	 */
281 	ndx++;
282 	nauxv = (auxv_t *)&nenvp[ndx];
283 	oauxv = (auxv_t *)&oenvp[ndx];
284 	*auxv = nauxv;
285 
286 	for (ndx = 0; (oauxv[ndx].a_type != AT_NULL); ndx++)
287 		nauxv[ndx] = oauxv[ndx];
288 	nauxv[ndx] = oauxv[ndx];
289 }
290 #else
291 /*
292  * Verify that the above routine is appropriate for any new platforms.
293  */
294 #error	unsupported architecture!
295 #endif
296 
297 /*
298  * The only command line argument recognized is -e, followed by a runtime
299  * linker environment variable.
300  */
301 int
302 rtld_getopt(char **argv, char ***envp, auxv_t **auxv, Word *lmflags,
303     Word *lmtflags, int aout)
304 {
305 	int	ndx;
306 
307 	for (ndx = 1; argv[ndx]; ndx++) {
308 		char	*str;
309 
310 		if (argv[ndx][0] != '-')
311 			break;
312 
313 		if (argv[ndx][1] == '\0') {
314 			ndx++;
315 			break;
316 		}
317 
318 		if (argv[ndx][1] != 'e')
319 			return (1);
320 
321 		if (argv[ndx][2] == '\0') {
322 			ndx++;
323 			if (argv[ndx] == NULL)
324 				return (1);
325 			str = argv[ndx];
326 		} else
327 			str = &argv[ndx][2];
328 
329 		/*
330 		 * If the environment variable starts with LD_, strip the LD_.
331 		 * Otherwise, take things as is.
332 		 */
333 		if ((str[0] == 'L') && (str[1] == 'D') && (str[2] == '_') &&
334 		    (str[3] != '\0'))
335 			str += 3;
336 		if (ld_flags_env(str, lmflags, lmtflags, 0, aout) == 1)
337 			return (1);
338 	}
339 
340 	/*
341 	 * Make sure an object file has been specified.
342 	 */
343 	if (argv[ndx] == 0)
344 		return (1);
345 
346 	/*
347 	 * Having gotten the arguments, clean ourselves off of the stack.
348 	 */
349 	stack_cleanup(argv, envp, auxv, ndx);
350 	return (0);
351 }
352 
353 /*
354  * Compare function for PathNode AVL tree.
355  */
356 static int
357 pnavl_compare(const void *n1, const void *n2)
358 {
359 	uint_t		hash1, hash2;
360 	const char	*st1, *st2;
361 	int		rc;
362 
363 	hash1 = ((PathNode *)n1)->pn_hash;
364 	hash2 = ((PathNode *)n2)->pn_hash;
365 
366 	if (hash1 > hash2)
367 		return (1);
368 	if (hash1 < hash2)
369 		return (-1);
370 
371 	st1 = ((PathNode *)n1)->pn_name;
372 	st2 = ((PathNode *)n2)->pn_name;
373 
374 	rc = strcmp(st1, st2);
375 	if (rc > 0)
376 		return (1);
377 	if (rc < 0)
378 		return (-1);
379 	return (0);
380 }
381 
382 /*
383  * Determine if a pathname has already been recorded on the full path name
384  * AVL tree.  This tree maintains a node for each path name that ld.so.1 has
385  * successfully loaded.  If the path name does not exist in this AVL tree, then
386  * the next insertion point is deposited in "where".  This value can be used by
387  * fpavl_insert() to expedite the insertion.
388  */
389 Rt_map *
390 fpavl_recorded(Lm_list *lml, const char *name, avl_index_t *where)
391 {
392 	FullPathNode	fpn, *fpnp;
393 	avl_tree_t	*avlt;
394 
395 	/*
396 	 * Create the avl tree if required.
397 	 */
398 	if ((avlt = lml->lm_fpavl) == NULL) {
399 		if ((avlt = calloc(sizeof (avl_tree_t), 1)) == 0)
400 			return (0);
401 		avl_create(avlt, pnavl_compare, sizeof (FullPathNode),
402 		    SGSOFFSETOF(FullPathNode, fpn_node.pn_avl));
403 		lml->lm_fpavl = avlt;
404 	}
405 
406 	fpn.fpn_node.pn_name = name;
407 	fpn.fpn_node.pn_hash = sgs_str_hash(name);
408 
409 	if ((fpnp = avl_find(lml->lm_fpavl, &fpn, where)) == NULL)
410 		return (NULL);
411 
412 	return (fpnp->fpn_lmp);
413 }
414 
415 /*
416  * Insert a name into the FullPathNode AVL tree for the link-map list.  The
417  * objects NAME() is the path that would have originally been searched for, and
418  * is therefore the name to associate with any "where" value.  If the object has
419  * a different PATHNAME(), perhaps because it has resolved to a different file
420  * (see fullpath()), then this name will be recorded as a separate FullPathNode
421  * (see load_file()).
422  */
423 int
424 fpavl_insert(Lm_list *lml, Rt_map *lmp, const char *name, avl_index_t where)
425 {
426 	FullPathNode	*fpnp;
427 
428 	if (where == 0) {
429 		/* LINTED */
430 		Rt_map	*_lmp = fpavl_recorded(lml, name, &where);
431 
432 		/*
433 		 * We better not get a hit now, we do not want duplicates in
434 		 * the tree.
435 		 */
436 		ASSERT(_lmp == 0);
437 	}
438 
439 	/*
440 	 * Insert new node in tree.
441 	 */
442 	if ((fpnp = calloc(sizeof (FullPathNode), 1)) == 0)
443 		return (0);
444 
445 	fpnp->fpn_node.pn_name = name;
446 	fpnp->fpn_node.pn_hash = sgs_str_hash(name);
447 	fpnp->fpn_lmp = lmp;
448 
449 	if (aplist_append(&FPNODE(lmp), fpnp, AL_CNT_FPNODE) == NULL) {
450 		free(fpnp);
451 		return (0);
452 	}
453 
454 	ASSERT(lml->lm_fpavl != NULL);
455 	avl_insert(lml->lm_fpavl, fpnp, where);
456 	return (1);
457 }
458 
459 /*
460  * Remove an object from the FullPath AVL tree.  Note, this is called *before*
461  * the objects link-map is torn down (remove_so), which is where any NAME() and
462  * PATHNAME() strings will be deallocated.
463  */
464 void
465 fpavl_remove(Rt_map *lmp)
466 {
467 	FullPathNode	*fpnp;
468 	Aliste		idx;
469 
470 	for (APLIST_TRAVERSE(FPNODE(lmp), idx, fpnp)) {
471 		avl_remove(LIST(lmp)->lm_fpavl, fpnp);
472 		free(fpnp);
473 	}
474 	free(FPNODE(lmp));
475 	FPNODE(lmp) = NULL;
476 }
477 
478 /*
479  * Determine if a pathname has already been recorded on the not-found AVL tree.
480  * This tree maintains a node for each path name that ld.so.1 has explicitly
481  * inspected, but has failed to load during a single ld.so.1 operation.  If the
482  * path name does not exist in this AVL tree, then the next insertion point is
483  * deposited in "where".  This value can be used by nfavl_insert() to expedite
484  * the insertion.
485  */
486 int
487 nfavl_recorded(const char *name, avl_index_t *where)
488 {
489 	PathNode	pn;
490 	avl_tree_t	*avlt;
491 
492 	/*
493 	 * Create the avl tree if required.
494 	 */
495 	if ((avlt = nfavl) == NULL) {
496 		if ((avlt = calloc(sizeof (avl_tree_t), 1)) == 0)
497 			return (0);
498 		avl_create(avlt, pnavl_compare, sizeof (PathNode),
499 		    SGSOFFSETOF(PathNode, pn_avl));
500 		nfavl = avlt;
501 	}
502 
503 	pn.pn_name = name;
504 	pn.pn_hash = sgs_str_hash(name);
505 
506 	if (avl_find(avlt, &pn, where) == NULL)
507 		return (0);
508 
509 	return (1);
510 }
511 
512 /*
513  * Insert a name into the not-found AVL tree.
514  */
515 void
516 nfavl_insert(const char *name, avl_index_t where)
517 {
518 	PathNode	*pnp;
519 
520 	if (where == 0) {
521 		/* LINTED */
522 		int	in_nfavl = nfavl_recorded(name, &where);
523 
524 		/*
525 		 * We better not get a hit now, we do not want duplicates in
526 		 * the tree.
527 		 */
528 		ASSERT(in_nfavl == 0);
529 	}
530 
531 	/*
532 	 * Insert new node in tree.
533 	 */
534 	if ((pnp = calloc(sizeof (PathNode), 1)) != 0) {
535 		pnp->pn_name = name;
536 		pnp->pn_hash = sgs_str_hash(name);
537 		avl_insert(nfavl, pnp, where);
538 	}
539 }
540 
541 /*
542  * Prior to calling an object, either via a .plt or through dlsym(), make sure
543  * its .init has fired.  Through topological sorting, ld.so.1 attempts to fire
544  * init's in the correct order, however, this order is typically based on needed
545  * dependencies and non-lazy relocation bindings.  Lazy relocations (.plts) can
546  * still occur and result in bindings that were not captured during topological
547  * sorting.  This routine compensates for this lack of binding information, and
548  * provides for dynamic .init firing.
549  */
550 void
551 is_dep_init(Rt_map *dlmp, Rt_map *clmp)
552 {
553 	Rt_map	**tobj;
554 
555 	/*
556 	 * If the caller is an auditor, and the destination isn't, then don't
557 	 * run any .inits (see comments in load_completion()).
558 	 */
559 	if ((LIST(clmp)->lm_flags & LML_FLG_NOAUDIT) &&
560 	    (LIST(clmp) != LIST(dlmp)))
561 		return;
562 
563 	if ((dlmp == clmp) || (rtld_flags & (RT_FL_BREADTH | RT_FL_INITFIRST)))
564 		return;
565 
566 	if ((FLAGS(dlmp) & (FLG_RT_RELOCED | FLG_RT_INITDONE)) ==
567 	    (FLG_RT_RELOCED | FLG_RT_INITDONE))
568 		return;
569 
570 	if ((FLAGS(dlmp) & (FLG_RT_RELOCED | FLG_RT_INITCALL)) ==
571 	    (FLG_RT_RELOCED | FLG_RT_INITCALL)) {
572 		DBG_CALL(Dbg_util_no_init(dlmp));
573 		return;
574 	}
575 
576 	if ((tobj = calloc(2, sizeof (Rt_map *))) != NULL) {
577 		tobj[0] = dlmp;
578 		call_init(tobj, DBG_INIT_DYN);
579 	}
580 }
581 
582 /*
583  * In a threaded environment insure the thread responsible for loading an object
584  * has completed .init processing for that object before any new thread is
585  * allowed to access the object.  This check is only valid with libthread
586  * TI_VERSION 2, where ld.so.1 implements locking through low level mutexes.
587  *
588  * When a new link-map is created, the thread that causes it to be loaded is
589  * identified by THREADID(dlmp).  Compare this with the current thread to
590  * determine if it must be blocked.
591  *
592  * NOTE, there are a number of instances (typically only for .plt processing)
593  * where we must skip this test:
594  *
595  *   .	any thread id of 0 - threads that call thr_exit() may be in this state
596  *	thus we can't deduce what tid they used to be.  Also some of the
597  *	lib/libthread worker threads have this id and must bind (to themselves
598  *	or libc) for libthread to function.
599  *
600  *   .	libthread itself binds to libc, and as libthread is INITFIRST
601  *	libc's .init can't have fired yet.  Luckly libc's .init is not required
602  *	by libthreads binding.
603  *
604  *   .	if the caller is an auditor, and the destination isn't, then don't
605  *	block (see comments in load_completion()).
606  */
607 void
608 /* ARGSUSED2 */
609 is_dep_ready(Rt_map *dlmp, Rt_map *clmp, int what)
610 {
611 	thread_t	tid;
612 
613 	if ((LIST(clmp)->lm_flags & LML_FLG_NOAUDIT) &&
614 	    (LIST(clmp) != LIST(dlmp)))
615 		return;
616 
617 	if ((rtld_flags & RT_FL_CONCUR) &&
618 	    ((FLAGS(dlmp) & FLG_RT_INITDONE) == 0) &&
619 	    ((FLAGS(clmp) & FLG_RT_INITFRST) == 0) &&
620 	    ((tid = rt_thr_self()) != 0) && (THREADID(dlmp) != tid)) {
621 		rtldexit(LIST(dlmp), 1);
622 	}
623 }
624 
625 /*
626  * Execute .{preinit|init|fini}array sections
627  */
628 void
629 call_array(Addr *array, uint_t arraysz, Rt_map *lmp, Word shtype)
630 {
631 	int	start, stop, incr, ndx;
632 	uint_t	arraycnt = (uint_t)(arraysz / sizeof (Addr));
633 
634 	if (array == NULL)
635 		return;
636 
637 	/*
638 	 * initarray & preinitarray are walked from beginning to end - while
639 	 * finiarray is walked from end to beginning.
640 	 */
641 	if (shtype == SHT_FINI_ARRAY) {
642 		start = arraycnt - 1;
643 		stop = incr = -1;
644 	} else {
645 		start = 0;
646 		stop = arraycnt;
647 		incr = 1;
648 	}
649 
650 	/*
651 	 * Call the .*array[] entries
652 	 */
653 	for (ndx = start; ndx != stop; ndx += incr) {
654 		void (*fptr)(void) = (void(*)())array[ndx];
655 
656 		DBG_CALL(Dbg_util_call_array(lmp, (void *)fptr, ndx, shtype));
657 
658 		leave(LIST(lmp), 0);
659 		(*fptr)();
660 		(void) enter(0);
661 	}
662 }
663 
664 
665 /*
666  * Execute any .init sections.  These are passed to us in an lmp array which
667  * (by default) will have been sorted.
668  */
669 void
670 call_init(Rt_map **tobj, int flag)
671 {
672 	Rt_map		**_tobj, **_nobj;
673 	static List	pending = { NULL, NULL };
674 
675 	/*
676 	 * If we're in the middle of an INITFIRST, this must complete before
677 	 * any new init's are fired.  In this case add the object list to the
678 	 * pending queue and return.  We'll pick up the queue after any
679 	 * INITFIRST objects have their init's fired.
680 	 */
681 	if (rtld_flags & RT_FL_INITFIRST) {
682 		(void) list_append(&pending, tobj);
683 		return;
684 	}
685 
686 	/*
687 	 * Traverse the tobj array firing each objects init.
688 	 */
689 	for (_tobj = _nobj = tobj, _nobj++; *_tobj != NULL; _tobj++, _nobj++) {
690 		Rt_map	*lmp = *_tobj;
691 		void	(*iptr)() = INIT(lmp);
692 
693 		if (FLAGS(lmp) & FLG_RT_INITCALL)
694 			continue;
695 
696 		FLAGS(lmp) |= FLG_RT_INITCALL;
697 
698 		/*
699 		 * Establish an initfirst state if necessary - no other inits
700 		 * will be fired (because of additional relocation bindings)
701 		 * when in this state.
702 		 */
703 		if (FLAGS(lmp) & FLG_RT_INITFRST)
704 			rtld_flags |= RT_FL_INITFIRST;
705 
706 		if (INITARRAY(lmp) || iptr) {
707 			Aliste		idx;
708 			Bnd_desc 	*bdp;
709 
710 			/*
711 			 * Make sure that all dependencies that have been
712 			 * relocated to are initialized before this objects
713 			 * .init is executed.  This insures that a dependency
714 			 * on an external item that must first be initialized
715 			 * by its associated object is satisfied.
716 			 */
717 			for (APLIST_TRAVERSE(DEPENDS(lmp), idx, bdp)) {
718 				if ((bdp->b_flags & BND_REFER) == 0)
719 					continue;
720 				is_dep_ready(bdp->b_depend, lmp, DBG_WAIT_INIT);
721 			}
722 			DBG_CALL(Dbg_util_call_init(lmp, flag));
723 		}
724 
725 		if (iptr) {
726 			leave(LIST(lmp), 0);
727 			(*iptr)();
728 			(void) enter(0);
729 		}
730 
731 		call_array(INITARRAY(lmp), INITARRAYSZ(lmp), lmp,
732 		    SHT_INIT_ARRAY);
733 
734 		if (INITARRAY(lmp) || iptr)
735 			DBG_CALL(Dbg_util_call_init(lmp, DBG_INIT_DONE));
736 
737 		/*
738 		 * Set the initdone flag regardless of whether this object
739 		 * actually contains an .init section.  This flag prevents us
740 		 * from processing this section again for an .init and also
741 		 * signifies that a .fini must be called should it exist.
742 		 * Clear the sort field for use in later .fini processing.
743 		 */
744 		FLAGS(lmp) |= FLG_RT_INITDONE;
745 		SORTVAL(lmp) = -1;
746 
747 		/*
748 		 * Wake anyone up who might be waiting on this .init.
749 		 */
750 		if (FLAGS1(lmp) & FL1_RT_INITWAIT) {
751 			DBG_CALL(Dbg_util_broadcast(lmp));
752 			(void) rt_cond_broadcast(CONDVAR(lmp));
753 			FLAGS1(lmp) &= ~FL1_RT_INITWAIT;
754 		}
755 
756 		/*
757 		 * If we're firing an INITFIRST object, and other objects must
758 		 * be fired which are not INITFIRST, make sure we grab any
759 		 * pending objects that might have been delayed as this
760 		 * INITFIRST was processed.
761 		 */
762 		if ((rtld_flags & RT_FL_INITFIRST) &&
763 		    ((*_nobj == NULL) || !(FLAGS(*_nobj) & FLG_RT_INITFRST))) {
764 			Listnode	*lnp;
765 			Rt_map		**pobj;
766 
767 			rtld_flags &= ~RT_FL_INITFIRST;
768 
769 			while ((lnp = pending.head) != NULL) {
770 				if ((pending.head = lnp->next) == NULL)
771 					pending.tail = NULL;
772 				pobj = lnp->data;
773 				free(lnp);
774 
775 				call_init(pobj, DBG_INIT_PEND);
776 			}
777 		}
778 	}
779 	free(tobj);
780 }
781 
782 /*
783  * Function called by atexit(3C).  Calls all .fini sections related with the
784  * mains dependent shared libraries in the order in which the shared libraries
785  * have been loaded.  Skip any .fini defined in the main executable, as this
786  * will be called by crt0 (main was never marked as initdone).
787  */
788 void
789 call_fini(Lm_list * lml, Rt_map ** tobj)
790 {
791 	Rt_map **_tobj;
792 
793 	for (_tobj = tobj; *_tobj != NULL; _tobj++) {
794 		Rt_map		*clmp, * lmp = *_tobj;
795 		Aliste		idx;
796 		Bnd_desc	*bdp;
797 
798 		/*
799 		 * If concurrency checking isn't enabled only fire .fini if
800 		 * .init has completed.  We collect all .fini sections of
801 		 * objects that had their .init collected, but that doesn't
802 		 * mean at the time that the .init had completed.
803 		 */
804 		if ((rtld_flags & RT_FL_CONCUR) ||
805 		    (FLAGS(lmp) & FLG_RT_INITDONE)) {
806 			void	(*fptr)(void) = FINI(lmp);
807 
808 			if (FINIARRAY(lmp) || fptr) {
809 				/*
810 				 * If concurrency checking is enabled make sure
811 				 * this object's .init is completed before
812 				 * calling any .fini.
813 				 */
814 				is_dep_ready(lmp, lmp, DBG_WAIT_FINI);
815 				DBG_CALL(Dbg_util_call_fini(lmp));
816 			}
817 
818 			call_array(FINIARRAY(lmp), FINIARRAYSZ(lmp), lmp,
819 			    SHT_FINI_ARRAY);
820 
821 			if (fptr) {
822 				leave(LIST(lmp), 0);
823 				(*fptr)();
824 				(void) enter(0);
825 			}
826 		}
827 
828 		/*
829 		 * Skip main, this is explicitly called last in atexit_fini().
830 		 */
831 		if (FLAGS(lmp) & FLG_RT_ISMAIN)
832 			continue;
833 
834 		/*
835 		 * Audit `close' operations at this point.  The library has
836 		 * exercised its last instructions (regardless of whether it
837 		 * will be unmapped or not).
838 		 *
839 		 * First call any global auditing.
840 		 */
841 		if (lml->lm_tflags & LML_TFLG_AUD_OBJCLOSE)
842 			_audit_objclose(&(auditors->ad_list), lmp);
843 
844 		/*
845 		 * Finally determine whether this object has local auditing
846 		 * requirements by inspecting itself and then its dependencies.
847 		 */
848 		if ((lml->lm_flags & LML_FLG_LOCAUDIT) == 0)
849 			continue;
850 
851 		if (FLAGS1(lmp) & LML_TFLG_AUD_OBJCLOSE)
852 			_audit_objclose(&(AUDITORS(lmp)->ad_list), lmp);
853 
854 		for (APLIST_TRAVERSE(CALLERS(lmp), idx, bdp)) {
855 			clmp = bdp->b_caller;
856 
857 			if (FLAGS1(clmp) & LML_TFLG_AUD_OBJCLOSE) {
858 				_audit_objclose(&(AUDITORS(clmp)->ad_list),
859 				    lmp);
860 				break;
861 			}
862 		}
863 	}
864 	DBG_CALL(Dbg_bind_plt_summary(lml, M_MACH, pltcnt21d, pltcnt24d,
865 	    pltcntu32, pltcntu44, pltcntfull, pltcntfar));
866 
867 	free(tobj);
868 }
869 
870 void
871 atexit_fini()
872 {
873 	Rt_map		**tobj, *lmp;
874 	Lm_list		*lml;
875 	Listnode	*lnp;
876 
877 	(void) enter(0);
878 
879 	rtld_flags |= RT_FL_ATEXIT;
880 
881 	lml = &lml_main;
882 	lml->lm_flags |= LML_FLG_ATEXIT;
883 	lml->lm_flags &= ~LML_FLG_INTRPOSETSORT;
884 	lmp = (Rt_map *)lml->lm_head;
885 
886 	/*
887 	 * Reverse topologically sort the main link-map for .fini execution.
888 	 */
889 	if (((tobj = tsort(lmp, lml->lm_obj, RT_SORT_FWD)) != 0) &&
890 	    (tobj != (Rt_map **)S_ERROR))
891 		call_fini(lml, tobj);
892 
893 	/*
894 	 * Add an explicit close to main and ld.so.1.  Although main's .fini is
895 	 * collected in call_fini() to provide for FINITARRAY processing, its
896 	 * audit_objclose is explicitly skipped.  This provides for it to be
897 	 * called last, here.  This is the reverse of the explicit calls to
898 	 * audit_objopen() made in setup().
899 	 */
900 	if ((lml->lm_tflags | FLAGS1(lmp)) & LML_TFLG_AUD_MASK) {
901 		audit_objclose(lmp, (Rt_map *)lml_rtld.lm_head);
902 		audit_objclose(lmp, lmp);
903 	}
904 
905 	/*
906 	 * Now that all .fini code has been run, see what unreferenced objects
907 	 * remain.
908 	 */
909 	unused(lml);
910 
911 	/*
912 	 * Traverse any alternative link-map lists.
913 	 */
914 	for (LIST_TRAVERSE(&dynlm_list, lnp, lml)) {
915 		/*
916 		 * Ignore the base-link-map list, which has already been
917 		 * processed, and the runtime linkers link-map list, which is
918 		 * typically processed last.
919 		 */
920 		if (lml->lm_flags & (LML_FLG_BASELM | LML_FLG_RTLDLM))
921 			continue;
922 
923 		if ((lmp = (Rt_map *)lml->lm_head) == 0)
924 			continue;
925 
926 		lml->lm_flags |= LML_FLG_ATEXIT;
927 		lml->lm_flags &= ~LML_FLG_INTRPOSETSORT;
928 
929 		/*
930 		 * Reverse topologically sort the link-map for .fini execution.
931 		 */
932 		if (((tobj = tsort(lmp, lml->lm_obj, RT_SORT_FWD)) != 0) &&
933 		    (tobj != (Rt_map **)S_ERROR))
934 			call_fini(lml, tobj);
935 
936 		unused(lml);
937 	}
938 
939 	/*
940 	 * Finally reverse topologically sort the runtime linkers link-map for
941 	 * .fini execution.
942 	 */
943 	lml = &lml_rtld;
944 	lml->lm_flags |= LML_FLG_ATEXIT;
945 	lml->lm_flags &= ~LML_FLG_INTRPOSETSORT;
946 	lmp = (Rt_map *)lml->lm_head;
947 
948 	if (((tobj = tsort(lmp, lml->lm_obj, RT_SORT_FWD)) != 0) &&
949 	    (tobj != (Rt_map **)S_ERROR))
950 		call_fini(lml, tobj);
951 
952 	leave(&lml_main, 0);
953 }
954 
955 
956 /*
957  * This routine is called to complete any runtime linker activity which may have
958  * resulted in objects being loaded.  This is called from all user entry points
959  * and from any internal dl*() requests.
960  */
961 void
962 load_completion(Rt_map *nlmp)
963 {
964 	Rt_map	**tobj = 0;
965 	Lm_list	*nlml;
966 
967 	/*
968 	 * Establish any .init processing.  Note, in a world of lazy loading,
969 	 * objects may have been loaded regardless of whether the users request
970 	 * was fulfilled (i.e., a dlsym() request may have failed to find a
971 	 * symbol but objects might have been loaded during its search).  Thus,
972 	 * any tsorting starts from the nlmp (new link-maps) pointer and not
973 	 * necessarily from the link-map that may have satisfied the request.
974 	 *
975 	 * Note, the primary link-map has an initialization phase where dynamic
976 	 * .init firing is suppressed.  This provides for a simple and clean
977 	 * handshake with the primary link-maps libc, which is important for
978 	 * establishing uberdata.  In addition, auditors often obtain handles
979 	 * to primary link-map objects as the objects are loaded, so as to
980 	 * inspect the link-map for symbols.  This inspection is allowed without
981 	 * running any code on the primary link-map, as running this code may
982 	 * reenter the auditor, who may not yet have finished its own
983 	 * initialization.
984 	 */
985 	if (nlmp)
986 		nlml = LIST(nlmp);
987 
988 	if (nlmp && nlml->lm_init && ((nlml != &lml_main) ||
989 	    (rtld_flags2 & (RT_FL2_PLMSETUP | RT_FL2_NOPLM)))) {
990 		if ((tobj = tsort(nlmp, LIST(nlmp)->lm_init,
991 		    RT_SORT_REV)) == (Rt_map **)S_ERROR)
992 			tobj = 0;
993 	}
994 
995 	/*
996 	 * Make sure any alternative link-map retrieves any external interfaces
997 	 * and initializes threads.
998 	 */
999 	if (nlmp && (nlml != &lml_main)) {
1000 		(void) rt_get_extern(nlml, nlmp);
1001 		rt_thr_init(nlml);
1002 	}
1003 
1004 	/*
1005 	 * Traverse the list of new link-maps and register any dynamic TLS.
1006 	 * This storage is established for any objects not on the primary
1007 	 * link-map, and for any objects added to the primary link-map after
1008 	 * static TLS has been registered.
1009 	 */
1010 	if (nlmp && nlml->lm_tls && ((nlml != &lml_main) ||
1011 	    (rtld_flags2 & (RT_FL2_PLMSETUP | RT_FL2_NOPLM)))) {
1012 		Rt_map	*lmp;
1013 
1014 		for (lmp = nlmp; lmp; lmp = (Rt_map *)NEXT(lmp)) {
1015 			if (PTTLS(lmp) && PTTLS(lmp)->p_memsz)
1016 				tls_modaddrem(lmp, TM_FLG_MODADD);
1017 		}
1018 		nlml->lm_tls = 0;
1019 	}
1020 
1021 	/*
1022 	 * Fire any .init's.
1023 	 */
1024 	if (tobj)
1025 		call_init(tobj, DBG_INIT_SORT);
1026 }
1027 
1028 /*
1029  * Append an item to the specified list, and return a pointer to the list
1030  * node created.
1031  */
1032 Listnode *
1033 list_append(List *lst, const void *item)
1034 {
1035 	Listnode	*_lnp;
1036 
1037 	if ((_lnp = malloc(sizeof (Listnode))) == 0)
1038 		return (0);
1039 
1040 	_lnp->data = (void *)item;
1041 	_lnp->next = NULL;
1042 
1043 	if (lst->head == NULL)
1044 		lst->tail = lst->head = _lnp;
1045 	else {
1046 		lst->tail->next = _lnp;
1047 		lst->tail = lst->tail->next;
1048 	}
1049 	return (_lnp);
1050 }
1051 
1052 
1053 /*
1054  * Add an item after specified listnode, and return a pointer to the list
1055  * node created.
1056  */
1057 Listnode *
1058 list_insert(List *lst, const void *item, Listnode *lnp)
1059 {
1060 	Listnode	*_lnp;
1061 
1062 	if ((_lnp = malloc(sizeof (Listnode))) == (Listnode *)0)
1063 		return (0);
1064 
1065 	_lnp->data = (void *)item;
1066 	_lnp->next = lnp->next;
1067 	if (_lnp->next == NULL)
1068 		lst->tail = _lnp;
1069 	lnp->next = _lnp;
1070 	return (_lnp);
1071 }
1072 
1073 /*
1074  * Prepend an item to the specified list, and return a pointer to the
1075  * list node created.
1076  */
1077 Listnode *
1078 list_prepend(List * lst, const void * item)
1079 {
1080 	Listnode	*_lnp;
1081 
1082 	if ((_lnp = malloc(sizeof (Listnode))) == (Listnode *)0)
1083 		return (0);
1084 
1085 	_lnp->data = (void *)item;
1086 
1087 	if (lst->head == NULL) {
1088 		_lnp->next = NULL;
1089 		lst->tail = lst->head = _lnp;
1090 	} else {
1091 		_lnp->next = lst->head;
1092 		lst->head = _lnp;
1093 	}
1094 	return (_lnp);
1095 }
1096 
1097 
1098 /*
1099  * Delete a 'listnode' from a list.
1100  */
1101 void
1102 list_delete(List *lst, void *item)
1103 {
1104 	Listnode	*clnp, *plnp;
1105 
1106 	for (plnp = NULL, clnp = lst->head; clnp; clnp = clnp->next) {
1107 		if (item == clnp->data)
1108 			break;
1109 		plnp = clnp;
1110 	}
1111 
1112 	if (clnp == 0)
1113 		return;
1114 
1115 	if (lst->head == clnp)
1116 		lst->head = clnp->next;
1117 	if (lst->tail == clnp)
1118 		lst->tail = plnp;
1119 
1120 	if (plnp)
1121 		plnp->next = clnp->next;
1122 
1123 	free(clnp);
1124 }
1125 
1126 /*
1127  * Append an item to the specified link map control list.
1128  */
1129 void
1130 lm_append(Lm_list *lml, Aliste lmco, Rt_map *lmp)
1131 {
1132 	Lm_cntl	*lmc;
1133 	int	add = 1;
1134 
1135 	/*
1136 	 * Indicate that this link-map list has a new object.
1137 	 */
1138 	(lml->lm_obj)++;
1139 
1140 	/*
1141 	 * If we're about to add a new object to the main link-map control list,
1142 	 * alert the debuggers that we are about to mess with this list.
1143 	 * Additions of individual objects to the main link-map control list
1144 	 * occur during initial setup as the applications immediate dependencies
1145 	 * are loaded.  Individual objects are also loaded on the main link-map
1146 	 * control list of new alternative link-map control lists.
1147 	 */
1148 	if ((lmco == ALIST_OFF_DATA) &&
1149 	    ((lml->lm_flags & LML_FLG_DBNOTIF) == 0))
1150 		rd_event(lml, RD_DLACTIVITY, RT_ADD);
1151 
1152 	/* LINTED */
1153 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, lmco);
1154 
1155 	/*
1156 	 * A link-map list header points to one of more link-map control lists
1157 	 * (see include/rtld.h).  The initial list, pointed to by lm_cntl, is
1158 	 * the list of relocated objects.  Other lists maintain objects that
1159 	 * are still being analyzed or relocated.  This list provides the core
1160 	 * link-map list information used by all ld.so.1 routines.
1161 	 */
1162 	if (lmc->lc_head == NULL) {
1163 		/*
1164 		 * If this is the first link-map for the given control list,
1165 		 * initialize the list.
1166 		 */
1167 		lmc->lc_head = lmc->lc_tail = lmp;
1168 		add = 0;
1169 
1170 	} else if (FLAGS(lmp) & FLG_RT_OBJINTPO) {
1171 		Rt_map	*tlmp;
1172 
1173 		/*
1174 		 * If this is an interposer then append the link-map following
1175 		 * any other interposers (these are objects that have been
1176 		 * previously preloaded, or were identified with -z interpose).
1177 		 * Interposers can only be inserted on the first link-map
1178 		 * control list, as once relocation has started, interposition
1179 		 * from new interposers can't be guaranteed.
1180 		 *
1181 		 * NOTE: We do not interpose on the head of a list.  This model
1182 		 * evolved because dynamic executables have already been fully
1183 		 * relocated within themselves and thus can't be interposed on.
1184 		 * Nowadays it's possible to have shared objects at the head of
1185 		 * a list, which conceptually means they could be interposed on.
1186 		 * But, shared objects can be created via dldump() and may only
1187 		 * be partially relocated (just relatives), in which case they
1188 		 * are interposable, but are marked as fixed (ET_EXEC).
1189 		 *
1190 		 * Thus we really don't have a clear method of deciding when the
1191 		 * head of a link-map is interposable.  So, to be consistent,
1192 		 * for now only add interposers after the link-map lists head
1193 		 * object.
1194 		 */
1195 		for (tlmp = (Rt_map *)NEXT(lmc->lc_head); tlmp;
1196 		    tlmp = (Rt_map *)NEXT(tlmp)) {
1197 
1198 			if (FLAGS(tlmp) & FLG_RT_OBJINTPO)
1199 				continue;
1200 
1201 			/*
1202 			 * Insert the new link-map before this non-interposer,
1203 			 * and indicate an interposer is found.
1204 			 */
1205 			NEXT((Rt_map *)PREV(tlmp)) = (Link_map *)lmp;
1206 			PREV(lmp) = PREV(tlmp);
1207 
1208 			NEXT(lmp) = (Link_map *)tlmp;
1209 			PREV(tlmp) = (Link_map *)lmp;
1210 
1211 			lmc->lc_flags |= LMC_FLG_REANALYZE;
1212 			add = 0;
1213 			break;
1214 		}
1215 	}
1216 
1217 	/*
1218 	 * Fall through to appending the new link map to the tail of the list.
1219 	 * If we're processing the initial objects of this link-map list, add
1220 	 * them to the backward compatibility list.
1221 	 */
1222 	if (add) {
1223 		NEXT(lmc->lc_tail) = (Link_map *)lmp;
1224 		PREV(lmp) = (Link_map *)lmc->lc_tail;
1225 		lmc->lc_tail = lmp;
1226 	}
1227 
1228 	/*
1229 	 * Having added this link-map to a control list, indicate which control
1230 	 * list the link-map belongs to.  Note, control list information is
1231 	 * always maintained as an offset, as the Alist can be reallocated.
1232 	 */
1233 	CNTL(lmp) = lmco;
1234 
1235 	/*
1236 	 * Indicate if an interposer is found.  Note that the first object on a
1237 	 * link-map can be explicitly defined as an interposer so that it can
1238 	 * provide interposition over direct binding requests.
1239 	 */
1240 	if (FLAGS(lmp) & MSK_RT_INTPOSE)
1241 		lml->lm_flags |= LML_FLG_INTRPOSE;
1242 
1243 	/*
1244 	 * For backward compatibility with debuggers, the link-map list contains
1245 	 * pointers to the main control list.
1246 	 */
1247 	if (lmco == ALIST_OFF_DATA) {
1248 		lml->lm_head = lmc->lc_head;
1249 		lml->lm_tail = lmc->lc_tail;
1250 	}
1251 }
1252 
1253 /*
1254  * Delete an item from the specified link map control list.
1255  */
1256 void
1257 lm_delete(Lm_list *lml, Rt_map *lmp)
1258 {
1259 	Lm_cntl	*lmc;
1260 
1261 	/*
1262 	 * If the control list pointer hasn't been initialized, this object
1263 	 * never got added to a link-map list.
1264 	 */
1265 	if (CNTL(lmp) == 0)
1266 		return;
1267 
1268 	/*
1269 	 * If we're about to delete an object from the main link-map control
1270 	 * list, alert the debuggers that we are about to mess with this list.
1271 	 */
1272 	if ((CNTL(lmp) == ALIST_OFF_DATA) &&
1273 	    ((lml->lm_flags & LML_FLG_DBNOTIF) == 0))
1274 		rd_event(lml, RD_DLACTIVITY, RT_DELETE);
1275 
1276 	/* LINTED */
1277 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, CNTL(lmp));
1278 
1279 	if (lmc->lc_head == lmp)
1280 		lmc->lc_head = (Rt_map *)NEXT(lmp);
1281 	else
1282 		NEXT((Rt_map *)PREV(lmp)) = (void *)NEXT(lmp);
1283 
1284 	if (lmc->lc_tail == lmp)
1285 		lmc->lc_tail = (Rt_map *)PREV(lmp);
1286 	else
1287 		PREV((Rt_map *)NEXT(lmp)) = PREV(lmp);
1288 
1289 	/*
1290 	 * For backward compatibility with debuggers, the link-map list contains
1291 	 * pointers to the main control list.
1292 	 */
1293 	if (lmc == (Lm_cntl *)&lml->lm_lists->al_data) {
1294 		lml->lm_head = lmc->lc_head;
1295 		lml->lm_tail = lmc->lc_tail;
1296 	}
1297 
1298 	/*
1299 	 * Indicate we have one less object on this control list.
1300 	 */
1301 	(lml->lm_obj)--;
1302 }
1303 
1304 /*
1305  * Move a link-map control list to another.  Objects that are being relocated
1306  * are maintained on secondary control lists.  Once their relocation is
1307  * complete, the entire list is appended to the previous control list, as this
1308  * list must have been the trigger for generating the new control list.
1309  */
1310 void
1311 lm_move(Lm_list *lml, Aliste nlmco, Aliste plmco, Lm_cntl *nlmc, Lm_cntl *plmc)
1312 {
1313 	Rt_map	*lmp;
1314 
1315 	/*
1316 	 * If we're about to add a new family of objects to the main link-map
1317 	 * control list, alert the debuggers that we are about to mess with this
1318 	 * list.  Additions of object families to the main link-map control
1319 	 * list occur during lazy loading, filtering and dlopen().
1320 	 */
1321 	if ((plmco == ALIST_OFF_DATA) &&
1322 	    ((lml->lm_flags & LML_FLG_DBNOTIF) == 0))
1323 		rd_event(lml, RD_DLACTIVITY, RT_ADD);
1324 
1325 	DBG_CALL(Dbg_file_cntl(lml, nlmco, plmco));
1326 
1327 	/*
1328 	 * Indicate each new link-map has been moved to the previous link-map
1329 	 * control list.
1330 	 */
1331 	for (lmp = nlmc->lc_head; lmp; lmp = (Rt_map *)NEXT(lmp))
1332 		CNTL(lmp) = plmco;
1333 
1334 	/*
1335 	 * Move the new link-map control list, to the callers link-map control
1336 	 * list.
1337 	 */
1338 	if (plmc->lc_head == 0) {
1339 		plmc->lc_head = nlmc->lc_head;
1340 		PREV(nlmc->lc_head) = 0;
1341 	} else {
1342 		NEXT(plmc->lc_tail) = (Link_map *)nlmc->lc_head;
1343 		PREV(nlmc->lc_head) = (Link_map *)plmc->lc_tail;
1344 	}
1345 
1346 	plmc->lc_tail = nlmc->lc_tail;
1347 	nlmc->lc_head = nlmc->lc_tail = 0;
1348 
1349 	/*
1350 	 * For backward compatibility with debuggers, the link-map list contains
1351 	 * pointers to the main control list.
1352 	 */
1353 	if (plmco == ALIST_OFF_DATA) {
1354 		lml->lm_head = plmc->lc_head;
1355 		lml->lm_tail = plmc->lc_tail;
1356 	}
1357 }
1358 
1359 /*
1360  * Environment variables can have a variety of defined permutations, and thus
1361  * the following infrastructure exists to allow this variety and to select the
1362  * required definition.
1363  *
1364  * Environment variables can be defined as 32- or 64-bit specific, and if so
1365  * they will take precedence over any instruction set neutral form.  Typically
1366  * this is only useful when the environment value is an informational string.
1367  *
1368  * Environment variables may be obtained from the standard user environment or
1369  * from a configuration file.  The latter provides a fallback if no user
1370  * environment setting is found, and can take two forms:
1371  *
1372  *  .	a replaceable definition - this will be used if no user environment
1373  *	setting has been seen, or
1374  *
1375  *  .	an permanent definition - this will be used no matter what user
1376  *	environment setting is seen.  In the case of list variables it will be
1377  *	appended to any process environment setting seen.
1378  *
1379  * Environment variables can be defined without a value (ie. LD_XXXX=) so as to
1380  * override any replaceable environment variables from a configuration file.
1381  */
1382 static	u_longlong_t		rplgen;		/* replaceable generic */
1383 						/*	variables */
1384 static	u_longlong_t		rplisa;		/* replaceable ISA specific */
1385 						/*	variables */
1386 static	u_longlong_t		prmgen;		/* permanent generic */
1387 						/*	variables */
1388 static	u_longlong_t		prmisa;		/* permanent ISA specific */
1389 						/*	variables */
1390 
1391 /*
1392  * Classify an environment variables type.
1393  */
1394 #define	ENV_TYP_IGNORE		0x1		/* ignore - variable is for */
1395 						/*	the wrong ISA */
1396 #define	ENV_TYP_ISA		0x2		/* variable is ISA specific */
1397 #define	ENV_TYP_CONFIG		0x4		/* variable obtained from a */
1398 						/*	config file */
1399 #define	ENV_TYP_PERMANT		0x8		/* variable is permanent */
1400 
1401 /*
1402  * Identify all environment variables.
1403  */
1404 #define	ENV_FLG_AUDIT		0x0000000001ULL
1405 #define	ENV_FLG_AUDIT_ARGS	0x0000000002ULL
1406 #define	ENV_FLG_BIND_NOW	0x0000000004ULL
1407 #define	ENV_FLG_BIND_NOT	0x0000000008ULL
1408 #define	ENV_FLG_BINDINGS	0x0000000010ULL
1409 #define	ENV_FLG_CONCURRENCY	0x0000000020ULL
1410 #define	ENV_FLG_CONFGEN		0x0000000040ULL
1411 #define	ENV_FLG_CONFIG		0x0000000080ULL
1412 #define	ENV_FLG_DEBUG		0x0000000100ULL
1413 #define	ENV_FLG_DEBUG_OUTPUT	0x0000000200ULL
1414 #define	ENV_FLG_DEMANGLE	0x0000000400ULL
1415 #define	ENV_FLG_FLAGS		0x0000000800ULL
1416 #define	ENV_FLG_INIT		0x0000001000ULL
1417 #define	ENV_FLG_LIBPATH		0x0000002000ULL
1418 #define	ENV_FLG_LOADAVAIL	0x0000004000ULL
1419 #define	ENV_FLG_LOADFLTR	0x0000008000ULL
1420 #define	ENV_FLG_NOAUDIT		0x0000010000ULL
1421 #define	ENV_FLG_NOAUXFLTR	0x0000020000ULL
1422 #define	ENV_FLG_NOBAPLT		0x0000040000ULL
1423 #define	ENV_FLG_NOCONFIG	0x0000080000ULL
1424 #define	ENV_FLG_NODIRCONFIG	0x0000100000ULL
1425 #define	ENV_FLG_NODIRECT	0x0000200000ULL
1426 #define	ENV_FLG_NOENVCONFIG	0x0000400000ULL
1427 #define	ENV_FLG_NOLAZY		0x0000800000ULL
1428 #define	ENV_FLG_NOOBJALTER	0x0001000000ULL
1429 #define	ENV_FLG_NOVERSION	0x0002000000ULL
1430 #define	ENV_FLG_PRELOAD		0x0004000000ULL
1431 #define	ENV_FLG_PROFILE		0x0008000000ULL
1432 #define	ENV_FLG_PROFILE_OUTPUT	0x0010000000ULL
1433 #define	ENV_FLG_SIGNAL		0x0020000000ULL
1434 #define	ENV_FLG_TRACE_OBJS	0x0040000000ULL
1435 #define	ENV_FLG_TRACE_PTHS	0x0080000000ULL
1436 #define	ENV_FLG_UNREF		0x0100000000ULL
1437 #define	ENV_FLG_UNUSED		0x0200000000ULL
1438 #define	ENV_FLG_VERBOSE		0x0400000000ULL
1439 #define	ENV_FLG_WARN		0x0800000000ULL
1440 #define	ENV_FLG_NOFLTCONFIG	0x1000000000ULL
1441 #define	ENV_FLG_BIND_LAZY	0x2000000000ULL
1442 #define	ENV_FLG_NOUNRESWEAK	0x4000000000ULL
1443 #define	ENV_FLG_NOPAREXT	0x8000000000ULL
1444 
1445 #ifdef	SIEBEL_DISABLE
1446 #define	ENV_FLG_FIX_1		0x8000000000ULL
1447 #endif
1448 
1449 #define	SEL_REPLACE		0x0001
1450 #define	SEL_PERMANT		0x0002
1451 #define	SEL_ACT_RT		0x0100	/* setting rtld_flags */
1452 #define	SEL_ACT_RT2		0x0200	/* setting rtld_flags2 */
1453 #define	SEL_ACT_STR		0x0400	/* setting string value */
1454 #define	SEL_ACT_LML		0x0800	/* setting lml_flags */
1455 #define	SEL_ACT_LMLT		0x1000	/* setting lml_tflags */
1456 #define	SEL_ACT_SPEC_1		0x2000	/* For FLG_{FLAGS, LIBPATH} */
1457 #define	SEL_ACT_SPEC_2		0x4000	/* need special handling */
1458 
1459 /*
1460  * Pattern match an LD_XXXX environment variable.  s1 points to the XXXX part
1461  * and len specifies its length (comparing a strings length before the string
1462  * itself speed things up).  s2 points to the token itself which has already
1463  * had any leading white-space removed.
1464  */
1465 static void
1466 ld_generic_env(const char *s1, size_t len, const char *s2, Word *lmflags,
1467     Word *lmtflags, uint_t env_flags, int aout)
1468 {
1469 	u_longlong_t	variable = 0;
1470 	ushort_t	select = 0;
1471 	const char	**str;
1472 	Word		val = 0;
1473 
1474 	/*
1475 	 * Determine whether we're dealing with a replaceable or permanent
1476 	 * string.
1477 	 */
1478 	if (env_flags & ENV_TYP_PERMANT) {
1479 		/*
1480 		 * If the string is from a configuration file and defined as
1481 		 * permanent, assign it as permanent.
1482 		 */
1483 		select |= SEL_PERMANT;
1484 	} else
1485 		select |= SEL_REPLACE;
1486 
1487 	/*
1488 	 * Parse the variable given.
1489 	 *
1490 	 * The LD_AUDIT family.
1491 	 */
1492 	if (*s1 == 'A') {
1493 		if ((len == MSG_LD_AUDIT_SIZE) && (strncmp(s1,
1494 		    MSG_ORIG(MSG_LD_AUDIT), MSG_LD_AUDIT_SIZE) == 0)) {
1495 			/*
1496 			 * Replaceable and permanent audit objects can exist.
1497 			 */
1498 			select |= SEL_ACT_STR;
1499 			if (select & SEL_REPLACE)
1500 				str = &rpl_audit;
1501 			else {
1502 				str = &prm_audit;
1503 				rpl_audit = 0;
1504 			}
1505 			variable = ENV_FLG_AUDIT;
1506 		} else if ((len == MSG_LD_AUDIT_ARGS_SIZE) &&
1507 		    (strncmp(s1, MSG_ORIG(MSG_LD_AUDIT_ARGS),
1508 		    MSG_LD_AUDIT_ARGS_SIZE) == 0)) {
1509 			/*
1510 			 * A specialized variable for plt_exit() use, not
1511 			 * documented for general use.
1512 			 */
1513 			select |= SEL_ACT_SPEC_2;
1514 			variable = ENV_FLG_AUDIT_ARGS;
1515 		}
1516 	}
1517 	/*
1518 	 * The LD_BIND family and LD_BREADTH (historic).
1519 	 */
1520 	else if (*s1 == 'B') {
1521 		if ((len == MSG_LD_BIND_LAZY_SIZE) && (strncmp(s1,
1522 		    MSG_ORIG(MSG_LD_BIND_LAZY),
1523 		    MSG_LD_BIND_LAZY_SIZE) == 0)) {
1524 			select |= SEL_ACT_RT2;
1525 			val = RT_FL2_BINDLAZY;
1526 			variable = ENV_FLG_BIND_LAZY;
1527 		} else if ((len == MSG_LD_BIND_NOW_SIZE) && (strncmp(s1,
1528 		    MSG_ORIG(MSG_LD_BIND_NOW), MSG_LD_BIND_NOW_SIZE) == 0)) {
1529 			select |= SEL_ACT_RT2;
1530 			val = RT_FL2_BINDNOW;
1531 			variable = ENV_FLG_BIND_NOW;
1532 		} else if ((len == MSG_LD_BIND_NOT_SIZE) && (strncmp(s1,
1533 		    MSG_ORIG(MSG_LD_BIND_NOT), MSG_LD_BIND_NOT_SIZE) == 0)) {
1534 			/*
1535 			 * Another trick, enabled to help debug AOUT
1536 			 * applications under BCP, but not documented for
1537 			 * general use.
1538 			 */
1539 			select |= SEL_ACT_RT;
1540 			val = RT_FL_NOBIND;
1541 			variable = ENV_FLG_BIND_NOT;
1542 		} else if ((len == MSG_LD_BINDINGS_SIZE) && (strncmp(s1,
1543 		    MSG_ORIG(MSG_LD_BINDINGS), MSG_LD_BINDINGS_SIZE) == 0)) {
1544 			/*
1545 			 * This variable is simply for backward compatibility.
1546 			 * If this and LD_DEBUG are both specified, only one of
1547 			 * the strings is going to get processed.
1548 			 */
1549 			select |= SEL_ACT_SPEC_2;
1550 			variable = ENV_FLG_BINDINGS;
1551 #ifndef LD_BREADTH_DISABLED
1552 		} else if ((len == MSG_LD_BREADTH_SIZE) && (strncmp(s1,
1553 		    MSG_ORIG(MSG_LD_BREADTH), MSG_LD_BREADTH_SIZE) == 0)) {
1554 			/*
1555 			 * Besides some old patches this is no longer available.
1556 			 */
1557 			rtld_flags |= RT_FL_BREADTH;
1558 			return;
1559 #endif
1560 		}
1561 	}
1562 	/*
1563 	 * LD_CONCURRENCY and LD_CONFIG family.
1564 	 */
1565 	else if (*s1 == 'C') {
1566 		if ((len == MSG_LD_CONCURRENCY_SIZE) && (strncmp(s1,
1567 		    MSG_ORIG(MSG_LD_CONCURRENCY),
1568 		    MSG_LD_CONCURRENCY_SIZE) == 0)) {
1569 			/*
1570 			 * Waiting in the wings, as concurrency checking isn't
1571 			 * yet enabled.
1572 			 */
1573 			select |= SEL_ACT_SPEC_2;
1574 			variable = ENV_FLG_CONCURRENCY;
1575 		} else if ((len == MSG_LD_CONFGEN_SIZE) && (strncmp(s1,
1576 		    MSG_ORIG(MSG_LD_CONFGEN), MSG_LD_CONFGEN_SIZE) == 0)) {
1577 			/*
1578 			 * Set by crle(1) to indicate it's building a
1579 			 * configuration file, not documented for general use.
1580 			 */
1581 			select |= SEL_ACT_SPEC_2;
1582 			variable = ENV_FLG_CONFGEN;
1583 		} else if ((len == MSG_LD_CONFIG_SIZE) && (strncmp(s1,
1584 		    MSG_ORIG(MSG_LD_CONFIG), MSG_LD_CONFIG_SIZE) == 0)) {
1585 			/*
1586 			 * Secure applications must use a default configuration
1587 			 * file.  A setting from a configuration file doesn't
1588 			 * make sense (given we must be reading a configuration
1589 			 * file to have gotten this).
1590 			 */
1591 			if ((rtld_flags & RT_FL_SECURE) ||
1592 			    (env_flags & ENV_TYP_CONFIG))
1593 				return;
1594 			select |= SEL_ACT_STR;
1595 			str = &config->c_name;
1596 			variable = ENV_FLG_CONFIG;
1597 		}
1598 	}
1599 	/*
1600 	 * The LD_DEBUG family and LD_DEMANGLE.
1601 	 */
1602 	else if (*s1 == 'D') {
1603 		if ((len == MSG_LD_DEBUG_SIZE) && (strncmp(s1,
1604 		    MSG_ORIG(MSG_LD_DEBUG), MSG_LD_DEBUG_SIZE) == 0)) {
1605 			select |= SEL_ACT_STR;
1606 			if (select & SEL_REPLACE)
1607 				str = &rpl_debug;
1608 			else {
1609 				str = &prm_debug;
1610 				rpl_debug = 0;
1611 			}
1612 			variable = ENV_FLG_DEBUG;
1613 		} else if ((len == MSG_LD_DEBUG_OUTPUT_SIZE) && (strncmp(s1,
1614 		    MSG_ORIG(MSG_LD_DEBUG_OUTPUT),
1615 		    MSG_LD_DEBUG_OUTPUT_SIZE) == 0)) {
1616 			select |= SEL_ACT_STR;
1617 			str = &dbg_file;
1618 			variable = ENV_FLG_DEBUG_OUTPUT;
1619 		} else if ((len == MSG_LD_DEMANGLE_SIZE) && (strncmp(s1,
1620 		    MSG_ORIG(MSG_LD_DEMANGLE), MSG_LD_DEMANGLE_SIZE) == 0)) {
1621 			select |= SEL_ACT_RT;
1622 			val = RT_FL_DEMANGLE;
1623 			variable = ENV_FLG_DEMANGLE;
1624 		}
1625 	}
1626 	/*
1627 	 * LD_FLAGS - collect the best variable definition.  On completion of
1628 	 * environment variable processing pass the result to ld_flags_env()
1629 	 * where they'll be decomposed and passed back to this routine.
1630 	 */
1631 	else if (*s1 == 'F') {
1632 		if ((len == MSG_LD_FLAGS_SIZE) && (strncmp(s1,
1633 		    MSG_ORIG(MSG_LD_FLAGS), MSG_LD_FLAGS_SIZE) == 0)) {
1634 			select |= SEL_ACT_SPEC_1;
1635 			if (select & SEL_REPLACE)
1636 				str = &rpl_ldflags;
1637 			else {
1638 				str = &prm_ldflags;
1639 				rpl_ldflags = 0;
1640 			}
1641 			variable = ENV_FLG_FLAGS;
1642 		}
1643 	}
1644 	/*
1645 	 * LD_INIT (internal, used by ldd(1)).
1646 	 */
1647 	else if (*s1 == 'I') {
1648 		if ((len == MSG_LD_INIT_SIZE) && (strncmp(s1,
1649 		    MSG_ORIG(MSG_LD_INIT), MSG_LD_INIT_SIZE) == 0)) {
1650 			select |= SEL_ACT_LML;
1651 			val = LML_FLG_TRC_INIT;
1652 			variable = ENV_FLG_INIT;
1653 		}
1654 	}
1655 	/*
1656 	 * The LD_LIBRARY_PATH and LD_LOAD families.
1657 	 */
1658 	else if (*s1 == 'L') {
1659 		if ((len == MSG_LD_LIBPATH_SIZE) && (strncmp(s1,
1660 		    MSG_ORIG(MSG_LD_LIBPATH), MSG_LD_LIBPATH_SIZE) == 0)) {
1661 			select |= SEL_ACT_SPEC_1;
1662 			if (select & SEL_REPLACE)
1663 				str = &rpl_libpath;
1664 			else {
1665 				str = &prm_libpath;
1666 				rpl_libpath = 0;
1667 			}
1668 			variable = ENV_FLG_LIBPATH;
1669 		} else if ((len == MSG_LD_LOADAVAIL_SIZE) && (strncmp(s1,
1670 		    MSG_ORIG(MSG_LD_LOADAVAIL), MSG_LD_LOADAVAIL_SIZE) == 0)) {
1671 			/*
1672 			 * Internal use by crle(1), not documented for general
1673 			 * use.
1674 			 */
1675 			select |= SEL_ACT_LML;
1676 			val = LML_FLG_LOADAVAIL;
1677 			variable = ENV_FLG_LOADAVAIL;
1678 		} else if ((len == MSG_LD_LOADFLTR_SIZE) && (strncmp(s1,
1679 		    MSG_ORIG(MSG_LD_LOADFLTR), MSG_LD_LOADFLTR_SIZE) == 0)) {
1680 			select |= SEL_ACT_SPEC_2;
1681 			variable = ENV_FLG_LOADFLTR;
1682 		}
1683 	}
1684 	/*
1685 	 * The LD_NO family.
1686 	 */
1687 	else if (*s1 == 'N') {
1688 		if ((len == MSG_LD_NOAUDIT_SIZE) && (strncmp(s1,
1689 		    MSG_ORIG(MSG_LD_NOAUDIT), MSG_LD_NOAUDIT_SIZE) == 0)) {
1690 			select |= SEL_ACT_RT;
1691 			val = RT_FL_NOAUDIT;
1692 			variable = ENV_FLG_NOAUDIT;
1693 		} else if ((len == MSG_LD_NOAUXFLTR_SIZE) && (strncmp(s1,
1694 		    MSG_ORIG(MSG_LD_NOAUXFLTR), MSG_LD_NOAUXFLTR_SIZE) == 0)) {
1695 			select |= SEL_ACT_RT;
1696 			val = RT_FL_NOAUXFLTR;
1697 			variable = ENV_FLG_NOAUXFLTR;
1698 		} else if ((len == MSG_LD_NOBAPLT_SIZE) && (strncmp(s1,
1699 		    MSG_ORIG(MSG_LD_NOBAPLT), MSG_LD_NOBAPLT_SIZE) == 0)) {
1700 			select |= SEL_ACT_RT;
1701 			val = RT_FL_NOBAPLT;
1702 			variable = ENV_FLG_NOBAPLT;
1703 		} else if ((len == MSG_LD_NOCONFIG_SIZE) && (strncmp(s1,
1704 		    MSG_ORIG(MSG_LD_NOCONFIG), MSG_LD_NOCONFIG_SIZE) == 0)) {
1705 			select |= SEL_ACT_RT;
1706 			val = RT_FL_NOCFG;
1707 			variable = ENV_FLG_NOCONFIG;
1708 		} else if ((len == MSG_LD_NODIRCONFIG_SIZE) && (strncmp(s1,
1709 		    MSG_ORIG(MSG_LD_NODIRCONFIG),
1710 		    MSG_LD_NODIRCONFIG_SIZE) == 0)) {
1711 			select |= SEL_ACT_RT;
1712 			val = RT_FL_NODIRCFG;
1713 			variable = ENV_FLG_NODIRCONFIG;
1714 		} else if ((len == MSG_LD_NODIRECT_SIZE) && (strncmp(s1,
1715 		    MSG_ORIG(MSG_LD_NODIRECT), MSG_LD_NODIRECT_SIZE) == 0)) {
1716 			select |= SEL_ACT_LMLT;
1717 			val = LML_TFLG_NODIRECT;
1718 			variable = ENV_FLG_NODIRECT;
1719 		} else if ((len == MSG_LD_NOENVCONFIG_SIZE) && (strncmp(s1,
1720 		    MSG_ORIG(MSG_LD_NOENVCONFIG),
1721 		    MSG_LD_NOENVCONFIG_SIZE) == 0)) {
1722 			select |= SEL_ACT_RT;
1723 			val = RT_FL_NOENVCFG;
1724 			variable = ENV_FLG_NOENVCONFIG;
1725 		} else if ((len == MSG_LD_NOFLTCONFIG_SIZE) && (strncmp(s1,
1726 		    MSG_ORIG(MSG_LD_NOFLTCONFIG),
1727 		    MSG_LD_NOFLTCONFIG_SIZE) == 0)) {
1728 			select |= SEL_ACT_RT2;
1729 			val = RT_FL2_NOFLTCFG;
1730 			variable = ENV_FLG_NOFLTCONFIG;
1731 		} else if ((len == MSG_LD_NOLAZY_SIZE) && (strncmp(s1,
1732 		    MSG_ORIG(MSG_LD_NOLAZY), MSG_LD_NOLAZY_SIZE) == 0)) {
1733 			select |= SEL_ACT_LMLT;
1734 			val = LML_TFLG_NOLAZYLD;
1735 			variable = ENV_FLG_NOLAZY;
1736 		} else if ((len == MSG_LD_NOOBJALTER_SIZE) && (strncmp(s1,
1737 		    MSG_ORIG(MSG_LD_NOOBJALTER),
1738 		    MSG_LD_NOOBJALTER_SIZE) == 0)) {
1739 			select |= SEL_ACT_RT;
1740 			val = RT_FL_NOOBJALT;
1741 			variable = ENV_FLG_NOOBJALTER;
1742 		} else if ((len == MSG_LD_NOVERSION_SIZE) && (strncmp(s1,
1743 		    MSG_ORIG(MSG_LD_NOVERSION), MSG_LD_NOVERSION_SIZE) == 0)) {
1744 			select |= SEL_ACT_RT;
1745 			val = RT_FL_NOVERSION;
1746 			variable = ENV_FLG_NOVERSION;
1747 		} else if ((len == MSG_LD_NOUNRESWEAK_SIZE) && (strncmp(s1,
1748 		    MSG_ORIG(MSG_LD_NOUNRESWEAK),
1749 		    MSG_LD_NOUNRESWEAK_SIZE) == 0)) {
1750 			/*
1751 			 * LD_NOUNRESWEAK (internal, used by ldd(1)).
1752 			 */
1753 			select |= SEL_ACT_LML;
1754 			val = LML_FLG_TRC_NOUNRESWEAK;
1755 			variable = ENV_FLG_NOUNRESWEAK;
1756 		} else if ((len == MSG_LD_NOPAREXT_SIZE) && (strncmp(s1,
1757 		    MSG_ORIG(MSG_LD_NOPAREXT), MSG_LD_NOPAREXT_SIZE) == 0)) {
1758 			select |= SEL_ACT_LML;
1759 			val = LML_FLG_TRC_NOPAREXT;
1760 			variable = ENV_FLG_NOPAREXT;
1761 		}
1762 	}
1763 	/*
1764 	 * LD_ORIGIN.
1765 	 */
1766 	else if (*s1 == 'O') {
1767 #ifndef	EXPAND_RELATIVE
1768 		if ((len == MSG_LD_ORIGIN_SIZE) && (strncmp(s1,
1769 		    MSG_ORIG(MSG_LD_ORIGIN), MSG_LD_ORIGIN_SIZE) == 0)) {
1770 			/*
1771 			 * Besides some old patches this is no longer required.
1772 			 */
1773 			rtld_flags |= RT_FL_RELATIVE;
1774 		}
1775 #endif
1776 		return;
1777 	}
1778 	/*
1779 	 * LD_PRELOAD and LD_PROFILE family.
1780 	 */
1781 	else if (*s1 == 'P') {
1782 		if ((len == MSG_LD_PRELOAD_SIZE) && (strncmp(s1,
1783 		    MSG_ORIG(MSG_LD_PRELOAD), MSG_LD_PRELOAD_SIZE) == 0)) {
1784 			select |= SEL_ACT_STR;
1785 			if (select & SEL_REPLACE)
1786 				str = &rpl_preload;
1787 			else  {
1788 				str = &prm_preload;
1789 				rpl_preload = 0;
1790 			}
1791 			variable = ENV_FLG_PRELOAD;
1792 		} else if ((len == MSG_LD_PROFILE_SIZE) && (strncmp(s1,
1793 		    MSG_ORIG(MSG_LD_PROFILE), MSG_LD_PROFILE_SIZE) == 0)) {
1794 			/*
1795 			 * Only one user library can be profiled at a time.
1796 			 */
1797 			select |= SEL_ACT_SPEC_2;
1798 			variable = ENV_FLG_PROFILE;
1799 		} else if ((len == MSG_LD_PROFILE_OUTPUT_SIZE) && (strncmp(s1,
1800 		    MSG_ORIG(MSG_LD_PROFILE_OUTPUT),
1801 		    MSG_LD_PROFILE_OUTPUT_SIZE) == 0)) {
1802 			/*
1803 			 * Only one user library can be profiled at a time.
1804 			 */
1805 			select |= SEL_ACT_STR;
1806 			str = &profile_out;
1807 			variable = ENV_FLG_PROFILE_OUTPUT;
1808 		}
1809 	}
1810 	/*
1811 	 * LD_SIGNAL.
1812 	 */
1813 	else if (*s1 == 'S') {
1814 		if (rtld_flags & RT_FL_SECURE)
1815 			return;
1816 		if ((len == MSG_LD_SIGNAL_SIZE) &&
1817 		    (strncmp(s1, MSG_ORIG(MSG_LD_SIGNAL),
1818 		    MSG_LD_SIGNAL_SIZE) == 0)) {
1819 			select |= SEL_ACT_SPEC_2;
1820 			variable = ENV_FLG_SIGNAL;
1821 		}
1822 	}
1823 	/*
1824 	 * The LD_TRACE family (internal, used by ldd(1)).  This definition is
1825 	 * the key to enabling all other ldd(1) specific environment variables.
1826 	 * In case an auditor is called, which in turn might exec(2) a
1827 	 * subprocess, this variable is disabled, so that any subprocess
1828 	 * escapes ldd(1) processing.
1829 	 */
1830 	else if (*s1 == 'T') {
1831 		if (((len == MSG_LD_TRACE_OBJS_SIZE) &&
1832 		    (strncmp(s1, MSG_ORIG(MSG_LD_TRACE_OBJS),
1833 		    MSG_LD_TRACE_OBJS_SIZE) == 0)) ||
1834 		    ((len == MSG_LD_TRACE_OBJS_E_SIZE) &&
1835 		    (((strncmp(s1, MSG_ORIG(MSG_LD_TRACE_OBJS_E),
1836 		    MSG_LD_TRACE_OBJS_E_SIZE) == 0) && !aout) ||
1837 		    ((strncmp(s1, MSG_ORIG(MSG_LD_TRACE_OBJS_A),
1838 		    MSG_LD_TRACE_OBJS_A_SIZE) == 0) && aout)))) {
1839 			char	*s0 = (char *)s1;
1840 
1841 			select |= SEL_ACT_SPEC_2;
1842 			variable = ENV_FLG_TRACE_OBJS;
1843 
1844 #if	defined(__sparc) || defined(__x86)
1845 			/*
1846 			 * The simplest way to "disable" this variable is to
1847 			 * truncate this string to "LD_'\0'". This string is
1848 			 * ignored by any ld.so.1 environment processing.
1849 			 * Use of such interfaces as unsetenv(3c) are overkill,
1850 			 * and would drag too much libc implementation detail
1851 			 * into ld.so.1.
1852 			 */
1853 			*s0 = '\0';
1854 #else
1855 /*
1856  * Verify that the above write is appropriate for any new platforms.
1857  */
1858 #error	unsupported architecture!
1859 #endif
1860 		} else if ((len == MSG_LD_TRACE_PTHS_SIZE) && (strncmp(s1,
1861 		    MSG_ORIG(MSG_LD_TRACE_PTHS),
1862 		    MSG_LD_TRACE_PTHS_SIZE) == 0)) {
1863 			select |= SEL_ACT_LML;
1864 			val = LML_FLG_TRC_SEARCH;
1865 			variable = ENV_FLG_TRACE_PTHS;
1866 		}
1867 	}
1868 	/*
1869 	 * LD_UNREF and LD_UNUSED (internal, used by ldd(1)).
1870 	 */
1871 	else if (*s1 == 'U') {
1872 		if ((len == MSG_LD_UNREF_SIZE) && (strncmp(s1,
1873 		    MSG_ORIG(MSG_LD_UNREF), MSG_LD_UNREF_SIZE) == 0)) {
1874 			select |= SEL_ACT_LML;
1875 			val = LML_FLG_TRC_UNREF;
1876 			variable = ENV_FLG_UNREF;
1877 		} else if ((len == MSG_LD_UNUSED_SIZE) && (strncmp(s1,
1878 		    MSG_ORIG(MSG_LD_UNUSED), MSG_LD_UNUSED_SIZE) == 0)) {
1879 			select |= SEL_ACT_LML;
1880 			val = LML_FLG_TRC_UNUSED;
1881 			variable = ENV_FLG_UNUSED;
1882 		}
1883 	}
1884 	/*
1885 	 * LD_VERBOSE (internal, used by ldd(1)).
1886 	 */
1887 	else if (*s1 == 'V') {
1888 		if ((len == MSG_LD_VERBOSE_SIZE) && (strncmp(s1,
1889 		    MSG_ORIG(MSG_LD_VERBOSE), MSG_LD_VERBOSE_SIZE) == 0)) {
1890 			select |= SEL_ACT_LML;
1891 			val = LML_FLG_TRC_VERBOSE;
1892 			variable = ENV_FLG_VERBOSE;
1893 		}
1894 	}
1895 	/*
1896 	 * LD_WARN (internal, used by ldd(1)).
1897 	 */
1898 	else if (*s1 == 'W') {
1899 		if ((len == MSG_LD_WARN_SIZE) && (strncmp(s1,
1900 		    MSG_ORIG(MSG_LD_WARN), MSG_LD_WARN_SIZE) == 0)) {
1901 			select |= SEL_ACT_LML;
1902 			val = LML_FLG_TRC_WARN;
1903 			variable = ENV_FLG_WARN;
1904 		}
1905 #ifdef	SIEBEL_DISABLE
1906 	}
1907 	/*
1908 	 * LD__FIX__ (undocumented, enable future technology that can't be
1909 	 * delivered in a patch release).
1910 	 */
1911 	else if (*s1 == '_') {
1912 		if ((len == MSG_LD_FIX_1_SIZE) && (strncmp(s1,
1913 		    MSG_ORIG(MSG_LD_FIX_1), MSG_LD_FIX_1_SIZE) == 0)) {
1914 			select |= SEL_ACT_RT;
1915 			val = RT_FL_DISFIX_1;
1916 			variable = ENV_FLG_FIX_1;
1917 		}
1918 #endif
1919 	}
1920 	if (variable == 0)
1921 		return;
1922 
1923 	/*
1924 	 * If the variable is already processed with ISA specific variable,
1925 	 * no further processing needed.
1926 	 */
1927 	if (((select & SEL_REPLACE) && (rplisa & variable)) ||
1928 	    ((select & SEL_PERMANT) && (prmisa & variable)))
1929 		return;
1930 
1931 	/*
1932 	 * Now mark the appropriate variables.
1933 	 * If the replaceable variable is already set, then the
1934 	 * process environment variable must be set. Any replaceable
1935 	 * variable specified in a configuration file can be ignored.
1936 	 */
1937 	if (env_flags & ENV_TYP_ISA) {
1938 		/*
1939 		 * This is ISA setting. We do the setting
1940 		 * even if s2 is NULL.
1941 		 * If s2 is NULL, we might need to undo
1942 		 * the setting.
1943 		 */
1944 		if (select & SEL_REPLACE) {
1945 			if (rplisa & variable)
1946 				return;
1947 			rplisa |= variable;
1948 		} else {
1949 			prmisa |= variable;
1950 		}
1951 	} else if (s2) {
1952 		/*
1953 		 * This is non0-ISA setting
1954 		 */
1955 		if (select & SEL_REPLACE) {
1956 			if (rplgen & variable)
1957 				return;
1958 			rplgen |= variable;
1959 		} else
1960 			prmgen |= variable;
1961 	} else
1962 		/*
1963 		 * This is non-ISA setting which
1964 		 * can be ignored.
1965 		 */
1966 		return;
1967 
1968 	/*
1969 	 * Now perform the setting.
1970 	 */
1971 	if (select & SEL_ACT_RT) {
1972 		if (s2)
1973 			rtld_flags |= val;
1974 		else
1975 			rtld_flags &= ~val;
1976 	} else if (select & SEL_ACT_RT2) {
1977 		if (s2)
1978 			rtld_flags2 |= val;
1979 		else
1980 			rtld_flags2 &= ~val;
1981 	} else if (select & SEL_ACT_STR)
1982 		*str = s2;
1983 	else if (select & SEL_ACT_LML) {
1984 		if (s2)
1985 			*lmflags |= val;
1986 		else
1987 			*lmflags &= ~val;
1988 	} else if (select & SEL_ACT_LMLT) {
1989 		if (s2)
1990 			*lmtflags |= val;
1991 		else
1992 			*lmtflags &= ~val;
1993 	} else if (select & SEL_ACT_SPEC_1) {
1994 		/*
1995 		 * variable is either ENV_FLG_FLAGS or ENV_FLG_LIBPATH
1996 		 */
1997 		*str = s2;
1998 		if ((select & SEL_REPLACE) && (env_flags & ENV_TYP_CONFIG)) {
1999 			if (s2) {
2000 				if (variable == ENV_FLG_FLAGS)
2001 					env_info |= ENV_INF_FLAGCFG;
2002 				else
2003 					env_info |= ENV_INF_PATHCFG;
2004 			} else {
2005 				if (variable == ENV_FLG_FLAGS)
2006 					env_info &= ~ENV_INF_FLAGCFG;
2007 				else
2008 					env_info &= ~ENV_INF_PATHCFG;
2009 			}
2010 		}
2011 	} else if (select & SEL_ACT_SPEC_2) {
2012 		/*
2013 		 * variables can be: ENV_FLG_
2014 		 * 	AUDIT_ARGS, BINDING, CONCURRENCY, CONFGEN,
2015 		 *	LOADFLTR, PROFILE, SIGNAL, TRACE_OBJS
2016 		 */
2017 		if (variable == ENV_FLG_AUDIT_ARGS) {
2018 			if (s2) {
2019 				audit_argcnt = atoi(s2);
2020 				audit_argcnt += audit_argcnt % 2;
2021 			} else
2022 				audit_argcnt = 0;
2023 		} else if (variable == ENV_FLG_BINDINGS) {
2024 			if (s2)
2025 				rpl_debug = MSG_ORIG(MSG_TKN_BINDINGS);
2026 			else
2027 				rpl_debug = 0;
2028 		} else if (variable == ENV_FLG_CONCURRENCY) {
2029 			if (s2)
2030 				rtld_flags &= ~RT_FL_NOCONCUR;
2031 			else
2032 				rtld_flags |= RT_FL_NOCONCUR;
2033 		} else if (variable == ENV_FLG_CONFGEN) {
2034 			if (s2) {
2035 				rtld_flags |= RT_FL_CONFGEN;
2036 				*lmflags |= LML_FLG_IGNRELERR;
2037 			} else {
2038 				rtld_flags &= ~RT_FL_CONFGEN;
2039 				*lmflags &= ~LML_FLG_IGNRELERR;
2040 			}
2041 		} else if (variable == ENV_FLG_LOADFLTR) {
2042 			if (s2) {
2043 				*lmtflags |= LML_TFLG_LOADFLTR;
2044 				if (*s2 == '2')
2045 					rtld_flags |= RT_FL_WARNFLTR;
2046 			} else {
2047 				*lmtflags &= ~LML_TFLG_LOADFLTR;
2048 				rtld_flags &= ~RT_FL_WARNFLTR;
2049 			}
2050 		} else if (variable == ENV_FLG_PROFILE) {
2051 			profile_name = s2;
2052 			if (s2) {
2053 				if (strcmp(s2, MSG_ORIG(MSG_FIL_RTLD)) == 0) {
2054 					return;
2055 				}
2056 				/* BEGIN CSTYLED */
2057 				if (rtld_flags & RT_FL_SECURE) {
2058 					profile_lib =
2059 #if	defined(_ELF64)
2060 					    MSG_ORIG(MSG_PTH_LDPROFSE_64);
2061 #else
2062 					    MSG_ORIG(MSG_PTH_LDPROFSE);
2063 #endif
2064 				} else {
2065 					profile_lib =
2066 #if	defined(_ELF64)
2067 					    MSG_ORIG(MSG_PTH_LDPROF_64);
2068 #else
2069 					    MSG_ORIG(MSG_PTH_LDPROF);
2070 #endif
2071 				}
2072 				/* END CSTYLED */
2073 			} else
2074 				profile_lib = 0;
2075 		} else if (variable == ENV_FLG_SIGNAL) {
2076 			killsig = s2 ? atoi(s2) : SIGKILL;
2077 		} else if (variable == ENV_FLG_TRACE_OBJS) {
2078 			if (s2) {
2079 				*lmflags |= LML_FLG_TRC_ENABLE;
2080 				if (*s2 == '2')
2081 					*lmflags |= LML_FLG_TRC_LDDSTUB;
2082 			} else
2083 				*lmflags &=
2084 				    ~(LML_FLG_TRC_ENABLE|LML_FLG_TRC_LDDSTUB);
2085 		}
2086 	}
2087 }
2088 
2089 /*
2090  * Determine whether we have an architecture specific environment variable.
2091  * If we do, and we're the wrong architecture, it'll just get ignored.
2092  * Otherwise the variable is processed in it's architecture neutral form.
2093  */
2094 static int
2095 ld_arch_env(const char *s1, size_t *len)
2096 {
2097 	size_t	_len = *len - 3;
2098 
2099 	if (s1[_len++] == '_') {
2100 		if ((s1[_len] == '3') && (s1[_len + 1] == '2')) {
2101 #if	defined(_ELF64)
2102 			return (ENV_TYP_IGNORE);
2103 #else
2104 			*len = *len - 3;
2105 			return (ENV_TYP_ISA);
2106 #endif
2107 		}
2108 		if ((s1[_len] == '6') && (s1[_len + 1] == '4')) {
2109 #if	defined(_ELF64)
2110 			*len = *len - 3;
2111 			return (ENV_TYP_ISA);
2112 #else
2113 			return (ENV_TYP_IGNORE);
2114 #endif
2115 		}
2116 	}
2117 	return (0);
2118 }
2119 
2120 
2121 /*
2122  * Process an LD_FLAGS environment variable.  The value can be a comma
2123  * separated set of tokens, which are sent (in upper case) into the generic
2124  * LD_XXXX environment variable engine.  For example:
2125  *
2126  *	LD_FLAGS=bind_now		->	LD_BIND_NOW=1
2127  *	LD_FLAGS=library_path=/foo:.	->	LD_LIBRARY_PATH=/foo:.
2128  *	LD_FLAGS=debug=files:detail	->	LD_DEBUG=files:detail
2129  * or
2130  *	LD_FLAGS=bind_now,library_path=/foo:.,debug=files:detail
2131  */
2132 static int
2133 ld_flags_env(const char *str, Word *lmflags, Word *lmtflags,
2134     uint_t env_flags, int aout)
2135 {
2136 	char	*nstr, *sstr, *estr = 0;
2137 	size_t	nlen, len;
2138 
2139 	if (str == 0)
2140 		return (0);
2141 
2142 	/*
2143 	 * Create a new string as we're going to transform the token(s) into
2144 	 * uppercase and separate tokens with nulls.
2145 	 */
2146 	len = strlen(str);
2147 	if ((nstr = malloc(len + 1)) == 0)
2148 		return (1);
2149 	(void) strcpy(nstr, str);
2150 
2151 	for (sstr = nstr; sstr; sstr++, len--) {
2152 		int	flags;
2153 
2154 		if ((*sstr != '\0') && (*sstr != ',')) {
2155 			if (estr == 0) {
2156 				if (*sstr == '=')
2157 					estr = sstr;
2158 				else {
2159 					/*
2160 					 * Translate token to uppercase.  Don't
2161 					 * use toupper(3C) as including this
2162 					 * code doubles the size of ld.so.1.
2163 					 */
2164 					if ((*sstr >= 'a') && (*sstr <= 'z'))
2165 						*sstr = *sstr - ('a' - 'A');
2166 				}
2167 			}
2168 			continue;
2169 		}
2170 
2171 		*sstr = '\0';
2172 		if (estr) {
2173 			nlen = estr - nstr;
2174 			if ((*++estr == '\0') || (*estr == ','))
2175 				estr = 0;
2176 		} else
2177 			nlen = sstr - nstr;
2178 
2179 		/*
2180 		 * Fabricate a boolean definition for any unqualified variable.
2181 		 * Thus LD_FLAGS=bind_now is represented as BIND_NOW=(null).
2182 		 * The value is sufficient to assert any boolean variables, plus
2183 		 * the term "(null)" is specifically chosen in case someone
2184 		 * mistakenly supplies something like LD_FLAGS=library_path.
2185 		 */
2186 		if (estr == 0)
2187 			estr = (char *)MSG_INTL(MSG_STR_NULL);
2188 
2189 		/*
2190 		 * Determine whether the environment variable is 32- or 64-bit
2191 		 * specific.  The length, len, will reflect the architecture
2192 		 * neutral portion of the string.
2193 		 */
2194 		if ((flags = ld_arch_env(nstr, &nlen)) != ENV_TYP_IGNORE) {
2195 			ld_generic_env(nstr, nlen, estr, lmflags,
2196 			    lmtflags, (env_flags | flags), aout);
2197 		}
2198 		if (len == 0)
2199 			return (0);
2200 
2201 		nstr = sstr + 1;
2202 		estr = 0;
2203 	}
2204 	return (0);
2205 }
2206 
2207 
2208 /*
2209  * Process a single environment string.  Only strings starting with `LD_' are
2210  * reserved for our use.  By convention, all strings should be of the form
2211  * `LD_XXXX=', if the string is followed by a non-null value the appropriate
2212  * functionality is enabled.  Also pick off applicable locale variables.
2213  */
2214 #define	LOC_LANG	1
2215 #define	LOC_MESG	2
2216 #define	LOC_ALL		3
2217 
2218 static void
2219 ld_str_env(const char *s1, Word *lmflags, Word *lmtflags, uint_t env_flags,
2220     int aout)
2221 {
2222 	const char	*s2;
2223 	static		size_t	loc = 0;
2224 
2225 	if (*s1++ != 'L')
2226 		return;
2227 
2228 	/*
2229 	 * See if we have any locale environment settings.  These environment
2230 	 * variables have a precedence, LC_ALL is higher than LC_MESSAGES which
2231 	 * is higher than LANG.
2232 	 */
2233 	s2 = s1;
2234 	if ((*s2++ == 'C') && (*s2++ == '_') && (*s2 != '\0')) {
2235 		if (strncmp(s2, MSG_ORIG(MSG_LC_ALL), MSG_LC_ALL_SIZE) == 0) {
2236 			s2 += MSG_LC_ALL_SIZE;
2237 			if ((*s2 != '\0') && (loc < LOC_ALL)) {
2238 				glcs[CI_LCMESSAGES].lc_un.lc_ptr = (char *)s2;
2239 				loc = LOC_ALL;
2240 			}
2241 		} else if (strncmp(s2, MSG_ORIG(MSG_LC_MESSAGES),
2242 		    MSG_LC_MESSAGES_SIZE) == 0) {
2243 			s2 += MSG_LC_MESSAGES_SIZE;
2244 			if ((*s2 != '\0') && (loc < LOC_MESG)) {
2245 				glcs[CI_LCMESSAGES].lc_un.lc_ptr = (char *)s2;
2246 				loc = LOC_MESG;
2247 			}
2248 		}
2249 		return;
2250 	}
2251 
2252 	s2 = s1;
2253 	if ((*s2++ == 'A') && (*s2++ == 'N') && (*s2++ == 'G') &&
2254 	    (*s2++ == '=') && (*s2 != '\0') && (loc < LOC_LANG)) {
2255 		glcs[CI_LCMESSAGES].lc_un.lc_ptr = (char *)s2;
2256 		loc = LOC_LANG;
2257 		return;
2258 	}
2259 
2260 	/*
2261 	 * Pick off any LD_XXXX environment variables.
2262 	 */
2263 	if ((*s1++ == 'D') && (*s1++ == '_') && (*s1 != '\0')) {
2264 		size_t	len;
2265 		int	flags;
2266 
2267 		/*
2268 		 * In a branded process we must ignore all LD_XXXX env vars
2269 		 * because they are intended for the brand's linker.
2270 		 * To affect the Solaris linker, use LD_BRAND_XXXX instead.
2271 		 */
2272 		if (rtld_flags2 & RT_FL2_BRANDED) {
2273 			if (strncmp(s1, MSG_ORIG(MSG_LD_BRAND_PREFIX),
2274 			    MSG_LD_BRAND_PREFIX_SIZE) != 0)
2275 				return;
2276 			s1 += MSG_LD_BRAND_PREFIX_SIZE;
2277 		}
2278 
2279 		/*
2280 		 * Environment variables with no value (ie. LD_XXXX=) typically
2281 		 * have no impact, however if environment variables are defined
2282 		 * within a configuration file, these null user settings can be
2283 		 * used to disable any configuration replaceable definitions.
2284 		 */
2285 		if ((s2 = strchr(s1, '=')) == 0) {
2286 			len = strlen(s1);
2287 			s2 = 0;
2288 		} else if (*++s2 == '\0') {
2289 			len = strlen(s1) - 1;
2290 			s2 = 0;
2291 		} else {
2292 			len = s2 - s1 - 1;
2293 			while (isspace(*s2))
2294 				s2++;
2295 		}
2296 
2297 		/*
2298 		 * Determine whether the environment variable is 32- or 64-bit
2299 		 * specific.  The length, len, will reflect the architecture
2300 		 * neutral portion of the string.
2301 		 */
2302 		if ((flags = ld_arch_env(s1, &len)) == ENV_TYP_IGNORE)
2303 			return;
2304 		env_flags |= flags;
2305 
2306 		ld_generic_env(s1, len, s2, lmflags, lmtflags, env_flags, aout);
2307 	}
2308 }
2309 
2310 /*
2311  * Internal getenv routine.  Called immediately after ld.so.1 initializes
2312  * itself.
2313  */
2314 int
2315 readenv_user(const char ** envp, Word *lmflags, Word *lmtflags, int aout)
2316 {
2317 	char	*locale;
2318 
2319 	if (envp == (const char **)0)
2320 		return (0);
2321 
2322 	while (*envp != (const char *)0)
2323 		ld_str_env(*envp++, lmflags, lmtflags, 0, aout);
2324 
2325 	/*
2326 	 * Having collected the best representation of any LD_FLAGS, process
2327 	 * these strings.
2328 	 */
2329 	if (ld_flags_env(rpl_ldflags, lmflags, lmtflags, 0, aout) == 1)
2330 		return (1);
2331 
2332 	/*
2333 	 * Don't allow environment controlled auditing when tracing or if
2334 	 * explicitly disabled.  Trigger all tracing modes from
2335 	 * LML_FLG_TRC_ENABLE.
2336 	 */
2337 	if ((*lmflags & LML_FLG_TRC_ENABLE) || (rtld_flags & RT_FL_NOAUDIT))
2338 		rpl_audit = profile_lib = profile_name = 0;
2339 	if ((*lmflags & LML_FLG_TRC_ENABLE) == 0)
2340 		*lmflags &= ~LML_MSK_TRC;
2341 
2342 	/*
2343 	 * If both LD_BIND_NOW and LD_BIND_LAZY are specified, the former wins.
2344 	 */
2345 	if ((rtld_flags2 & (RT_FL2_BINDNOW | RT_FL2_BINDLAZY)) ==
2346 	    (RT_FL2_BINDNOW | RT_FL2_BINDLAZY))
2347 		rtld_flags2 &= ~RT_FL2_BINDLAZY;
2348 
2349 	/*
2350 	 * When using ldd(1) -r or -d against an executable, assert -p.
2351 	 */
2352 	if ((*lmflags &
2353 	    (LML_FLG_TRC_WARN | LML_FLG_TRC_LDDSTUB)) == LML_FLG_TRC_WARN)
2354 		*lmflags |= LML_FLG_TRC_NOPAREXT;
2355 
2356 	/*
2357 	 * If we have a locale setting make sure its worth processing further.
2358 	 * C and POSIX locales don't need any processing.  In addition, to
2359 	 * ensure no one escapes the /usr/lib/locale hierarchy, don't allow
2360 	 * the locale to contain a segment that leads upward in the file system
2361 	 * hierarchy (i.e. no '..' segments).   Given that we'll be confined to
2362 	 * the /usr/lib/locale hierarchy, there is no need to extensively
2363 	 * validate the mode or ownership of any message file (as libc's
2364 	 * generic handling of message files does).  Duplicate the string so
2365 	 * that new locale setting can generically cleanup any previous locales.
2366 	 */
2367 	if ((locale = glcs[CI_LCMESSAGES].lc_un.lc_ptr) != 0) {
2368 		if (((*locale == 'C') && (*(locale + 1) == '\0')) ||
2369 		    (strcmp(locale, MSG_ORIG(MSG_TKN_POSIX)) == 0) ||
2370 		    (strstr(locale, MSG_ORIG(MSG_TKN_DOTDOT)) != NULL))
2371 			glcs[CI_LCMESSAGES].lc_un.lc_ptr = 0;
2372 		else
2373 			glcs[CI_LCMESSAGES].lc_un.lc_ptr = strdup(locale);
2374 	}
2375 	return (0);
2376 }
2377 
2378 /*
2379  * Configuration environment processing.  Called after the a.out has been
2380  * processed (as the a.out can specify its own configuration file).
2381  */
2382 int
2383 readenv_config(Rtc_env * envtbl, Addr addr, int aout)
2384 {
2385 	Word	*lmflags = &(lml_main.lm_flags);
2386 	Word	*lmtflags = &(lml_main.lm_tflags);
2387 
2388 	if (envtbl == (Rtc_env *)0)
2389 		return (0);
2390 
2391 	while (envtbl->env_str) {
2392 		uint_t	env_flags = ENV_TYP_CONFIG;
2393 
2394 		if (envtbl->env_flags & RTC_ENV_PERMANT)
2395 			env_flags |= ENV_TYP_PERMANT;
2396 
2397 		ld_str_env((const char *)(envtbl->env_str + addr),
2398 		    lmflags, lmtflags, env_flags, 0);
2399 		envtbl++;
2400 	}
2401 
2402 	/*
2403 	 * Having collected the best representation of any LD_FLAGS, process
2404 	 * these strings.
2405 	 */
2406 	if (ld_flags_env(rpl_ldflags, lmflags, lmtflags, 0, aout) == 1)
2407 		return (1);
2408 	if (ld_flags_env(prm_ldflags, lmflags, lmtflags, ENV_TYP_CONFIG,
2409 	    aout) == 1)
2410 		return (1);
2411 
2412 	/*
2413 	 * Don't allow environment controlled auditing when tracing or if
2414 	 * explicitly disabled.  Trigger all tracing modes from
2415 	 * LML_FLG_TRC_ENABLE.
2416 	 */
2417 	if ((*lmflags & LML_FLG_TRC_ENABLE) || (rtld_flags & RT_FL_NOAUDIT))
2418 		prm_audit = profile_lib = profile_name = 0;
2419 	if ((*lmflags & LML_FLG_TRC_ENABLE) == 0)
2420 		*lmflags &= ~LML_MSK_TRC;
2421 
2422 	return (0);
2423 }
2424 
2425 int
2426 dowrite(Prfbuf * prf)
2427 {
2428 	/*
2429 	 * We do not have a valid file descriptor, so we are unable
2430 	 * to flush the buffer.
2431 	 */
2432 	if (prf->pr_fd == -1)
2433 		return (0);
2434 	(void) write(prf->pr_fd, prf->pr_buf, prf->pr_cur - prf->pr_buf);
2435 	prf->pr_cur = prf->pr_buf;
2436 	return (1);
2437 }
2438 
2439 /*
2440  * Simplified printing.  The following conversion specifications are supported:
2441  *
2442  *	% [#] [-] [min field width] [. precision] s|d|x|c
2443  *
2444  *
2445  * dorprf takes the output buffer in the form of Prfbuf which permits
2446  * the verification of the output buffer size and the concatenation
2447  * of data to an already existing output buffer.  The Prfbuf
2448  * structure contains the following:
2449  *
2450  *  pr_buf	pointer to the beginning of the output buffer.
2451  *  pr_cur	pointer to the next available byte in the output buffer.  By
2452  *		setting pr_cur ahead of pr_buf you can append to an already
2453  *		existing buffer.
2454  *  pr_len	the size of the output buffer.  By setting pr_len to '0' you
2455  *		disable protection from overflows in the output buffer.
2456  *  pr_fd	a pointer to the file-descriptor the buffer will eventually be
2457  *		output to.  If pr_fd is set to '-1' then it's assumed there is
2458  *		no output buffer, and doprf() will return with an error to
2459  *		indicate an output buffer overflow.  If pr_fd is > -1 then when
2460  *		the output buffer is filled it will be flushed to pr_fd and will
2461  *		then be	available for additional data.
2462  */
2463 #define	FLG_UT_MINUS	0x0001	/* - */
2464 #define	FLG_UT_SHARP	0x0002	/* # */
2465 #define	FLG_UT_DOTSEEN	0x0008	/* dot appeared in format spec */
2466 
2467 /*
2468  * This macro is for use from within doprf only.  It is to be used for checking
2469  * the output buffer size and placing characters into the buffer.
2470  */
2471 #define	PUTC(c) \
2472 	{ \
2473 		char tmpc; \
2474 		\
2475 		tmpc = (c); \
2476 		if (bufsiz && (bp >= bufend)) { \
2477 			prf->pr_cur = bp; \
2478 			if (dowrite(prf) == 0) \
2479 				return (0); \
2480 			bp = prf->pr_cur; \
2481 		} \
2482 		*bp++ = tmpc; \
2483 	}
2484 
2485 /*
2486  * Define a local buffer size for building a numeric value - large enough to
2487  * hold a 64-bit value.
2488  */
2489 #define	NUM_SIZE	22
2490 
2491 size_t
2492 doprf(const char *format, va_list args, Prfbuf *prf)
2493 {
2494 	char	c;
2495 	char	*bp = prf->pr_cur;
2496 	char	*bufend = prf->pr_buf + prf->pr_len;
2497 	size_t	bufsiz = prf->pr_len;
2498 
2499 	while ((c = *format++) != '\0') {
2500 		if (c != '%') {
2501 			PUTC(c);
2502 		} else {
2503 			int	base = 0, flag = 0, width = 0, prec = 0;
2504 			size_t	_i;
2505 			int	_c, _n;
2506 			char	*_s;
2507 			int	ls = 0;
2508 again:
2509 			c = *format++;
2510 			switch (c) {
2511 			case '-':
2512 				flag |= FLG_UT_MINUS;
2513 				goto again;
2514 			case '#':
2515 				flag |= FLG_UT_SHARP;
2516 				goto again;
2517 			case '.':
2518 				flag |= FLG_UT_DOTSEEN;
2519 				goto again;
2520 			case '0':
2521 			case '1':
2522 			case '2':
2523 			case '3':
2524 			case '4':
2525 			case '5':
2526 			case '6':
2527 			case '7':
2528 			case '8':
2529 			case '9':
2530 				if (flag & FLG_UT_DOTSEEN)
2531 					prec = (prec * 10) + c - '0';
2532 				else
2533 					width = (width * 10) + c - '0';
2534 				goto again;
2535 			case 'x':
2536 			case 'X':
2537 				base = 16;
2538 				break;
2539 			case 'd':
2540 			case 'D':
2541 			case 'u':
2542 				base = 10;
2543 				flag &= ~FLG_UT_SHARP;
2544 				break;
2545 			case 'l':
2546 				base = 10;
2547 				ls++; /* number of l's (long or long long) */
2548 				if ((*format == 'l') ||
2549 				    (*format == 'd') || (*format == 'D') ||
2550 				    (*format == 'x') || (*format == 'X') ||
2551 				    (*format == 'o') || (*format == 'O'))
2552 					goto again;
2553 				break;
2554 			case 'o':
2555 			case 'O':
2556 				base = 8;
2557 				break;
2558 			case 'c':
2559 				_c = va_arg(args, int);
2560 
2561 				for (_i = 24; _i > 0; _i -= 8) {
2562 					if ((c = ((_c >> _i) & 0x7f)) != 0) {
2563 						PUTC(c);
2564 					}
2565 				}
2566 				if ((c = ((_c >> _i) & 0x7f)) != 0) {
2567 					PUTC(c);
2568 				}
2569 				break;
2570 			case 's':
2571 				_s = va_arg(args, char *);
2572 				_i = strlen(_s);
2573 				/* LINTED */
2574 				_n = (int)(width - _i);
2575 				if (!prec)
2576 					/* LINTED */
2577 					prec = (int)_i;
2578 
2579 				if (width && !(flag & FLG_UT_MINUS)) {
2580 					while (_n-- > 0)
2581 						PUTC(' ');
2582 				}
2583 				while (((c = *_s++) != 0) && prec--) {
2584 					PUTC(c);
2585 				}
2586 				if (width && (flag & FLG_UT_MINUS)) {
2587 					while (_n-- > 0)
2588 						PUTC(' ');
2589 				}
2590 				break;
2591 			case '%':
2592 				PUTC('%');
2593 				break;
2594 			default:
2595 				break;
2596 			}
2597 
2598 			/*
2599 			 * Numeric processing
2600 			 */
2601 			if (base) {
2602 				char		local[NUM_SIZE];
2603 				size_t		ssize = 0, psize = 0;
2604 				const char	*string =
2605 				    MSG_ORIG(MSG_STR_HEXNUM);
2606 				const char	*prefix =
2607 				    MSG_ORIG(MSG_STR_EMPTY);
2608 				u_longlong_t	num;
2609 
2610 				switch (ls) {
2611 				case 0:	/* int */
2612 					num = (u_longlong_t)
2613 					    va_arg(args, uint_t);
2614 					break;
2615 				case 1:	/* long */
2616 					num = (u_longlong_t)
2617 					    va_arg(args, ulong_t);
2618 					break;
2619 				case 2:	/* long long */
2620 					num = va_arg(args, u_longlong_t);
2621 					break;
2622 				}
2623 
2624 				if (flag & FLG_UT_SHARP) {
2625 					if (base == 16) {
2626 						prefix = MSG_ORIG(MSG_STR_HEX);
2627 						psize = 2;
2628 					} else {
2629 						prefix = MSG_ORIG(MSG_STR_ZERO);
2630 						psize = 1;
2631 					}
2632 				}
2633 				if ((base == 10) && (long)num < 0) {
2634 					prefix = MSG_ORIG(MSG_STR_NEGATE);
2635 					psize = MSG_STR_NEGATE_SIZE;
2636 					num = (u_longlong_t)(-(longlong_t)num);
2637 				}
2638 
2639 				/*
2640 				 * Convert the numeric value into a local
2641 				 * string (stored in reverse order).
2642 				 */
2643 				_s = local;
2644 				do {
2645 					*_s++ = string[num % base];
2646 					num /= base;
2647 					ssize++;
2648 				} while (num);
2649 
2650 				ASSERT(ssize < sizeof (local));
2651 
2652 				/*
2653 				 * Provide any precision or width padding.
2654 				 */
2655 				if (prec) {
2656 					/* LINTED */
2657 					_n = (int)(prec - ssize);
2658 					while ((_n-- > 0) &&
2659 					    (ssize < sizeof (local))) {
2660 						*_s++ = '0';
2661 						ssize++;
2662 					}
2663 				}
2664 				if (width && !(flag & FLG_UT_MINUS)) {
2665 					/* LINTED */
2666 					_n = (int)(width - ssize - psize);
2667 					while (_n-- > 0) {
2668 						PUTC(' ');
2669 					}
2670 				}
2671 
2672 				/*
2673 				 * Print any prefix and the numeric string
2674 				 */
2675 				while (*prefix)
2676 					PUTC(*prefix++);
2677 				do {
2678 					PUTC(*--_s);
2679 				} while (_s > local);
2680 
2681 				/*
2682 				 * Provide any width padding.
2683 				 */
2684 				if (width && (flag & FLG_UT_MINUS)) {
2685 					/* LINTED */
2686 					_n = (int)(width - ssize - psize);
2687 					while (_n-- > 0)
2688 						PUTC(' ');
2689 				}
2690 			}
2691 		}
2692 	}
2693 
2694 	PUTC('\0');
2695 	prf->pr_cur = bp;
2696 	return (1);
2697 }
2698 
2699 static int
2700 doprintf(const char *format, va_list args, Prfbuf *prf)
2701 {
2702 	char	*ocur = prf->pr_cur;
2703 
2704 	if (doprf(format, args, prf) == 0)
2705 		return (0);
2706 	/* LINTED */
2707 	return ((int)(prf->pr_cur - ocur));
2708 }
2709 
2710 /* VARARGS2 */
2711 int
2712 sprintf(char *buf, const char *format, ...)
2713 {
2714 	va_list	args;
2715 	int	len;
2716 	Prfbuf	prf;
2717 
2718 	va_start(args, format);
2719 	prf.pr_buf = prf.pr_cur = buf;
2720 	prf.pr_len = 0;
2721 	prf.pr_fd = -1;
2722 	len = doprintf(format, args, &prf);
2723 	va_end(args);
2724 
2725 	/*
2726 	 * sprintf() return value excludes the terminating null byte.
2727 	 */
2728 	return (len - 1);
2729 }
2730 
2731 /* VARARGS3 */
2732 int
2733 snprintf(char *buf, size_t n, const char *format, ...)
2734 {
2735 	va_list	args;
2736 	int	len;
2737 	Prfbuf	prf;
2738 
2739 	va_start(args, format);
2740 	prf.pr_buf = prf.pr_cur = buf;
2741 	prf.pr_len = n;
2742 	prf.pr_fd = -1;
2743 	len = doprintf(format, args, &prf);
2744 	va_end(args);
2745 
2746 	return (len);
2747 }
2748 
2749 /* VARARGS2 */
2750 int
2751 bufprint(Prfbuf *prf, const char *format, ...)
2752 {
2753 	va_list	args;
2754 	int	len;
2755 
2756 	va_start(args, format);
2757 	len = doprintf(format, args, prf);
2758 	va_end(args);
2759 
2760 	return (len);
2761 }
2762 
2763 /*PRINTFLIKE1*/
2764 int
2765 printf(const char *format, ...)
2766 {
2767 	va_list	args;
2768 	char 	buffer[ERRSIZE];
2769 	Prfbuf	prf;
2770 
2771 	va_start(args, format);
2772 	prf.pr_buf = prf.pr_cur = buffer;
2773 	prf.pr_len = ERRSIZE;
2774 	prf.pr_fd = 1;
2775 	(void) doprf(format, args, &prf);
2776 	va_end(args);
2777 	/*
2778 	 * Trim trailing '\0' form buffer
2779 	 */
2780 	prf.pr_cur--;
2781 	return (dowrite(&prf));
2782 }
2783 
2784 static char	errbuf[ERRSIZE], *nextptr = errbuf, *prevptr = 0;
2785 
2786 /*PRINTFLIKE3*/
2787 void
2788 eprintf(Lm_list *lml, Error error, const char *format, ...)
2789 {
2790 	va_list		args;
2791 	int		overflow = 0;
2792 	static int	lock = 0;
2793 	Prfbuf		prf;
2794 
2795 	if (lock || (nextptr == (errbuf + ERRSIZE)))
2796 		return;
2797 
2798 	/*
2799 	 * Note: this lock is here to prevent the same thread from recursively
2800 	 * entering itself during a eprintf.  ie: during eprintf malloc() fails
2801 	 * and we try and call eprintf ... and then malloc() fails ....
2802 	 */
2803 	lock = 1;
2804 
2805 	/*
2806 	 * If we have completed startup initialization, all error messages
2807 	 * must be saved.  These are reported through dlerror().  If we're
2808 	 * still in the initialization stage, output the error directly and
2809 	 * add a newline.
2810 	 */
2811 	va_start(args, format);
2812 
2813 	prf.pr_buf = prf.pr_cur = nextptr;
2814 	prf.pr_len = ERRSIZE - (nextptr - errbuf);
2815 
2816 	if (!(rtld_flags & RT_FL_APPLIC))
2817 		prf.pr_fd = 2;
2818 	else
2819 		prf.pr_fd = -1;
2820 
2821 	if (error > ERR_NONE) {
2822 		if ((error == ERR_FATAL) && (rtld_flags2 & RT_FL2_FTL2WARN))
2823 			error = ERR_WARNING;
2824 		if (error == ERR_WARNING) {
2825 			if (err_strs[ERR_WARNING] == 0)
2826 				err_strs[ERR_WARNING] =
2827 				    MSG_INTL(MSG_ERR_WARNING);
2828 		} else if (error == ERR_FATAL) {
2829 			if (err_strs[ERR_FATAL] == 0)
2830 				err_strs[ERR_FATAL] = MSG_INTL(MSG_ERR_FATAL);
2831 		} else if (error == ERR_ELF) {
2832 			if (err_strs[ERR_ELF] == 0)
2833 				err_strs[ERR_ELF] = MSG_INTL(MSG_ERR_ELF);
2834 		}
2835 		if (procname) {
2836 			if (bufprint(&prf, MSG_ORIG(MSG_STR_EMSGFOR1),
2837 			    rtldname, procname, err_strs[error]) == 0)
2838 				overflow = 1;
2839 		} else {
2840 			if (bufprint(&prf, MSG_ORIG(MSG_STR_EMSGFOR2),
2841 			    rtldname, err_strs[error]) == 0)
2842 				overflow = 1;
2843 		}
2844 		if (overflow == 0) {
2845 			/*
2846 			 * Remove the terminating '\0'.
2847 			 */
2848 			prf.pr_cur--;
2849 		}
2850 	}
2851 
2852 	if ((overflow == 0) && doprf(format, args, &prf) == 0)
2853 		overflow = 1;
2854 
2855 	/*
2856 	 * If this is an ELF error, it will have been generated by a support
2857 	 * object that has a dependency on libelf.  ld.so.1 doesn't generate any
2858 	 * ELF error messages as it doesn't interact with libelf.  Determine the
2859 	 * ELF error string.
2860 	 */
2861 	if ((overflow == 0) && (error == ERR_ELF)) {
2862 		static int		(*elfeno)() = 0;
2863 		static const char	*(*elfemg)();
2864 		const char		*emsg;
2865 		Rt_map			*dlmp, *lmp = lml_rtld.lm_head;
2866 
2867 		if (NEXT(lmp) && (elfeno == 0)) {
2868 			if (((elfemg = (const char *(*)())dlsym_intn(RTLD_NEXT,
2869 			    MSG_ORIG(MSG_SYM_ELFERRMSG), lmp, &dlmp)) == 0) ||
2870 			    ((elfeno = (int (*)())dlsym_intn(RTLD_NEXT,
2871 			    MSG_ORIG(MSG_SYM_ELFERRNO), lmp, &dlmp)) == 0))
2872 				elfeno = 0;
2873 		}
2874 
2875 		/*
2876 		 * Lookup the message; equivalent to elf_errmsg(elf_errno()).
2877 		 */
2878 		if (elfeno && ((emsg = (* elfemg)((* elfeno)())) != 0)) {
2879 			prf.pr_cur--;
2880 			if (bufprint(&prf, MSG_ORIG(MSG_STR_EMSGFOR2),
2881 			    emsg) == 0)
2882 				overflow = 1;
2883 		}
2884 	}
2885 
2886 	/*
2887 	 * Push out any message that's been built.  Note, in the case of an
2888 	 * overflow condition, this message may be incomplete, in which case
2889 	 * make sure any partial string is null terminated.
2890 	 */
2891 	if (overflow)
2892 		*(prf.pr_cur) = '\0';
2893 	if ((rtld_flags & (RT_FL_APPLIC | RT_FL_SILENCERR)) == 0) {
2894 		*(prf.pr_cur - 1) = '\n';
2895 		(void) dowrite(&prf);
2896 	}
2897 
2898 	DBG_CALL(Dbg_util_str(lml, nextptr));
2899 	va_end(args);
2900 
2901 	/*
2902 	 * Determine if there was insufficient space left in the buffer to
2903 	 * complete the message.  If so, we'll have printed out as much as had
2904 	 * been processed if we're not yet executing the application.
2905 	 * Otherwise, there will be some debugging diagnostic indicating
2906 	 * as much of the error message as possible.  Write out a final buffer
2907 	 * overflow diagnostic - unlocalized, so we don't chance more errors.
2908 	 */
2909 	if (overflow) {
2910 		char	*str = (char *)MSG_INTL(MSG_EMG_BUFOVRFLW);
2911 
2912 		if ((rtld_flags & RT_FL_SILENCERR) == 0) {
2913 			lasterr = str;
2914 
2915 			if ((rtld_flags & RT_FL_APPLIC) == 0) {
2916 				(void) write(2, str, strlen(str));
2917 				(void) write(2, MSG_ORIG(MSG_STR_NL),
2918 				    MSG_STR_NL_SIZE);
2919 			}
2920 		}
2921 		DBG_CALL(Dbg_util_str(lml, str));
2922 
2923 		lock = 0;
2924 		nextptr = errbuf + ERRSIZE;
2925 		return;
2926 	}
2927 
2928 	/*
2929 	 * If the application has started, then error messages are being saved
2930 	 * for retrieval by dlerror(), or possible flushing from rtldexit() in
2931 	 * the case of a fatal error.  In this case, establish the next error
2932 	 * pointer.  If we haven't started the application, the whole message
2933 	 * buffer can be reused.
2934 	 */
2935 	if ((rtld_flags & RT_FL_SILENCERR) == 0) {
2936 		lasterr = nextptr;
2937 
2938 		/*
2939 		 * Note, should we encounter an error such as ENOMEM, there may
2940 		 * be a number of the same error messages (ie. an operation
2941 		 * fails with ENOMEM, and then the attempts to construct the
2942 		 * error message itself, which incurs additional ENOMEM errors).
2943 		 * Compare any previous error message with the one we've just
2944 		 * created to prevent any duplication clutter.
2945 		 */
2946 		if ((rtld_flags & RT_FL_APPLIC) &&
2947 		    ((prevptr == 0) || (strcmp(prevptr, nextptr) != 0))) {
2948 			prevptr = nextptr;
2949 			nextptr = prf.pr_cur;
2950 			*nextptr = '\0';
2951 		}
2952 	}
2953 	lock = 0;
2954 }
2955 
2956 
2957 #if	DEBUG
2958 /*
2959  * Provide assfail() for ASSERT() statements,
2960  * see <sys/debug.h> for further details.
2961  */
2962 int
2963 assfail(const char *a, const char *f, int l)
2964 {
2965 	(void) printf("assertion failed: %s, file: %s, line: %d\n", a, f, l);
2966 	(void) _lwp_kill(_lwp_self(), SIGABRT);
2967 	return (0);
2968 }
2969 #endif
2970 
2971 /*
2972  * Exit.  If we arrive here with a non zero status it's because of a fatal
2973  * error condition (most commonly a relocation error).  If the application has
2974  * already had control, then the actual fatal error message will have been
2975  * recorded in the dlerror() message buffer.  Print the message before really
2976  * exiting.
2977  */
2978 void
2979 rtldexit(Lm_list * lml, int status)
2980 {
2981 	if (status) {
2982 		if (rtld_flags & RT_FL_APPLIC) {
2983 			/*
2984 			 * If the error buffer has been used, write out all
2985 			 * pending messages - lasterr is simply a pointer to
2986 			 * the last message in this buffer.  However, if the
2987 			 * buffer couldn't be created at all, lasterr points
2988 			 * to a constant error message string.
2989 			 */
2990 			if (*errbuf) {
2991 				char	*errptr = errbuf;
2992 				char	*errend = errbuf + ERRSIZE;
2993 
2994 				while ((errptr < errend) && *errptr) {
2995 					size_t	size = strlen(errptr);
2996 					(void) write(2, errptr, size);
2997 					(void) write(2, MSG_ORIG(MSG_STR_NL),
2998 					    MSG_STR_NL_SIZE);
2999 					errptr += (size + 1);
3000 				}
3001 			}
3002 			if (lasterr && ((lasterr < errbuf) ||
3003 			    (lasterr > (errbuf + ERRSIZE)))) {
3004 				(void) write(2, lasterr, strlen(lasterr));
3005 				(void) write(2, MSG_ORIG(MSG_STR_NL),
3006 				    MSG_STR_NL_SIZE);
3007 			}
3008 		}
3009 		leave(lml, 0);
3010 		(void) _lwp_kill(_lwp_self(), killsig);
3011 	}
3012 	_exit(status);
3013 }
3014 
3015 /*
3016  * Routines to co-ordinate the opening of /dev/zero and /proc.
3017  * dz_fd is exported for possible use by libld.so, and to insure it gets
3018  * closed on leaving ld.so.1.
3019  */
3020 int	dz_fd = FD_UNAVAIL;
3021 
3022 void
3023 dz_init(int fd)
3024 {
3025 	dz_fd = fd;
3026 }
3027 
3028 
3029 /*
3030  * mmap() a page from MAP_ANON
3031  *
3032  * Note: MAP_ANON is only on Solaris8++, we use this routine to
3033  *       not only mmap(MAP_ANON) but to also probe if it is available
3034  *	 on the current OS.
3035  */
3036 Am_ret
3037 anon_map(Lm_list *lml, caddr_t *addr, size_t len, int prot, int flags)
3038 {
3039 #if defined(MAP_ANON)
3040 	static int	noanon = 0;
3041 	caddr_t		va;
3042 
3043 	if (noanon == 0) {
3044 		if ((va = (caddr_t)mmap(*addr, len, prot,
3045 		    (flags | MAP_ANON), -1, 0)) != MAP_FAILED) {
3046 			*addr = va;
3047 			return (AM_OK);
3048 		}
3049 
3050 		if ((errno != EBADF) && (errno != EINVAL)) {
3051 			int	err = errno;
3052 			eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_MMAPANON),
3053 			    MSG_ORIG(MSG_PTH_DEVZERO), strerror(err));
3054 			return (AM_ERROR);
3055 		} else
3056 			noanon = 1;
3057 	}
3058 #endif
3059 	return (AM_NOSUP);
3060 }
3061 
3062 /*
3063  * Map anonymous memory from /dev/zero, or via MAP_ANON.
3064  *
3065  * (MAP_ANON only appears on Solaris 8, so we need fall-back
3066  * behavior for older systems.)
3067  */
3068 caddr_t
3069 dz_map(Lm_list *lml, caddr_t addr, size_t len, int prot, int flags)
3070 {
3071 	caddr_t	va;
3072 	int	err;
3073 	Am_ret	amret;
3074 
3075 	amret = anon_map(lml, &addr, len, prot, flags);
3076 
3077 	if (amret == AM_OK)
3078 		return (addr);
3079 	if (amret == AM_ERROR)
3080 		return (MAP_FAILED);
3081 
3082 	/* amret == AM_NOSUP -> fallback to a devzero mmaping */
3083 
3084 	if (dz_fd == FD_UNAVAIL) {
3085 		if ((dz_fd = open(MSG_ORIG(MSG_PTH_DEVZERO),
3086 		    O_RDONLY)) == FD_UNAVAIL) {
3087 			err = errno;
3088 			eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN),
3089 			    MSG_ORIG(MSG_PTH_DEVZERO), strerror(err));
3090 			return (MAP_FAILED);
3091 		}
3092 	}
3093 
3094 	if ((va = mmap(addr, len, prot, flags, dz_fd, 0)) == MAP_FAILED) {
3095 		err = errno;
3096 		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_MMAP),
3097 		    MSG_ORIG(MSG_PTH_DEVZERO), strerror(err));
3098 	}
3099 	return (va);
3100 }
3101 
3102 static int	pr_fd = FD_UNAVAIL;
3103 
3104 int
3105 pr_open(Lm_list *lml)
3106 {
3107 	char	proc[16];
3108 
3109 	if (pr_fd == FD_UNAVAIL) {
3110 		(void) snprintf(proc, 16, MSG_ORIG(MSG_FMT_PROC),
3111 		    (int)getpid());
3112 		if ((pr_fd = open(proc, O_RDONLY)) == FD_UNAVAIL) {
3113 			int	err = errno;
3114 
3115 			eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN), proc,
3116 			    strerror(err));
3117 		}
3118 	}
3119 	return (pr_fd);
3120 }
3121 
3122 static int	nu_fd = FD_UNAVAIL;
3123 
3124 caddr_t
3125 nu_map(Lm_list *lml, caddr_t addr, size_t len, int prot, int flags)
3126 {
3127 	caddr_t	va;
3128 	int	err;
3129 
3130 	if (nu_fd == FD_UNAVAIL) {
3131 		if ((nu_fd = open(MSG_ORIG(MSG_PTH_DEVNULL),
3132 		    O_RDONLY)) == FD_UNAVAIL) {
3133 			err = errno;
3134 			eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN),
3135 			    MSG_ORIG(MSG_PTH_DEVNULL), strerror(err));
3136 			return (MAP_FAILED);
3137 		}
3138 	}
3139 
3140 	if ((va = (caddr_t)mmap(addr, len, prot, flags, nu_fd, 0)) ==
3141 	    MAP_FAILED) {
3142 		err = errno;
3143 		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_MMAP),
3144 		    MSG_ORIG(MSG_PTH_DEVNULL), strerror(err));
3145 	}
3146 	return (va);
3147 }
3148 
3149 /*
3150  * Generic entry point from user code - simply grabs a lock, and bumps the
3151  * entrance count.
3152  */
3153 int
3154 enter(int flags)
3155 {
3156 	if (rt_bind_guard(THR_FLG_RTLD | thr_flg_nolock | flags)) {
3157 		if (!thr_flg_nolock)
3158 			(void) rt_mutex_lock(&rtldlock);
3159 		if (rtld_flags & RT_FL_OPERATION)
3160 			ld_entry_cnt++;
3161 		return (1);
3162 	}
3163 	return (0);
3164 }
3165 
3166 /*
3167  * Determine whether a search path has been used.
3168  */
3169 static void
3170 is_path_used(Lm_list *lml, Word unref, int *nl, Pnode *pnp, const char *obj)
3171 {
3172 	for (; pnp; pnp = pnp->p_next) {
3173 		const char	*fmt, *name;
3174 
3175 		if ((pnp->p_len == 0) || (pnp->p_orig & PN_FLG_USED))
3176 			continue;
3177 
3178 		/*
3179 		 * If this pathname originated from an expanded token, use the
3180 		 * original for any diagnostic output.
3181 		 */
3182 		if ((name = pnp->p_oname) == 0)
3183 			name = pnp->p_name;
3184 
3185 		if (unref == 0) {
3186 			if ((*nl)++ == 0)
3187 				DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
3188 			DBG_CALL(Dbg_unused_path(lml, name, pnp->p_orig,
3189 			    (pnp->p_orig & PN_FLG_DUPLICAT), obj));
3190 			continue;
3191 		}
3192 
3193 		if (pnp->p_orig & LA_SER_LIBPATH) {
3194 			if (pnp->p_orig & LA_SER_CONFIG) {
3195 				if (pnp->p_orig & PN_FLG_DUPLICAT)
3196 					fmt = MSG_INTL(MSG_DUP_LDLIBPATHC);
3197 				else
3198 					fmt = MSG_INTL(MSG_USD_LDLIBPATHC);
3199 			} else {
3200 				if (pnp->p_orig & PN_FLG_DUPLICAT)
3201 					fmt = MSG_INTL(MSG_DUP_LDLIBPATH);
3202 				else
3203 					fmt = MSG_INTL(MSG_USD_LDLIBPATH);
3204 			}
3205 		} else if (pnp->p_orig & LA_SER_RUNPATH) {
3206 			fmt = MSG_INTL(MSG_USD_RUNPATH);
3207 		} else
3208 			continue;
3209 
3210 		if ((*nl)++ == 0)
3211 			(void) printf(MSG_ORIG(MSG_STR_NL));
3212 		(void) printf(fmt, name, obj);
3213 	}
3214 }
3215 
3216 /*
3217  * Generate diagnostics as to whether an object has been used.  A symbolic
3218  * reference that gets bound to an object marks it as used.  Dependencies that
3219  * are unused when RTLD_NOW is in effect should be removed from future builds
3220  * of an object.  Dependencies that are unused without RTLD_NOW in effect are
3221  * candidates for lazy-loading.
3222  *
3223  * Unreferenced objects identify objects that are defined as dependencies but
3224  * are unreferenced by the caller.  These unreferenced objects may however be
3225  * referenced by other objects within the process, and therefore don't qualify
3226  * as completely unused.  They are still an unnecessary overhead.
3227  *
3228  * Unreferenced runpaths are also captured under ldd -U, or "unused,detail"
3229  * debugging.
3230  */
3231 void
3232 unused(Lm_list *lml)
3233 {
3234 	Rt_map		*lmp;
3235 	int		nl = 0;
3236 	Word		unref, unuse;
3237 
3238 	/*
3239 	 * If we're not tracing unused references or dependencies, or debugging
3240 	 * there's nothing to do.
3241 	 */
3242 	unref = lml->lm_flags & LML_FLG_TRC_UNREF;
3243 	unuse = lml->lm_flags & LML_FLG_TRC_UNUSED;
3244 
3245 	if ((unref == 0) && (unuse == 0) && (DBG_ENABLED == 0))
3246 		return;
3247 
3248 	/*
3249 	 * Detect unused global search paths.
3250 	 */
3251 	if (rpl_libdirs)
3252 		is_path_used(lml, unref, &nl, rpl_libdirs, config->c_name);
3253 	if (prm_libdirs)
3254 		is_path_used(lml, unref, &nl, prm_libdirs, config->c_name);
3255 
3256 	nl = 0;
3257 	lmp = lml->lm_head;
3258 	if (RLIST(lmp))
3259 		is_path_used(lml, unref, &nl, RLIST(lmp), NAME(lmp));
3260 
3261 	/*
3262 	 * Traverse the link-maps looking for unreferenced or unused
3263 	 * dependencies.  Ignore the first object on a link-map list, as this
3264 	 * is always used.
3265 	 */
3266 	nl = 0;
3267 	for (lmp = (Rt_map *)NEXT(lmp); lmp; lmp = (Rt_map *)NEXT(lmp)) {
3268 		/*
3269 		 * Determine if this object contains any runpaths that have
3270 		 * not been used.
3271 		 */
3272 		if (RLIST(lmp))
3273 			is_path_used(lml, unref, &nl, RLIST(lmp), NAME(lmp));
3274 
3275 		/*
3276 		 * If tracing unreferenced objects, or under debugging,
3277 		 * determine whether any of this objects callers haven't
3278 		 * referenced it.
3279 		 */
3280 		if (unref || DBG_ENABLED) {
3281 			Bnd_desc	*bdp;
3282 			Aliste		idx;
3283 
3284 			for (APLIST_TRAVERSE(CALLERS(lmp), idx, bdp)) {
3285 				Rt_map	*clmp;
3286 
3287 				if (bdp->b_flags & BND_REFER)
3288 					continue;
3289 
3290 				clmp = bdp->b_caller;
3291 				if (FLAGS1(clmp) & FL1_RT_LDDSTUB)
3292 					continue;
3293 
3294 				/* BEGIN CSTYLED */
3295 				if (nl++ == 0) {
3296 					if (unref)
3297 					    (void) printf(MSG_ORIG(MSG_STR_NL));
3298 					else
3299 					    DBG_CALL(Dbg_util_nl(lml,
3300 						DBG_NL_STD));
3301 				}
3302 
3303 				if (unref)
3304 				    (void) printf(MSG_INTL(MSG_LDD_UNREF_FMT),
3305 					NAME(lmp), NAME(clmp));
3306 				else
3307 				    DBG_CALL(Dbg_unused_unref(lmp, NAME(clmp)));
3308 				/* END CSTYLED */
3309 			}
3310 		}
3311 
3312 		/*
3313 		 * If tracing unused objects simply display those objects that
3314 		 * haven't been referenced by anyone.
3315 		 */
3316 		if (FLAGS1(lmp) & FL1_RT_USED)
3317 			continue;
3318 
3319 		if (nl++ == 0) {
3320 			if (unref || unuse)
3321 				(void) printf(MSG_ORIG(MSG_STR_NL));
3322 			else
3323 				DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
3324 		}
3325 		if (CYCGROUP(lmp)) {
3326 			if (unref || unuse)
3327 				(void) printf(MSG_INTL(MSG_LDD_UNCYC_FMT),
3328 				    NAME(lmp), CYCGROUP(lmp));
3329 			else
3330 				DBG_CALL(Dbg_unused_file(lml, NAME(lmp), 0,
3331 				    CYCGROUP(lmp)));
3332 		} else {
3333 			if (unref || unuse)
3334 				(void) printf(MSG_INTL(MSG_LDD_UNUSED_FMT),
3335 				    NAME(lmp));
3336 			else
3337 				DBG_CALL(Dbg_unused_file(lml, NAME(lmp), 0, 0));
3338 		}
3339 	}
3340 
3341 	DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
3342 }
3343 
3344 /*
3345  * Initialization routine for the Fmap structure.  If the fmap structure is
3346  * already in use, any mapping is released.  The structure is then initialized
3347  * in preparation for further use.
3348  */
3349 void
3350 fmap_setup()
3351 {
3352 #if defined(MAP_ALIGN)
3353 	/*
3354 	 * If MAP_ALIGN is set, the fm_addr has been seeded with an alignment
3355 	 * value.  Otherwise, if fm_addr is non-null it indicates a mapping that
3356 	 * should now be freed.
3357 	 */
3358 	if (fmap->fm_maddr && ((fmap->fm_mflags & MAP_ALIGN) == 0))
3359 		(void) munmap((caddr_t)fmap->fm_maddr, fmap->fm_msize);
3360 
3361 	/*
3362 	 * Providing we haven't determined that this system doesn't support
3363 	 * MAP_ALIGN, initialize the mapping address with the default segment
3364 	 * alignment.
3365 	 */
3366 	if ((rtld_flags2 & RT_FL2_NOMALIGN) == 0) {
3367 		fmap->fm_maddr = (char *)M_SEGM_ALIGN;
3368 		fmap->fm_mflags = MAP_PRIVATE | MAP_ALIGN;
3369 	} else {
3370 		fmap->fm_maddr = 0;
3371 		fmap->fm_mflags = MAP_PRIVATE;
3372 	}
3373 #else
3374 	if (fmap->fm_maddr)
3375 		(void) munmap((caddr_t)fmap->fm_maddr, fmap->fm_msize);
3376 
3377 	fmap->fm_maddr = 0;
3378 	fmap->fm_mflags = MAP_PRIVATE;
3379 #endif
3380 
3381 	fmap->fm_msize = FMAP_SIZE;
3382 	fmap->fm_hwptr = 0;
3383 }
3384 
3385 /*
3386  * Generic cleanup routine called prior to returning control to the user.
3387  * Insures that any ld.so.1 specific file descriptors or temporary mapping are
3388  * released, and any locks dropped.
3389  */
3390 void
3391 leave(Lm_list *lml, int flags)
3392 {
3393 	Lm_list	*elml = lml;
3394 	Rt_map	*clmp;
3395 	Aliste	idx;
3396 
3397 	/*
3398 	 * Alert the debuggers that the link-maps are consistent.  Note, in the
3399 	 * case of tearing down a whole link-map list, lml will be null.  In
3400 	 * this case use the main link-map list to test for a notification.
3401 	 */
3402 	if (elml == 0)
3403 		elml = &lml_main;
3404 	if (elml->lm_flags & LML_FLG_DBNOTIF)
3405 		rd_event(elml, RD_DLACTIVITY, RT_CONSISTENT);
3406 
3407 	/*
3408 	 * Alert any auditors that the link-maps are consistent.
3409 	 */
3410 	for (APLIST_TRAVERSE(elml->lm_actaudit, idx, clmp)) {
3411 		audit_activity(clmp, LA_ACT_CONSISTENT);
3412 
3413 		aplist_delete(elml->lm_actaudit, &idx);
3414 	}
3415 
3416 	if (dz_fd != FD_UNAVAIL) {
3417 		(void) close(dz_fd);
3418 		dz_fd = FD_UNAVAIL;
3419 	}
3420 
3421 	if (pr_fd != FD_UNAVAIL) {
3422 		(void) close(pr_fd);
3423 		pr_fd = FD_UNAVAIL;
3424 	}
3425 
3426 	if (nu_fd != FD_UNAVAIL) {
3427 		(void) close(nu_fd);
3428 		nu_fd = FD_UNAVAIL;
3429 	}
3430 
3431 	fmap_setup();
3432 
3433 	/*
3434 	 * Reinitialize error message pointer, and any overflow indication.
3435 	 */
3436 	nextptr = errbuf;
3437 	prevptr = 0;
3438 
3439 	/*
3440 	 * Don't drop our lock if we are running on our link-map list as
3441 	 * there's little point in doing so since we are single-threaded.
3442 	 *
3443 	 * LML_FLG_HOLDLOCK is set for:
3444 	 *	*) The ld.so.1's link-map list.
3445 	 *	*) The auditor's link-map if the environment is
3446 	 *	   libc/libthread un-unified.
3447 	 */
3448 	if (lml && (lml->lm_flags & LML_FLG_HOLDLOCK))
3449 		return;
3450 
3451 	if (rt_bind_clear(0) & THR_FLG_RTLD) {
3452 		if (!thr_flg_nolock)
3453 			(void) rt_mutex_unlock(&rtldlock);
3454 		(void) rt_bind_clear(THR_FLG_RTLD | thr_flg_nolock | flags);
3455 	}
3456 }
3457 
3458 int
3459 callable(Rt_map *clmp, Rt_map *dlmp, Grp_hdl *ghp, uint_t slflags)
3460 {
3461 	APlist		*calp, *dalp;
3462 	Aliste		idx1, idx2;
3463 	Grp_hdl		*ghp1, *ghp2;
3464 
3465 	/*
3466 	 * An object can always find symbols within itself.
3467 	 */
3468 	if (clmp == dlmp)
3469 		return (1);
3470 
3471 	/*
3472 	 * The search for a singleton must look in every loaded object.
3473 	 */
3474 	if (slflags & LKUP_SINGLETON)
3475 		return (1);
3476 
3477 	/*
3478 	 * Don't allow an object to bind to an object that is being deleted
3479 	 * unless the binder is also being deleted.
3480 	 */
3481 	if ((FLAGS(dlmp) & FLG_RT_DELETE) &&
3482 	    ((FLAGS(clmp) & FLG_RT_DELETE) == 0))
3483 		return (0);
3484 
3485 	/*
3486 	 * An object with world access can always bind to an object with global
3487 	 * visibility.
3488 	 */
3489 	if ((MODE(clmp) & RTLD_WORLD) && (MODE(dlmp) & RTLD_GLOBAL))
3490 		return (1);
3491 
3492 	/*
3493 	 * An object with local access can only bind to an object that is a
3494 	 * member of the same group.
3495 	 */
3496 	if (((MODE(clmp) & RTLD_GROUP) == 0) ||
3497 	    ((calp = GROUPS(clmp)) == NULL) || ((dalp = GROUPS(dlmp)) == NULL))
3498 		return (0);
3499 
3500 	/*
3501 	 * Traverse the list of groups the caller is a part of.
3502 	 */
3503 	for (APLIST_TRAVERSE(calp, idx1, ghp1)) {
3504 		/*
3505 		 * If we're testing for the ability of two objects to bind to
3506 		 * each other regardless of a specific group, ignore that group.
3507 		 */
3508 		if (ghp && (ghp1 == ghp))
3509 			continue;
3510 
3511 		/*
3512 		 * Traverse the list of groups the destination is a part of.
3513 		 */
3514 		for (APLIST_TRAVERSE(dalp, idx2, ghp2)) {
3515 			Grp_desc	*gdp;
3516 			Aliste		idx3;
3517 
3518 			if (ghp1 != ghp2)
3519 				continue;
3520 
3521 			/*
3522 			 * Make sure the relationship between the destination
3523 			 * and the caller provide symbols for relocation.
3524 			 * Parents are maintained as callers, but unless the
3525 			 * destination object was opened with RTLD_PARENT, the
3526 			 * parent doesn't provide symbols for the destination
3527 			 * to relocate against.
3528 			 */
3529 			for (ALIST_TRAVERSE(ghp2->gh_depends, idx3, gdp)) {
3530 				if (dlmp != gdp->gd_depend)
3531 					continue;
3532 
3533 				if (gdp->gd_flags & GPD_RELOC)
3534 					return (1);
3535 			}
3536 		}
3537 	}
3538 	return (0);
3539 }
3540 
3541 /*
3542  * Initialize the environ symbol.  Traditionally this is carried out by the crt
3543  * code prior to jumping to main.  However, init sections get fired before this
3544  * variable is initialized, so ld.so.1 sets this directly from the AUX vector
3545  * information.  In addition, a process may have multiple link-maps (ld.so.1's
3546  * debugging and preloading objects), and link auditing, and each may need an
3547  * environ variable set.
3548  *
3549  * This routine is called after a relocation() pass, and thus provides for:
3550  *
3551  *  o	setting environ on the main link-map after the initial application and
3552  *	its dependencies have been established.  Typically environ lives in the
3553  *	application (provided by its crt), but in older applications it might
3554  *	be in libc.  Who knows what's expected of applications not built on
3555  *	Solaris.
3556  *
3557  *  o	after loading a new shared object.  We can add shared objects to various
3558  *	link-maps, and any link-map dependencies requiring getopt() require
3559  *	their own environ.  In addition, lazy loading might bring in the
3560  *	supplier of environ (libc used to be a lazy loading candidate) after
3561  *	the link-map has been established and other objects are present.
3562  *
3563  * This routine handles all these scenarios, without adding unnecessary overhead
3564  * to ld.so.1.
3565  */
3566 void
3567 set_environ(Lm_list *lml)
3568 {
3569 	Rt_map		*dlmp;
3570 	Sym		*sym;
3571 	Slookup		sl;
3572 	uint_t		binfo;
3573 
3574 	/*
3575 	 * Initialize the symbol lookup data structure.
3576 	 */
3577 	SLOOKUP_INIT(sl, MSG_ORIG(MSG_SYM_ENVIRON), lml->lm_head, lml->lm_head,
3578 	    ld_entry_cnt, 0, 0, 0, 0, LKUP_WEAK);
3579 
3580 	if (sym = LM_LOOKUP_SYM(lml->lm_head)(&sl, &dlmp, &binfo, 0)) {
3581 		lml->lm_environ = (char ***)sym->st_value;
3582 
3583 		if (!(FLAGS(dlmp) & FLG_RT_FIXED))
3584 			lml->lm_environ =
3585 			    (char ***)((uintptr_t)lml->lm_environ +
3586 			    (uintptr_t)ADDR(dlmp));
3587 		*(lml->lm_environ) = (char **)environ;
3588 		lml->lm_flags |= LML_FLG_ENVIRON;
3589 	}
3590 }
3591 
3592 /*
3593  * Determine whether we have a secure executable.  Uid and gid information
3594  * can be passed to us via the aux vector, however if these values are -1
3595  * then use the appropriate system call to obtain them.
3596  *
3597  *  o	If the user is the root they can do anything
3598  *
3599  *  o	If the real and effective uid's don't match, or the real and
3600  *	effective gid's don't match then this is determined to be a `secure'
3601  *	application.
3602  *
3603  * This function is called prior to any dependency processing (see _setup.c).
3604  * Any secure setting will remain in effect for the life of the process.
3605  */
3606 void
3607 security(uid_t uid, uid_t euid, gid_t gid, gid_t egid, int auxflags)
3608 {
3609 #ifdef AT_SUN_AUXFLAGS
3610 	if (auxflags != -1) {
3611 		if ((auxflags & AF_SUN_SETUGID) != 0)
3612 			rtld_flags |= RT_FL_SECURE;
3613 		return;
3614 	}
3615 #endif
3616 	if (uid == (uid_t)-1)
3617 		uid = getuid();
3618 	if (uid) {
3619 		if (euid == (uid_t)-1)
3620 			euid = geteuid();
3621 		if (uid != euid)
3622 			rtld_flags |= RT_FL_SECURE;
3623 		else {
3624 			if (gid == (gid_t)-1)
3625 				gid = getgid();
3626 			if (egid == (gid_t)-1)
3627 				egid = getegid();
3628 			if (gid != egid)
3629 				rtld_flags |= RT_FL_SECURE;
3630 		}
3631 	}
3632 }
3633 
3634 /*
3635  * _REENTRANT code gets errno redefined to a function so provide for return
3636  * of the thread errno if applicable.  This has no meaning in ld.so.1 which
3637  * is basically singled threaded.  Provide the interface for our dependencies.
3638  */
3639 #undef errno
3640 int *
3641 ___errno()
3642 {
3643 	extern	int	errno;
3644 
3645 	return (&errno);
3646 }
3647 
3648 /*
3649  * The interface with the c library which is supplied through libdl.so.1.
3650  * A non-null argument allows a function pointer array to be passed to us which
3651  * is used to re-initialize the linker libc table.
3652  */
3653 void
3654 _ld_libc(void * ptr)
3655 {
3656 	get_lcinterface(_caller(caller(), CL_EXECDEF), (Lc_interface *)ptr);
3657 }
3658 
3659 /*
3660  * Determine whether a symbol name should be demangled.
3661  */
3662 const char *
3663 demangle(const char *name)
3664 {
3665 	if (rtld_flags & RT_FL_DEMANGLE)
3666 		return (conv_demangle_name(name));
3667 	else
3668 		return (name);
3669 }
3670