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