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