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