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