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