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