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