xref: /titanic_51/usr/src/cmd/sgs/rtld/common/util.c (revision c3a9724da5c6e77268b3f725df640f2848b1ebf8)
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] == 0)
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 == 0);
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)) != 0) {
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 List	pending = { NULL, 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) list_append(&pending, tobj);
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 			Listnode	*lnp;
850 			Rt_map		**pobj;
851 
852 			rtld_flags &= ~RT_FL_INITFIRST;
853 
854 			while ((lnp = pending.head) != NULL) {
855 				if ((pending.head = lnp->next) == NULL)
856 					pending.tail = NULL;
857 				pobj = lnp->data;
858 				free(lnp);
859 
860 				call_init(pobj, DBG_INIT_PEND);
861 			}
862 		}
863 	}
864 	free(tobj);
865 }
866 
867 /*
868  * Function called by atexit(3C).  Calls all .fini sections related with the
869  * mains dependent shared libraries in the order in which the shared libraries
870  * have been loaded.  Skip any .fini defined in the main executable, as this
871  * will be called by crt0 (main was never marked as initdone).
872  */
873 void
874 call_fini(Lm_list * lml, Rt_map ** tobj)
875 {
876 	Rt_map **_tobj;
877 
878 	for (_tobj = tobj; *_tobj != NULL; _tobj++) {
879 		Rt_map		*clmp, * lmp = *_tobj;
880 		Aliste		idx;
881 		Bnd_desc	*bdp;
882 
883 		/*
884 		 * Only fire a .fini if the objects corresponding .init has
885 		 * completed.  We collect all .fini sections of objects that
886 		 * had their .init collected, but that doesn't mean that at
887 		 * the time of collection, that the .init had completed.
888 		 */
889 		if (FLAGS(lmp) & FLG_RT_INITDONE) {
890 			void	(*fptr)(void) = FINI(lmp);
891 
892 			if (FINIARRAY(lmp) || fptr)
893 				DBG_CALL(Dbg_util_call_fini(lmp));
894 
895 			call_array(FINIARRAY(lmp), FINIARRAYSZ(lmp), lmp,
896 			    SHT_FINI_ARRAY);
897 
898 			if (fptr) {
899 				leave(LIST(lmp), 0);
900 				(*fptr)();
901 				(void) enter(0);
902 			}
903 		}
904 
905 		/*
906 		 * Skip main, this is explicitly called last in atexit_fini().
907 		 */
908 		if (FLAGS(lmp) & FLG_RT_ISMAIN)
909 			continue;
910 
911 		/*
912 		 * Audit `close' operations at this point.  The library has
913 		 * exercised its last instructions (regardless of whether it
914 		 * will be unmapped or not).
915 		 *
916 		 * First call any global auditing.
917 		 */
918 		if (lml->lm_tflags & LML_TFLG_AUD_OBJCLOSE)
919 			_audit_objclose(&(auditors->ad_list), lmp);
920 
921 		/*
922 		 * Finally determine whether this object has local auditing
923 		 * requirements by inspecting itself and then its dependencies.
924 		 */
925 		if ((lml->lm_flags & LML_FLG_LOCAUDIT) == 0)
926 			continue;
927 
928 		if (AFLAGS(lmp) & LML_TFLG_AUD_OBJCLOSE)
929 			_audit_objclose(&(AUDITORS(lmp)->ad_list), lmp);
930 
931 		for (APLIST_TRAVERSE(CALLERS(lmp), idx, bdp)) {
932 			clmp = bdp->b_caller;
933 
934 			if (AFLAGS(clmp) & LML_TFLG_AUD_OBJCLOSE) {
935 				_audit_objclose(&(AUDITORS(clmp)->ad_list),
936 				    lmp);
937 				break;
938 			}
939 		}
940 	}
941 	DBG_CALL(Dbg_bind_plt_summary(lml, M_MACH, pltcnt21d, pltcnt24d,
942 	    pltcntu32, pltcntu44, pltcntfull, pltcntfar));
943 
944 	free(tobj);
945 }
946 
947 void
948 atexit_fini()
949 {
950 	Rt_map		**tobj, *lmp;
951 	Lm_list		*lml;
952 	Listnode	*lnp;
953 
954 	(void) enter(0);
955 
956 	rtld_flags |= RT_FL_ATEXIT;
957 
958 	lml = &lml_main;
959 	lml->lm_flags |= LML_FLG_ATEXIT;
960 	lml->lm_flags &= ~LML_FLG_INTRPOSETSORT;
961 	lmp = (Rt_map *)lml->lm_head;
962 
963 	/*
964 	 * Reverse topologically sort the main link-map for .fini execution.
965 	 */
966 	if (((tobj = tsort(lmp, lml->lm_obj, RT_SORT_FWD)) != 0) &&
967 	    (tobj != (Rt_map **)S_ERROR))
968 		call_fini(lml, tobj);
969 
970 	/*
971 	 * Add an explicit close to main and ld.so.1.  Although main's .fini is
972 	 * collected in call_fini() to provide for FINITARRAY processing, its
973 	 * audit_objclose is explicitly skipped.  This provides for it to be
974 	 * called last, here.  This is the reverse of the explicit calls to
975 	 * audit_objopen() made in setup().
976 	 */
977 	if ((lml->lm_tflags | AFLAGS(lmp)) & LML_TFLG_AUD_MASK) {
978 		audit_objclose(lmp, (Rt_map *)lml_rtld.lm_head);
979 		audit_objclose(lmp, lmp);
980 	}
981 
982 	/*
983 	 * Now that all .fini code has been run, see what unreferenced objects
984 	 * remain.
985 	 */
986 	unused(lml);
987 
988 	/*
989 	 * Traverse any alternative link-map lists.
990 	 */
991 	for (LIST_TRAVERSE(&dynlm_list, lnp, lml)) {
992 		/*
993 		 * Ignore the base-link-map list, which has already been
994 		 * processed, and the runtime linkers link-map list, which is
995 		 * typically processed last.
996 		 */
997 		if (lml->lm_flags & (LML_FLG_BASELM | LML_FLG_RTLDLM))
998 			continue;
999 
1000 		if ((lmp = (Rt_map *)lml->lm_head) == 0)
1001 			continue;
1002 
1003 		lml->lm_flags |= LML_FLG_ATEXIT;
1004 		lml->lm_flags &= ~LML_FLG_INTRPOSETSORT;
1005 
1006 		/*
1007 		 * Reverse topologically sort the link-map for .fini execution.
1008 		 */
1009 		if (((tobj = tsort(lmp, lml->lm_obj, RT_SORT_FWD)) != 0) &&
1010 		    (tobj != (Rt_map **)S_ERROR))
1011 			call_fini(lml, tobj);
1012 
1013 		unused(lml);
1014 	}
1015 
1016 	/*
1017 	 * Finally reverse topologically sort the runtime linkers link-map for
1018 	 * .fini execution.
1019 	 */
1020 	lml = &lml_rtld;
1021 	lml->lm_flags |= LML_FLG_ATEXIT;
1022 	lml->lm_flags &= ~LML_FLG_INTRPOSETSORT;
1023 	lmp = (Rt_map *)lml->lm_head;
1024 
1025 	if (((tobj = tsort(lmp, lml->lm_obj, RT_SORT_FWD)) != 0) &&
1026 	    (tobj != (Rt_map **)S_ERROR))
1027 		call_fini(lml, tobj);
1028 
1029 	leave(&lml_main, 0);
1030 }
1031 
1032 
1033 /*
1034  * This routine is called to complete any runtime linker activity which may have
1035  * resulted in objects being loaded.  This is called from all user entry points
1036  * and from any internal dl*() requests.
1037  */
1038 void
1039 load_completion(Rt_map *nlmp)
1040 {
1041 	Rt_map	**tobj = 0;
1042 	Lm_list	*nlml;
1043 
1044 	/*
1045 	 * Establish any .init processing.  Note, in a world of lazy loading,
1046 	 * objects may have been loaded regardless of whether the users request
1047 	 * was fulfilled (i.e., a dlsym() request may have failed to find a
1048 	 * symbol but objects might have been loaded during its search).  Thus,
1049 	 * any tsorting starts from the nlmp (new link-maps) pointer and not
1050 	 * necessarily from the link-map that may have satisfied the request.
1051 	 *
1052 	 * Note, the primary link-map has an initialization phase where dynamic
1053 	 * .init firing is suppressed.  This provides for a simple and clean
1054 	 * handshake with the primary link-maps libc, which is important for
1055 	 * establishing uberdata.  In addition, auditors often obtain handles
1056 	 * to primary link-map objects as the objects are loaded, so as to
1057 	 * inspect the link-map for symbols.  This inspection is allowed without
1058 	 * running any code on the primary link-map, as running this code may
1059 	 * reenter the auditor, who may not yet have finished its own
1060 	 * initialization.
1061 	 */
1062 	if (nlmp)
1063 		nlml = LIST(nlmp);
1064 
1065 	if (nlmp && nlml->lm_init && ((nlml != &lml_main) ||
1066 	    (rtld_flags2 & (RT_FL2_PLMSETUP | RT_FL2_NOPLM)))) {
1067 		if ((tobj = tsort(nlmp, nlml->lm_init,
1068 		    RT_SORT_REV)) == (Rt_map **)S_ERROR)
1069 			tobj = 0;
1070 	}
1071 
1072 	/*
1073 	 * Make sure any alternative link-map retrieves any external interfaces
1074 	 * and initializes threads.
1075 	 */
1076 	if (nlmp && (nlml != &lml_main)) {
1077 		(void) rt_get_extern(nlml, nlmp);
1078 		rt_thr_init(nlml);
1079 	}
1080 
1081 	/*
1082 	 * Traverse the list of new link-maps and register any dynamic TLS.
1083 	 * This storage is established for any objects not on the primary
1084 	 * link-map, and for any objects added to the primary link-map after
1085 	 * static TLS has been registered.
1086 	 */
1087 	if (nlmp && nlml->lm_tls && ((nlml != &lml_main) ||
1088 	    (rtld_flags2 & (RT_FL2_PLMSETUP | RT_FL2_NOPLM)))) {
1089 		Rt_map	*lmp;
1090 
1091 		for (lmp = nlmp; lmp; lmp = NEXT_RT_MAP(lmp)) {
1092 			if (PTTLS(lmp) && PTTLS(lmp)->p_memsz)
1093 				tls_modaddrem(lmp, TM_FLG_MODADD);
1094 		}
1095 		nlml->lm_tls = 0;
1096 	}
1097 
1098 	/*
1099 	 * Fire any .init's.
1100 	 */
1101 	if (tobj)
1102 		call_init(tobj, DBG_INIT_SORT);
1103 }
1104 
1105 /*
1106  * Append an item to the specified list, and return a pointer to the list
1107  * node created.
1108  */
1109 Listnode *
1110 list_append(List *lst, const void *item)
1111 {
1112 	Listnode	*_lnp;
1113 
1114 	if ((_lnp = malloc(sizeof (Listnode))) == NULL)
1115 		return (NULL);
1116 
1117 	_lnp->data = (void *)item;
1118 	_lnp->next = NULL;
1119 
1120 	if (lst->head == NULL)
1121 		lst->tail = lst->head = _lnp;
1122 	else {
1123 		lst->tail->next = _lnp;
1124 		lst->tail = lst->tail->next;
1125 	}
1126 	return (_lnp);
1127 }
1128 
1129 /*
1130  * Add an item after specified listnode, and return a pointer to the list
1131  * node created.
1132  */
1133 Listnode *
1134 list_insert(List *lst, const void *item, Listnode *lnp)
1135 {
1136 	Listnode	*_lnp;
1137 
1138 	if ((_lnp = malloc(sizeof (Listnode))) == NULL)
1139 		return (NULL);
1140 
1141 	_lnp->data = (void *)item;
1142 	_lnp->next = lnp->next;
1143 	if (_lnp->next == NULL)
1144 		lst->tail = _lnp;
1145 	lnp->next = _lnp;
1146 	return (_lnp);
1147 }
1148 
1149 /*
1150  * Prepend an item to the specified list, and return a pointer to the
1151  * list node created.
1152  */
1153 Listnode *
1154 list_prepend(List *lst, const void *item)
1155 {
1156 	Listnode	*_lnp;
1157 
1158 	if ((_lnp = malloc(sizeof (Listnode))) == NULL)
1159 		return (0);
1160 
1161 	_lnp->data = (void *)item;
1162 
1163 	if (lst->head == NULL) {
1164 		_lnp->next = NULL;
1165 		lst->tail = lst->head = _lnp;
1166 	} else {
1167 		_lnp->next = lst->head;
1168 		lst->head = _lnp;
1169 	}
1170 	return (_lnp);
1171 }
1172 
1173 /*
1174  * Delete a 'listnode' from a list.
1175  */
1176 void
1177 list_delete(List *lst, void *item)
1178 {
1179 	Listnode	*clnp, *plnp;
1180 
1181 	for (plnp = NULL, clnp = lst->head; clnp; clnp = clnp->next) {
1182 		if (item == clnp->data)
1183 			break;
1184 		plnp = clnp;
1185 	}
1186 
1187 	if (clnp == NULL)
1188 		return;
1189 
1190 	if (lst->head == clnp)
1191 		lst->head = clnp->next;
1192 	if (lst->tail == clnp)
1193 		lst->tail = plnp;
1194 
1195 	if (plnp)
1196 		plnp->next = clnp->next;
1197 
1198 	free(clnp);
1199 }
1200 
1201 /*
1202  * Append an item to the specified link map control list.
1203  */
1204 void
1205 lm_append(Lm_list *lml, Aliste lmco, Rt_map *lmp)
1206 {
1207 	Lm_cntl	*lmc;
1208 	int	add = 1;
1209 
1210 	/*
1211 	 * Indicate that this link-map list has a new object.
1212 	 */
1213 	(lml->lm_obj)++;
1214 
1215 	/*
1216 	 * If we're about to add a new object to the main link-map control list,
1217 	 * alert the debuggers that we are about to mess with this list.
1218 	 * Additions of individual objects to the main link-map control list
1219 	 * occur during initial setup as the applications immediate dependencies
1220 	 * are loaded.  Individual objects are also loaded on the main link-map
1221 	 * control list of new alternative link-map control lists.
1222 	 */
1223 	if ((lmco == ALIST_OFF_DATA) &&
1224 	    ((lml->lm_flags & LML_FLG_DBNOTIF) == 0))
1225 		rd_event(lml, RD_DLACTIVITY, RT_ADD);
1226 
1227 	/* LINTED */
1228 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, lmco);
1229 
1230 	/*
1231 	 * A link-map list header points to one of more link-map control lists
1232 	 * (see include/rtld.h).  The initial list, pointed to by lm_cntl, is
1233 	 * the list of relocated objects.  Other lists maintain objects that
1234 	 * are still being analyzed or relocated.  This list provides the core
1235 	 * link-map list information used by all ld.so.1 routines.
1236 	 */
1237 	if (lmc->lc_head == NULL) {
1238 		/*
1239 		 * If this is the first link-map for the given control list,
1240 		 * initialize the list.
1241 		 */
1242 		lmc->lc_head = lmc->lc_tail = lmp;
1243 		add = 0;
1244 
1245 	} else if (FLAGS(lmp) & FLG_RT_OBJINTPO) {
1246 		Rt_map	*tlmp;
1247 
1248 		/*
1249 		 * If this is an interposer then append the link-map following
1250 		 * any other interposers (these are objects that have been
1251 		 * previously preloaded, or were identified with -z interpose).
1252 		 * Interposers can only be inserted on the first link-map
1253 		 * control list, as once relocation has started, interposition
1254 		 * from new interposers can't be guaranteed.
1255 		 *
1256 		 * NOTE: We do not interpose on the head of a list.  This model
1257 		 * evolved because dynamic executables have already been fully
1258 		 * relocated within themselves and thus can't be interposed on.
1259 		 * Nowadays it's possible to have shared objects at the head of
1260 		 * a list, which conceptually means they could be interposed on.
1261 		 * But, shared objects can be created via dldump() and may only
1262 		 * be partially relocated (just relatives), in which case they
1263 		 * are interposable, but are marked as fixed (ET_EXEC).
1264 		 *
1265 		 * Thus we really don't have a clear method of deciding when the
1266 		 * head of a link-map is interposable.  So, to be consistent,
1267 		 * for now only add interposers after the link-map lists head
1268 		 * object.
1269 		 */
1270 		for (tlmp = NEXT_RT_MAP(lmc->lc_head); tlmp;
1271 		    tlmp = NEXT_RT_MAP(tlmp)) {
1272 
1273 			if (FLAGS(tlmp) & FLG_RT_OBJINTPO)
1274 				continue;
1275 
1276 			/*
1277 			 * Insert the new link-map before this non-interposer,
1278 			 * and indicate an interposer is found.
1279 			 */
1280 			NEXT(PREV_RT_MAP(tlmp)) = (Link_map *)lmp;
1281 			PREV(lmp) = PREV(tlmp);
1282 
1283 			NEXT(lmp) = (Link_map *)tlmp;
1284 			PREV(tlmp) = (Link_map *)lmp;
1285 
1286 			lmc->lc_flags |= LMC_FLG_REANALYZE;
1287 			add = 0;
1288 			break;
1289 		}
1290 	}
1291 
1292 	/*
1293 	 * Fall through to appending the new link map to the tail of the list.
1294 	 * If we're processing the initial objects of this link-map list, add
1295 	 * them to the backward compatibility list.
1296 	 */
1297 	if (add) {
1298 		NEXT(lmc->lc_tail) = (Link_map *)lmp;
1299 		PREV(lmp) = (Link_map *)lmc->lc_tail;
1300 		lmc->lc_tail = lmp;
1301 	}
1302 
1303 	/*
1304 	 * Having added this link-map to a control list, indicate which control
1305 	 * list the link-map belongs to.  Note, control list information is
1306 	 * always maintained as an offset, as the Alist can be reallocated.
1307 	 */
1308 	CNTL(lmp) = lmco;
1309 
1310 	/*
1311 	 * Indicate if an interposer is found.  Note that the first object on a
1312 	 * link-map can be explicitly defined as an interposer so that it can
1313 	 * provide interposition over direct binding requests.
1314 	 */
1315 	if (FLAGS(lmp) & MSK_RT_INTPOSE)
1316 		lml->lm_flags |= LML_FLG_INTRPOSE;
1317 
1318 	/*
1319 	 * For backward compatibility with debuggers, the link-map list contains
1320 	 * pointers to the main control list.
1321 	 */
1322 	if (lmco == ALIST_OFF_DATA) {
1323 		lml->lm_head = lmc->lc_head;
1324 		lml->lm_tail = lmc->lc_tail;
1325 	}
1326 }
1327 
1328 /*
1329  * Delete an item from the specified link map control list.
1330  */
1331 void
1332 lm_delete(Lm_list *lml, Rt_map *lmp)
1333 {
1334 	Lm_cntl	*lmc;
1335 
1336 	/*
1337 	 * If the control list pointer hasn't been initialized, this object
1338 	 * never got added to a link-map list.
1339 	 */
1340 	if (CNTL(lmp) == 0)
1341 		return;
1342 
1343 	/*
1344 	 * If we're about to delete an object from the main link-map control
1345 	 * list, alert the debuggers that we are about to mess with this list.
1346 	 */
1347 	if ((CNTL(lmp) == ALIST_OFF_DATA) &&
1348 	    ((lml->lm_flags & LML_FLG_DBNOTIF) == 0))
1349 		rd_event(lml, RD_DLACTIVITY, RT_DELETE);
1350 
1351 	/* LINTED */
1352 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, CNTL(lmp));
1353 
1354 	if (lmc->lc_head == lmp)
1355 		lmc->lc_head = NEXT_RT_MAP(lmp);
1356 	else
1357 		NEXT(PREV_RT_MAP(lmp)) = (void *)NEXT(lmp);
1358 
1359 	if (lmc->lc_tail == lmp)
1360 		lmc->lc_tail = PREV_RT_MAP(lmp);
1361 	else
1362 		PREV(NEXT_RT_MAP(lmp)) = PREV(lmp);
1363 
1364 	/*
1365 	 * For backward compatibility with debuggers, the link-map list contains
1366 	 * pointers to the main control list.
1367 	 */
1368 	if (lmc == (Lm_cntl *)&lml->lm_lists->al_data) {
1369 		lml->lm_head = lmc->lc_head;
1370 		lml->lm_tail = lmc->lc_tail;
1371 	}
1372 
1373 	/*
1374 	 * Indicate we have one less object on this control list.
1375 	 */
1376 	(lml->lm_obj)--;
1377 }
1378 
1379 /*
1380  * Move a link-map control list to another.  Objects that are being relocated
1381  * are maintained on secondary control lists.  Once their relocation is
1382  * complete, the entire list is appended to the previous control list, as this
1383  * list must have been the trigger for generating the new control list.
1384  */
1385 void
1386 lm_move(Lm_list *lml, Aliste nlmco, Aliste plmco, Lm_cntl *nlmc, Lm_cntl *plmc)
1387 {
1388 	Rt_map	*lmp;
1389 
1390 	/*
1391 	 * If we're about to add a new family of objects to the main link-map
1392 	 * control list, alert the debuggers that we are about to mess with this
1393 	 * list.  Additions of object families to the main link-map control
1394 	 * list occur during lazy loading, filtering and dlopen().
1395 	 */
1396 	if ((plmco == ALIST_OFF_DATA) &&
1397 	    ((lml->lm_flags & LML_FLG_DBNOTIF) == 0))
1398 		rd_event(lml, RD_DLACTIVITY, RT_ADD);
1399 
1400 	DBG_CALL(Dbg_file_cntl(lml, nlmco, plmco));
1401 
1402 	/*
1403 	 * Indicate each new link-map has been moved to the previous link-map
1404 	 * control list.
1405 	 */
1406 	for (lmp = nlmc->lc_head; lmp; lmp = NEXT_RT_MAP(lmp)) {
1407 		CNTL(lmp) = plmco;
1408 
1409 		/*
1410 		 * If these objects are being added to the main link-map
1411 		 * control list, indicate that there are init's available
1412 		 * for harvesting.
1413 		 */
1414 		if (plmco == ALIST_OFF_DATA) {
1415 			lml->lm_init++;
1416 			lml->lm_flags |= LML_FLG_OBJADDED;
1417 		}
1418 	}
1419 
1420 	/*
1421 	 * Move the new link-map control list, to the callers link-map control
1422 	 * list.
1423 	 */
1424 	if (plmc->lc_head == NULL) {
1425 		plmc->lc_head = nlmc->lc_head;
1426 		PREV(nlmc->lc_head) = NULL;
1427 	} else {
1428 		NEXT(plmc->lc_tail) = (Link_map *)nlmc->lc_head;
1429 		PREV(nlmc->lc_head) = (Link_map *)plmc->lc_tail;
1430 	}
1431 
1432 	plmc->lc_tail = nlmc->lc_tail;
1433 	nlmc->lc_head = nlmc->lc_tail = NULL;
1434 
1435 	/*
1436 	 * For backward compatibility with debuggers, the link-map list contains
1437 	 * pointers to the main control list.
1438 	 */
1439 	if (plmco == ALIST_OFF_DATA) {
1440 		lml->lm_head = plmc->lc_head;
1441 		lml->lm_tail = plmc->lc_tail;
1442 	}
1443 }
1444 
1445 /*
1446  * Environment variables can have a variety of defined permutations, and thus
1447  * the following infrastructure exists to allow this variety and to select the
1448  * required definition.
1449  *
1450  * Environment variables can be defined as 32- or 64-bit specific, and if so
1451  * they will take precedence over any instruction set neutral form.  Typically
1452  * this is only useful when the environment value is an informational string.
1453  *
1454  * Environment variables may be obtained from the standard user environment or
1455  * from a configuration file.  The latter provides a fallback if no user
1456  * environment setting is found, and can take two forms:
1457  *
1458  *  .	a replaceable definition - this will be used if no user environment
1459  *	setting has been seen, or
1460  *
1461  *  .	an permanent definition - this will be used no matter what user
1462  *	environment setting is seen.  In the case of list variables it will be
1463  *	appended to any process environment setting seen.
1464  *
1465  * Environment variables can be defined without a value (ie. LD_XXXX=) so as to
1466  * override any replaceable environment variables from a configuration file.
1467  */
1468 static	u_longlong_t		rplgen;		/* replaceable generic */
1469 						/*	variables */
1470 static	u_longlong_t		rplisa;		/* replaceable ISA specific */
1471 						/*	variables */
1472 static	u_longlong_t		prmgen;		/* permanent generic */
1473 						/*	variables */
1474 static	u_longlong_t		prmisa;		/* permanent ISA specific */
1475 						/*	variables */
1476 
1477 /*
1478  * Classify an environment variables type.
1479  */
1480 #define	ENV_TYP_IGNORE		0x1		/* ignore - variable is for */
1481 						/*	the wrong ISA */
1482 #define	ENV_TYP_ISA		0x2		/* variable is ISA specific */
1483 #define	ENV_TYP_CONFIG		0x4		/* variable obtained from a */
1484 						/*	config file */
1485 #define	ENV_TYP_PERMANT		0x8		/* variable is permanent */
1486 
1487 /*
1488  * Identify all environment variables.
1489  */
1490 #define	ENV_FLG_AUDIT		0x0000000001ULL
1491 #define	ENV_FLG_AUDIT_ARGS	0x0000000002ULL
1492 #define	ENV_FLG_BIND_NOW	0x0000000004ULL
1493 #define	ENV_FLG_BIND_NOT	0x0000000008ULL
1494 #define	ENV_FLG_BINDINGS	0x0000000010ULL
1495 
1496 #define	ENV_FLG_CONFGEN		0x0000000040ULL
1497 #define	ENV_FLG_CONFIG		0x0000000080ULL
1498 #define	ENV_FLG_DEBUG		0x0000000100ULL
1499 #define	ENV_FLG_DEBUG_OUTPUT	0x0000000200ULL
1500 #define	ENV_FLG_DEMANGLE	0x0000000400ULL
1501 #define	ENV_FLG_FLAGS		0x0000000800ULL
1502 #define	ENV_FLG_INIT		0x0000001000ULL
1503 #define	ENV_FLG_LIBPATH		0x0000002000ULL
1504 #define	ENV_FLG_LOADAVAIL	0x0000004000ULL
1505 #define	ENV_FLG_LOADFLTR	0x0000008000ULL
1506 #define	ENV_FLG_NOAUDIT		0x0000010000ULL
1507 #define	ENV_FLG_NOAUXFLTR	0x0000020000ULL
1508 #define	ENV_FLG_NOBAPLT		0x0000040000ULL
1509 #define	ENV_FLG_NOCONFIG	0x0000080000ULL
1510 #define	ENV_FLG_NODIRCONFIG	0x0000100000ULL
1511 #define	ENV_FLG_NODIRECT	0x0000200000ULL
1512 #define	ENV_FLG_NOENVCONFIG	0x0000400000ULL
1513 #define	ENV_FLG_NOLAZY		0x0000800000ULL
1514 #define	ENV_FLG_NOOBJALTER	0x0001000000ULL
1515 #define	ENV_FLG_NOVERSION	0x0002000000ULL
1516 #define	ENV_FLG_PRELOAD		0x0004000000ULL
1517 #define	ENV_FLG_PROFILE		0x0008000000ULL
1518 #define	ENV_FLG_PROFILE_OUTPUT	0x0010000000ULL
1519 #define	ENV_FLG_SIGNAL		0x0020000000ULL
1520 #define	ENV_FLG_TRACE_OBJS	0x0040000000ULL
1521 #define	ENV_FLG_TRACE_PTHS	0x0080000000ULL
1522 #define	ENV_FLG_UNREF		0x0100000000ULL
1523 #define	ENV_FLG_UNUSED		0x0200000000ULL
1524 #define	ENV_FLG_VERBOSE		0x0400000000ULL
1525 #define	ENV_FLG_WARN		0x0800000000ULL
1526 #define	ENV_FLG_NOFLTCONFIG	0x1000000000ULL
1527 #define	ENV_FLG_BIND_LAZY	0x2000000000ULL
1528 #define	ENV_FLG_NOUNRESWEAK	0x4000000000ULL
1529 #define	ENV_FLG_NOPAREXT	0x8000000000ULL
1530 
1531 #define	SEL_REPLACE		0x0001
1532 #define	SEL_PERMANT		0x0002
1533 #define	SEL_ACT_RT		0x0100	/* setting rtld_flags */
1534 #define	SEL_ACT_RT2		0x0200	/* setting rtld_flags2 */
1535 #define	SEL_ACT_STR		0x0400	/* setting string value */
1536 #define	SEL_ACT_LML		0x0800	/* setting lml_flags */
1537 #define	SEL_ACT_LMLT		0x1000	/* setting lml_tflags */
1538 #define	SEL_ACT_SPEC_1		0x2000	/* For FLG_{FLAGS, LIBPATH} */
1539 #define	SEL_ACT_SPEC_2		0x4000	/* need special handling */
1540 
1541 /*
1542  * Pattern match an LD_XXXX environment variable.  s1 points to the XXXX part
1543  * and len specifies its length (comparing a strings length before the string
1544  * itself speed things up).  s2 points to the token itself which has already
1545  * had any leading white-space removed.
1546  */
1547 static void
1548 ld_generic_env(const char *s1, size_t len, const char *s2, Word *lmflags,
1549     Word *lmtflags, uint_t env_flags, int aout)
1550 {
1551 	u_longlong_t	variable = 0;
1552 	ushort_t	select = 0;
1553 	const char	**str;
1554 	Word		val = 0;
1555 
1556 	/*
1557 	 * Determine whether we're dealing with a replaceable or permanent
1558 	 * string.
1559 	 */
1560 	if (env_flags & ENV_TYP_PERMANT) {
1561 		/*
1562 		 * If the string is from a configuration file and defined as
1563 		 * permanent, assign it as permanent.
1564 		 */
1565 		select |= SEL_PERMANT;
1566 	} else
1567 		select |= SEL_REPLACE;
1568 
1569 	/*
1570 	 * Parse the variable given.
1571 	 *
1572 	 * The LD_AUDIT family.
1573 	 */
1574 	if (*s1 == 'A') {
1575 		if ((len == MSG_LD_AUDIT_SIZE) && (strncmp(s1,
1576 		    MSG_ORIG(MSG_LD_AUDIT), MSG_LD_AUDIT_SIZE) == 0)) {
1577 			/*
1578 			 * Replaceable and permanent audit objects can exist.
1579 			 */
1580 			select |= SEL_ACT_STR;
1581 			if (select & SEL_REPLACE)
1582 				str = &rpl_audit;
1583 			else {
1584 				str = &prm_audit;
1585 				rpl_audit = 0;
1586 			}
1587 			variable = ENV_FLG_AUDIT;
1588 		} else if ((len == MSG_LD_AUDIT_ARGS_SIZE) &&
1589 		    (strncmp(s1, MSG_ORIG(MSG_LD_AUDIT_ARGS),
1590 		    MSG_LD_AUDIT_ARGS_SIZE) == 0)) {
1591 			/*
1592 			 * A specialized variable for plt_exit() use, not
1593 			 * documented for general use.
1594 			 */
1595 			select |= SEL_ACT_SPEC_2;
1596 			variable = ENV_FLG_AUDIT_ARGS;
1597 		}
1598 	}
1599 	/*
1600 	 * The LD_BIND family.
1601 	 */
1602 	else if (*s1 == 'B') {
1603 		if ((len == MSG_LD_BIND_LAZY_SIZE) && (strncmp(s1,
1604 		    MSG_ORIG(MSG_LD_BIND_LAZY),
1605 		    MSG_LD_BIND_LAZY_SIZE) == 0)) {
1606 			select |= SEL_ACT_RT2;
1607 			val = RT_FL2_BINDLAZY;
1608 			variable = ENV_FLG_BIND_LAZY;
1609 		} else if ((len == MSG_LD_BIND_NOW_SIZE) && (strncmp(s1,
1610 		    MSG_ORIG(MSG_LD_BIND_NOW), MSG_LD_BIND_NOW_SIZE) == 0)) {
1611 			select |= SEL_ACT_RT2;
1612 			val = RT_FL2_BINDNOW;
1613 			variable = ENV_FLG_BIND_NOW;
1614 		} else if ((len == MSG_LD_BIND_NOT_SIZE) && (strncmp(s1,
1615 		    MSG_ORIG(MSG_LD_BIND_NOT), MSG_LD_BIND_NOT_SIZE) == 0)) {
1616 			/*
1617 			 * Another trick, enabled to help debug AOUT
1618 			 * applications under BCP, but not documented for
1619 			 * general use.
1620 			 */
1621 			select |= SEL_ACT_RT;
1622 			val = RT_FL_NOBIND;
1623 			variable = ENV_FLG_BIND_NOT;
1624 		} else if ((len == MSG_LD_BINDINGS_SIZE) && (strncmp(s1,
1625 		    MSG_ORIG(MSG_LD_BINDINGS), MSG_LD_BINDINGS_SIZE) == 0)) {
1626 			/*
1627 			 * This variable is simply for backward compatibility.
1628 			 * If this and LD_DEBUG are both specified, only one of
1629 			 * the strings is going to get processed.
1630 			 */
1631 			select |= SEL_ACT_SPEC_2;
1632 			variable = ENV_FLG_BINDINGS;
1633 		}
1634 	}
1635 	/*
1636 	 * LD_CONFIG family.
1637 	 */
1638 	else if (*s1 == 'C') {
1639 		if ((len == MSG_LD_CONFGEN_SIZE) && (strncmp(s1,
1640 		    MSG_ORIG(MSG_LD_CONFGEN), MSG_LD_CONFGEN_SIZE) == 0)) {
1641 			/*
1642 			 * Set by crle(1) to indicate it's building a
1643 			 * configuration file, not documented for general use.
1644 			 */
1645 			select |= SEL_ACT_SPEC_2;
1646 			variable = ENV_FLG_CONFGEN;
1647 		} else if ((len == MSG_LD_CONFIG_SIZE) && (strncmp(s1,
1648 		    MSG_ORIG(MSG_LD_CONFIG), MSG_LD_CONFIG_SIZE) == 0)) {
1649 			/*
1650 			 * Secure applications must use a default configuration
1651 			 * file.  A setting from a configuration file doesn't
1652 			 * make sense (given we must be reading a configuration
1653 			 * file to have gotten this).
1654 			 */
1655 			if ((rtld_flags & RT_FL_SECURE) ||
1656 			    (env_flags & ENV_TYP_CONFIG))
1657 				return;
1658 			select |= SEL_ACT_STR;
1659 			str = &config->c_name;
1660 			variable = ENV_FLG_CONFIG;
1661 		}
1662 	}
1663 	/*
1664 	 * The LD_DEBUG family and LD_DEMANGLE.
1665 	 */
1666 	else if (*s1 == 'D') {
1667 		if ((len == MSG_LD_DEBUG_SIZE) && (strncmp(s1,
1668 		    MSG_ORIG(MSG_LD_DEBUG), MSG_LD_DEBUG_SIZE) == 0)) {
1669 			select |= SEL_ACT_STR;
1670 			if (select & SEL_REPLACE)
1671 				str = &rpl_debug;
1672 			else {
1673 				str = &prm_debug;
1674 				rpl_debug = 0;
1675 			}
1676 			variable = ENV_FLG_DEBUG;
1677 		} else if ((len == MSG_LD_DEBUG_OUTPUT_SIZE) && (strncmp(s1,
1678 		    MSG_ORIG(MSG_LD_DEBUG_OUTPUT),
1679 		    MSG_LD_DEBUG_OUTPUT_SIZE) == 0)) {
1680 			select |= SEL_ACT_STR;
1681 			str = &dbg_file;
1682 			variable = ENV_FLG_DEBUG_OUTPUT;
1683 		} else if ((len == MSG_LD_DEMANGLE_SIZE) && (strncmp(s1,
1684 		    MSG_ORIG(MSG_LD_DEMANGLE), MSG_LD_DEMANGLE_SIZE) == 0)) {
1685 			select |= SEL_ACT_RT;
1686 			val = RT_FL_DEMANGLE;
1687 			variable = ENV_FLG_DEMANGLE;
1688 		}
1689 	}
1690 	/*
1691 	 * LD_FLAGS - collect the best variable definition.  On completion of
1692 	 * environment variable processing pass the result to ld_flags_env()
1693 	 * where they'll be decomposed and passed back to this routine.
1694 	 */
1695 	else if (*s1 == 'F') {
1696 		if ((len == MSG_LD_FLAGS_SIZE) && (strncmp(s1,
1697 		    MSG_ORIG(MSG_LD_FLAGS), MSG_LD_FLAGS_SIZE) == 0)) {
1698 			select |= SEL_ACT_SPEC_1;
1699 			if (select & SEL_REPLACE)
1700 				str = &rpl_ldflags;
1701 			else {
1702 				str = &prm_ldflags;
1703 				rpl_ldflags = 0;
1704 			}
1705 			variable = ENV_FLG_FLAGS;
1706 		}
1707 	}
1708 	/*
1709 	 * LD_INIT (internal, used by ldd(1)).
1710 	 */
1711 	else if (*s1 == 'I') {
1712 		if ((len == MSG_LD_INIT_SIZE) && (strncmp(s1,
1713 		    MSG_ORIG(MSG_LD_INIT), MSG_LD_INIT_SIZE) == 0)) {
1714 			select |= SEL_ACT_LML;
1715 			val = LML_FLG_TRC_INIT;
1716 			variable = ENV_FLG_INIT;
1717 		}
1718 	}
1719 	/*
1720 	 * The LD_LIBRARY_PATH and LD_LOAD families.
1721 	 */
1722 	else if (*s1 == 'L') {
1723 		if ((len == MSG_LD_LIBPATH_SIZE) && (strncmp(s1,
1724 		    MSG_ORIG(MSG_LD_LIBPATH), MSG_LD_LIBPATH_SIZE) == 0)) {
1725 			select |= SEL_ACT_SPEC_1;
1726 			if (select & SEL_REPLACE)
1727 				str = &rpl_libpath;
1728 			else {
1729 				str = &prm_libpath;
1730 				rpl_libpath = 0;
1731 			}
1732 			variable = ENV_FLG_LIBPATH;
1733 		} else if ((len == MSG_LD_LOADAVAIL_SIZE) && (strncmp(s1,
1734 		    MSG_ORIG(MSG_LD_LOADAVAIL), MSG_LD_LOADAVAIL_SIZE) == 0)) {
1735 			/*
1736 			 * Internal use by crle(1), not documented for general
1737 			 * use.
1738 			 */
1739 			select |= SEL_ACT_LML;
1740 			val = LML_FLG_LOADAVAIL;
1741 			variable = ENV_FLG_LOADAVAIL;
1742 		} else if ((len == MSG_LD_LOADFLTR_SIZE) && (strncmp(s1,
1743 		    MSG_ORIG(MSG_LD_LOADFLTR), MSG_LD_LOADFLTR_SIZE) == 0)) {
1744 			select |= SEL_ACT_SPEC_2;
1745 			variable = ENV_FLG_LOADFLTR;
1746 		}
1747 	}
1748 	/*
1749 	 * The LD_NO family.
1750 	 */
1751 	else if (*s1 == 'N') {
1752 		if ((len == MSG_LD_NOAUDIT_SIZE) && (strncmp(s1,
1753 		    MSG_ORIG(MSG_LD_NOAUDIT), MSG_LD_NOAUDIT_SIZE) == 0)) {
1754 			select |= SEL_ACT_RT;
1755 			val = RT_FL_NOAUDIT;
1756 			variable = ENV_FLG_NOAUDIT;
1757 		} else if ((len == MSG_LD_NOAUXFLTR_SIZE) && (strncmp(s1,
1758 		    MSG_ORIG(MSG_LD_NOAUXFLTR), MSG_LD_NOAUXFLTR_SIZE) == 0)) {
1759 			select |= SEL_ACT_RT;
1760 			val = RT_FL_NOAUXFLTR;
1761 			variable = ENV_FLG_NOAUXFLTR;
1762 		} else if ((len == MSG_LD_NOBAPLT_SIZE) && (strncmp(s1,
1763 		    MSG_ORIG(MSG_LD_NOBAPLT), MSG_LD_NOBAPLT_SIZE) == 0)) {
1764 			select |= SEL_ACT_RT;
1765 			val = RT_FL_NOBAPLT;
1766 			variable = ENV_FLG_NOBAPLT;
1767 		} else if ((len == MSG_LD_NOCONFIG_SIZE) && (strncmp(s1,
1768 		    MSG_ORIG(MSG_LD_NOCONFIG), MSG_LD_NOCONFIG_SIZE) == 0)) {
1769 			select |= SEL_ACT_RT;
1770 			val = RT_FL_NOCFG;
1771 			variable = ENV_FLG_NOCONFIG;
1772 		} else if ((len == MSG_LD_NODIRCONFIG_SIZE) && (strncmp(s1,
1773 		    MSG_ORIG(MSG_LD_NODIRCONFIG),
1774 		    MSG_LD_NODIRCONFIG_SIZE) == 0)) {
1775 			select |= SEL_ACT_RT;
1776 			val = RT_FL_NODIRCFG;
1777 			variable = ENV_FLG_NODIRCONFIG;
1778 		} else if ((len == MSG_LD_NODIRECT_SIZE) && (strncmp(s1,
1779 		    MSG_ORIG(MSG_LD_NODIRECT), MSG_LD_NODIRECT_SIZE) == 0)) {
1780 			select |= SEL_ACT_LMLT;
1781 			val = LML_TFLG_NODIRECT;
1782 			variable = ENV_FLG_NODIRECT;
1783 		} else if ((len == MSG_LD_NOENVCONFIG_SIZE) && (strncmp(s1,
1784 		    MSG_ORIG(MSG_LD_NOENVCONFIG),
1785 		    MSG_LD_NOENVCONFIG_SIZE) == 0)) {
1786 			select |= SEL_ACT_RT;
1787 			val = RT_FL_NOENVCFG;
1788 			variable = ENV_FLG_NOENVCONFIG;
1789 		} else if ((len == MSG_LD_NOFLTCONFIG_SIZE) && (strncmp(s1,
1790 		    MSG_ORIG(MSG_LD_NOFLTCONFIG),
1791 		    MSG_LD_NOFLTCONFIG_SIZE) == 0)) {
1792 			select |= SEL_ACT_RT2;
1793 			val = RT_FL2_NOFLTCFG;
1794 			variable = ENV_FLG_NOFLTCONFIG;
1795 		} else if ((len == MSG_LD_NOLAZY_SIZE) && (strncmp(s1,
1796 		    MSG_ORIG(MSG_LD_NOLAZY), MSG_LD_NOLAZY_SIZE) == 0)) {
1797 			select |= SEL_ACT_LMLT;
1798 			val = LML_TFLG_NOLAZYLD;
1799 			variable = ENV_FLG_NOLAZY;
1800 		} else if ((len == MSG_LD_NOOBJALTER_SIZE) && (strncmp(s1,
1801 		    MSG_ORIG(MSG_LD_NOOBJALTER),
1802 		    MSG_LD_NOOBJALTER_SIZE) == 0)) {
1803 			select |= SEL_ACT_RT;
1804 			val = RT_FL_NOOBJALT;
1805 			variable = ENV_FLG_NOOBJALTER;
1806 		} else if ((len == MSG_LD_NOVERSION_SIZE) && (strncmp(s1,
1807 		    MSG_ORIG(MSG_LD_NOVERSION), MSG_LD_NOVERSION_SIZE) == 0)) {
1808 			select |= SEL_ACT_RT;
1809 			val = RT_FL_NOVERSION;
1810 			variable = ENV_FLG_NOVERSION;
1811 		} else if ((len == MSG_LD_NOUNRESWEAK_SIZE) && (strncmp(s1,
1812 		    MSG_ORIG(MSG_LD_NOUNRESWEAK),
1813 		    MSG_LD_NOUNRESWEAK_SIZE) == 0)) {
1814 			/*
1815 			 * LD_NOUNRESWEAK (internal, used by ldd(1)).
1816 			 */
1817 			select |= SEL_ACT_LML;
1818 			val = LML_FLG_TRC_NOUNRESWEAK;
1819 			variable = ENV_FLG_NOUNRESWEAK;
1820 		} else if ((len == MSG_LD_NOPAREXT_SIZE) && (strncmp(s1,
1821 		    MSG_ORIG(MSG_LD_NOPAREXT), MSG_LD_NOPAREXT_SIZE) == 0)) {
1822 			select |= SEL_ACT_LML;
1823 			val = LML_FLG_TRC_NOPAREXT;
1824 			variable = ENV_FLG_NOPAREXT;
1825 		}
1826 	}
1827 	/*
1828 	 * LD_PRELOAD and LD_PROFILE family.
1829 	 */
1830 	else if (*s1 == 'P') {
1831 		if ((len == MSG_LD_PRELOAD_SIZE) && (strncmp(s1,
1832 		    MSG_ORIG(MSG_LD_PRELOAD), MSG_LD_PRELOAD_SIZE) == 0)) {
1833 			select |= SEL_ACT_STR;
1834 			if (select & SEL_REPLACE)
1835 				str = &rpl_preload;
1836 			else  {
1837 				str = &prm_preload;
1838 				rpl_preload = 0;
1839 			}
1840 			variable = ENV_FLG_PRELOAD;
1841 		} else if ((len == MSG_LD_PROFILE_SIZE) && (strncmp(s1,
1842 		    MSG_ORIG(MSG_LD_PROFILE), MSG_LD_PROFILE_SIZE) == 0)) {
1843 			/*
1844 			 * Only one user library can be profiled at a time.
1845 			 */
1846 			select |= SEL_ACT_SPEC_2;
1847 			variable = ENV_FLG_PROFILE;
1848 		} else if ((len == MSG_LD_PROFILE_OUTPUT_SIZE) && (strncmp(s1,
1849 		    MSG_ORIG(MSG_LD_PROFILE_OUTPUT),
1850 		    MSG_LD_PROFILE_OUTPUT_SIZE) == 0)) {
1851 			/*
1852 			 * Only one user library can be profiled at a time.
1853 			 */
1854 			select |= SEL_ACT_STR;
1855 			str = &profile_out;
1856 			variable = ENV_FLG_PROFILE_OUTPUT;
1857 		}
1858 	}
1859 	/*
1860 	 * LD_SIGNAL.
1861 	 */
1862 	else if (*s1 == 'S') {
1863 		if (rtld_flags & RT_FL_SECURE)
1864 			return;
1865 		if ((len == MSG_LD_SIGNAL_SIZE) &&
1866 		    (strncmp(s1, MSG_ORIG(MSG_LD_SIGNAL),
1867 		    MSG_LD_SIGNAL_SIZE) == 0)) {
1868 			select |= SEL_ACT_SPEC_2;
1869 			variable = ENV_FLG_SIGNAL;
1870 		}
1871 	}
1872 	/*
1873 	 * The LD_TRACE family (internal, used by ldd(1)).  This definition is
1874 	 * the key to enabling all other ldd(1) specific environment variables.
1875 	 * In case an auditor is called, which in turn might exec(2) a
1876 	 * subprocess, this variable is disabled, so that any subprocess
1877 	 * escapes ldd(1) processing.
1878 	 */
1879 	else if (*s1 == 'T') {
1880 		if (((len == MSG_LD_TRACE_OBJS_SIZE) &&
1881 		    (strncmp(s1, MSG_ORIG(MSG_LD_TRACE_OBJS),
1882 		    MSG_LD_TRACE_OBJS_SIZE) == 0)) ||
1883 		    ((len == MSG_LD_TRACE_OBJS_E_SIZE) &&
1884 		    (((strncmp(s1, MSG_ORIG(MSG_LD_TRACE_OBJS_E),
1885 		    MSG_LD_TRACE_OBJS_E_SIZE) == 0) && !aout) ||
1886 		    ((strncmp(s1, MSG_ORIG(MSG_LD_TRACE_OBJS_A),
1887 		    MSG_LD_TRACE_OBJS_A_SIZE) == 0) && aout)))) {
1888 			char	*s0 = (char *)s1;
1889 
1890 			select |= SEL_ACT_SPEC_2;
1891 			variable = ENV_FLG_TRACE_OBJS;
1892 
1893 #if	defined(__sparc) || defined(__x86)
1894 			/*
1895 			 * The simplest way to "disable" this variable is to
1896 			 * truncate this string to "LD_'\0'". This string is
1897 			 * ignored by any ld.so.1 environment processing.
1898 			 * Use of such interfaces as unsetenv(3c) are overkill,
1899 			 * and would drag too much libc implementation detail
1900 			 * into ld.so.1.
1901 			 */
1902 			*s0 = '\0';
1903 #else
1904 /*
1905  * Verify that the above write is appropriate for any new platforms.
1906  */
1907 #error	unsupported architecture!
1908 #endif
1909 		} else if ((len == MSG_LD_TRACE_PTHS_SIZE) && (strncmp(s1,
1910 		    MSG_ORIG(MSG_LD_TRACE_PTHS),
1911 		    MSG_LD_TRACE_PTHS_SIZE) == 0)) {
1912 			select |= SEL_ACT_LML;
1913 			val = LML_FLG_TRC_SEARCH;
1914 			variable = ENV_FLG_TRACE_PTHS;
1915 		}
1916 	}
1917 	/*
1918 	 * LD_UNREF and LD_UNUSED (internal, used by ldd(1)).
1919 	 */
1920 	else if (*s1 == 'U') {
1921 		if ((len == MSG_LD_UNREF_SIZE) && (strncmp(s1,
1922 		    MSG_ORIG(MSG_LD_UNREF), MSG_LD_UNREF_SIZE) == 0)) {
1923 			select |= SEL_ACT_LML;
1924 			val = LML_FLG_TRC_UNREF;
1925 			variable = ENV_FLG_UNREF;
1926 		} else if ((len == MSG_LD_UNUSED_SIZE) && (strncmp(s1,
1927 		    MSG_ORIG(MSG_LD_UNUSED), MSG_LD_UNUSED_SIZE) == 0)) {
1928 			select |= SEL_ACT_LML;
1929 			val = LML_FLG_TRC_UNUSED;
1930 			variable = ENV_FLG_UNUSED;
1931 		}
1932 	}
1933 	/*
1934 	 * LD_VERBOSE (internal, used by ldd(1)).
1935 	 */
1936 	else if (*s1 == 'V') {
1937 		if ((len == MSG_LD_VERBOSE_SIZE) && (strncmp(s1,
1938 		    MSG_ORIG(MSG_LD_VERBOSE), MSG_LD_VERBOSE_SIZE) == 0)) {
1939 			select |= SEL_ACT_LML;
1940 			val = LML_FLG_TRC_VERBOSE;
1941 			variable = ENV_FLG_VERBOSE;
1942 		}
1943 	}
1944 	/*
1945 	 * LD_WARN (internal, used by ldd(1)).
1946 	 */
1947 	else if (*s1 == 'W') {
1948 		if ((len == MSG_LD_WARN_SIZE) && (strncmp(s1,
1949 		    MSG_ORIG(MSG_LD_WARN), MSG_LD_WARN_SIZE) == 0)) {
1950 			select |= SEL_ACT_LML;
1951 			val = LML_FLG_TRC_WARN;
1952 			variable = ENV_FLG_WARN;
1953 		}
1954 	}
1955 
1956 	if (variable == 0)
1957 		return;
1958 
1959 	/*
1960 	 * If the variable is already processed with ISA specific variable,
1961 	 * no further processing needed.
1962 	 */
1963 	if (((select & SEL_REPLACE) && (rplisa & variable)) ||
1964 	    ((select & SEL_PERMANT) && (prmisa & variable)))
1965 		return;
1966 
1967 	/*
1968 	 * Now mark the appropriate variables.
1969 	 * If the replaceable variable is already set, then the
1970 	 * process environment variable must be set. Any replaceable
1971 	 * variable specified in a configuration file can be ignored.
1972 	 */
1973 	if (env_flags & ENV_TYP_ISA) {
1974 		/*
1975 		 * This is ISA setting. We do the setting
1976 		 * even if s2 is NULL.
1977 		 * If s2 is NULL, we might need to undo
1978 		 * the setting.
1979 		 */
1980 		if (select & SEL_REPLACE) {
1981 			if (rplisa & variable)
1982 				return;
1983 			rplisa |= variable;
1984 		} else {
1985 			prmisa |= variable;
1986 		}
1987 	} else if (s2) {
1988 		/*
1989 		 * This is non0-ISA setting
1990 		 */
1991 		if (select & SEL_REPLACE) {
1992 			if (rplgen & variable)
1993 				return;
1994 			rplgen |= variable;
1995 		} else
1996 			prmgen |= variable;
1997 	} else
1998 		/*
1999 		 * This is non-ISA setting which
2000 		 * can be ignored.
2001 		 */
2002 		return;
2003 
2004 	/*
2005 	 * Now perform the setting.
2006 	 */
2007 	if (select & SEL_ACT_RT) {
2008 		if (s2)
2009 			rtld_flags |= val;
2010 		else
2011 			rtld_flags &= ~val;
2012 	} else if (select & SEL_ACT_RT2) {
2013 		if (s2)
2014 			rtld_flags2 |= val;
2015 		else
2016 			rtld_flags2 &= ~val;
2017 	} else if (select & SEL_ACT_STR)
2018 		*str = s2;
2019 	else if (select & SEL_ACT_LML) {
2020 		if (s2)
2021 			*lmflags |= val;
2022 		else
2023 			*lmflags &= ~val;
2024 	} else if (select & SEL_ACT_LMLT) {
2025 		if (s2)
2026 			*lmtflags |= val;
2027 		else
2028 			*lmtflags &= ~val;
2029 	} else if (select & SEL_ACT_SPEC_1) {
2030 		/*
2031 		 * variable is either ENV_FLG_FLAGS or ENV_FLG_LIBPATH
2032 		 */
2033 		*str = s2;
2034 		if ((select & SEL_REPLACE) && (env_flags & ENV_TYP_CONFIG)) {
2035 			if (s2) {
2036 				if (variable == ENV_FLG_FLAGS)
2037 					env_info |= ENV_INF_FLAGCFG;
2038 				else
2039 					env_info |= ENV_INF_PATHCFG;
2040 			} else {
2041 				if (variable == ENV_FLG_FLAGS)
2042 					env_info &= ~ENV_INF_FLAGCFG;
2043 				else
2044 					env_info &= ~ENV_INF_PATHCFG;
2045 			}
2046 		}
2047 	} else if (select & SEL_ACT_SPEC_2) {
2048 		/*
2049 		 * variables can be: ENV_FLG_
2050 		 * 	AUDIT_ARGS, BINDING, CONCURRENCY, CONFGEN,
2051 		 *	LOADFLTR, PROFILE, SIGNAL, TRACE_OBJS
2052 		 */
2053 		if (variable == ENV_FLG_AUDIT_ARGS) {
2054 			if (s2) {
2055 				audit_argcnt = atoi(s2);
2056 				audit_argcnt += audit_argcnt % 2;
2057 			} else
2058 				audit_argcnt = 0;
2059 		} else if (variable == ENV_FLG_BINDINGS) {
2060 			if (s2)
2061 				rpl_debug = MSG_ORIG(MSG_TKN_BINDINGS);
2062 			else
2063 				rpl_debug = 0;
2064 		} else if (variable == ENV_FLG_CONFGEN) {
2065 			if (s2) {
2066 				rtld_flags |= RT_FL_CONFGEN;
2067 				*lmflags |= LML_FLG_IGNRELERR;
2068 			} else {
2069 				rtld_flags &= ~RT_FL_CONFGEN;
2070 				*lmflags &= ~LML_FLG_IGNRELERR;
2071 			}
2072 		} else if (variable == ENV_FLG_LOADFLTR) {
2073 			if (s2) {
2074 				*lmtflags |= LML_TFLG_LOADFLTR;
2075 				if (*s2 == '2')
2076 					rtld_flags |= RT_FL_WARNFLTR;
2077 			} else {
2078 				*lmtflags &= ~LML_TFLG_LOADFLTR;
2079 				rtld_flags &= ~RT_FL_WARNFLTR;
2080 			}
2081 		} else if (variable == ENV_FLG_PROFILE) {
2082 			profile_name = s2;
2083 			if (s2) {
2084 				if (strcmp(s2, MSG_ORIG(MSG_FIL_RTLD)) == 0) {
2085 					return;
2086 				}
2087 				/* BEGIN CSTYLED */
2088 				if (rtld_flags & RT_FL_SECURE) {
2089 					profile_lib =
2090 #if	defined(_ELF64)
2091 					    MSG_ORIG(MSG_PTH_LDPROFSE_64);
2092 #else
2093 					    MSG_ORIG(MSG_PTH_LDPROFSE);
2094 #endif
2095 				} else {
2096 					profile_lib =
2097 #if	defined(_ELF64)
2098 					    MSG_ORIG(MSG_PTH_LDPROF_64);
2099 #else
2100 					    MSG_ORIG(MSG_PTH_LDPROF);
2101 #endif
2102 				}
2103 				/* END CSTYLED */
2104 			} else
2105 				profile_lib = NULL;
2106 		} else if (variable == ENV_FLG_SIGNAL) {
2107 			killsig = s2 ? atoi(s2) : SIGKILL;
2108 		} else if (variable == ENV_FLG_TRACE_OBJS) {
2109 			if (s2) {
2110 				*lmflags |= LML_FLG_TRC_ENABLE;
2111 				if (*s2 == '2')
2112 					*lmflags |= LML_FLG_TRC_LDDSTUB;
2113 			} else
2114 				*lmflags &=
2115 				    ~(LML_FLG_TRC_ENABLE|LML_FLG_TRC_LDDSTUB);
2116 		}
2117 	}
2118 }
2119 
2120 /*
2121  * Determine whether we have an architecture specific environment variable.
2122  * If we do, and we're the wrong architecture, it'll just get ignored.
2123  * Otherwise the variable is processed in it's architecture neutral form.
2124  */
2125 static int
2126 ld_arch_env(const char *s1, size_t *len)
2127 {
2128 	size_t	_len = *len - 3;
2129 
2130 	if (s1[_len++] == '_') {
2131 		if ((s1[_len] == '3') && (s1[_len + 1] == '2')) {
2132 #if	defined(_ELF64)
2133 			return (ENV_TYP_IGNORE);
2134 #else
2135 			*len = *len - 3;
2136 			return (ENV_TYP_ISA);
2137 #endif
2138 		}
2139 		if ((s1[_len] == '6') && (s1[_len + 1] == '4')) {
2140 #if	defined(_ELF64)
2141 			*len = *len - 3;
2142 			return (ENV_TYP_ISA);
2143 #else
2144 			return (ENV_TYP_IGNORE);
2145 #endif
2146 		}
2147 	}
2148 	return (0);
2149 }
2150 
2151 
2152 /*
2153  * Process an LD_FLAGS environment variable.  The value can be a comma
2154  * separated set of tokens, which are sent (in upper case) into the generic
2155  * LD_XXXX environment variable engine.  For example:
2156  *
2157  *	LD_FLAGS=bind_now		->	LD_BIND_NOW=1
2158  *	LD_FLAGS=library_path=/foo:.	->	LD_LIBRARY_PATH=/foo:.
2159  *	LD_FLAGS=debug=files:detail	->	LD_DEBUG=files:detail
2160  * or
2161  *	LD_FLAGS=bind_now,library_path=/foo:.,debug=files:detail
2162  */
2163 static int
2164 ld_flags_env(const char *str, Word *lmflags, Word *lmtflags,
2165     uint_t env_flags, int aout)
2166 {
2167 	char	*nstr, *sstr, *estr = NULL;
2168 	size_t	nlen, len;
2169 
2170 	if (str == NULL)
2171 		return (0);
2172 
2173 	/*
2174 	 * Create a new string as we're going to transform the token(s) into
2175 	 * uppercase and separate tokens with nulls.
2176 	 */
2177 	len = strlen(str);
2178 	if ((nstr = malloc(len + 1)) == NULL)
2179 		return (1);
2180 	(void) strcpy(nstr, str);
2181 
2182 	for (sstr = nstr; sstr; sstr++, len--) {
2183 		int	flags;
2184 
2185 		if ((*sstr != '\0') && (*sstr != ',')) {
2186 			if (estr == NULL) {
2187 				if (*sstr == '=')
2188 					estr = sstr;
2189 				else {
2190 					/*
2191 					 * Translate token to uppercase.  Don't
2192 					 * use toupper(3C) as including this
2193 					 * code doubles the size of ld.so.1.
2194 					 */
2195 					if ((*sstr >= 'a') && (*sstr <= 'z'))
2196 						*sstr = *sstr - ('a' - 'A');
2197 				}
2198 			}
2199 			continue;
2200 		}
2201 
2202 		*sstr = '\0';
2203 		if (estr) {
2204 			nlen = estr - nstr;
2205 			if ((*++estr == '\0') || (*estr == ','))
2206 				estr = 0;
2207 		} else
2208 			nlen = sstr - nstr;
2209 
2210 		/*
2211 		 * Fabricate a boolean definition for any unqualified variable.
2212 		 * Thus LD_FLAGS=bind_now is represented as BIND_NOW=(null).
2213 		 * The value is sufficient to assert any boolean variables, plus
2214 		 * the term "(null)" is specifically chosen in case someone
2215 		 * mistakenly supplies something like LD_FLAGS=library_path.
2216 		 */
2217 		if (estr == NULL)
2218 			estr = (char *)MSG_INTL(MSG_STR_NULL);
2219 
2220 		/*
2221 		 * Determine whether the environment variable is 32- or 64-bit
2222 		 * specific.  The length, len, will reflect the architecture
2223 		 * neutral portion of the string.
2224 		 */
2225 		if ((flags = ld_arch_env(nstr, &nlen)) != ENV_TYP_IGNORE) {
2226 			ld_generic_env(nstr, nlen, estr, lmflags,
2227 			    lmtflags, (env_flags | flags), aout);
2228 		}
2229 		if (len == 0)
2230 			return (0);
2231 
2232 		nstr = sstr + 1;
2233 		estr = 0;
2234 	}
2235 	return (0);
2236 }
2237 
2238 
2239 /*
2240  * Process a single environment string.  Only strings starting with `LD_' are
2241  * reserved for our use.  By convention, all strings should be of the form
2242  * `LD_XXXX=', if the string is followed by a non-null value the appropriate
2243  * functionality is enabled.  Also pick off applicable locale variables.
2244  */
2245 #define	LOC_LANG	1
2246 #define	LOC_MESG	2
2247 #define	LOC_ALL		3
2248 
2249 static void
2250 ld_str_env(const char *s1, Word *lmflags, Word *lmtflags, uint_t env_flags,
2251     int aout)
2252 {
2253 	const char	*s2;
2254 	static		size_t	loc = 0;
2255 
2256 	if (*s1++ != 'L')
2257 		return;
2258 
2259 	/*
2260 	 * See if we have any locale environment settings.  These environment
2261 	 * variables have a precedence, LC_ALL is higher than LC_MESSAGES which
2262 	 * is higher than LANG.
2263 	 */
2264 	s2 = s1;
2265 	if ((*s2++ == 'C') && (*s2++ == '_') && (*s2 != '\0')) {
2266 		if (strncmp(s2, MSG_ORIG(MSG_LC_ALL), MSG_LC_ALL_SIZE) == 0) {
2267 			s2 += MSG_LC_ALL_SIZE;
2268 			if ((*s2 != '\0') && (loc < LOC_ALL)) {
2269 				glcs[CI_LCMESSAGES].lc_un.lc_ptr = (char *)s2;
2270 				loc = LOC_ALL;
2271 			}
2272 		} else if (strncmp(s2, MSG_ORIG(MSG_LC_MESSAGES),
2273 		    MSG_LC_MESSAGES_SIZE) == 0) {
2274 			s2 += MSG_LC_MESSAGES_SIZE;
2275 			if ((*s2 != '\0') && (loc < LOC_MESG)) {
2276 				glcs[CI_LCMESSAGES].lc_un.lc_ptr = (char *)s2;
2277 				loc = LOC_MESG;
2278 			}
2279 		}
2280 		return;
2281 	}
2282 
2283 	s2 = s1;
2284 	if ((*s2++ == 'A') && (*s2++ == 'N') && (*s2++ == 'G') &&
2285 	    (*s2++ == '=') && (*s2 != '\0') && (loc < LOC_LANG)) {
2286 		glcs[CI_LCMESSAGES].lc_un.lc_ptr = (char *)s2;
2287 		loc = LOC_LANG;
2288 		return;
2289 	}
2290 
2291 	/*
2292 	 * Pick off any LD_XXXX environment variables.
2293 	 */
2294 	if ((*s1++ == 'D') && (*s1++ == '_') && (*s1 != '\0')) {
2295 		size_t	len;
2296 		int	flags;
2297 
2298 		/*
2299 		 * In a branded process we must ignore all LD_XXXX env vars
2300 		 * because they are intended for the brand's linker.
2301 		 * To affect the Solaris linker, use LD_BRAND_XXXX instead.
2302 		 */
2303 		if (rtld_flags2 & RT_FL2_BRANDED) {
2304 			if (strncmp(s1, MSG_ORIG(MSG_LD_BRAND_PREFIX),
2305 			    MSG_LD_BRAND_PREFIX_SIZE) != 0)
2306 				return;
2307 			s1 += MSG_LD_BRAND_PREFIX_SIZE;
2308 		}
2309 
2310 		/*
2311 		 * Environment variables with no value (ie. LD_XXXX=) typically
2312 		 * have no impact, however if environment variables are defined
2313 		 * within a configuration file, these null user settings can be
2314 		 * used to disable any configuration replaceable definitions.
2315 		 */
2316 		if ((s2 = strchr(s1, '=')) == NULL) {
2317 			len = strlen(s1);
2318 			s2 = 0;
2319 		} else if (*++s2 == '\0') {
2320 			len = strlen(s1) - 1;
2321 			s2 = 0;
2322 		} else {
2323 			len = s2 - s1 - 1;
2324 			while (isspace(*s2))
2325 				s2++;
2326 		}
2327 
2328 		/*
2329 		 * Determine whether the environment variable is 32- or 64-bit
2330 		 * specific.  The length, len, will reflect the architecture
2331 		 * neutral portion of the string.
2332 		 */
2333 		if ((flags = ld_arch_env(s1, &len)) == ENV_TYP_IGNORE)
2334 			return;
2335 		env_flags |= flags;
2336 
2337 		ld_generic_env(s1, len, s2, lmflags, lmtflags, env_flags, aout);
2338 	}
2339 }
2340 
2341 /*
2342  * Internal getenv routine.  Called immediately after ld.so.1 initializes
2343  * itself.
2344  */
2345 int
2346 readenv_user(const char **envp, Word *lmflags, Word *lmtflags, int aout)
2347 {
2348 	char	*locale;
2349 
2350 	if (envp == NULL)
2351 		return (0);
2352 
2353 	while (*envp != NULL)
2354 		ld_str_env(*envp++, lmflags, lmtflags, 0, aout);
2355 
2356 	/*
2357 	 * Having collected the best representation of any LD_FLAGS, process
2358 	 * these strings.
2359 	 */
2360 	if (ld_flags_env(rpl_ldflags, lmflags, lmtflags, 0, aout) == 1)
2361 		return (1);
2362 
2363 	/*
2364 	 * Don't allow environment controlled auditing when tracing or if
2365 	 * explicitly disabled.  Trigger all tracing modes from
2366 	 * LML_FLG_TRC_ENABLE.
2367 	 */
2368 	if ((*lmflags & LML_FLG_TRC_ENABLE) || (rtld_flags & RT_FL_NOAUDIT))
2369 		rpl_audit = profile_lib = profile_name = NULL;
2370 	if ((*lmflags & LML_FLG_TRC_ENABLE) == 0)
2371 		*lmflags &= ~LML_MSK_TRC;
2372 
2373 	/*
2374 	 * If both LD_BIND_NOW and LD_BIND_LAZY are specified, the former wins.
2375 	 */
2376 	if ((rtld_flags2 & (RT_FL2_BINDNOW | RT_FL2_BINDLAZY)) ==
2377 	    (RT_FL2_BINDNOW | RT_FL2_BINDLAZY))
2378 		rtld_flags2 &= ~RT_FL2_BINDLAZY;
2379 
2380 	/*
2381 	 * When using ldd(1) -r or -d against an executable, assert -p.
2382 	 */
2383 	if ((*lmflags &
2384 	    (LML_FLG_TRC_WARN | LML_FLG_TRC_LDDSTUB)) == LML_FLG_TRC_WARN)
2385 		*lmflags |= LML_FLG_TRC_NOPAREXT;
2386 
2387 	/*
2388 	 * If we have a locale setting make sure its worth processing further.
2389 	 * C and POSIX locales don't need any processing.  In addition, to
2390 	 * ensure no one escapes the /usr/lib/locale hierarchy, don't allow
2391 	 * the locale to contain a segment that leads upward in the file system
2392 	 * hierarchy (i.e. no '..' segments).   Given that we'll be confined to
2393 	 * the /usr/lib/locale hierarchy, there is no need to extensively
2394 	 * validate the mode or ownership of any message file (as libc's
2395 	 * generic handling of message files does).  Duplicate the string so
2396 	 * that new locale setting can generically cleanup any previous locales.
2397 	 */
2398 	if ((locale = glcs[CI_LCMESSAGES].lc_un.lc_ptr) != 0) {
2399 		if (((*locale == 'C') && (*(locale + 1) == '\0')) ||
2400 		    (strcmp(locale, MSG_ORIG(MSG_TKN_POSIX)) == 0) ||
2401 		    (strstr(locale, MSG_ORIG(MSG_TKN_DOTDOT)) != NULL))
2402 			glcs[CI_LCMESSAGES].lc_un.lc_ptr = 0;
2403 		else
2404 			glcs[CI_LCMESSAGES].lc_un.lc_ptr = strdup(locale);
2405 	}
2406 	return (0);
2407 }
2408 
2409 /*
2410  * Configuration environment processing.  Called after the a.out has been
2411  * processed (as the a.out can specify its own configuration file).
2412  */
2413 int
2414 readenv_config(Rtc_env * envtbl, Addr addr, int aout)
2415 {
2416 	Word	*lmflags = &(lml_main.lm_flags);
2417 	Word	*lmtflags = &(lml_main.lm_tflags);
2418 
2419 	if (envtbl == NULL)
2420 		return (0);
2421 
2422 	while (envtbl->env_str) {
2423 		uint_t	env_flags = ENV_TYP_CONFIG;
2424 
2425 		if (envtbl->env_flags & RTC_ENV_PERMANT)
2426 			env_flags |= ENV_TYP_PERMANT;
2427 
2428 		ld_str_env((const char *)(envtbl->env_str + addr),
2429 		    lmflags, lmtflags, env_flags, 0);
2430 		envtbl++;
2431 	}
2432 
2433 	/*
2434 	 * Having collected the best representation of any LD_FLAGS, process
2435 	 * these strings.
2436 	 */
2437 	if (ld_flags_env(rpl_ldflags, lmflags, lmtflags, 0, aout) == 1)
2438 		return (1);
2439 	if (ld_flags_env(prm_ldflags, lmflags, lmtflags, ENV_TYP_CONFIG,
2440 	    aout) == 1)
2441 		return (1);
2442 
2443 	/*
2444 	 * Don't allow environment controlled auditing when tracing or if
2445 	 * explicitly disabled.  Trigger all tracing modes from
2446 	 * LML_FLG_TRC_ENABLE.
2447 	 */
2448 	if ((*lmflags & LML_FLG_TRC_ENABLE) || (rtld_flags & RT_FL_NOAUDIT))
2449 		prm_audit = profile_lib = profile_name = NULL;
2450 	if ((*lmflags & LML_FLG_TRC_ENABLE) == 0)
2451 		*lmflags &= ~LML_MSK_TRC;
2452 
2453 	return (0);
2454 }
2455 
2456 int
2457 dowrite(Prfbuf * prf)
2458 {
2459 	/*
2460 	 * We do not have a valid file descriptor, so we are unable
2461 	 * to flush the buffer.
2462 	 */
2463 	if (prf->pr_fd == -1)
2464 		return (0);
2465 	(void) write(prf->pr_fd, prf->pr_buf, prf->pr_cur - prf->pr_buf);
2466 	prf->pr_cur = prf->pr_buf;
2467 	return (1);
2468 }
2469 
2470 /*
2471  * Simplified printing.  The following conversion specifications are supported:
2472  *
2473  *	% [#] [-] [min field width] [. precision] s|d|x|c
2474  *
2475  *
2476  * dorprf takes the output buffer in the form of Prfbuf which permits
2477  * the verification of the output buffer size and the concatenation
2478  * of data to an already existing output buffer.  The Prfbuf
2479  * structure contains the following:
2480  *
2481  *  pr_buf	pointer to the beginning of the output buffer.
2482  *  pr_cur	pointer to the next available byte in the output buffer.  By
2483  *		setting pr_cur ahead of pr_buf you can append to an already
2484  *		existing buffer.
2485  *  pr_len	the size of the output buffer.  By setting pr_len to '0' you
2486  *		disable protection from overflows in the output buffer.
2487  *  pr_fd	a pointer to the file-descriptor the buffer will eventually be
2488  *		output to.  If pr_fd is set to '-1' then it's assumed there is
2489  *		no output buffer, and doprf() will return with an error to
2490  *		indicate an output buffer overflow.  If pr_fd is > -1 then when
2491  *		the output buffer is filled it will be flushed to pr_fd and will
2492  *		then be	available for additional data.
2493  */
2494 #define	FLG_UT_MINUS	0x0001	/* - */
2495 #define	FLG_UT_SHARP	0x0002	/* # */
2496 #define	FLG_UT_DOTSEEN	0x0008	/* dot appeared in format spec */
2497 
2498 /*
2499  * This macro is for use from within doprf only.  It is to be used for checking
2500  * the output buffer size and placing characters into the buffer.
2501  */
2502 #define	PUTC(c) \
2503 	{ \
2504 		char tmpc; \
2505 		\
2506 		tmpc = (c); \
2507 		if (bufsiz && (bp >= bufend)) { \
2508 			prf->pr_cur = bp; \
2509 			if (dowrite(prf) == 0) \
2510 				return (0); \
2511 			bp = prf->pr_cur; \
2512 		} \
2513 		*bp++ = tmpc; \
2514 	}
2515 
2516 /*
2517  * Define a local buffer size for building a numeric value - large enough to
2518  * hold a 64-bit value.
2519  */
2520 #define	NUM_SIZE	22
2521 
2522 size_t
2523 doprf(const char *format, va_list args, Prfbuf *prf)
2524 {
2525 	char	c;
2526 	char	*bp = prf->pr_cur;
2527 	char	*bufend = prf->pr_buf + prf->pr_len;
2528 	size_t	bufsiz = prf->pr_len;
2529 
2530 	while ((c = *format++) != '\0') {
2531 		if (c != '%') {
2532 			PUTC(c);
2533 		} else {
2534 			int	base = 0, flag = 0, width = 0, prec = 0;
2535 			size_t	_i;
2536 			int	_c, _n;
2537 			char	*_s;
2538 			int	ls = 0;
2539 again:
2540 			c = *format++;
2541 			switch (c) {
2542 			case '-':
2543 				flag |= FLG_UT_MINUS;
2544 				goto again;
2545 			case '#':
2546 				flag |= FLG_UT_SHARP;
2547 				goto again;
2548 			case '.':
2549 				flag |= FLG_UT_DOTSEEN;
2550 				goto again;
2551 			case '0':
2552 			case '1':
2553 			case '2':
2554 			case '3':
2555 			case '4':
2556 			case '5':
2557 			case '6':
2558 			case '7':
2559 			case '8':
2560 			case '9':
2561 				if (flag & FLG_UT_DOTSEEN)
2562 					prec = (prec * 10) + c - '0';
2563 				else
2564 					width = (width * 10) + c - '0';
2565 				goto again;
2566 			case 'x':
2567 			case 'X':
2568 				base = 16;
2569 				break;
2570 			case 'd':
2571 			case 'D':
2572 			case 'u':
2573 				base = 10;
2574 				flag &= ~FLG_UT_SHARP;
2575 				break;
2576 			case 'l':
2577 				base = 10;
2578 				ls++; /* number of l's (long or long long) */
2579 				if ((*format == 'l') ||
2580 				    (*format == 'd') || (*format == 'D') ||
2581 				    (*format == 'x') || (*format == 'X') ||
2582 				    (*format == 'o') || (*format == 'O'))
2583 					goto again;
2584 				break;
2585 			case 'o':
2586 			case 'O':
2587 				base = 8;
2588 				break;
2589 			case 'c':
2590 				_c = va_arg(args, int);
2591 
2592 				for (_i = 24; _i > 0; _i -= 8) {
2593 					if ((c = ((_c >> _i) & 0x7f)) != 0) {
2594 						PUTC(c);
2595 					}
2596 				}
2597 				if ((c = ((_c >> _i) & 0x7f)) != 0) {
2598 					PUTC(c);
2599 				}
2600 				break;
2601 			case 's':
2602 				_s = va_arg(args, char *);
2603 				_i = strlen(_s);
2604 				/* LINTED */
2605 				_n = (int)(width - _i);
2606 				if (!prec)
2607 					/* LINTED */
2608 					prec = (int)_i;
2609 
2610 				if (width && !(flag & FLG_UT_MINUS)) {
2611 					while (_n-- > 0)
2612 						PUTC(' ');
2613 				}
2614 				while (((c = *_s++) != 0) && prec--) {
2615 					PUTC(c);
2616 				}
2617 				if (width && (flag & FLG_UT_MINUS)) {
2618 					while (_n-- > 0)
2619 						PUTC(' ');
2620 				}
2621 				break;
2622 			case '%':
2623 				PUTC('%');
2624 				break;
2625 			default:
2626 				break;
2627 			}
2628 
2629 			/*
2630 			 * Numeric processing
2631 			 */
2632 			if (base) {
2633 				char		local[NUM_SIZE];
2634 				size_t		ssize = 0, psize = 0;
2635 				const char	*string =
2636 				    MSG_ORIG(MSG_STR_HEXNUM);
2637 				const char	*prefix =
2638 				    MSG_ORIG(MSG_STR_EMPTY);
2639 				u_longlong_t	num;
2640 
2641 				switch (ls) {
2642 				case 0:	/* int */
2643 					num = (u_longlong_t)
2644 					    va_arg(args, uint_t);
2645 					break;
2646 				case 1:	/* long */
2647 					num = (u_longlong_t)
2648 					    va_arg(args, ulong_t);
2649 					break;
2650 				case 2:	/* long long */
2651 					num = va_arg(args, u_longlong_t);
2652 					break;
2653 				}
2654 
2655 				if (flag & FLG_UT_SHARP) {
2656 					if (base == 16) {
2657 						prefix = MSG_ORIG(MSG_STR_HEX);
2658 						psize = 2;
2659 					} else {
2660 						prefix = MSG_ORIG(MSG_STR_ZERO);
2661 						psize = 1;
2662 					}
2663 				}
2664 				if ((base == 10) && (long)num < 0) {
2665 					prefix = MSG_ORIG(MSG_STR_NEGATE);
2666 					psize = MSG_STR_NEGATE_SIZE;
2667 					num = (u_longlong_t)(-(longlong_t)num);
2668 				}
2669 
2670 				/*
2671 				 * Convert the numeric value into a local
2672 				 * string (stored in reverse order).
2673 				 */
2674 				_s = local;
2675 				do {
2676 					*_s++ = string[num % base];
2677 					num /= base;
2678 					ssize++;
2679 				} while (num);
2680 
2681 				ASSERT(ssize < sizeof (local));
2682 
2683 				/*
2684 				 * Provide any precision or width padding.
2685 				 */
2686 				if (prec) {
2687 					/* LINTED */
2688 					_n = (int)(prec - ssize);
2689 					while ((_n-- > 0) &&
2690 					    (ssize < sizeof (local))) {
2691 						*_s++ = '0';
2692 						ssize++;
2693 					}
2694 				}
2695 				if (width && !(flag & FLG_UT_MINUS)) {
2696 					/* LINTED */
2697 					_n = (int)(width - ssize - psize);
2698 					while (_n-- > 0) {
2699 						PUTC(' ');
2700 					}
2701 				}
2702 
2703 				/*
2704 				 * Print any prefix and the numeric string
2705 				 */
2706 				while (*prefix)
2707 					PUTC(*prefix++);
2708 				do {
2709 					PUTC(*--_s);
2710 				} while (_s > local);
2711 
2712 				/*
2713 				 * Provide any width padding.
2714 				 */
2715 				if (width && (flag & FLG_UT_MINUS)) {
2716 					/* LINTED */
2717 					_n = (int)(width - ssize - psize);
2718 					while (_n-- > 0)
2719 						PUTC(' ');
2720 				}
2721 			}
2722 		}
2723 	}
2724 
2725 	PUTC('\0');
2726 	prf->pr_cur = bp;
2727 	return (1);
2728 }
2729 
2730 static int
2731 doprintf(const char *format, va_list args, Prfbuf *prf)
2732 {
2733 	char	*ocur = prf->pr_cur;
2734 
2735 	if (doprf(format, args, prf) == 0)
2736 		return (0);
2737 	/* LINTED */
2738 	return ((int)(prf->pr_cur - ocur));
2739 }
2740 
2741 /* VARARGS2 */
2742 int
2743 sprintf(char *buf, const char *format, ...)
2744 {
2745 	va_list	args;
2746 	int	len;
2747 	Prfbuf	prf;
2748 
2749 	va_start(args, format);
2750 	prf.pr_buf = prf.pr_cur = buf;
2751 	prf.pr_len = 0;
2752 	prf.pr_fd = -1;
2753 	len = doprintf(format, args, &prf);
2754 	va_end(args);
2755 
2756 	/*
2757 	 * sprintf() return value excludes the terminating null byte.
2758 	 */
2759 	return (len - 1);
2760 }
2761 
2762 /* VARARGS3 */
2763 int
2764 snprintf(char *buf, size_t n, const char *format, ...)
2765 {
2766 	va_list	args;
2767 	int	len;
2768 	Prfbuf	prf;
2769 
2770 	va_start(args, format);
2771 	prf.pr_buf = prf.pr_cur = buf;
2772 	prf.pr_len = n;
2773 	prf.pr_fd = -1;
2774 	len = doprintf(format, args, &prf);
2775 	va_end(args);
2776 
2777 	return (len);
2778 }
2779 
2780 /* VARARGS2 */
2781 int
2782 bufprint(Prfbuf *prf, const char *format, ...)
2783 {
2784 	va_list	args;
2785 	int	len;
2786 
2787 	va_start(args, format);
2788 	len = doprintf(format, args, prf);
2789 	va_end(args);
2790 
2791 	return (len);
2792 }
2793 
2794 /*PRINTFLIKE1*/
2795 int
2796 printf(const char *format, ...)
2797 {
2798 	va_list	args;
2799 	char 	buffer[ERRSIZE];
2800 	Prfbuf	prf;
2801 
2802 	va_start(args, format);
2803 	prf.pr_buf = prf.pr_cur = buffer;
2804 	prf.pr_len = ERRSIZE;
2805 	prf.pr_fd = 1;
2806 	(void) doprf(format, args, &prf);
2807 	va_end(args);
2808 	/*
2809 	 * Trim trailing '\0' form buffer
2810 	 */
2811 	prf.pr_cur--;
2812 	return (dowrite(&prf));
2813 }
2814 
2815 static char	errbuf[ERRSIZE], *nextptr = errbuf, *prevptr = 0;
2816 
2817 /*
2818  * All error messages go through eprintf().  During process initialization,
2819  * these messages are directed to the standard error, however once control has
2820  * been passed to the applications code these messages are stored in an internal
2821  * buffer for use with dlerror().  Note, fatal error conditions that may occur
2822  * while running the application will still cause a standard error message, see
2823  * rtldexit() in this file for details.
2824  * The RT_FL_APPLIC flag serves to indicate the transition between process
2825  * initialization and when the applications code is running.
2826  */
2827 /*PRINTFLIKE3*/
2828 void
2829 eprintf(Lm_list *lml, Error error, const char *format, ...)
2830 {
2831 	va_list		args;
2832 	int		overflow = 0;
2833 	static int	lock = 0;
2834 	Prfbuf		prf;
2835 
2836 	if (lock || (nextptr == (errbuf + ERRSIZE)))
2837 		return;
2838 
2839 	/*
2840 	 * Note: this lock is here to prevent the same thread from recursively
2841 	 * entering itself during a eprintf.  ie: during eprintf malloc() fails
2842 	 * and we try and call eprintf ... and then malloc() fails ....
2843 	 */
2844 	lock = 1;
2845 
2846 	/*
2847 	 * If we have completed startup initialization, all error messages
2848 	 * must be saved.  These are reported through dlerror().  If we're
2849 	 * still in the initialization stage, output the error directly and
2850 	 * add a newline.
2851 	 */
2852 	va_start(args, format);
2853 
2854 	prf.pr_buf = prf.pr_cur = nextptr;
2855 	prf.pr_len = ERRSIZE - (nextptr - errbuf);
2856 
2857 	if (!(rtld_flags & RT_FL_APPLIC))
2858 		prf.pr_fd = 2;
2859 	else
2860 		prf.pr_fd = -1;
2861 
2862 	if (error > ERR_NONE) {
2863 		if ((error == ERR_FATAL) && (rtld_flags2 & RT_FL2_FTL2WARN))
2864 			error = ERR_WARNING;
2865 		if (error == ERR_WARNING) {
2866 			if (err_strs[ERR_WARNING] == 0)
2867 				err_strs[ERR_WARNING] =
2868 				    MSG_INTL(MSG_ERR_WARNING);
2869 		} else if (error == ERR_FATAL) {
2870 			if (err_strs[ERR_FATAL] == 0)
2871 				err_strs[ERR_FATAL] = MSG_INTL(MSG_ERR_FATAL);
2872 		} else if (error == ERR_ELF) {
2873 			if (err_strs[ERR_ELF] == 0)
2874 				err_strs[ERR_ELF] = MSG_INTL(MSG_ERR_ELF);
2875 		}
2876 		if (procname) {
2877 			if (bufprint(&prf, MSG_ORIG(MSG_STR_EMSGFOR1),
2878 			    rtldname, procname, err_strs[error]) == 0)
2879 				overflow = 1;
2880 		} else {
2881 			if (bufprint(&prf, MSG_ORIG(MSG_STR_EMSGFOR2),
2882 			    rtldname, err_strs[error]) == 0)
2883 				overflow = 1;
2884 		}
2885 		if (overflow == 0) {
2886 			/*
2887 			 * Remove the terminating '\0'.
2888 			 */
2889 			prf.pr_cur--;
2890 		}
2891 	}
2892 
2893 	if ((overflow == 0) && doprf(format, args, &prf) == 0)
2894 		overflow = 1;
2895 
2896 	/*
2897 	 * If this is an ELF error, it will have been generated by a support
2898 	 * object that has a dependency on libelf.  ld.so.1 doesn't generate any
2899 	 * ELF error messages as it doesn't interact with libelf.  Determine the
2900 	 * ELF error string.
2901 	 */
2902 	if ((overflow == 0) && (error == ERR_ELF)) {
2903 		static int		(*elfeno)() = 0;
2904 		static const char	*(*elfemg)();
2905 		const char		*emsg;
2906 		Rt_map			*dlmp, *lmp = lml_rtld.lm_head;
2907 
2908 		if (NEXT(lmp) && (elfeno == 0)) {
2909 			if (((elfemg = (const char *(*)())dlsym_intn(RTLD_NEXT,
2910 			    MSG_ORIG(MSG_SYM_ELFERRMSG), lmp, &dlmp)) == 0) ||
2911 			    ((elfeno = (int (*)())dlsym_intn(RTLD_NEXT,
2912 			    MSG_ORIG(MSG_SYM_ELFERRNO), lmp, &dlmp)) == 0))
2913 				elfeno = 0;
2914 		}
2915 
2916 		/*
2917 		 * Lookup the message; equivalent to elf_errmsg(elf_errno()).
2918 		 */
2919 		if (elfeno && ((emsg = (* elfemg)((* elfeno)())) != 0)) {
2920 			prf.pr_cur--;
2921 			if (bufprint(&prf, MSG_ORIG(MSG_STR_EMSGFOR2),
2922 			    emsg) == 0)
2923 				overflow = 1;
2924 		}
2925 	}
2926 
2927 	/*
2928 	 * Push out any message that's been built.  Note, in the case of an
2929 	 * overflow condition, this message may be incomplete, in which case
2930 	 * make sure any partial string is null terminated.
2931 	 */
2932 	if ((rtld_flags & (RT_FL_APPLIC | RT_FL_SILENCERR)) == 0) {
2933 		*(prf.pr_cur - 1) = '\n';
2934 		(void) dowrite(&prf);
2935 	}
2936 	if (overflow)
2937 		*(prf.pr_cur - 1) = '\0';
2938 
2939 	DBG_CALL(Dbg_util_str(lml, nextptr));
2940 	va_end(args);
2941 
2942 	/*
2943 	 * Determine if there was insufficient space left in the buffer to
2944 	 * complete the message.  If so, we'll have printed out as much as had
2945 	 * been processed if we're not yet executing the application.
2946 	 * Otherwise, there will be some debugging diagnostic indicating
2947 	 * as much of the error message as possible.  Write out a final buffer
2948 	 * overflow diagnostic - unlocalized, so we don't chance more errors.
2949 	 */
2950 	if (overflow) {
2951 		char	*str = (char *)MSG_INTL(MSG_EMG_BUFOVRFLW);
2952 
2953 		if ((rtld_flags & RT_FL_SILENCERR) == 0) {
2954 			lasterr = str;
2955 
2956 			if ((rtld_flags & RT_FL_APPLIC) == 0) {
2957 				(void) write(2, str, strlen(str));
2958 				(void) write(2, MSG_ORIG(MSG_STR_NL),
2959 				    MSG_STR_NL_SIZE);
2960 			}
2961 		}
2962 		DBG_CALL(Dbg_util_str(lml, str));
2963 
2964 		lock = 0;
2965 		nextptr = errbuf + ERRSIZE;
2966 		return;
2967 	}
2968 
2969 	/*
2970 	 * If the application has started, then error messages are being saved
2971 	 * for retrieval by dlerror(), or possible flushing from rtldexit() in
2972 	 * the case of a fatal error.  In this case, establish the next error
2973 	 * pointer.  If we haven't started the application, the whole message
2974 	 * buffer can be reused.
2975 	 */
2976 	if ((rtld_flags & RT_FL_SILENCERR) == 0) {
2977 		lasterr = nextptr;
2978 
2979 		/*
2980 		 * Note, should we encounter an error such as ENOMEM, there may
2981 		 * be a number of the same error messages (ie. an operation
2982 		 * fails with ENOMEM, and then the attempts to construct the
2983 		 * error message itself, which incurs additional ENOMEM errors).
2984 		 * Compare any previous error message with the one we've just
2985 		 * created to prevent any duplication clutter.
2986 		 */
2987 		if ((rtld_flags & RT_FL_APPLIC) &&
2988 		    ((prevptr == 0) || (strcmp(prevptr, nextptr) != 0))) {
2989 			prevptr = nextptr;
2990 			nextptr = prf.pr_cur;
2991 			*nextptr = '\0';
2992 		}
2993 	}
2994 	lock = 0;
2995 }
2996 
2997 
2998 #if	DEBUG
2999 /*
3000  * Provide assfail() for ASSERT() statements.  See <sys/debug.h> for further
3001  * details.
3002  */
3003 int
3004 assfail(const char *a, const char *f, int l)
3005 {
3006 	(void) printf("assertion failed: %s, file: %s, line: %d\n", a, f, l);
3007 	(void) _lwp_kill(_lwp_self(), SIGABRT);
3008 	return (0);
3009 }
3010 #endif
3011 
3012 /*
3013  * Exit.  If we arrive here with a non zero status it's because of a fatal
3014  * error condition (most commonly a relocation error).  If the application has
3015  * already had control, then the actual fatal error message will have been
3016  * recorded in the dlerror() message buffer.  Print the message before really
3017  * exiting.
3018  */
3019 void
3020 rtldexit(Lm_list * lml, int status)
3021 {
3022 	if (status) {
3023 		if (rtld_flags & RT_FL_APPLIC) {
3024 			/*
3025 			 * If the error buffer has been used, write out all
3026 			 * pending messages - lasterr is simply a pointer to
3027 			 * the last message in this buffer.  However, if the
3028 			 * buffer couldn't be created at all, lasterr points
3029 			 * to a constant error message string.
3030 			 */
3031 			if (*errbuf) {
3032 				char	*errptr = errbuf;
3033 				char	*errend = errbuf + ERRSIZE;
3034 
3035 				while ((errptr < errend) && *errptr) {
3036 					size_t	size = strlen(errptr);
3037 					(void) write(2, errptr, size);
3038 					(void) write(2, MSG_ORIG(MSG_STR_NL),
3039 					    MSG_STR_NL_SIZE);
3040 					errptr += (size + 1);
3041 				}
3042 			}
3043 			if (lasterr && ((lasterr < errbuf) ||
3044 			    (lasterr > (errbuf + ERRSIZE)))) {
3045 				(void) write(2, lasterr, strlen(lasterr));
3046 				(void) write(2, MSG_ORIG(MSG_STR_NL),
3047 				    MSG_STR_NL_SIZE);
3048 			}
3049 		}
3050 		leave(lml, 0);
3051 		(void) _lwp_kill(_lwp_self(), killsig);
3052 	}
3053 	_exit(status);
3054 }
3055 
3056 /*
3057  * Map anonymous memory via MAP_ANON (added in Solaris 8).
3058  */
3059 void *
3060 dz_map(Lm_list *lml, caddr_t addr, size_t len, int prot, int flags)
3061 {
3062 	caddr_t	va;
3063 
3064 	if ((va = (caddr_t)mmap(addr, len, prot,
3065 	    (flags | MAP_ANON), -1, 0)) == MAP_FAILED) {
3066 		int	err = errno;
3067 		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_MMAPANON),
3068 		    strerror(err));
3069 		return (MAP_FAILED);
3070 	}
3071 	return (va);
3072 }
3073 
3074 static int	nu_fd = FD_UNAVAIL;
3075 
3076 void *
3077 nu_map(Lm_list *lml, caddr_t addr, size_t len, int prot, int flags)
3078 {
3079 	caddr_t	va;
3080 	int	err;
3081 
3082 	if (nu_fd == FD_UNAVAIL) {
3083 		if ((nu_fd = open(MSG_ORIG(MSG_PTH_DEVNULL),
3084 		    O_RDONLY)) == FD_UNAVAIL) {
3085 			err = errno;
3086 			eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_OPEN),
3087 			    MSG_ORIG(MSG_PTH_DEVNULL), strerror(err));
3088 			return (MAP_FAILED);
3089 		}
3090 	}
3091 
3092 	if ((va = (caddr_t)mmap(addr, len, prot, flags, nu_fd, 0)) ==
3093 	    MAP_FAILED) {
3094 		err = errno;
3095 		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_SYS_MMAP),
3096 		    MSG_ORIG(MSG_PTH_DEVNULL), strerror(err));
3097 	}
3098 	return (va);
3099 }
3100 
3101 /*
3102  * Generic entry point from user code - simply grabs a lock, and bumps the
3103  * entrance count.
3104  */
3105 int
3106 enter(int flags)
3107 {
3108 	if (rt_bind_guard(THR_FLG_RTLD | thr_flg_nolock | flags)) {
3109 		if (!thr_flg_nolock)
3110 			(void) rt_mutex_lock(&rtldlock);
3111 		if (rtld_flags & RT_FL_OPERATION)
3112 			ld_entry_cnt++;
3113 		return (1);
3114 	}
3115 	return (0);
3116 }
3117 
3118 /*
3119  * Determine whether a search path has been used.
3120  */
3121 static void
3122 is_path_used(Lm_list *lml, Word unref, int *nl, Alist *alp, const char *obj)
3123 {
3124 	Pdesc	*pdp;
3125 	Aliste	idx;
3126 
3127 	for (ALIST_TRAVERSE(alp, idx, pdp)) {
3128 		const char	*fmt, *name;
3129 
3130 		if ((pdp->pd_plen == 0) || (pdp->pd_flags & PD_FLG_USED))
3131 			continue;
3132 
3133 		/*
3134 		 * If this pathname originated from an expanded token, use the
3135 		 * original for any diagnostic output.
3136 		 */
3137 		if ((name = pdp->pd_oname) == NULL)
3138 			name = pdp->pd_pname;
3139 
3140 		if (unref == 0) {
3141 			if ((*nl)++ == 0)
3142 				DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
3143 			DBG_CALL(Dbg_unused_path(lml, name, pdp->pd_flags,
3144 			    (pdp->pd_flags & PD_FLG_DUPLICAT), obj));
3145 			continue;
3146 		}
3147 
3148 		if (pdp->pd_flags & LA_SER_LIBPATH) {
3149 			if (pdp->pd_flags & LA_SER_CONFIG) {
3150 				if (pdp->pd_flags & PD_FLG_DUPLICAT)
3151 					fmt = MSG_INTL(MSG_DUP_LDLIBPATHC);
3152 				else
3153 					fmt = MSG_INTL(MSG_USD_LDLIBPATHC);
3154 			} else {
3155 				if (pdp->pd_flags & PD_FLG_DUPLICAT)
3156 					fmt = MSG_INTL(MSG_DUP_LDLIBPATH);
3157 				else
3158 					fmt = MSG_INTL(MSG_USD_LDLIBPATH);
3159 			}
3160 		} else if (pdp->pd_flags & LA_SER_RUNPATH) {
3161 			fmt = MSG_INTL(MSG_USD_RUNPATH);
3162 		} else
3163 			continue;
3164 
3165 		if ((*nl)++ == 0)
3166 			(void) printf(MSG_ORIG(MSG_STR_NL));
3167 		(void) printf(fmt, name, obj);
3168 	}
3169 }
3170 
3171 /*
3172  * Generate diagnostics as to whether an object has been used.  A symbolic
3173  * reference that gets bound to an object marks it as used.  Dependencies that
3174  * are unused when RTLD_NOW is in effect should be removed from future builds
3175  * of an object.  Dependencies that are unused without RTLD_NOW in effect are
3176  * candidates for lazy-loading.
3177  *
3178  * Unreferenced objects identify objects that are defined as dependencies but
3179  * are unreferenced by the caller.  These unreferenced objects may however be
3180  * referenced by other objects within the process, and therefore don't qualify
3181  * as completely unused.  They are still an unnecessary overhead.
3182  *
3183  * Unreferenced runpaths are also captured under ldd -U, or "unused,detail"
3184  * debugging.
3185  */
3186 void
3187 unused(Lm_list *lml)
3188 {
3189 	Rt_map		*lmp;
3190 	int		nl = 0;
3191 	Word		unref, unuse;
3192 
3193 	/*
3194 	 * If we're not tracing unused references or dependencies, or debugging
3195 	 * there's nothing to do.
3196 	 */
3197 	unref = lml->lm_flags & LML_FLG_TRC_UNREF;
3198 	unuse = lml->lm_flags & LML_FLG_TRC_UNUSED;
3199 
3200 	if ((unref == 0) && (unuse == 0) && (DBG_ENABLED == 0))
3201 		return;
3202 
3203 	/*
3204 	 * Detect unused global search paths.
3205 	 */
3206 	if (rpl_libdirs)
3207 		is_path_used(lml, unref, &nl, rpl_libdirs, config->c_name);
3208 	if (prm_libdirs)
3209 		is_path_used(lml, unref, &nl, prm_libdirs, config->c_name);
3210 
3211 	nl = 0;
3212 	lmp = lml->lm_head;
3213 	if (RLIST(lmp))
3214 		is_path_used(lml, unref, &nl, RLIST(lmp), NAME(lmp));
3215 
3216 	/*
3217 	 * Traverse the link-maps looking for unreferenced or unused
3218 	 * dependencies.  Ignore the first object on a link-map list, as this
3219 	 * is always used.
3220 	 */
3221 	nl = 0;
3222 	for (lmp = NEXT_RT_MAP(lmp); lmp; lmp = NEXT_RT_MAP(lmp)) {
3223 		/*
3224 		 * Determine if this object contains any runpaths that have
3225 		 * not been used.
3226 		 */
3227 		if (RLIST(lmp))
3228 			is_path_used(lml, unref, &nl, RLIST(lmp), NAME(lmp));
3229 
3230 		/*
3231 		 * If tracing unreferenced objects, or under debugging,
3232 		 * determine whether any of this objects callers haven't
3233 		 * referenced it.
3234 		 */
3235 		if (unref || DBG_ENABLED) {
3236 			Bnd_desc	*bdp;
3237 			Aliste		idx;
3238 
3239 			for (APLIST_TRAVERSE(CALLERS(lmp), idx, bdp)) {
3240 				Rt_map	*clmp;
3241 
3242 				if (bdp->b_flags & BND_REFER)
3243 					continue;
3244 
3245 				clmp = bdp->b_caller;
3246 				if (FLAGS1(clmp) & FL1_RT_LDDSTUB)
3247 					continue;
3248 
3249 				/* BEGIN CSTYLED */
3250 				if (nl++ == 0) {
3251 					if (unref)
3252 					    (void) printf(MSG_ORIG(MSG_STR_NL));
3253 					else
3254 					    DBG_CALL(Dbg_util_nl(lml,
3255 						DBG_NL_STD));
3256 				}
3257 
3258 				if (unref)
3259 				    (void) printf(MSG_INTL(MSG_LDD_UNREF_FMT),
3260 					NAME(lmp), NAME(clmp));
3261 				else
3262 				    DBG_CALL(Dbg_unused_unref(lmp, NAME(clmp)));
3263 				/* END CSTYLED */
3264 			}
3265 		}
3266 
3267 		/*
3268 		 * If tracing unused objects simply display those objects that
3269 		 * haven't been referenced by anyone.
3270 		 */
3271 		if (FLAGS1(lmp) & FL1_RT_USED)
3272 			continue;
3273 
3274 		if (nl++ == 0) {
3275 			if (unref || unuse)
3276 				(void) printf(MSG_ORIG(MSG_STR_NL));
3277 			else
3278 				DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
3279 		}
3280 		if (CYCGROUP(lmp)) {
3281 			if (unref || unuse)
3282 				(void) printf(MSG_INTL(MSG_LDD_UNCYC_FMT),
3283 				    NAME(lmp), CYCGROUP(lmp));
3284 			else
3285 				DBG_CALL(Dbg_unused_file(lml, NAME(lmp), 0,
3286 				    CYCGROUP(lmp)));
3287 		} else {
3288 			if (unref || unuse)
3289 				(void) printf(MSG_INTL(MSG_LDD_UNUSED_FMT),
3290 				    NAME(lmp));
3291 			else
3292 				DBG_CALL(Dbg_unused_file(lml, NAME(lmp), 0, 0));
3293 		}
3294 	}
3295 
3296 	DBG_CALL(Dbg_util_nl(lml, DBG_NL_STD));
3297 }
3298 
3299 /*
3300  * Generic cleanup routine called prior to returning control to the user.
3301  * Insures that any ld.so.1 specific file descriptors or temporary mapping are
3302  * released, and any locks dropped.
3303  */
3304 void
3305 leave(Lm_list *lml, int flags)
3306 {
3307 	Lm_list		*elml = lml;
3308 	Rt_map		*clmp;
3309 	Aliste		idx;
3310 
3311 	/*
3312 	 * Alert the debuggers that the link-maps are consistent.  Note, in the
3313 	 * case of tearing down a whole link-map list, lml will be null.  In
3314 	 * this case use the main link-map list to test for a notification.
3315 	 */
3316 	if (elml == NULL)
3317 		elml = &lml_main;
3318 	if (elml->lm_flags & LML_FLG_DBNOTIF)
3319 		rd_event(elml, RD_DLACTIVITY, RT_CONSISTENT);
3320 
3321 	/*
3322 	 * Alert any auditors that the link-maps are consistent.
3323 	 */
3324 	for (APLIST_TRAVERSE(elml->lm_actaudit, idx, clmp)) {
3325 		audit_activity(clmp, LA_ACT_CONSISTENT);
3326 
3327 		aplist_delete(elml->lm_actaudit, &idx);
3328 	}
3329 
3330 	if (nu_fd != FD_UNAVAIL) {
3331 		(void) close(nu_fd);
3332 		nu_fd = FD_UNAVAIL;
3333 	}
3334 
3335 	/*
3336 	 * Reinitialize error message pointer, and any overflow indication.
3337 	 */
3338 	nextptr = errbuf;
3339 	prevptr = 0;
3340 
3341 	/*
3342 	 * Defragment any freed memory.
3343 	 */
3344 	if (aplist_nitems(free_alp))
3345 		defrag();
3346 
3347 	/*
3348 	 * Don't drop our lock if we are running on our link-map list as
3349 	 * there's little point in doing so since we are single-threaded.
3350 	 *
3351 	 * LML_FLG_HOLDLOCK is set for:
3352 	 *	*) The ld.so.1's link-map list.
3353 	 *	*) The auditor's link-map if the environment is
3354 	 *	   libc/libthread un-unified.
3355 	 */
3356 	if (lml && (lml->lm_flags & LML_FLG_HOLDLOCK))
3357 		return;
3358 
3359 	if (rt_bind_clear(0) & THR_FLG_RTLD) {
3360 		if (!thr_flg_nolock)
3361 			(void) rt_mutex_unlock(&rtldlock);
3362 		(void) rt_bind_clear(THR_FLG_RTLD | thr_flg_nolock | flags);
3363 	}
3364 }
3365 
3366 int
3367 callable(Rt_map *clmp, Rt_map *dlmp, Grp_hdl *ghp, uint_t slflags)
3368 {
3369 	APlist		*calp, *dalp;
3370 	Aliste		idx1, idx2;
3371 	Grp_hdl		*ghp1, *ghp2;
3372 
3373 	/*
3374 	 * An object can always find symbols within itself.
3375 	 */
3376 	if (clmp == dlmp)
3377 		return (1);
3378 
3379 	/*
3380 	 * The search for a singleton must look in every loaded object.
3381 	 */
3382 	if (slflags & LKUP_SINGLETON)
3383 		return (1);
3384 
3385 	/*
3386 	 * Don't allow an object to bind to an object that is being deleted
3387 	 * unless the binder is also being deleted.
3388 	 */
3389 	if ((FLAGS(dlmp) & FLG_RT_DELETE) &&
3390 	    ((FLAGS(clmp) & FLG_RT_DELETE) == 0))
3391 		return (0);
3392 
3393 	/*
3394 	 * An object with world access can always bind to an object with global
3395 	 * visibility.
3396 	 */
3397 	if (((MODE(clmp) & RTLD_WORLD) || (slflags & LKUP_WORLD)) &&
3398 	    (MODE(dlmp) & RTLD_GLOBAL))
3399 		return (1);
3400 
3401 	/*
3402 	 * An object with local access can only bind to an object that is a
3403 	 * member of the same group.
3404 	 */
3405 	if (((MODE(clmp) & RTLD_GROUP) == 0) ||
3406 	    ((calp = GROUPS(clmp)) == NULL) || ((dalp = GROUPS(dlmp)) == NULL))
3407 		return (0);
3408 
3409 	/*
3410 	 * Traverse the list of groups the caller is a part of.
3411 	 */
3412 	for (APLIST_TRAVERSE(calp, idx1, ghp1)) {
3413 		/*
3414 		 * If we're testing for the ability of two objects to bind to
3415 		 * each other regardless of a specific group, ignore that group.
3416 		 */
3417 		if (ghp && (ghp1 == ghp))
3418 			continue;
3419 
3420 		/*
3421 		 * Traverse the list of groups the destination is a part of.
3422 		 */
3423 		for (APLIST_TRAVERSE(dalp, idx2, ghp2)) {
3424 			Grp_desc	*gdp;
3425 			Aliste		idx3;
3426 
3427 			if (ghp1 != ghp2)
3428 				continue;
3429 
3430 			/*
3431 			 * Make sure the relationship between the destination
3432 			 * and the caller provide symbols for relocation.
3433 			 * Parents are maintained as callers, but unless the
3434 			 * destination object was opened with RTLD_PARENT, the
3435 			 * parent doesn't provide symbols for the destination
3436 			 * to relocate against.
3437 			 */
3438 			for (ALIST_TRAVERSE(ghp2->gh_depends, idx3, gdp)) {
3439 				if (dlmp != gdp->gd_depend)
3440 					continue;
3441 
3442 				if (gdp->gd_flags & GPD_RELOC)
3443 					return (1);
3444 			}
3445 		}
3446 	}
3447 	return (0);
3448 }
3449 
3450 /*
3451  * Initialize the environ symbol.  Traditionally this is carried out by the crt
3452  * code prior to jumping to main.  However, init sections get fired before this
3453  * variable is initialized, so ld.so.1 sets this directly from the AUX vector
3454  * information.  In addition, a process may have multiple link-maps (ld.so.1's
3455  * debugging and preloading objects), and link auditing, and each may need an
3456  * environ variable set.
3457  *
3458  * This routine is called after a relocation() pass, and thus provides for:
3459  *
3460  *  o	setting environ on the main link-map after the initial application and
3461  *	its dependencies have been established.  Typically environ lives in the
3462  *	application (provided by its crt), but in older applications it might
3463  *	be in libc.  Who knows what's expected of applications not built on
3464  *	Solaris.
3465  *
3466  *  o	after loading a new shared object.  We can add shared objects to various
3467  *	link-maps, and any link-map dependencies requiring getopt() require
3468  *	their own environ.  In addition, lazy loading might bring in the
3469  *	supplier of environ (libc used to be a lazy loading candidate) after
3470  *	the link-map has been established and other objects are present.
3471  *
3472  * This routine handles all these scenarios, without adding unnecessary overhead
3473  * to ld.so.1.
3474  */
3475 void
3476 set_environ(Lm_list *lml)
3477 {
3478 	Rt_map		*dlmp;
3479 	Sym		*sym;
3480 	Slookup		sl;
3481 	uint_t		binfo;
3482 
3483 	/*
3484 	 * Initialize the symbol lookup data structure.
3485 	 */
3486 	SLOOKUP_INIT(sl, MSG_ORIG(MSG_SYM_ENVIRON), lml->lm_head, lml->lm_head,
3487 	    ld_entry_cnt, 0, 0, 0, 0, LKUP_WEAK);
3488 
3489 	if (sym = LM_LOOKUP_SYM(lml->lm_head)(&sl, &dlmp, &binfo, 0)) {
3490 		lml->lm_environ = (char ***)sym->st_value;
3491 
3492 		if (!(FLAGS(dlmp) & FLG_RT_FIXED))
3493 			lml->lm_environ =
3494 			    (char ***)((uintptr_t)lml->lm_environ +
3495 			    (uintptr_t)ADDR(dlmp));
3496 		*(lml->lm_environ) = (char **)environ;
3497 		lml->lm_flags |= LML_FLG_ENVIRON;
3498 	}
3499 }
3500 
3501 /*
3502  * Determine whether we have a secure executable.  Uid and gid information
3503  * can be passed to us via the aux vector, however if these values are -1
3504  * then use the appropriate system call to obtain them.
3505  *
3506  *  o	If the user is the root they can do anything
3507  *
3508  *  o	If the real and effective uid's don't match, or the real and
3509  *	effective gid's don't match then this is determined to be a `secure'
3510  *	application.
3511  *
3512  * This function is called prior to any dependency processing (see _setup.c).
3513  * Any secure setting will remain in effect for the life of the process.
3514  */
3515 void
3516 security(uid_t uid, uid_t euid, gid_t gid, gid_t egid, int auxflags)
3517 {
3518 	if (auxflags != -1) {
3519 		if ((auxflags & AF_SUN_SETUGID) != 0)
3520 			rtld_flags |= RT_FL_SECURE;
3521 		return;
3522 	}
3523 
3524 	if (uid == (uid_t)-1)
3525 		uid = getuid();
3526 	if (uid) {
3527 		if (euid == (uid_t)-1)
3528 			euid = geteuid();
3529 		if (uid != euid)
3530 			rtld_flags |= RT_FL_SECURE;
3531 		else {
3532 			if (gid == (gid_t)-1)
3533 				gid = getgid();
3534 			if (egid == (gid_t)-1)
3535 				egid = getegid();
3536 			if (gid != egid)
3537 				rtld_flags |= RT_FL_SECURE;
3538 		}
3539 	}
3540 }
3541 
3542 /*
3543  * Determine whether ld.so.1 itself is owned by root and has its mode setuid.
3544  */
3545 int
3546 is_rtld_setuid()
3547 {
3548 	rtld_stat_t	status;
3549 
3550 	if ((rtld_flags2 & RT_FL2_SETUID) ||
3551 	    ((rtld_stat(NAME(lml_rtld.lm_head), &status) == 0) &&
3552 	    (status.st_uid == 0) && (status.st_mode & S_ISUID))) {
3553 		rtld_flags2 |= RT_FL2_SETUID;
3554 		return (1);
3555 	}
3556 	return (0);
3557 }
3558 
3559 /*
3560  * _REENTRANT code gets errno redefined to a function so provide for return
3561  * of the thread errno if applicable.  This has no meaning in ld.so.1 which
3562  * is basically singled threaded.  Provide the interface for our dependencies.
3563  */
3564 #undef errno
3565 int *
3566 ___errno()
3567 {
3568 	extern	int	errno;
3569 
3570 	return (&errno);
3571 }
3572 
3573 /*
3574  * The interface with the c library which is supplied through libdl.so.1.
3575  * A non-null argument allows a function pointer array to be passed to us which
3576  * is used to re-initialize the linker libc table.
3577  */
3578 void
3579 _ld_libc(void * ptr)
3580 {
3581 	get_lcinterface(_caller(caller(), CL_EXECDEF), (Lc_interface *)ptr);
3582 }
3583 
3584 /*
3585  * Determine whether a symbol name should be demangled.
3586  */
3587 const char *
3588 demangle(const char *name)
3589 {
3590 	if (rtld_flags & RT_FL_DEMANGLE)
3591 		return (conv_demangle_name(name));
3592 	else
3593 		return (name);
3594 }
3595 
3596 
3597 #ifndef _LP64
3598 /*
3599  * Wrappers on stat() and fstat() for 32-bit rtld that uses stat64()
3600  * underneath while preserving the object size limits of a non-largefile
3601  * enabled 32-bit process. The purpose of this is to prevent large inode
3602  * values from causing stat() to fail.
3603  */
3604 inline static int
3605 rtld_stat_process(int r, struct stat64 *lbuf, rtld_stat_t *restrict buf)
3606 {
3607 	extern int	errno;
3608 
3609 	/*
3610 	 * Although we used a 64-bit capable stat(), the 32-bit rtld
3611 	 * can only handle objects < 2GB in size. If this object is
3612 	 * too big, turn the success into an overflow error.
3613 	 */
3614 	if ((lbuf->st_size & 0xffffffff80000000) != 0) {
3615 		errno = EOVERFLOW;
3616 		return (-1);
3617 	}
3618 
3619 	/*
3620 	 * Transfer the information needed by rtld into a rtld_stat_t
3621 	 * structure that preserves the non-largile types for everything
3622 	 * except inode.
3623 	 */
3624 	buf->st_dev = lbuf->st_dev;
3625 	buf->st_ino = lbuf->st_ino;
3626 	buf->st_mode = lbuf->st_mode;
3627 	buf->st_uid = lbuf->st_uid;
3628 	buf->st_size = (off_t)lbuf->st_size;
3629 	buf->st_mtim = lbuf->st_mtim;
3630 #ifdef sparc
3631 	buf->st_blksize = lbuf->st_blksize;
3632 #endif
3633 
3634 	return (r);
3635 }
3636 
3637 int
3638 rtld_stat(const char *restrict path, rtld_stat_t *restrict buf)
3639 {
3640 	struct stat64	lbuf;
3641 	int		r;
3642 
3643 	r = stat64(path, &lbuf);
3644 	if (r != -1)
3645 		r = rtld_stat_process(r, &lbuf, buf);
3646 	return (r);
3647 }
3648 
3649 int
3650 rtld_fstat(int fildes, rtld_stat_t *restrict buf)
3651 {
3652 	struct stat64	lbuf;
3653 	int		r;
3654 
3655 	r = fstat64(fildes, &lbuf);
3656 	if (r != -1)
3657 		r = rtld_stat_process(r, &lbuf, buf);
3658 	return (r);
3659 }
3660 #endif
3661