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