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