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