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