xref: /titanic_51/usr/src/uts/common/os/exec.c (revision df0345f7d6cc87cde9e532e8362f1aca053d98cc)
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 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1988 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/sysmacros.h>
33 #include <sys/systm.h>
34 #include <sys/signal.h>
35 #include <sys/cred_impl.h>
36 #include <sys/policy.h>
37 #include <sys/user.h>
38 #include <sys/errno.h>
39 #include <sys/file.h>
40 #include <sys/vfs.h>
41 #include <sys/vnode.h>
42 #include <sys/mman.h>
43 #include <sys/acct.h>
44 #include <sys/cpuvar.h>
45 #include <sys/proc.h>
46 #include <sys/cmn_err.h>
47 #include <sys/debug.h>
48 #include <sys/pathname.h>
49 #include <sys/vm.h>
50 #include <sys/lgrp.h>
51 #include <sys/vtrace.h>
52 #include <sys/exec.h>
53 #include <sys/exechdr.h>
54 #include <sys/kmem.h>
55 #include <sys/prsystm.h>
56 #include <sys/modctl.h>
57 #include <sys/vmparam.h>
58 #include <sys/door.h>
59 #include <sys/schedctl.h>
60 #include <sys/utrap.h>
61 #include <sys/systeminfo.h>
62 #include <sys/stack.h>
63 #include <sys/rctl.h>
64 #include <sys/dtrace.h>
65 #include <sys/lwpchan_impl.h>
66 #include <sys/pool.h>
67 #include <sys/sdt.h>
68 #include <sys/brand.h>
69 
70 #include <c2/audit.h>
71 
72 #include <vm/hat.h>
73 #include <vm/anon.h>
74 #include <vm/as.h>
75 #include <vm/seg.h>
76 #include <vm/seg_vn.h>
77 
78 #define	PRIV_RESET		0x01	/* needs to reset privs */
79 #define	PRIV_SETID		0x02	/* needs to change uids */
80 #define	PRIV_SETUGID		0x04	/* is setuid/setgid/forced privs */
81 #define	PRIV_INCREASE		0x08	/* child runs with more privs */
82 #define	MAC_FLAGS		0x10	/* need to adjust MAC flags */
83 
84 static int execsetid(struct vnode *, struct vattr *, uid_t *, uid_t *);
85 static int hold_execsw(struct execsw *);
86 
87 uint_t auxv_hwcap = 0;	/* auxv AT_SUN_HWCAP value; determined on the fly */
88 #if defined(_SYSCALL32_IMPL)
89 uint_t auxv_hwcap32 = 0;	/* 32-bit version of auxv_hwcap */
90 #endif
91 
92 #define	PSUIDFLAGS		(SNOCD|SUGID)
93 
94 /*
95  * exec() - wrapper around exece providing NULL environment pointer
96  */
97 int
98 exec(const char *fname, const char **argp)
99 {
100 	return (exece(fname, argp, NULL));
101 }
102 
103 /*
104  * exece() - system call wrapper around exec_common()
105  */
106 int
107 exece(const char *fname, const char **argp, const char **envp)
108 {
109 	int error;
110 
111 	error = exec_common(fname, argp, envp, EBA_NONE);
112 	return (error ? (set_errno(error)) : 0);
113 }
114 
115 int
116 exec_common(const char *fname, const char **argp, const char **envp,
117     int brand_action)
118 {
119 	vnode_t *vp = NULL, *dir = NULL, *tmpvp = NULL;
120 	proc_t *p = ttoproc(curthread);
121 	klwp_t *lwp = ttolwp(curthread);
122 	struct user *up = PTOU(p);
123 	long execsz;		/* temporary count of exec size */
124 	int i;
125 	int error;
126 	char exec_file[MAXCOMLEN+1];
127 	struct pathname pn;
128 	struct pathname resolvepn;
129 	struct uarg args;
130 	struct execa ua;
131 	k_sigset_t savedmask;
132 	lwpdir_t *lwpdir = NULL;
133 	lwpdir_t **tidhash;
134 	lwpdir_t *old_lwpdir = NULL;
135 	uint_t old_lwpdir_sz;
136 	lwpdir_t **old_tidhash;
137 	uint_t old_tidhash_sz;
138 	lwpent_t *lep;
139 	boolean_t brandme = B_FALSE;
140 
141 	/*
142 	 * exec() is not supported for the /proc agent lwp.
143 	 */
144 	if (curthread == p->p_agenttp)
145 		return (ENOTSUP);
146 
147 	if (brand_action != EBA_NONE) {
148 		/*
149 		 * Brand actions are not supported for processes that are not
150 		 * running in a branded zone.
151 		 */
152 		if (!ZONE_IS_BRANDED(p->p_zone))
153 			return (ENOTSUP);
154 
155 		if (brand_action == EBA_NATIVE) {
156 			/* Only branded processes can be unbranded */
157 			if (!PROC_IS_BRANDED(p))
158 				return (ENOTSUP);
159 		} else {
160 			/* Only unbranded processes can be branded */
161 			if (PROC_IS_BRANDED(p))
162 				return (ENOTSUP);
163 			brandme = B_TRUE;
164 		}
165 	} else {
166 		/*
167 		 * If this is a native zone, or if the process is already
168 		 * branded, then we don't need to do anything.  If this is
169 		 * a native process in a branded zone, we need to brand the
170 		 * process as it exec()s the new binary.
171 		 */
172 		if (ZONE_IS_BRANDED(p->p_zone) && !PROC_IS_BRANDED(p))
173 			brandme = B_TRUE;
174 	}
175 
176 	/*
177 	 * Inform /proc that an exec() has started.
178 	 * Hold signals that are ignored by default so that we will
179 	 * not be interrupted by a signal that will be ignored after
180 	 * successful completion of gexec().
181 	 */
182 	mutex_enter(&p->p_lock);
183 	prexecstart();
184 	schedctl_finish_sigblock(curthread);
185 	savedmask = curthread->t_hold;
186 	sigorset(&curthread->t_hold, &ignoredefault);
187 	mutex_exit(&p->p_lock);
188 
189 	/*
190 	 * Look up path name and remember last component for later.
191 	 * To help coreadm expand its %d token, we attempt to save
192 	 * the directory containing the executable in p_execdir. The
193 	 * first call to lookuppn() may fail and return EINVAL because
194 	 * dirvpp is non-NULL. In that case, we make a second call to
195 	 * lookuppn() with dirvpp set to NULL; p_execdir will be NULL,
196 	 * but coreadm is allowed to expand %d to the empty string and
197 	 * there are other cases in which that failure may occur.
198 	 */
199 	if ((error = pn_get((char *)fname, UIO_USERSPACE, &pn)) != 0)
200 		goto out;
201 	pn_alloc(&resolvepn);
202 	if ((error = lookuppn(&pn, &resolvepn, FOLLOW, &dir, &vp)) != 0) {
203 		pn_free(&resolvepn);
204 		pn_free(&pn);
205 		if (error != EINVAL)
206 			goto out;
207 
208 		dir = NULL;
209 		if ((error = pn_get((char *)fname, UIO_USERSPACE, &pn)) != 0)
210 			goto out;
211 		pn_alloc(&resolvepn);
212 		if ((error = lookuppn(&pn, &resolvepn, FOLLOW, NULLVPP,
213 		    &vp)) != 0) {
214 			pn_free(&resolvepn);
215 			pn_free(&pn);
216 			goto out;
217 		}
218 	}
219 	if (vp == NULL) {
220 		if (dir != NULL)
221 			VN_RELE(dir);
222 		error = ENOENT;
223 		pn_free(&resolvepn);
224 		pn_free(&pn);
225 		goto out;
226 	}
227 
228 	if ((error = secpolicy_basic_exec(CRED(), vp)) != 0) {
229 		if (dir != NULL)
230 			VN_RELE(dir);
231 		pn_free(&resolvepn);
232 		pn_free(&pn);
233 		VN_RELE(vp);
234 		goto out;
235 	}
236 
237 	/*
238 	 * We do not allow executing files in attribute directories.
239 	 * We test this by determining whether the resolved path
240 	 * contains a "/" when we're in an attribute directory;
241 	 * only if the pathname does not contain a "/" the resolved path
242 	 * points to a file in the current working (attribute) directory.
243 	 */
244 	if ((p->p_user.u_cdir->v_flag & V_XATTRDIR) != 0 &&
245 	    strchr(resolvepn.pn_path, '/') == NULL) {
246 		if (dir != NULL)
247 			VN_RELE(dir);
248 		error = EACCES;
249 		pn_free(&resolvepn);
250 		pn_free(&pn);
251 		VN_RELE(vp);
252 		goto out;
253 	}
254 
255 	bzero(exec_file, MAXCOMLEN+1);
256 	(void) strncpy(exec_file, pn.pn_path, MAXCOMLEN);
257 	bzero(&args, sizeof (args));
258 	args.pathname = resolvepn.pn_path;
259 	/* don't free resolvepn until we are done with args */
260 	pn_free(&pn);
261 
262 	/*
263 	 * Specific exec handlers, or policies determined via
264 	 * /etc/system may override the historical default.
265 	 */
266 	args.stk_prot = PROT_ZFOD;
267 	args.dat_prot = PROT_ZFOD;
268 
269 	CPU_STATS_ADD_K(sys, sysexec, 1);
270 	DTRACE_PROC1(exec, char *, args.pathname);
271 
272 	ua.fname = fname;
273 	ua.argp = argp;
274 	ua.envp = envp;
275 
276 	/* If necessary, brand this process before we start the exec. */
277 	if (brandme)
278 		brand_setbrand(p);
279 
280 	if ((error = gexec(&vp, &ua, &args, NULL, 0, &execsz,
281 	    exec_file, p->p_cred, brand_action)) != 0) {
282 		if (brandme)
283 			brand_clearbrand(p);
284 		VN_RELE(vp);
285 		if (dir != NULL)
286 			VN_RELE(dir);
287 		pn_free(&resolvepn);
288 		goto fail;
289 	}
290 
291 	/*
292 	 * Free floating point registers (sun4u only)
293 	 */
294 	ASSERT(lwp != NULL);
295 	lwp_freeregs(lwp, 1);
296 
297 	/*
298 	 * Free thread and process context ops.
299 	 */
300 	if (curthread->t_ctx)
301 		freectx(curthread, 1);
302 	if (p->p_pctx)
303 		freepctx(p, 1);
304 
305 	/*
306 	 * Remember file name for accounting; clear any cached DTrace predicate.
307 	 */
308 	up->u_acflag &= ~AFORK;
309 	bcopy(exec_file, up->u_comm, MAXCOMLEN+1);
310 	curthread->t_predcache = NULL;
311 
312 	/*
313 	 * Clear contract template state
314 	 */
315 	lwp_ctmpl_clear(lwp);
316 
317 	/*
318 	 * Save the directory in which we found the executable for expanding
319 	 * the %d token used in core file patterns.
320 	 */
321 	mutex_enter(&p->p_lock);
322 	tmpvp = p->p_execdir;
323 	p->p_execdir = dir;
324 	if (p->p_execdir != NULL)
325 		VN_HOLD(p->p_execdir);
326 	mutex_exit(&p->p_lock);
327 
328 	if (tmpvp != NULL)
329 		VN_RELE(tmpvp);
330 
331 	/*
332 	 * Reset stack state to the user stack, clear set of signals
333 	 * caught on the signal stack, and reset list of signals that
334 	 * restart system calls; the new program's environment should
335 	 * not be affected by detritus from the old program.  Any
336 	 * pending held signals remain held, so don't clear t_hold.
337 	 */
338 	mutex_enter(&p->p_lock);
339 	lwp->lwp_oldcontext = 0;
340 	lwp->lwp_ustack = 0;
341 	lwp->lwp_old_stk_ctl = 0;
342 	sigemptyset(&up->u_signodefer);
343 	sigemptyset(&up->u_sigonstack);
344 	sigemptyset(&up->u_sigresethand);
345 	lwp->lwp_sigaltstack.ss_sp = 0;
346 	lwp->lwp_sigaltstack.ss_size = 0;
347 	lwp->lwp_sigaltstack.ss_flags = SS_DISABLE;
348 
349 	/*
350 	 * Make saved resource limit == current resource limit.
351 	 */
352 	for (i = 0; i < RLIM_NLIMITS; i++) {
353 		/*CONSTCOND*/
354 		if (RLIM_SAVED(i)) {
355 			(void) rctl_rlimit_get(rctlproc_legacy[i], p,
356 			    &up->u_saved_rlimit[i]);
357 		}
358 	}
359 
360 	/*
361 	 * If the action was to catch the signal, then the action
362 	 * must be reset to SIG_DFL.
363 	 */
364 	sigdefault(p);
365 	p->p_flag &= ~(SNOWAIT|SJCTL);
366 	p->p_flag |= (SEXECED|SMSACCT|SMSFORK);
367 	up->u_signal[SIGCLD - 1] = SIG_DFL;
368 
369 	/*
370 	 * Delete the dot4 sigqueues/signotifies.
371 	 */
372 	sigqfree(p);
373 
374 	mutex_exit(&p->p_lock);
375 
376 	mutex_enter(&p->p_pflock);
377 	p->p_prof.pr_base = NULL;
378 	p->p_prof.pr_size = 0;
379 	p->p_prof.pr_off = 0;
380 	p->p_prof.pr_scale = 0;
381 	p->p_prof.pr_samples = 0;
382 	mutex_exit(&p->p_pflock);
383 
384 	ASSERT(curthread->t_schedctl == NULL);
385 
386 #if defined(__sparc)
387 	if (p->p_utraps != NULL)
388 		utrap_free(p);
389 #endif	/* __sparc */
390 
391 	/*
392 	 * Close all close-on-exec files.
393 	 */
394 	close_exec(P_FINFO(p));
395 	TRACE_2(TR_FAC_PROC, TR_PROC_EXEC, "proc_exec:p %p up %p", p, up);
396 
397 	/* Unbrand ourself if necessary. */
398 	if (PROC_IS_BRANDED(p) && (brand_action == EBA_NATIVE))
399 		brand_clearbrand(p);
400 
401 	setregs(&args);
402 
403 	/* Mark this as an executable vnode */
404 	mutex_enter(&vp->v_lock);
405 	vp->v_flag |= VVMEXEC;
406 	mutex_exit(&vp->v_lock);
407 
408 	VN_RELE(vp);
409 	if (dir != NULL)
410 		VN_RELE(dir);
411 	pn_free(&resolvepn);
412 
413 	/*
414 	 * Allocate a new lwp directory and lwpid hash table if necessary.
415 	 */
416 	if (curthread->t_tid != 1 || p->p_lwpdir_sz != 2) {
417 		lwpdir = kmem_zalloc(2 * sizeof (lwpdir_t), KM_SLEEP);
418 		lwpdir->ld_next = lwpdir + 1;
419 		tidhash = kmem_zalloc(2 * sizeof (lwpdir_t *), KM_SLEEP);
420 		if (p->p_lwpdir != NULL)
421 			lep = p->p_lwpdir[curthread->t_dslot].ld_entry;
422 		else
423 			lep = kmem_zalloc(sizeof (*lep), KM_SLEEP);
424 	}
425 
426 	if (PROC_IS_BRANDED(p))
427 		BROP(p)->b_exec();
428 
429 	mutex_enter(&p->p_lock);
430 	prbarrier(p);
431 
432 	/*
433 	 * Reset lwp id to the default value of 1.
434 	 * This is a single-threaded process now
435 	 * and lwp #1 is lwp_wait()able by default.
436 	 * The t_unpark flag should not be inherited.
437 	 */
438 	ASSERT(p->p_lwpcnt == 1 && p->p_zombcnt == 0);
439 	curthread->t_tid = 1;
440 	kpreempt_disable();
441 	ASSERT(curthread->t_lpl != NULL);
442 	p->p_t1_lgrpid = curthread->t_lpl->lpl_lgrpid;
443 	kpreempt_enable();
444 	if (p->p_tr_lgrpid != LGRP_NONE && p->p_tr_lgrpid != p->p_t1_lgrpid) {
445 		lgrp_update_trthr_migrations(1);
446 	}
447 	curthread->t_unpark = 0;
448 	curthread->t_proc_flag |= TP_TWAIT;
449 	curthread->t_proc_flag &= ~TP_DAEMON;	/* daemons shouldn't exec */
450 	p->p_lwpdaemon = 0;			/* but oh well ... */
451 	p->p_lwpid = 1;
452 
453 	/*
454 	 * Install the newly-allocated lwp directory and lwpid hash table
455 	 * and insert the current thread into the new hash table.
456 	 */
457 	if (lwpdir != NULL) {
458 		old_lwpdir = p->p_lwpdir;
459 		old_lwpdir_sz = p->p_lwpdir_sz;
460 		old_tidhash = p->p_tidhash;
461 		old_tidhash_sz = p->p_tidhash_sz;
462 		p->p_lwpdir = p->p_lwpfree = lwpdir;
463 		p->p_lwpdir_sz = 2;
464 		p->p_tidhash = tidhash;
465 		p->p_tidhash_sz = 2;
466 		lep->le_thread = curthread;
467 		lep->le_lwpid = curthread->t_tid;
468 		lep->le_start = curthread->t_start;
469 		lwp_hash_in(p, lep);
470 	}
471 
472 	/*
473 	 * Restore the saved signal mask and
474 	 * inform /proc that the exec() has finished.
475 	 */
476 	curthread->t_hold = savedmask;
477 	prexecend();
478 	mutex_exit(&p->p_lock);
479 	if (old_lwpdir) {
480 		kmem_free(old_lwpdir, old_lwpdir_sz * sizeof (lwpdir_t));
481 		kmem_free(old_tidhash, old_tidhash_sz * sizeof (lwpdir_t *));
482 	}
483 
484 	ASSERT(error == 0);
485 	DTRACE_PROC(exec__success);
486 	return (0);
487 
488 fail:
489 	DTRACE_PROC1(exec__failure, int, error);
490 out:		/* error return */
491 	mutex_enter(&p->p_lock);
492 	curthread->t_hold = savedmask;
493 	prexecend();
494 	mutex_exit(&p->p_lock);
495 	ASSERT(error != 0);
496 	return (error);
497 }
498 
499 
500 /*
501  * Perform generic exec duties and switchout to object-file specific
502  * handler.
503  */
504 int
505 gexec(
506 	struct vnode **vpp,
507 	struct execa *uap,
508 	struct uarg *args,
509 	struct intpdata *idatap,
510 	int level,
511 	long *execsz,
512 	caddr_t exec_file,
513 	struct cred *cred,
514 	int brand_action)
515 {
516 	struct vnode *vp;
517 	proc_t *pp = ttoproc(curthread);
518 	struct execsw *eswp;
519 	int error = 0;
520 	int suidflags = 0;
521 	ssize_t resid;
522 	uid_t uid, gid;
523 	struct vattr vattr;
524 	char magbuf[MAGIC_BYTES];
525 	int setid;
526 	cred_t *oldcred, *newcred = NULL;
527 	int privflags = 0;
528 	int setidfl;
529 
530 	/*
531 	 * If the SNOCD or SUGID flag is set, turn it off and remember the
532 	 * previous setting so we can restore it if we encounter an error.
533 	 */
534 	if (level == 0 && (pp->p_flag & PSUIDFLAGS)) {
535 		mutex_enter(&pp->p_lock);
536 		suidflags = pp->p_flag & PSUIDFLAGS;
537 		pp->p_flag &= ~PSUIDFLAGS;
538 		mutex_exit(&pp->p_lock);
539 	}
540 
541 	if ((error = execpermissions(*vpp, &vattr, args)) != 0)
542 		goto bad;
543 
544 	/* need to open vnode for stateful file systems like rfs */
545 	if ((error = VOP_OPEN(vpp, FREAD, CRED(), NULL)) != 0)
546 		goto bad;
547 	vp = *vpp;
548 
549 	/*
550 	 * Note: to support binary compatibility with SunOS a.out
551 	 * executables, we read in the first four bytes, as the
552 	 * magic number is in bytes 2-3.
553 	 */
554 	if (error = vn_rdwr(UIO_READ, vp, magbuf, sizeof (magbuf),
555 	    (offset_t)0, UIO_SYSSPACE, 0, (rlim64_t)0, CRED(), &resid))
556 		goto bad;
557 	if (resid != 0)
558 		goto bad;
559 
560 	if ((eswp = findexec_by_hdr(magbuf)) == NULL)
561 		goto bad;
562 
563 	if (level == 0 &&
564 	    (privflags = execsetid(vp, &vattr, &uid, &gid)) != 0) {
565 
566 		newcred = cred = crdup(cred);
567 
568 		/* If we can, drop the PA bit */
569 		if ((privflags & PRIV_RESET) != 0)
570 			priv_adjust_PA(cred);
571 
572 		if (privflags & PRIV_SETID) {
573 			cred->cr_uid = uid;
574 			cred->cr_gid = gid;
575 			cred->cr_suid = uid;
576 			cred->cr_sgid = gid;
577 		}
578 
579 		if (privflags & MAC_FLAGS) {
580 			if (!(CR_FLAGS(cred) & NET_MAC_AWARE_INHERIT))
581 				CR_FLAGS(cred) &= ~NET_MAC_AWARE;
582 			CR_FLAGS(cred) &= ~NET_MAC_AWARE_INHERIT;
583 		}
584 
585 		/*
586 		 * Implement the privilege updates:
587 		 *
588 		 * Restrict with L:
589 		 *
590 		 *	I' = I & L
591 		 *
592 		 *	E' = P' = (I' + F) & A
593 		 *
594 		 * But if running under ptrace, we cap I with P.
595 		 */
596 		if ((privflags & PRIV_RESET) != 0) {
597 			if ((privflags & PRIV_INCREASE) != 0 &&
598 			    (pp->p_proc_flag & P_PR_PTRACE) != 0)
599 				priv_intersect(&CR_OPPRIV(cred),
600 				    &CR_IPRIV(cred));
601 			priv_intersect(&CR_LPRIV(cred), &CR_IPRIV(cred));
602 			CR_EPRIV(cred) = CR_PPRIV(cred) = CR_IPRIV(cred);
603 			priv_adjust_PA(cred);
604 		}
605 	}
606 
607 	/* SunOS 4.x buy-back */
608 	if ((vp->v_vfsp->vfs_flag & VFS_NOSETUID) &&
609 	    (vattr.va_mode & (VSUID|VSGID))) {
610 		cmn_err(CE_NOTE,
611 		    "!%s, uid %d: setuid execution not allowed, dev=%lx",
612 		    exec_file, cred->cr_uid, vp->v_vfsp->vfs_dev);
613 	}
614 
615 	/*
616 	 * execsetid() told us whether or not we had to change the
617 	 * credentials of the process.  In privflags, it told us
618 	 * whether we gained any privileges or executed a set-uid executable.
619 	 */
620 	setid = (privflags & (PRIV_SETUGID|PRIV_INCREASE));
621 
622 	/*
623 	 * Use /etc/system variable to determine if the stack
624 	 * should be marked as executable by default.
625 	 */
626 	if (noexec_user_stack)
627 		args->stk_prot &= ~PROT_EXEC;
628 
629 	args->execswp = eswp; /* Save execsw pointer in uarg for exec_func */
630 	args->ex_vp = vp;
631 
632 	/*
633 	 * Traditionally, the setid flags told the sub processes whether
634 	 * the file just executed was set-uid or set-gid; this caused
635 	 * some confusion as the 'setid' flag did not match the SUGID
636 	 * process flag which is only set when the uids/gids do not match.
637 	 * A script set-gid/set-uid to the real uid/gid would start with
638 	 * /dev/fd/X but an executable would happily trust LD_LIBRARY_PATH.
639 	 * Now we flag those cases where the calling process cannot
640 	 * be trusted to influence the newly exec'ed process, either
641 	 * because it runs with more privileges or when the uids/gids
642 	 * do in fact not match.
643 	 * This also makes the runtime linker agree with the on exec
644 	 * values of SNOCD and SUGID.
645 	 */
646 	setidfl = 0;
647 	if (cred->cr_uid != cred->cr_ruid || (cred->cr_rgid != cred->cr_gid &&
648 	    !supgroupmember(cred->cr_gid, cred))) {
649 		setidfl |= EXECSETID_UGIDS;
650 	}
651 	if (setid & PRIV_SETUGID)
652 		setidfl |= EXECSETID_SETID;
653 	if (setid & PRIV_INCREASE)
654 		setidfl |= EXECSETID_PRIVS;
655 
656 	error = (*eswp->exec_func)(vp, uap, args, idatap, level, execsz,
657 	    setidfl, exec_file, cred, brand_action);
658 	rw_exit(eswp->exec_lock);
659 	if (error != 0) {
660 		if (newcred != NULL)
661 			crfree(newcred);
662 		goto bad;
663 	}
664 
665 	if (level == 0) {
666 		mutex_enter(&pp->p_crlock);
667 		if (newcred != NULL) {
668 			/*
669 			 * Free the old credentials, and set the new ones.
670 			 * Do this for both the process and the (single) thread.
671 			 */
672 			crfree(pp->p_cred);
673 			pp->p_cred = cred;	/* cred already held for proc */
674 			crhold(cred);		/* hold new cred for thread */
675 			/*
676 			 * DTrace accesses t_cred in probe context.  t_cred
677 			 * must always be either NULL, or point to a valid,
678 			 * allocated cred structure.
679 			 */
680 			oldcred = curthread->t_cred;
681 			curthread->t_cred = cred;
682 			crfree(oldcred);
683 		}
684 		/*
685 		 * On emerging from a successful exec(), the saved
686 		 * uid and gid equal the effective uid and gid.
687 		 */
688 		cred->cr_suid = cred->cr_uid;
689 		cred->cr_sgid = cred->cr_gid;
690 
691 		/*
692 		 * If the real and effective ids do not match, this
693 		 * is a setuid process that should not dump core.
694 		 * The group comparison is tricky; we prevent the code
695 		 * from flagging SNOCD when executing with an effective gid
696 		 * which is a supplementary group.
697 		 */
698 		if (cred->cr_ruid != cred->cr_uid ||
699 		    (cred->cr_rgid != cred->cr_gid &&
700 		    !supgroupmember(cred->cr_gid, cred)) ||
701 		    (privflags & PRIV_INCREASE) != 0)
702 			suidflags = PSUIDFLAGS;
703 		else
704 			suidflags = 0;
705 
706 		mutex_exit(&pp->p_crlock);
707 		if (suidflags) {
708 			mutex_enter(&pp->p_lock);
709 			pp->p_flag |= suidflags;
710 			mutex_exit(&pp->p_lock);
711 		}
712 		if (setid && (pp->p_proc_flag & P_PR_PTRACE) == 0) {
713 			/*
714 			 * If process is traced via /proc, arrange to
715 			 * invalidate the associated /proc vnode.
716 			 */
717 			if (pp->p_plist || (pp->p_proc_flag & P_PR_TRACE))
718 				args->traceinval = 1;
719 		}
720 		if (pp->p_proc_flag & P_PR_PTRACE)
721 			psignal(pp, SIGTRAP);
722 		if (args->traceinval)
723 			prinvalidate(&pp->p_user);
724 	}
725 
726 	return (0);
727 bad:
728 	if (error == 0)
729 		error = ENOEXEC;
730 
731 	if (suidflags) {
732 		mutex_enter(&pp->p_lock);
733 		pp->p_flag |= suidflags;
734 		mutex_exit(&pp->p_lock);
735 	}
736 	return (error);
737 }
738 
739 extern char *execswnames[];
740 
741 struct execsw *
742 allocate_execsw(char *name, char *magic, size_t magic_size)
743 {
744 	int i, j;
745 	char *ename;
746 	char *magicp;
747 
748 	mutex_enter(&execsw_lock);
749 	for (i = 0; i < nexectype; i++) {
750 		if (execswnames[i] == NULL) {
751 			ename = kmem_alloc(strlen(name) + 1, KM_SLEEP);
752 			(void) strcpy(ename, name);
753 			execswnames[i] = ename;
754 			/*
755 			 * Set the magic number last so that we
756 			 * don't need to hold the execsw_lock in
757 			 * findexectype().
758 			 */
759 			magicp = kmem_alloc(magic_size, KM_SLEEP);
760 			for (j = 0; j < magic_size; j++)
761 				magicp[j] = magic[j];
762 			execsw[i].exec_magic = magicp;
763 			mutex_exit(&execsw_lock);
764 			return (&execsw[i]);
765 		}
766 	}
767 	mutex_exit(&execsw_lock);
768 	return (NULL);
769 }
770 
771 /*
772  * Find the exec switch table entry with the corresponding magic string.
773  */
774 struct execsw *
775 findexecsw(char *magic)
776 {
777 	struct execsw *eswp;
778 
779 	for (eswp = execsw; eswp < &execsw[nexectype]; eswp++) {
780 		ASSERT(eswp->exec_maglen <= MAGIC_BYTES);
781 		if (magic && eswp->exec_maglen != 0 &&
782 		    bcmp(magic, eswp->exec_magic, eswp->exec_maglen) == 0)
783 			return (eswp);
784 	}
785 	return (NULL);
786 }
787 
788 /*
789  * Find the execsw[] index for the given exec header string by looking for the
790  * magic string at a specified offset and length for each kind of executable
791  * file format until one matches.  If no execsw[] entry is found, try to
792  * autoload a module for this magic string.
793  */
794 struct execsw *
795 findexec_by_hdr(char *header)
796 {
797 	struct execsw *eswp;
798 
799 	for (eswp = execsw; eswp < &execsw[nexectype]; eswp++) {
800 		ASSERT(eswp->exec_maglen <= MAGIC_BYTES);
801 		if (header && eswp->exec_maglen != 0 &&
802 		    bcmp(&header[eswp->exec_magoff], eswp->exec_magic,
803 		    eswp->exec_maglen) == 0) {
804 			if (hold_execsw(eswp) != 0)
805 				return (NULL);
806 			return (eswp);
807 		}
808 	}
809 	return (NULL);	/* couldn't find the type */
810 }
811 
812 /*
813  * Find the execsw[] index for the given magic string.  If no execsw[] entry
814  * is found, try to autoload a module for this magic string.
815  */
816 struct execsw *
817 findexec_by_magic(char *magic)
818 {
819 	struct execsw *eswp;
820 
821 	for (eswp = execsw; eswp < &execsw[nexectype]; eswp++) {
822 		ASSERT(eswp->exec_maglen <= MAGIC_BYTES);
823 		if (magic && eswp->exec_maglen != 0 &&
824 		    bcmp(magic, eswp->exec_magic, eswp->exec_maglen) == 0) {
825 			if (hold_execsw(eswp) != 0)
826 				return (NULL);
827 			return (eswp);
828 		}
829 	}
830 	return (NULL);	/* couldn't find the type */
831 }
832 
833 static int
834 hold_execsw(struct execsw *eswp)
835 {
836 	char *name;
837 
838 	rw_enter(eswp->exec_lock, RW_READER);
839 	while (!LOADED_EXEC(eswp)) {
840 		rw_exit(eswp->exec_lock);
841 		name = execswnames[eswp-execsw];
842 		ASSERT(name);
843 		if (modload("exec", name) == -1)
844 			return (-1);
845 		rw_enter(eswp->exec_lock, RW_READER);
846 	}
847 	return (0);
848 }
849 
850 static int
851 execsetid(struct vnode *vp, struct vattr *vattrp, uid_t *uidp, uid_t *gidp)
852 {
853 	proc_t *pp = ttoproc(curthread);
854 	uid_t uid, gid;
855 	cred_t *cr = pp->p_cred;
856 	int privflags = 0;
857 
858 	/*
859 	 * Remember credentials.
860 	 */
861 	uid = cr->cr_uid;
862 	gid = cr->cr_gid;
863 
864 	/* Will try to reset the PRIV_AWARE bit later. */
865 	if ((CR_FLAGS(cr) & (PRIV_AWARE|PRIV_AWARE_INHERIT)) == PRIV_AWARE)
866 		privflags |= PRIV_RESET;
867 
868 	if ((vp->v_vfsp->vfs_flag & VFS_NOSETUID) == 0) {
869 		/*
870 		 * Set-uid root execution only allowed if the limit set
871 		 * holds all unsafe privileges.
872 		 */
873 		if ((vattrp->va_mode & VSUID) && (vattrp->va_uid != 0 ||
874 		    priv_issubset(&priv_unsafe, &CR_LPRIV(cr)))) {
875 			uid = vattrp->va_uid;
876 			privflags |= PRIV_SETUGID;
877 		}
878 		if (vattrp->va_mode & VSGID) {
879 			gid = vattrp->va_gid;
880 			privflags |= PRIV_SETUGID;
881 		}
882 	}
883 
884 	/*
885 	 * Do we need to change our credential anyway?
886 	 * This is the case when E != I or P != I, as
887 	 * we need to do the assignments (with F empty and A full)
888 	 * Or when I is not a subset of L; in that case we need to
889 	 * enforce L.
890 	 *
891 	 *		I' = L & I
892 	 *
893 	 *		E' = P' = (I' + F) & A
894 	 * or
895 	 *		E' = P' = I'
896 	 */
897 	if (!priv_isequalset(&CR_EPRIV(cr), &CR_IPRIV(cr)) ||
898 	    !priv_issubset(&CR_IPRIV(cr), &CR_LPRIV(cr)) ||
899 	    !priv_isequalset(&CR_PPRIV(cr), &CR_IPRIV(cr)))
900 		privflags |= PRIV_RESET;
901 
902 	/* If MAC-aware flag(s) are on, need to update cred to remove. */
903 	if ((CR_FLAGS(cr) & NET_MAC_AWARE) ||
904 	    (CR_FLAGS(cr) & NET_MAC_AWARE_INHERIT))
905 		privflags |= MAC_FLAGS;
906 
907 	/*
908 	 * When we introduce the "forced" set then we will need
909 	 * to set PRIV_INCREASE here if I not a subset of P.
910 	 * If the "allowed" set is introduced we will need to do
911 	 * a similar thing; however, it seems more reasonable to
912 	 * have the allowed set reduce "L": script language interpreters
913 	 * would typically have an allowed set of "all".
914 	 */
915 
916 	/*
917 	 * Set setuid/setgid protections if no ptrace() compatibility.
918 	 * For privileged processes, honor setuid/setgid even in
919 	 * the presence of ptrace() compatibility.
920 	 */
921 	if (((pp->p_proc_flag & P_PR_PTRACE) == 0 ||
922 	    PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, (uid == 0))) &&
923 	    (cr->cr_uid != uid ||
924 	    cr->cr_gid != gid ||
925 	    cr->cr_suid != uid ||
926 	    cr->cr_sgid != gid)) {
927 		*uidp = uid;
928 		*gidp = gid;
929 		privflags |= PRIV_SETID;
930 	}
931 	return (privflags);
932 }
933 
934 int
935 execpermissions(struct vnode *vp, struct vattr *vattrp, struct uarg *args)
936 {
937 	int error;
938 	proc_t *p = ttoproc(curthread);
939 
940 	vattrp->va_mask = AT_MODE | AT_UID | AT_GID | AT_SIZE;
941 	if (error = VOP_GETATTR(vp, vattrp, ATTR_EXEC, p->p_cred, NULL))
942 		return (error);
943 	/*
944 	 * Check the access mode.
945 	 * If VPROC, ask /proc if the file is an object file.
946 	 */
947 	if ((error = VOP_ACCESS(vp, VEXEC, 0, p->p_cred, NULL)) != 0 ||
948 	    !(vp->v_type == VREG || (vp->v_type == VPROC && pr_isobject(vp))) ||
949 	    (vp->v_vfsp->vfs_flag & VFS_NOEXEC) != 0 ||
950 	    (vattrp->va_mode & (VEXEC|(VEXEC>>3)|(VEXEC>>6))) == 0) {
951 		if (error == 0)
952 			error = EACCES;
953 		return (error);
954 	}
955 
956 	if ((p->p_plist || (p->p_proc_flag & (P_PR_PTRACE|P_PR_TRACE))) &&
957 	    (error = VOP_ACCESS(vp, VREAD, 0, p->p_cred, NULL))) {
958 		/*
959 		 * If process is under ptrace(2) compatibility,
960 		 * fail the exec(2).
961 		 */
962 		if (p->p_proc_flag & P_PR_PTRACE)
963 			goto bad;
964 		/*
965 		 * Process is traced via /proc.
966 		 * Arrange to invalidate the /proc vnode.
967 		 */
968 		args->traceinval = 1;
969 	}
970 	return (0);
971 bad:
972 	if (error == 0)
973 		error = ENOEXEC;
974 	return (error);
975 }
976 
977 /*
978  * Map a section of an executable file into the user's
979  * address space.
980  */
981 int
982 execmap(struct vnode *vp, caddr_t addr, size_t len, size_t zfodlen,
983     off_t offset, int prot, int page, uint_t szc)
984 {
985 	int error = 0;
986 	off_t oldoffset;
987 	caddr_t zfodbase, oldaddr;
988 	size_t end, oldlen;
989 	size_t zfoddiff;
990 	label_t ljb;
991 	proc_t *p = ttoproc(curthread);
992 
993 	oldaddr = addr;
994 	addr = (caddr_t)((uintptr_t)addr & (uintptr_t)PAGEMASK);
995 	if (len) {
996 		oldlen = len;
997 		len += ((size_t)oldaddr - (size_t)addr);
998 		oldoffset = offset;
999 		offset = (off_t)((uintptr_t)offset & PAGEMASK);
1000 		if (page) {
1001 			spgcnt_t  prefltmem, availm, npages;
1002 			int preread;
1003 			uint_t mflag = MAP_PRIVATE | MAP_FIXED;
1004 
1005 			if ((prot & (PROT_WRITE | PROT_EXEC)) == PROT_EXEC) {
1006 				mflag |= MAP_TEXT;
1007 			} else {
1008 				mflag |= MAP_INITDATA;
1009 			}
1010 
1011 			if (valid_usr_range(addr, len, prot, p->p_as,
1012 			    p->p_as->a_userlimit) != RANGE_OKAY) {
1013 				error = ENOMEM;
1014 				goto bad;
1015 			}
1016 			if (error = VOP_MAP(vp, (offset_t)offset,
1017 			    p->p_as, &addr, len, prot, PROT_ALL,
1018 			    mflag, CRED(), NULL))
1019 				goto bad;
1020 
1021 			/*
1022 			 * If the segment can fit, then we prefault
1023 			 * the entire segment in.  This is based on the
1024 			 * model that says the best working set of a
1025 			 * small program is all of its pages.
1026 			 */
1027 			npages = (spgcnt_t)btopr(len);
1028 			prefltmem = freemem - desfree;
1029 			preread =
1030 			    (npages < prefltmem && len < PGTHRESH) ? 1 : 0;
1031 
1032 			/*
1033 			 * If we aren't prefaulting the segment,
1034 			 * increment "deficit", if necessary to ensure
1035 			 * that pages will become available when this
1036 			 * process starts executing.
1037 			 */
1038 			availm = freemem - lotsfree;
1039 			if (preread == 0 && npages > availm &&
1040 			    deficit < lotsfree) {
1041 				deficit += MIN((pgcnt_t)(npages - availm),
1042 				    lotsfree - deficit);
1043 			}
1044 
1045 			if (preread) {
1046 				TRACE_2(TR_FAC_PROC, TR_EXECMAP_PREREAD,
1047 				    "execmap preread:freemem %d size %lu",
1048 				    freemem, len);
1049 				(void) as_fault(p->p_as->a_hat, p->p_as,
1050 				    (caddr_t)addr, len, F_INVAL, S_READ);
1051 			}
1052 		} else {
1053 			if (valid_usr_range(addr, len, prot, p->p_as,
1054 			    p->p_as->a_userlimit) != RANGE_OKAY) {
1055 				error = ENOMEM;
1056 				goto bad;
1057 			}
1058 
1059 			if (error = as_map(p->p_as, addr, len,
1060 			    segvn_create, zfod_argsp))
1061 				goto bad;
1062 			/*
1063 			 * Read in the segment in one big chunk.
1064 			 */
1065 			if (error = vn_rdwr(UIO_READ, vp, (caddr_t)oldaddr,
1066 			    oldlen, (offset_t)oldoffset, UIO_USERSPACE, 0,
1067 			    (rlim64_t)0, CRED(), (ssize_t *)0))
1068 				goto bad;
1069 			/*
1070 			 * Now set protections.
1071 			 */
1072 			if (prot != PROT_ZFOD) {
1073 				(void) as_setprot(p->p_as, (caddr_t)addr,
1074 				    len, prot);
1075 			}
1076 		}
1077 	}
1078 
1079 	if (zfodlen) {
1080 		struct as *as = curproc->p_as;
1081 		struct seg *seg;
1082 		uint_t zprot = 0;
1083 
1084 		end = (size_t)addr + len;
1085 		zfodbase = (caddr_t)roundup(end, PAGESIZE);
1086 		zfoddiff = (uintptr_t)zfodbase - end;
1087 		if (zfoddiff) {
1088 			/*
1089 			 * Before we go to zero the remaining space on the last
1090 			 * page, make sure we have write permission.
1091 			 */
1092 
1093 			AS_LOCK_ENTER(as, &as->a_lock, RW_READER);
1094 			seg = as_segat(curproc->p_as, (caddr_t)end);
1095 			if (seg != NULL)
1096 				SEGOP_GETPROT(seg, (caddr_t)end, zfoddiff - 1,
1097 				    &zprot);
1098 			AS_LOCK_EXIT(as, &as->a_lock);
1099 
1100 			if (seg != NULL && (zprot & PROT_WRITE) == 0) {
1101 				(void) as_setprot(as, (caddr_t)end,
1102 				    zfoddiff - 1, zprot | PROT_WRITE);
1103 			}
1104 
1105 			if (on_fault(&ljb)) {
1106 				no_fault();
1107 				if (seg != NULL && (zprot & PROT_WRITE) == 0)
1108 					(void) as_setprot(as, (caddr_t)end,
1109 					    zfoddiff - 1, zprot);
1110 				error = EFAULT;
1111 				goto bad;
1112 			}
1113 			uzero((void *)end, zfoddiff);
1114 			no_fault();
1115 			if (seg != NULL && (zprot & PROT_WRITE) == 0)
1116 				(void) as_setprot(as, (caddr_t)end,
1117 				    zfoddiff - 1, zprot);
1118 		}
1119 		if (zfodlen > zfoddiff) {
1120 			struct segvn_crargs crargs =
1121 			    SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
1122 
1123 			zfodlen -= zfoddiff;
1124 			if (valid_usr_range(zfodbase, zfodlen, prot, p->p_as,
1125 			    p->p_as->a_userlimit) != RANGE_OKAY) {
1126 				error = ENOMEM;
1127 				goto bad;
1128 			}
1129 			if (szc > 0) {
1130 				/*
1131 				 * ASSERT alignment because the mapelfexec()
1132 				 * caller for the szc > 0 case extended zfod
1133 				 * so it's end is pgsz aligned.
1134 				 */
1135 				size_t pgsz = page_get_pagesize(szc);
1136 				ASSERT(IS_P2ALIGNED(zfodbase + zfodlen, pgsz));
1137 
1138 				if (IS_P2ALIGNED(zfodbase, pgsz)) {
1139 					crargs.szc = szc;
1140 				} else {
1141 					crargs.szc = AS_MAP_HEAP;
1142 				}
1143 			} else {
1144 				crargs.szc = AS_MAP_NO_LPOOB;
1145 			}
1146 			if (error = as_map(p->p_as, (caddr_t)zfodbase,
1147 			    zfodlen, segvn_create, &crargs))
1148 				goto bad;
1149 			if (prot != PROT_ZFOD) {
1150 				(void) as_setprot(p->p_as, (caddr_t)zfodbase,
1151 				    zfodlen, prot);
1152 			}
1153 		}
1154 	}
1155 	return (0);
1156 bad:
1157 	return (error);
1158 }
1159 
1160 void
1161 setexecenv(struct execenv *ep)
1162 {
1163 	proc_t *p = ttoproc(curthread);
1164 	klwp_t *lwp = ttolwp(curthread);
1165 	struct vnode *vp;
1166 
1167 	p->p_bssbase = ep->ex_bssbase;
1168 	p->p_brkbase = ep->ex_brkbase;
1169 	p->p_brksize = ep->ex_brksize;
1170 	if (p->p_exec)
1171 		VN_RELE(p->p_exec);	/* out with the old */
1172 	vp = p->p_exec = ep->ex_vp;
1173 	if (vp != NULL)
1174 		VN_HOLD(vp);		/* in with the new */
1175 
1176 	lwp->lwp_sigaltstack.ss_sp = 0;
1177 	lwp->lwp_sigaltstack.ss_size = 0;
1178 	lwp->lwp_sigaltstack.ss_flags = SS_DISABLE;
1179 }
1180 
1181 int
1182 execopen(struct vnode **vpp, int *fdp)
1183 {
1184 	struct vnode *vp = *vpp;
1185 	file_t *fp;
1186 	int error = 0;
1187 	int filemode = FREAD;
1188 
1189 	VN_HOLD(vp);		/* open reference */
1190 	if (error = falloc(NULL, filemode, &fp, fdp)) {
1191 		VN_RELE(vp);
1192 		*fdp = -1;	/* just in case falloc changed value */
1193 		return (error);
1194 	}
1195 	if (error = VOP_OPEN(&vp, filemode, CRED(), NULL)) {
1196 		VN_RELE(vp);
1197 		setf(*fdp, NULL);
1198 		unfalloc(fp);
1199 		*fdp = -1;
1200 		return (error);
1201 	}
1202 	*vpp = vp;		/* vnode should not have changed */
1203 	fp->f_vnode = vp;
1204 	mutex_exit(&fp->f_tlock);
1205 	setf(*fdp, fp);
1206 	return (0);
1207 }
1208 
1209 int
1210 execclose(int fd)
1211 {
1212 	return (closeandsetf(fd, NULL));
1213 }
1214 
1215 
1216 /*
1217  * noexec stub function.
1218  */
1219 /*ARGSUSED*/
1220 int
1221 noexec(
1222     struct vnode *vp,
1223     struct execa *uap,
1224     struct uarg *args,
1225     struct intpdata *idatap,
1226     int level,
1227     long *execsz,
1228     int setid,
1229     caddr_t exec_file,
1230     struct cred *cred)
1231 {
1232 	cmn_err(CE_WARN, "missing exec capability for %s", uap->fname);
1233 	return (ENOEXEC);
1234 }
1235 
1236 /*
1237  * Support routines for building a user stack.
1238  *
1239  * execve(path, argv, envp) must construct a new stack with the specified
1240  * arguments and environment variables (see exec_args() for a description
1241  * of the user stack layout).  To do this, we copy the arguments and
1242  * environment variables from the old user address space into the kernel,
1243  * free the old as, create the new as, and copy our buffered information
1244  * to the new stack.  Our kernel buffer has the following structure:
1245  *
1246  *	+-----------------------+ <--- stk_base + stk_size
1247  *	| string offsets	|
1248  *	+-----------------------+ <--- stk_offp
1249  *	|			|
1250  *	| STK_AVAIL() space	|
1251  *	|			|
1252  *	+-----------------------+ <--- stk_strp
1253  *	| strings		|
1254  *	+-----------------------+ <--- stk_base
1255  *
1256  * When we add a string, we store the string's contents (including the null
1257  * terminator) at stk_strp, and we store the offset of the string relative to
1258  * stk_base at --stk_offp.  At strings are added, stk_strp increases and
1259  * stk_offp decreases.  The amount of space remaining, STK_AVAIL(), is just
1260  * the difference between these pointers.  If we run out of space, we return
1261  * an error and exec_args() starts all over again with a buffer twice as large.
1262  * When we're all done, the kernel buffer looks like this:
1263  *
1264  *	+-----------------------+ <--- stk_base + stk_size
1265  *	| argv[0] offset	|
1266  *	+-----------------------+
1267  *	| ...			|
1268  *	+-----------------------+
1269  *	| argv[argc-1] offset	|
1270  *	+-----------------------+
1271  *	| envp[0] offset	|
1272  *	+-----------------------+
1273  *	| ...			|
1274  *	+-----------------------+
1275  *	| envp[envc-1] offset	|
1276  *	+-----------------------+
1277  *	| AT_SUN_PLATFORM offset|
1278  *	+-----------------------+
1279  *	| AT_SUN_EXECNAME offset|
1280  *	+-----------------------+ <--- stk_offp
1281  *	|			|
1282  *	| STK_AVAIL() space	|
1283  *	|			|
1284  *	+-----------------------+ <--- stk_strp
1285  *	| AT_SUN_EXECNAME offset|
1286  *	+-----------------------+
1287  *	| AT_SUN_PLATFORM offset|
1288  *	+-----------------------+
1289  *	| envp[envc-1] string	|
1290  *	+-----------------------+
1291  *	| ...			|
1292  *	+-----------------------+
1293  *	| envp[0] string	|
1294  *	+-----------------------+
1295  *	| argv[argc-1] string	|
1296  *	+-----------------------+
1297  *	| ...			|
1298  *	+-----------------------+
1299  *	| argv[0] string	|
1300  *	+-----------------------+ <--- stk_base
1301  */
1302 
1303 #define	STK_AVAIL(args)		((char *)(args)->stk_offp - (args)->stk_strp)
1304 
1305 /*
1306  * Add a string to the stack.
1307  */
1308 static int
1309 stk_add(uarg_t *args, const char *sp, enum uio_seg segflg)
1310 {
1311 	int error;
1312 	size_t len;
1313 
1314 	if (STK_AVAIL(args) < sizeof (int))
1315 		return (E2BIG);
1316 	*--args->stk_offp = args->stk_strp - args->stk_base;
1317 
1318 	if (segflg == UIO_USERSPACE) {
1319 		error = copyinstr(sp, args->stk_strp, STK_AVAIL(args), &len);
1320 		if (error != 0)
1321 			return (error);
1322 	} else {
1323 		len = strlen(sp) + 1;
1324 		if (len > STK_AVAIL(args))
1325 			return (E2BIG);
1326 		bcopy(sp, args->stk_strp, len);
1327 	}
1328 
1329 	args->stk_strp += len;
1330 
1331 	return (0);
1332 }
1333 
1334 static int
1335 stk_getptr(uarg_t *args, char *src, char **dst)
1336 {
1337 	int error;
1338 
1339 	if (args->from_model == DATAMODEL_NATIVE) {
1340 		ulong_t ptr;
1341 		error = fulword(src, &ptr);
1342 		*dst = (caddr_t)ptr;
1343 	} else {
1344 		uint32_t ptr;
1345 		error = fuword32(src, &ptr);
1346 		*dst = (caddr_t)(uintptr_t)ptr;
1347 	}
1348 	return (error);
1349 }
1350 
1351 static int
1352 stk_putptr(uarg_t *args, char *addr, char *value)
1353 {
1354 	if (args->to_model == DATAMODEL_NATIVE)
1355 		return (sulword(addr, (ulong_t)value));
1356 	else
1357 		return (suword32(addr, (uint32_t)(uintptr_t)value));
1358 }
1359 
1360 static int
1361 stk_copyin(execa_t *uap, uarg_t *args, intpdata_t *intp, void **auxvpp)
1362 {
1363 	char *sp;
1364 	int argc, error;
1365 	int argv_empty = 0;
1366 	size_t ptrsize = args->from_ptrsize;
1367 	size_t size, pad;
1368 	char *argv = (char *)uap->argp;
1369 	char *envp = (char *)uap->envp;
1370 
1371 	/*
1372 	 * Copy interpreter's name and argument to argv[0] and argv[1].
1373 	 */
1374 	if (intp != NULL && intp->intp_name != NULL) {
1375 		if ((error = stk_add(args, intp->intp_name, UIO_SYSSPACE)) != 0)
1376 			return (error);
1377 		if (intp->intp_arg != NULL &&
1378 		    (error = stk_add(args, intp->intp_arg, UIO_SYSSPACE)) != 0)
1379 			return (error);
1380 		if (args->fname != NULL)
1381 			error = stk_add(args, args->fname, UIO_SYSSPACE);
1382 		else
1383 			error = stk_add(args, uap->fname, UIO_USERSPACE);
1384 		if (error)
1385 			return (error);
1386 
1387 		/*
1388 		 * Check for an empty argv[].
1389 		 */
1390 		if (stk_getptr(args, argv, &sp))
1391 			return (EFAULT);
1392 		if (sp == NULL)
1393 			argv_empty = 1;
1394 
1395 		argv += ptrsize;		/* ignore original argv[0] */
1396 	}
1397 
1398 	if (argv_empty == 0) {
1399 		/*
1400 		 * Add argv[] strings to the stack.
1401 		 */
1402 		for (;;) {
1403 			if (stk_getptr(args, argv, &sp))
1404 				return (EFAULT);
1405 			if (sp == NULL)
1406 				break;
1407 			if ((error = stk_add(args, sp, UIO_USERSPACE)) != 0)
1408 				return (error);
1409 			argv += ptrsize;
1410 		}
1411 	}
1412 	argc = (int *)(args->stk_base + args->stk_size) - args->stk_offp;
1413 	args->arglen = args->stk_strp - args->stk_base;
1414 
1415 	/*
1416 	 * Add environ[] strings to the stack.
1417 	 */
1418 	if (envp != NULL) {
1419 		for (;;) {
1420 			if (stk_getptr(args, envp, &sp))
1421 				return (EFAULT);
1422 			if (sp == NULL)
1423 				break;
1424 			if ((error = stk_add(args, sp, UIO_USERSPACE)) != 0)
1425 				return (error);
1426 			envp += ptrsize;
1427 		}
1428 	}
1429 	args->na = (int *)(args->stk_base + args->stk_size) - args->stk_offp;
1430 	args->ne = args->na - argc;
1431 
1432 	/*
1433 	 * Add AT_SUN_PLATFORM, AT_SUN_EXECNAME, AT_SUN_BRANDNAME, and
1434 	 * AT_SUN_EMULATOR strings to the stack.
1435 	 */
1436 	if (auxvpp != NULL && *auxvpp != NULL) {
1437 		if ((error = stk_add(args, platform, UIO_SYSSPACE)) != 0)
1438 			return (error);
1439 		if ((error = stk_add(args, args->pathname, UIO_SYSSPACE)) != 0)
1440 			return (error);
1441 		if (args->brandname != NULL &&
1442 		    (error = stk_add(args, args->brandname, UIO_SYSSPACE)) != 0)
1443 			return (error);
1444 		if (args->emulator != NULL &&
1445 		    (error = stk_add(args, args->emulator, UIO_SYSSPACE)) != 0)
1446 			return (error);
1447 	}
1448 
1449 	/*
1450 	 * Compute the size of the stack.  This includes all the pointers,
1451 	 * the space reserved for the aux vector, and all the strings.
1452 	 * The total number of pointers is args->na (which is argc + envc)
1453 	 * plus 4 more: (1) a pointer's worth of space for argc; (2) the NULL
1454 	 * after the last argument (i.e. argv[argc]); (3) the NULL after the
1455 	 * last environment variable (i.e. envp[envc]); and (4) the NULL after
1456 	 * all the strings, at the very top of the stack.
1457 	 */
1458 	size = (args->na + 4) * args->to_ptrsize + args->auxsize +
1459 	    (args->stk_strp - args->stk_base);
1460 
1461 	/*
1462 	 * Pad the string section with zeroes to align the stack size.
1463 	 */
1464 	pad = P2NPHASE(size, args->stk_align);
1465 
1466 	if (STK_AVAIL(args) < pad)
1467 		return (E2BIG);
1468 
1469 	args->usrstack_size = size + pad;
1470 
1471 	while (pad-- != 0)
1472 		*args->stk_strp++ = 0;
1473 
1474 	args->nc = args->stk_strp - args->stk_base;
1475 
1476 	return (0);
1477 }
1478 
1479 static int
1480 stk_copyout(uarg_t *args, char *usrstack, void **auxvpp, user_t *up)
1481 {
1482 	size_t ptrsize = args->to_ptrsize;
1483 	ssize_t pslen;
1484 	char *kstrp = args->stk_base;
1485 	char *ustrp = usrstack - args->nc - ptrsize;
1486 	char *usp = usrstack - args->usrstack_size;
1487 	int *offp = (int *)(args->stk_base + args->stk_size);
1488 	int envc = args->ne;
1489 	int argc = args->na - envc;
1490 	int i;
1491 
1492 	/*
1493 	 * Record argc for /proc.
1494 	 */
1495 	up->u_argc = argc;
1496 
1497 	/*
1498 	 * Put argc on the stack.  Note that even though it's an int,
1499 	 * it always consumes ptrsize bytes (for alignment).
1500 	 */
1501 	if (stk_putptr(args, usp, (char *)(uintptr_t)argc))
1502 		return (-1);
1503 
1504 	/*
1505 	 * Add argc space (ptrsize) to usp and record argv for /proc.
1506 	 */
1507 	up->u_argv = (uintptr_t)(usp += ptrsize);
1508 
1509 	/*
1510 	 * Put the argv[] pointers on the stack.
1511 	 */
1512 	for (i = 0; i < argc; i++, usp += ptrsize)
1513 		if (stk_putptr(args, usp, &ustrp[*--offp]))
1514 			return (-1);
1515 
1516 	/*
1517 	 * Copy arguments to u_psargs.
1518 	 */
1519 	pslen = MIN(args->arglen, PSARGSZ) - 1;
1520 	for (i = 0; i < pslen; i++)
1521 		up->u_psargs[i] = (kstrp[i] == '\0' ? ' ' : kstrp[i]);
1522 	while (i < PSARGSZ)
1523 		up->u_psargs[i++] = '\0';
1524 
1525 	/*
1526 	 * Add space for argv[]'s NULL terminator (ptrsize) to usp and
1527 	 * record envp for /proc.
1528 	 */
1529 	up->u_envp = (uintptr_t)(usp += ptrsize);
1530 
1531 	/*
1532 	 * Put the envp[] pointers on the stack.
1533 	 */
1534 	for (i = 0; i < envc; i++, usp += ptrsize)
1535 		if (stk_putptr(args, usp, &ustrp[*--offp]))
1536 			return (-1);
1537 
1538 	/*
1539 	 * Add space for envp[]'s NULL terminator (ptrsize) to usp and
1540 	 * remember where the stack ends, which is also where auxv begins.
1541 	 */
1542 	args->stackend = usp += ptrsize;
1543 
1544 	/*
1545 	 * Put all the argv[], envp[], and auxv strings on the stack.
1546 	 */
1547 	if (copyout(args->stk_base, ustrp, args->nc))
1548 		return (-1);
1549 
1550 	/*
1551 	 * Fill in the aux vector now that we know the user stack addresses
1552 	 * for the AT_SUN_PLATFORM, AT_SUN_EXECNAME, AT_SUN_BRANDNAME and
1553 	 * AT_SUN_EMULATOR strings.
1554 	 */
1555 	if (auxvpp != NULL && *auxvpp != NULL) {
1556 		if (args->to_model == DATAMODEL_NATIVE) {
1557 			auxv_t **a = (auxv_t **)auxvpp;
1558 			ADDAUX(*a, AT_SUN_PLATFORM, (long)&ustrp[*--offp])
1559 			ADDAUX(*a, AT_SUN_EXECNAME, (long)&ustrp[*--offp])
1560 			if (args->brandname != NULL)
1561 				ADDAUX(*a,
1562 				    AT_SUN_BRANDNAME, (long)&ustrp[*--offp])
1563 			if (args->emulator != NULL)
1564 				ADDAUX(*a,
1565 				    AT_SUN_EMULATOR, (long)&ustrp[*--offp])
1566 		} else {
1567 			auxv32_t **a = (auxv32_t **)auxvpp;
1568 			ADDAUX(*a,
1569 			    AT_SUN_PLATFORM, (int)(uintptr_t)&ustrp[*--offp])
1570 			ADDAUX(*a,
1571 			    AT_SUN_EXECNAME, (int)(uintptr_t)&ustrp[*--offp])
1572 			if (args->brandname != NULL)
1573 				ADDAUX(*a, AT_SUN_BRANDNAME,
1574 				    (int)(uintptr_t)&ustrp[*--offp])
1575 			if (args->emulator != NULL)
1576 				ADDAUX(*a, AT_SUN_EMULATOR,
1577 				    (int)(uintptr_t)&ustrp[*--offp])
1578 		}
1579 	}
1580 
1581 	return (0);
1582 }
1583 
1584 /*
1585  * Initialize a new user stack with the specified arguments and environment.
1586  * The initial user stack layout is as follows:
1587  *
1588  *	User Stack
1589  *	+---------------+ <--- curproc->p_usrstack
1590  *	|		|
1591  *	| slew		|
1592  *	|		|
1593  *	+---------------+
1594  *	| NULL		|
1595  *	+---------------+
1596  *	|		|
1597  *	| auxv strings	|
1598  *	|		|
1599  *	+---------------+
1600  *	|		|
1601  *	| envp strings	|
1602  *	|		|
1603  *	+---------------+
1604  *	|		|
1605  *	| argv strings	|
1606  *	|		|
1607  *	+---------------+ <--- ustrp
1608  *	|		|
1609  *	| aux vector	|
1610  *	|		|
1611  *	+---------------+ <--- auxv
1612  *	| NULL		|
1613  *	+---------------+
1614  *	| envp[envc-1]	|
1615  *	+---------------+
1616  *	| ...		|
1617  *	+---------------+
1618  *	| envp[0]	|
1619  *	+---------------+ <--- envp[]
1620  *	| NULL		|
1621  *	+---------------+
1622  *	| argv[argc-1]	|
1623  *	+---------------+
1624  *	| ...		|
1625  *	+---------------+
1626  *	| argv[0]	|
1627  *	+---------------+ <--- argv[]
1628  *	| argc		|
1629  *	+---------------+ <--- stack base
1630  */
1631 int
1632 exec_args(execa_t *uap, uarg_t *args, intpdata_t *intp, void **auxvpp)
1633 {
1634 	size_t size;
1635 	int error;
1636 	proc_t *p = ttoproc(curthread);
1637 	user_t *up = PTOU(p);
1638 	char *usrstack;
1639 	rctl_entity_p_t e;
1640 	struct as *as;
1641 	extern int use_stk_lpg;
1642 	size_t sp_slew;
1643 
1644 	args->from_model = p->p_model;
1645 	if (p->p_model == DATAMODEL_NATIVE) {
1646 		args->from_ptrsize = sizeof (long);
1647 	} else {
1648 		args->from_ptrsize = sizeof (int32_t);
1649 	}
1650 
1651 	if (args->to_model == DATAMODEL_NATIVE) {
1652 		args->to_ptrsize = sizeof (long);
1653 		args->ncargs = NCARGS;
1654 		args->stk_align = STACK_ALIGN;
1655 		if (args->addr32)
1656 			usrstack = (char *)USRSTACK64_32;
1657 		else
1658 			usrstack = (char *)USRSTACK;
1659 	} else {
1660 		args->to_ptrsize = sizeof (int32_t);
1661 		args->ncargs = NCARGS32;
1662 		args->stk_align = STACK_ALIGN32;
1663 		usrstack = (char *)USRSTACK32;
1664 	}
1665 
1666 	ASSERT(P2PHASE((uintptr_t)usrstack, args->stk_align) == 0);
1667 
1668 #if defined(__sparc)
1669 	/*
1670 	 * Make sure user register windows are empty before
1671 	 * attempting to make a new stack.
1672 	 */
1673 	(void) flush_user_windows_to_stack(NULL);
1674 #endif
1675 
1676 	for (size = PAGESIZE; ; size *= 2) {
1677 		args->stk_size = size;
1678 		args->stk_base = kmem_alloc(size, KM_SLEEP);
1679 		args->stk_strp = args->stk_base;
1680 		args->stk_offp = (int *)(args->stk_base + size);
1681 		error = stk_copyin(uap, args, intp, auxvpp);
1682 		if (error == 0)
1683 			break;
1684 		kmem_free(args->stk_base, size);
1685 		if (error != E2BIG && error != ENAMETOOLONG)
1686 			return (error);
1687 		if (size >= args->ncargs)
1688 			return (E2BIG);
1689 	}
1690 
1691 	size = args->usrstack_size;
1692 
1693 	ASSERT(error == 0);
1694 	ASSERT(P2PHASE(size, args->stk_align) == 0);
1695 	ASSERT((ssize_t)STK_AVAIL(args) >= 0);
1696 
1697 	if (size > args->ncargs) {
1698 		kmem_free(args->stk_base, args->stk_size);
1699 		return (E2BIG);
1700 	}
1701 
1702 	/*
1703 	 * Leave only the current lwp and force the other lwps to exit.
1704 	 * If another lwp beat us to the punch by calling exit(), bail out.
1705 	 */
1706 	if ((error = exitlwps(0)) != 0) {
1707 		kmem_free(args->stk_base, args->stk_size);
1708 		return (error);
1709 	}
1710 
1711 	/*
1712 	 * Revoke any doors created by the process.
1713 	 */
1714 	if (p->p_door_list)
1715 		door_exit();
1716 
1717 	/*
1718 	 * Release schedctl data structures.
1719 	 */
1720 	if (p->p_pagep)
1721 		schedctl_proc_cleanup();
1722 
1723 	/*
1724 	 * Clean up any DTrace helpers for the process.
1725 	 */
1726 	if (p->p_dtrace_helpers != NULL) {
1727 		ASSERT(dtrace_helpers_cleanup != NULL);
1728 		(*dtrace_helpers_cleanup)();
1729 	}
1730 
1731 	mutex_enter(&p->p_lock);
1732 	/*
1733 	 * Cleanup the DTrace provider associated with this process.
1734 	 */
1735 	if (p->p_dtrace_probes) {
1736 		ASSERT(dtrace_fasttrap_exec_ptr != NULL);
1737 		dtrace_fasttrap_exec_ptr(p);
1738 	}
1739 	mutex_exit(&p->p_lock);
1740 
1741 	/*
1742 	 * discard the lwpchan cache.
1743 	 */
1744 	if (p->p_lcp != NULL)
1745 		lwpchan_destroy_cache(1);
1746 
1747 	/*
1748 	 * Delete the POSIX timers.
1749 	 */
1750 	if (p->p_itimer != NULL)
1751 		timer_exit();
1752 
1753 	if (audit_active)
1754 		audit_exec(args->stk_base, args->stk_base + args->arglen,
1755 		    args->na - args->ne, args->ne);
1756 
1757 	/*
1758 	 * Ensure that we don't change resource associations while we
1759 	 * change address spaces.
1760 	 */
1761 	mutex_enter(&p->p_lock);
1762 	pool_barrier_enter();
1763 	mutex_exit(&p->p_lock);
1764 
1765 	/*
1766 	 * Destroy the old address space and create a new one.
1767 	 * From here on, any errors are fatal to the exec()ing process.
1768 	 * On error we return -1, which means the caller must SIGKILL
1769 	 * the process.
1770 	 */
1771 	relvm();
1772 
1773 	mutex_enter(&p->p_lock);
1774 	pool_barrier_exit();
1775 	mutex_exit(&p->p_lock);
1776 
1777 	up->u_execsw = args->execswp;
1778 
1779 	p->p_brkbase = NULL;
1780 	p->p_brksize = 0;
1781 	p->p_brkpageszc = 0;
1782 	p->p_stksize = 0;
1783 	p->p_stkpageszc = 0;
1784 	p->p_model = args->to_model;
1785 	p->p_usrstack = usrstack;
1786 	p->p_stkprot = args->stk_prot;
1787 	p->p_datprot = args->dat_prot;
1788 
1789 	/*
1790 	 * Reset resource controls such that all controls are again active as
1791 	 * well as appropriate to the potentially new address model for the
1792 	 * process.
1793 	 */
1794 	e.rcep_p.proc = p;
1795 	e.rcep_t = RCENTITY_PROCESS;
1796 	rctl_set_reset(p->p_rctls, p, &e);
1797 
1798 	/* Too early to call map_pgsz for the heap */
1799 	if (use_stk_lpg) {
1800 		p->p_stkpageszc = page_szc(map_pgsz(MAPPGSZ_STK, p, 0, 0, 0));
1801 	}
1802 
1803 	mutex_enter(&p->p_lock);
1804 	p->p_flag |= SAUTOLPG;	/* kernel controls page sizes */
1805 	mutex_exit(&p->p_lock);
1806 
1807 	/*
1808 	 * Some platforms may choose to randomize real stack start by adding a
1809 	 * small slew (not more than a few hundred bytes) to the top of the
1810 	 * stack. This helps avoid cache thrashing when identical processes
1811 	 * simultaneously share caches that don't provide enough associativity
1812 	 * (e.g. sun4v systems). In this case stack slewing makes the same hot
1813 	 * stack variables in different processes to live in different cache
1814 	 * sets increasing effective associativity.
1815 	 */
1816 	sp_slew = exec_get_spslew();
1817 	ASSERT(P2PHASE(sp_slew, args->stk_align) == 0);
1818 	exec_set_sp(size + sp_slew);
1819 
1820 	as = as_alloc();
1821 	p->p_as = as;
1822 	as->a_proc = p;
1823 	if (p->p_model == DATAMODEL_ILP32 || args->addr32)
1824 		as->a_userlimit = (caddr_t)USERLIMIT32;
1825 	(void) hat_setup(as->a_hat, HAT_ALLOC);
1826 	hat_join_srd(as->a_hat, args->ex_vp);
1827 
1828 	/*
1829 	 * Finally, write out the contents of the new stack.
1830 	 */
1831 	error = stk_copyout(args, usrstack - sp_slew, auxvpp, up);
1832 	kmem_free(args->stk_base, args->stk_size);
1833 	return (error);
1834 }
1835