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