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