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