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