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