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