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