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