Home | History | Annotate | Line # | Download | only in kern
kern_exec.c revision 1.340
      1 /*	$NetBSD: kern_exec.c,v 1.340 2012/02/19 21:06:49 rmind Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*-
     30  * Copyright (C) 1993, 1994, 1996 Christopher G. Demetriou
     31  * Copyright (C) 1992 Wolfgang Solfrank.
     32  * Copyright (C) 1992 TooLs GmbH.
     33  * All rights reserved.
     34  *
     35  * Redistribution and use in source and binary forms, with or without
     36  * modification, are permitted provided that the following conditions
     37  * are met:
     38  * 1. Redistributions of source code must retain the above copyright
     39  *    notice, this list of conditions and the following disclaimer.
     40  * 2. Redistributions in binary form must reproduce the above copyright
     41  *    notice, this list of conditions and the following disclaimer in the
     42  *    documentation and/or other materials provided with the distribution.
     43  * 3. All advertising materials mentioning features or use of this software
     44  *    must display the following acknowledgement:
     45  *	This product includes software developed by TooLs GmbH.
     46  * 4. The name of TooLs GmbH may not be used to endorse or promote products
     47  *    derived from this software without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
     50  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     51  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     52  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     53  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     54  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     55  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     56  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     57  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     58  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     59  */
     60 
     61 #include <sys/cdefs.h>
     62 __KERNEL_RCSID(0, "$NetBSD: kern_exec.c,v 1.340 2012/02/19 21:06:49 rmind Exp $");
     63 
     64 #include "opt_exec.h"
     65 #include "opt_ktrace.h"
     66 #include "opt_modular.h"
     67 #include "opt_syscall_debug.h"
     68 #include "veriexec.h"
     69 #include "opt_pax.h"
     70 
     71 #include <sys/param.h>
     72 #include <sys/systm.h>
     73 #include <sys/filedesc.h>
     74 #include <sys/kernel.h>
     75 #include <sys/proc.h>
     76 #include <sys/mount.h>
     77 #include <sys/malloc.h>
     78 #include <sys/kmem.h>
     79 #include <sys/namei.h>
     80 #include <sys/vnode.h>
     81 #include <sys/file.h>
     82 #include <sys/acct.h>
     83 #include <sys/atomic.h>
     84 #include <sys/exec.h>
     85 #include <sys/ktrace.h>
     86 #include <sys/uidinfo.h>
     87 #include <sys/wait.h>
     88 #include <sys/mman.h>
     89 #include <sys/ras.h>
     90 #include <sys/signalvar.h>
     91 #include <sys/stat.h>
     92 #include <sys/syscall.h>
     93 #include <sys/kauth.h>
     94 #include <sys/lwpctl.h>
     95 #include <sys/pax.h>
     96 #include <sys/cpu.h>
     97 #include <sys/module.h>
     98 #include <sys/syscallvar.h>
     99 #include <sys/syscallargs.h>
    100 #if NVERIEXEC > 0
    101 #include <sys/verified_exec.h>
    102 #endif /* NVERIEXEC > 0 */
    103 #include <sys/sdt.h>
    104 #include <sys/spawn.h>
    105 #include <sys/prot.h>
    106 #include <sys/cprng.h>
    107 
    108 #include <uvm/uvm_extern.h>
    109 
    110 #include <machine/reg.h>
    111 
    112 #include <compat/common/compat_util.h>
    113 
    114 static int exec_sigcode_map(struct proc *, const struct emul *);
    115 
    116 #ifdef DEBUG_EXEC
    117 #define DPRINTF(a) printf a
    118 #define COPYPRINTF(s, a, b) printf("%s, %d: copyout%s @%p %zu\n", __func__, \
    119     __LINE__, (s), (a), (b))
    120 #else
    121 #define DPRINTF(a)
    122 #define COPYPRINTF(s, a, b)
    123 #endif /* DEBUG_EXEC */
    124 
    125 /*
    126  * DTrace SDT provider definitions
    127  */
    128 SDT_PROBE_DEFINE(proc,,,exec,
    129 	    "char *", NULL,
    130 	    NULL, NULL, NULL, NULL,
    131 	    NULL, NULL, NULL, NULL);
    132 SDT_PROBE_DEFINE(proc,,,exec_success,
    133 	    "char *", NULL,
    134 	    NULL, NULL, NULL, NULL,
    135 	    NULL, NULL, NULL, NULL);
    136 SDT_PROBE_DEFINE(proc,,,exec_failure,
    137 	    "int", NULL,
    138 	    NULL, NULL, NULL, NULL,
    139 	    NULL, NULL, NULL, NULL);
    140 
    141 /*
    142  * Exec function switch:
    143  *
    144  * Note that each makecmds function is responsible for loading the
    145  * exec package with the necessary functions for any exec-type-specific
    146  * handling.
    147  *
    148  * Functions for specific exec types should be defined in their own
    149  * header file.
    150  */
    151 static const struct execsw	**execsw = NULL;
    152 static int			nexecs;
    153 
    154 u_int	exec_maxhdrsz;	 /* must not be static - used by netbsd32 */
    155 
    156 /* list of dynamically loaded execsw entries */
    157 static LIST_HEAD(execlist_head, exec_entry) ex_head =
    158     LIST_HEAD_INITIALIZER(ex_head);
    159 struct exec_entry {
    160 	LIST_ENTRY(exec_entry)	ex_list;
    161 	SLIST_ENTRY(exec_entry)	ex_slist;
    162 	const struct execsw	*ex_sw;
    163 };
    164 
    165 #ifndef __HAVE_SYSCALL_INTERN
    166 void	syscall(void);
    167 #endif
    168 
    169 /* NetBSD emul struct */
    170 struct emul emul_netbsd = {
    171 	.e_name =		"netbsd",
    172 	.e_path =		NULL,
    173 #ifndef __HAVE_MINIMAL_EMUL
    174 	.e_flags =		EMUL_HAS_SYS___syscall,
    175 	.e_errno =		NULL,
    176 	.e_nosys =		SYS_syscall,
    177 	.e_nsysent =		SYS_NSYSENT,
    178 #endif
    179 	.e_sysent =		sysent,
    180 #ifdef SYSCALL_DEBUG
    181 	.e_syscallnames =	syscallnames,
    182 #else
    183 	.e_syscallnames =	NULL,
    184 #endif
    185 	.e_sendsig =		sendsig,
    186 	.e_trapsignal =		trapsignal,
    187 	.e_tracesig =		NULL,
    188 	.e_sigcode =		NULL,
    189 	.e_esigcode =		NULL,
    190 	.e_sigobject =		NULL,
    191 	.e_setregs =		setregs,
    192 	.e_proc_exec =		NULL,
    193 	.e_proc_fork =		NULL,
    194 	.e_proc_exit =		NULL,
    195 	.e_lwp_fork =		NULL,
    196 	.e_lwp_exit =		NULL,
    197 #ifdef __HAVE_SYSCALL_INTERN
    198 	.e_syscall_intern =	syscall_intern,
    199 #else
    200 	.e_syscall =		syscall,
    201 #endif
    202 	.e_sysctlovly =		NULL,
    203 	.e_fault =		NULL,
    204 	.e_vm_default_addr =	uvm_default_mapaddr,
    205 	.e_usertrap =		NULL,
    206 	.e_ucsize =		sizeof(ucontext_t),
    207 	.e_startlwp =		startlwp
    208 };
    209 
    210 /*
    211  * Exec lock. Used to control access to execsw[] structures.
    212  * This must not be static so that netbsd32 can access it, too.
    213  */
    214 krwlock_t exec_lock;
    215 
    216 static kmutex_t sigobject_lock;
    217 
    218 /*
    219  * Data used between a loadvm and execve part of an "exec" operation
    220  */
    221 struct execve_data {
    222 	struct exec_package	ed_pack;
    223 	struct pathbuf		*ed_pathbuf;
    224 	struct vattr		ed_attr;
    225 	struct ps_strings	ed_arginfo;
    226 	char			*ed_argp;
    227 	const char		*ed_pathstring;
    228 	char			*ed_resolvedpathbuf;
    229 	size_t			ed_ps_strings_sz;
    230 	int			ed_szsigcode;
    231 	long			ed_argc;
    232 	long			ed_envc;
    233 };
    234 
    235 /*
    236  * data passed from parent lwp to child during a posix_spawn()
    237  */
    238 struct spawn_exec_data {
    239 	struct execve_data	sed_exec;
    240 	size_t 			sed_actions_len;
    241 	struct posix_spawn_file_actions_entry
    242 				*sed_actions;
    243 	struct posix_spawnattr	*sed_attrs;
    244 	struct proc		*sed_parent;
    245 	kcondvar_t		sed_cv_child_ready;
    246 	kmutex_t		sed_mtx_child;
    247 	int			sed_error;
    248 };
    249 
    250 static void *
    251 exec_pool_alloc(struct pool *pp, int flags)
    252 {
    253 
    254 	return (void *)uvm_km_alloc(kernel_map, NCARGS, 0,
    255 	    UVM_KMF_PAGEABLE | UVM_KMF_WAITVA);
    256 }
    257 
    258 static void
    259 exec_pool_free(struct pool *pp, void *addr)
    260 {
    261 
    262 	uvm_km_free(kernel_map, (vaddr_t)addr, NCARGS, UVM_KMF_PAGEABLE);
    263 }
    264 
    265 static struct pool exec_pool;
    266 
    267 static struct pool_allocator exec_palloc = {
    268 	.pa_alloc = exec_pool_alloc,
    269 	.pa_free = exec_pool_free,
    270 	.pa_pagesz = NCARGS
    271 };
    272 
    273 /*
    274  * check exec:
    275  * given an "executable" described in the exec package's namei info,
    276  * see what we can do with it.
    277  *
    278  * ON ENTRY:
    279  *	exec package with appropriate namei info
    280  *	lwp pointer of exec'ing lwp
    281  *	NO SELF-LOCKED VNODES
    282  *
    283  * ON EXIT:
    284  *	error:	nothing held, etc.  exec header still allocated.
    285  *	ok:	filled exec package, executable's vnode (unlocked).
    286  *
    287  * EXEC SWITCH ENTRY:
    288  * 	Locked vnode to check, exec package, proc.
    289  *
    290  * EXEC SWITCH EXIT:
    291  *	ok:	return 0, filled exec package, executable's vnode (unlocked).
    292  *	error:	destructive:
    293  *			everything deallocated execept exec header.
    294  *		non-destructive:
    295  *			error code, executable's vnode (unlocked),
    296  *			exec header unmodified.
    297  */
    298 int
    299 /*ARGSUSED*/
    300 check_exec(struct lwp *l, struct exec_package *epp, struct pathbuf *pb)
    301 {
    302 	int		error, i;
    303 	struct vnode	*vp;
    304 	struct nameidata nd;
    305 	size_t		resid;
    306 
    307 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb);
    308 
    309 	/* first get the vnode */
    310 	if ((error = namei(&nd)) != 0)
    311 		return error;
    312 	epp->ep_vp = vp = nd.ni_vp;
    313 	/* this cannot overflow as both are size PATH_MAX */
    314 	strcpy(epp->ep_resolvedname, nd.ni_pnbuf);
    315 
    316 #ifdef DIAGNOSTIC
    317 	/* paranoia (take this out once namei stuff stabilizes) */
    318 	memset(nd.ni_pnbuf, '~', PATH_MAX);
    319 #endif
    320 
    321 	/* check access and type */
    322 	if (vp->v_type != VREG) {
    323 		error = EACCES;
    324 		goto bad1;
    325 	}
    326 	if ((error = VOP_ACCESS(vp, VEXEC, l->l_cred)) != 0)
    327 		goto bad1;
    328 
    329 	/* get attributes */
    330 	if ((error = VOP_GETATTR(vp, epp->ep_vap, l->l_cred)) != 0)
    331 		goto bad1;
    332 
    333 	/* Check mount point */
    334 	if (vp->v_mount->mnt_flag & MNT_NOEXEC) {
    335 		error = EACCES;
    336 		goto bad1;
    337 	}
    338 	if (vp->v_mount->mnt_flag & MNT_NOSUID)
    339 		epp->ep_vap->va_mode &= ~(S_ISUID | S_ISGID);
    340 
    341 	/* try to open it */
    342 	if ((error = VOP_OPEN(vp, FREAD, l->l_cred)) != 0)
    343 		goto bad1;
    344 
    345 	/* unlock vp, since we need it unlocked from here on out. */
    346 	VOP_UNLOCK(vp);
    347 
    348 #if NVERIEXEC > 0
    349 	error = veriexec_verify(l, vp, epp->ep_resolvedname,
    350 	    epp->ep_flags & EXEC_INDIR ? VERIEXEC_INDIRECT : VERIEXEC_DIRECT,
    351 	    NULL);
    352 	if (error)
    353 		goto bad2;
    354 #endif /* NVERIEXEC > 0 */
    355 
    356 #ifdef PAX_SEGVGUARD
    357 	error = pax_segvguard(l, vp, epp->ep_resolvedname, false);
    358 	if (error)
    359 		goto bad2;
    360 #endif /* PAX_SEGVGUARD */
    361 
    362 	/* now we have the file, get the exec header */
    363 	error = vn_rdwr(UIO_READ, vp, epp->ep_hdr, epp->ep_hdrlen, 0,
    364 			UIO_SYSSPACE, 0, l->l_cred, &resid, NULL);
    365 	if (error)
    366 		goto bad2;
    367 	epp->ep_hdrvalid = epp->ep_hdrlen - resid;
    368 
    369 	/*
    370 	 * Set up default address space limits.  Can be overridden
    371 	 * by individual exec packages.
    372 	 *
    373 	 * XXX probably should be all done in the exec packages.
    374 	 */
    375 	epp->ep_vm_minaddr = VM_MIN_ADDRESS;
    376 	epp->ep_vm_maxaddr = VM_MAXUSER_ADDRESS;
    377 	/*
    378 	 * set up the vmcmds for creation of the process
    379 	 * address space
    380 	 */
    381 	error = ENOEXEC;
    382 	for (i = 0; i < nexecs; i++) {
    383 		int newerror;
    384 
    385 		epp->ep_esch = execsw[i];
    386 		newerror = (*execsw[i]->es_makecmds)(l, epp);
    387 
    388 		if (!newerror) {
    389 			/* Seems ok: check that entry point is not too high */
    390 			if (epp->ep_entry > epp->ep_vm_maxaddr) {
    391 #ifdef DIAGNOSTIC
    392 				printf("%s: rejecting %p due to "
    393 				    "too high entry address (> %p)\n",
    394 					 __func__, (void *)epp->ep_entry,
    395 					 (void *)epp->ep_vm_maxaddr);
    396 #endif
    397 				error = ENOEXEC;
    398 				break;
    399 			}
    400 			/* Seems ok: check that entry point is not too low */
    401 			if (epp->ep_entry < epp->ep_vm_minaddr) {
    402 #ifdef DIAGNOSTIC
    403 				printf("%s: rejecting %p due to "
    404 				    "too low entry address (< %p)\n",
    405 				     __func__, (void *)epp->ep_entry,
    406 				     (void *)epp->ep_vm_minaddr);
    407 #endif
    408 				error = ENOEXEC;
    409 				break;
    410 			}
    411 
    412 			/* check limits */
    413 			if ((epp->ep_tsize > MAXTSIZ) ||
    414 			    (epp->ep_dsize > (u_quad_t)l->l_proc->p_rlimit
    415 						    [RLIMIT_DATA].rlim_cur)) {
    416 #ifdef DIAGNOSTIC
    417 				printf("%s: rejecting due to "
    418 				    "limits (t=%llu > %llu || d=%llu > %llu)\n",
    419 				    __func__,
    420 				    (unsigned long long)epp->ep_tsize,
    421 				    (unsigned long long)MAXTSIZ,
    422 				    (unsigned long long)epp->ep_dsize,
    423 				    (unsigned long long)
    424 				    l->l_proc->p_rlimit[RLIMIT_DATA].rlim_cur);
    425 #endif
    426 				error = ENOMEM;
    427 				break;
    428 			}
    429 			return 0;
    430 		}
    431 
    432 		if (epp->ep_emul_root != NULL) {
    433 			vrele(epp->ep_emul_root);
    434 			epp->ep_emul_root = NULL;
    435 		}
    436 		if (epp->ep_interp != NULL) {
    437 			vrele(epp->ep_interp);
    438 			epp->ep_interp = NULL;
    439 		}
    440 
    441 		/* make sure the first "interesting" error code is saved. */
    442 		if (error == ENOEXEC)
    443 			error = newerror;
    444 
    445 		if (epp->ep_flags & EXEC_DESTR)
    446 			/* Error from "#!" code, tidied up by recursive call */
    447 			return error;
    448 	}
    449 
    450 	/* not found, error */
    451 
    452 	/*
    453 	 * free any vmspace-creation commands,
    454 	 * and release their references
    455 	 */
    456 	kill_vmcmds(&epp->ep_vmcmds);
    457 
    458 bad2:
    459 	/*
    460 	 * close and release the vnode, restore the old one, free the
    461 	 * pathname buf, and punt.
    462 	 */
    463 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    464 	VOP_CLOSE(vp, FREAD, l->l_cred);
    465 	vput(vp);
    466 	return error;
    467 
    468 bad1:
    469 	/*
    470 	 * free the namei pathname buffer, and put the vnode
    471 	 * (which we don't yet have open).
    472 	 */
    473 	vput(vp);				/* was still locked */
    474 	return error;
    475 }
    476 
    477 #ifdef __MACHINE_STACK_GROWS_UP
    478 #define STACK_PTHREADSPACE NBPG
    479 #else
    480 #define STACK_PTHREADSPACE 0
    481 #endif
    482 
    483 static int
    484 execve_fetch_element(char * const *array, size_t index, char **value)
    485 {
    486 	return copyin(array + index, value, sizeof(*value));
    487 }
    488 
    489 /*
    490  * exec system call
    491  */
    492 int
    493 sys_execve(struct lwp *l, const struct sys_execve_args *uap, register_t *retval)
    494 {
    495 	/* {
    496 		syscallarg(const char *)	path;
    497 		syscallarg(char * const *)	argp;
    498 		syscallarg(char * const *)	envp;
    499 	} */
    500 
    501 	return execve1(l, SCARG(uap, path), SCARG(uap, argp),
    502 	    SCARG(uap, envp), execve_fetch_element);
    503 }
    504 
    505 int
    506 sys_fexecve(struct lwp *l, const struct sys_fexecve_args *uap,
    507     register_t *retval)
    508 {
    509 	/* {
    510 		syscallarg(int)			fd;
    511 		syscallarg(char * const *)	argp;
    512 		syscallarg(char * const *)	envp;
    513 	} */
    514 
    515 	return ENOSYS;
    516 }
    517 
    518 /*
    519  * Load modules to try and execute an image that we do not understand.
    520  * If no execsw entries are present, we load those likely to be needed
    521  * in order to run native images only.  Otherwise, we autoload all
    522  * possible modules that could let us run the binary.  XXX lame
    523  */
    524 static void
    525 exec_autoload(void)
    526 {
    527 #ifdef MODULAR
    528 	static const char * const native[] = {
    529 		"exec_elf32",
    530 		"exec_elf64",
    531 		"exec_script",
    532 		NULL
    533 	};
    534 	static const char * const compat[] = {
    535 		"exec_elf32",
    536 		"exec_elf64",
    537 		"exec_script",
    538 		"exec_aout",
    539 		"exec_coff",
    540 		"exec_ecoff",
    541 		"compat_aoutm68k",
    542 		"compat_freebsd",
    543 		"compat_ibcs2",
    544 		"compat_linux",
    545 		"compat_linux32",
    546 		"compat_netbsd32",
    547 		"compat_sunos",
    548 		"compat_sunos32",
    549 		"compat_svr4",
    550 		"compat_svr4_32",
    551 		"compat_ultrix",
    552 		NULL
    553 	};
    554 	char const * const *list;
    555 	int i;
    556 
    557 	list = (nexecs == 0 ? native : compat);
    558 	for (i = 0; list[i] != NULL; i++) {
    559 		if (module_autoload(list[i], MODULE_CLASS_MISC) != 0) {
    560 		    	continue;
    561 		}
    562 	   	yield();
    563 	}
    564 #endif
    565 }
    566 
    567 static int
    568 execve_loadvm(struct lwp *l, const char *path, char * const *args,
    569 	char * const *envs, execve_fetch_element_t fetch_element,
    570 	struct execve_data * restrict data)
    571 {
    572 	int			error;
    573 	struct proc		*p;
    574 	char			*dp, *sp;
    575 	size_t			i, len;
    576 	struct exec_fakearg	*tmpfap;
    577 	u_int			modgen;
    578 
    579 	KASSERT(data != NULL);
    580 
    581 	p = l->l_proc;
    582  	modgen = 0;
    583 
    584 	SDT_PROBE(proc,,,exec, path, 0, 0, 0, 0);
    585 
    586 	/*
    587 	 * Check if we have exceeded our number of processes limit.
    588 	 * This is so that we handle the case where a root daemon
    589 	 * forked, ran setuid to become the desired user and is trying
    590 	 * to exec. The obvious place to do the reference counting check
    591 	 * is setuid(), but we don't do the reference counting check there
    592 	 * like other OS's do because then all the programs that use setuid()
    593 	 * must be modified to check the return code of setuid() and exit().
    594 	 * It is dangerous to make setuid() fail, because it fails open and
    595 	 * the program will continue to run as root. If we make it succeed
    596 	 * and return an error code, again we are not enforcing the limit.
    597 	 * The best place to enforce the limit is here, when the process tries
    598 	 * to execute a new image, because eventually the process will need
    599 	 * to call exec in order to do something useful.
    600 	 */
    601  retry:
    602 	if ((p->p_flag & PK_SUGID) && kauth_authorize_generic(l->l_cred,
    603 	    KAUTH_GENERIC_ISSUSER, NULL) != 0 && chgproccnt(kauth_cred_getuid(
    604 	    l->l_cred), 0) > p->p_rlimit[RLIMIT_NPROC].rlim_cur)
    605 		return EAGAIN;
    606 
    607 	/*
    608 	 * Drain existing references and forbid new ones.  The process
    609 	 * should be left alone until we're done here.  This is necessary
    610 	 * to avoid race conditions - e.g. in ptrace() - that might allow
    611 	 * a local user to illicitly obtain elevated privileges.
    612 	 */
    613 	rw_enter(&p->p_reflock, RW_WRITER);
    614 
    615 	/*
    616 	 * Init the namei data to point the file user's program name.
    617 	 * This is done here rather than in check_exec(), so that it's
    618 	 * possible to override this settings if any of makecmd/probe
    619 	 * functions call check_exec() recursively - for example,
    620 	 * see exec_script_makecmds().
    621 	 */
    622 	error = pathbuf_copyin(path, &data->ed_pathbuf);
    623 	if (error) {
    624 		DPRINTF(("%s: pathbuf_copyin path @%p %d\n", __func__,
    625 		    path, error));
    626 		goto clrflg;
    627 	}
    628 	data->ed_pathstring = pathbuf_stringcopy_get(data->ed_pathbuf);
    629 
    630 	data->ed_resolvedpathbuf = PNBUF_GET();
    631 #ifdef DIAGNOSTIC
    632 	strcpy(data->ed_resolvedpathbuf, "/wrong");
    633 #endif
    634 
    635 	/*
    636 	 * initialize the fields of the exec package.
    637 	 */
    638 	data->ed_pack.ep_name = path;
    639 	data->ed_pack.ep_kname = data->ed_pathstring;
    640 	data->ed_pack.ep_resolvedname = data->ed_resolvedpathbuf;
    641 	data->ed_pack.ep_hdr = kmem_alloc(exec_maxhdrsz, KM_SLEEP);
    642 	data->ed_pack.ep_hdrlen = exec_maxhdrsz;
    643 	data->ed_pack.ep_hdrvalid = 0;
    644 	data->ed_pack.ep_emul_arg = NULL;
    645 	data->ed_pack.ep_emul_arg_free = NULL;
    646 	data->ed_pack.ep_vmcmds.evs_cnt = 0;
    647 	data->ed_pack.ep_vmcmds.evs_used = 0;
    648 	data->ed_pack.ep_vap = &data->ed_attr;
    649 	data->ed_pack.ep_flags = 0;
    650 	data->ed_pack.ep_emul_root = NULL;
    651 	data->ed_pack.ep_interp = NULL;
    652 	data->ed_pack.ep_esch = NULL;
    653 	data->ed_pack.ep_pax_flags = 0;
    654 
    655 	rw_enter(&exec_lock, RW_READER);
    656 
    657 	/* see if we can run it. */
    658 	if ((error = check_exec(l, &data->ed_pack, data->ed_pathbuf)) != 0) {
    659 		if (error != ENOENT) {
    660 			DPRINTF(("%s: check exec failed %d\n",
    661 			    __func__, error));
    662 		}
    663 		goto freehdr;
    664 	}
    665 
    666 	/* XXX -- THE FOLLOWING SECTION NEEDS MAJOR CLEANUP */
    667 
    668 	/* allocate an argument buffer */
    669 	data->ed_argp = pool_get(&exec_pool, PR_WAITOK);
    670 	KASSERT(data->ed_argp != NULL);
    671 	dp = data->ed_argp;
    672 	data->ed_argc = 0;
    673 
    674 	/* copy the fake args list, if there's one, freeing it as we go */
    675 	if (data->ed_pack.ep_flags & EXEC_HASARGL) {
    676 		tmpfap = data->ed_pack.ep_fa;
    677 		while (tmpfap->fa_arg != NULL) {
    678 			const char *cp;
    679 
    680 			cp = tmpfap->fa_arg;
    681 			while (*cp)
    682 				*dp++ = *cp++;
    683 			*dp++ = '\0';
    684 			ktrexecarg(tmpfap->fa_arg, cp - tmpfap->fa_arg);
    685 
    686 			kmem_free(tmpfap->fa_arg, tmpfap->fa_len);
    687 			tmpfap++; data->ed_argc++;
    688 		}
    689 		kmem_free(data->ed_pack.ep_fa, data->ed_pack.ep_fa_len);
    690 		data->ed_pack.ep_flags &= ~EXEC_HASARGL;
    691 	}
    692 
    693 	/* Now get argv & environment */
    694 	if (args == NULL) {
    695 		DPRINTF(("%s: null args\n", __func__));
    696 		error = EINVAL;
    697 		goto bad;
    698 	}
    699 	/* 'i' will index the argp/envp element to be retrieved */
    700 	i = 0;
    701 	if (data->ed_pack.ep_flags & EXEC_SKIPARG)
    702 		i++;
    703 
    704 	while (1) {
    705 		len = data->ed_argp + ARG_MAX - dp;
    706 		if ((error = (*fetch_element)(args, i, &sp)) != 0) {
    707 			DPRINTF(("%s: fetch_element args %d\n",
    708 			    __func__, error));
    709 			goto bad;
    710 		}
    711 		if (!sp)
    712 			break;
    713 		if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    714 			DPRINTF(("%s: copyinstr args %d\n", __func__, error));
    715 			if (error == ENAMETOOLONG)
    716 				error = E2BIG;
    717 			goto bad;
    718 		}
    719 		ktrexecarg(dp, len - 1);
    720 		dp += len;
    721 		i++;
    722 		data->ed_argc++;
    723 	}
    724 
    725 	data->ed_envc = 0;
    726 	/* environment need not be there */
    727 	if (envs != NULL) {
    728 		i = 0;
    729 		while (1) {
    730 			len = data->ed_argp + ARG_MAX - dp;
    731 			if ((error = (*fetch_element)(envs, i, &sp)) != 0) {
    732 				DPRINTF(("%s: fetch_element env %d\n",
    733 				    __func__, error));
    734 				goto bad;
    735 			}
    736 			if (!sp)
    737 				break;
    738 			if ((error = copyinstr(sp, dp, len, &len)) != 0) {
    739 				DPRINTF(("%s: copyinstr env %d\n",
    740 				    __func__, error));
    741 				if (error == ENAMETOOLONG)
    742 					error = E2BIG;
    743 				goto bad;
    744 			}
    745 
    746 			ktrexecenv(dp, len - 1);
    747 			dp += len;
    748 			i++;
    749 			data->ed_envc++;
    750 		}
    751 	}
    752 
    753 	dp = (char *) ALIGN(dp);
    754 
    755 	data->ed_szsigcode = data->ed_pack.ep_esch->es_emul->e_esigcode -
    756 	    data->ed_pack.ep_esch->es_emul->e_sigcode;
    757 
    758 #ifdef __MACHINE_STACK_GROWS_UP
    759 /* See big comment lower down */
    760 #define	RTLD_GAP	32
    761 #else
    762 #define	RTLD_GAP	0
    763 #endif
    764 
    765 	/* Now check if args & environ fit into new stack */
    766 	if (data->ed_pack.ep_flags & EXEC_32) {
    767 		data->ed_ps_strings_sz = sizeof(struct ps_strings32);
    768 		len = ((data->ed_argc + data->ed_envc + 2 +
    769 		    data->ed_pack.ep_esch->es_arglen) *
    770 		    sizeof(int) + sizeof(int) + dp + RTLD_GAP +
    771 		    data->ed_szsigcode + data->ed_ps_strings_sz + STACK_PTHREADSPACE)
    772 		    - data->ed_argp;
    773 	} else {
    774 		data->ed_ps_strings_sz = sizeof(struct ps_strings);
    775 		len = ((data->ed_argc + data->ed_envc + 2 +
    776 		    data->ed_pack.ep_esch->es_arglen) *
    777 		    sizeof(char *) + sizeof(int) + dp + RTLD_GAP +
    778 		    data->ed_szsigcode + data->ed_ps_strings_sz + STACK_PTHREADSPACE)
    779 		    - data->ed_argp;
    780 	}
    781 
    782 #ifdef PAX_ASLR
    783 	if (pax_aslr_active(l))
    784 		len += (cprng_fast32() % PAGE_SIZE);
    785 #endif /* PAX_ASLR */
    786 
    787 	/* make the stack "safely" aligned */
    788 	len = STACK_LEN_ALIGN(len, STACK_ALIGNBYTES);
    789 
    790 	if (len > data->ed_pack.ep_ssize) {
    791 		/* in effect, compare to initial limit */
    792 		DPRINTF(("%s: stack limit exceeded %zu\n", __func__, len));
    793 		goto bad;
    794 	}
    795 	/* adjust "active stack depth" for process VSZ */
    796 	data->ed_pack.ep_ssize = len;
    797 
    798 	return 0;
    799 
    800  bad:
    801 	/* free the vmspace-creation commands, and release their references */
    802 	kill_vmcmds(&data->ed_pack.ep_vmcmds);
    803 	/* kill any opened file descriptor, if necessary */
    804 	if (data->ed_pack.ep_flags & EXEC_HASFD) {
    805 		data->ed_pack.ep_flags &= ~EXEC_HASFD;
    806 		fd_close(data->ed_pack.ep_fd);
    807 	}
    808 	/* close and put the exec'd file */
    809 	vn_lock(data->ed_pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    810 	VOP_CLOSE(data->ed_pack.ep_vp, FREAD, l->l_cred);
    811 	vput(data->ed_pack.ep_vp);
    812 	pool_put(&exec_pool, data->ed_argp);
    813 
    814  freehdr:
    815 	kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
    816 	if (data->ed_pack.ep_emul_root != NULL)
    817 		vrele(data->ed_pack.ep_emul_root);
    818 	if (data->ed_pack.ep_interp != NULL)
    819 		vrele(data->ed_pack.ep_interp);
    820 
    821 	rw_exit(&exec_lock);
    822 
    823 	pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
    824 	pathbuf_destroy(data->ed_pathbuf);
    825 	PNBUF_PUT(data->ed_resolvedpathbuf);
    826 
    827  clrflg:
    828 	rw_exit(&p->p_reflock);
    829 
    830 	if (modgen != module_gen && error == ENOEXEC) {
    831 		modgen = module_gen;
    832 		exec_autoload();
    833 		goto retry;
    834 	}
    835 
    836 	SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
    837 	return error;
    838 }
    839 
    840 static int
    841 execve_runproc(struct lwp *l, struct execve_data * restrict data)
    842 {
    843 	int error = 0;
    844 	struct proc		*p;
    845 	size_t			i;
    846 	char			*stack, *dp;
    847 	const char		*commandname;
    848 	struct ps_strings32	arginfo32;
    849 	struct exec_vmcmd	*base_vcp;
    850 	void			*aip;
    851 	struct vmspace		*vm;
    852 	ksiginfo_t		ksi;
    853 	ksiginfoq_t		kq;
    854 	bool			proc_is_new;
    855 
    856 	KASSERT(rw_lock_held(&exec_lock));
    857 	KASSERT(data != NULL);
    858 	if (data == NULL)
    859 		return (EINVAL);
    860 
    861 	p = l->l_proc;
    862 	proc_is_new = p->p_vmspace == NULL;
    863 
    864 	base_vcp = NULL;
    865 
    866 	if (data->ed_pack.ep_flags & EXEC_32)
    867 		aip = &arginfo32;
    868 	else
    869 		aip = &data->ed_arginfo;
    870 
    871 	/* Get rid of other LWPs. */
    872 	if (p->p_nlwps > 1) {
    873 		mutex_enter(p->p_lock);
    874 		exit_lwps(l);
    875 		mutex_exit(p->p_lock);
    876 	}
    877 	KDASSERT(p->p_nlwps == 1);
    878 
    879 	/* Destroy any lwpctl info. */
    880 	if (p->p_lwpctl != NULL)
    881 		lwp_ctl_exit();
    882 
    883 	/* Remove POSIX timers */
    884 	timers_free(p, TIMERS_POSIX);
    885 
    886 	/*
    887 	 * Do whatever is necessary to prepare the address space
    888 	 * for remapping.  Note that this might replace the current
    889 	 * vmspace with another!
    890 	 */
    891 	uvmspace_exec(l, data->ed_pack.ep_vm_minaddr, data->ed_pack.ep_vm_maxaddr);
    892 
    893 	/* record proc's vnode, for use by procfs and others */
    894         if (p->p_textvp)
    895                 vrele(p->p_textvp);
    896 	vref(data->ed_pack.ep_vp);
    897 	p->p_textvp = data->ed_pack.ep_vp;
    898 
    899 	/* Now map address space */
    900 	vm = p->p_vmspace;
    901 	vm->vm_taddr = (void *)data->ed_pack.ep_taddr;
    902 	vm->vm_tsize = btoc(data->ed_pack.ep_tsize);
    903 	vm->vm_daddr = (void*)data->ed_pack.ep_daddr;
    904 	vm->vm_dsize = btoc(data->ed_pack.ep_dsize);
    905 	vm->vm_ssize = btoc(data->ed_pack.ep_ssize);
    906 	vm->vm_issize = 0;
    907 	vm->vm_maxsaddr = (void *)data->ed_pack.ep_maxsaddr;
    908 	vm->vm_minsaddr = (void *)data->ed_pack.ep_minsaddr;
    909 
    910 #ifdef PAX_ASLR
    911 	pax_aslr_init(l, vm);
    912 #endif /* PAX_ASLR */
    913 
    914 	/* create the new process's VM space by running the vmcmds */
    915 #ifdef DIAGNOSTIC
    916 	if (data->ed_pack.ep_vmcmds.evs_used == 0)
    917 		panic("%s: no vmcmds", __func__);
    918 #endif
    919 
    920 #ifdef DEBUG_EXEC
    921 	{
    922 		size_t j;
    923 		struct exec_vmcmd *vp = &data->ed_pack.ep_vmcmds.evs_cmds[0];
    924 		DPRINTF(("vmcmds %u\n", data->ed_pack.ep_vmcmds.evs_used));
    925 		for (j = 0; j < data->ed_pack.ep_vmcmds.evs_used; j++) {
    926 			DPRINTF(("vmcmd[%zu] = vmcmd_map_%s %#"
    927 			    PRIxVADDR"/%#"PRIxVSIZE" fd@%#"
    928 			    PRIxVSIZE" prot=0%o flags=%d\n", j,
    929 			    vp[j].ev_proc == vmcmd_map_pagedvn ?
    930 			    "pagedvn" :
    931 			    vp[j].ev_proc == vmcmd_map_readvn ?
    932 			    "readvn" :
    933 			    vp[j].ev_proc == vmcmd_map_zero ?
    934 			    "zero" : "*unknown*",
    935 			    vp[j].ev_addr, vp[j].ev_len,
    936 			    vp[j].ev_offset, vp[j].ev_prot,
    937 			    vp[j].ev_flags));
    938 		}
    939 	}
    940 #endif	/* DEBUG_EXEC */
    941 
    942 	for (i = 0; i < data->ed_pack.ep_vmcmds.evs_used && !error; i++) {
    943 		struct exec_vmcmd *vcp;
    944 
    945 		vcp = &data->ed_pack.ep_vmcmds.evs_cmds[i];
    946 		if (vcp->ev_flags & VMCMD_RELATIVE) {
    947 #ifdef DIAGNOSTIC
    948 			if (base_vcp == NULL)
    949 				panic("%s: relative vmcmd with no base",
    950 				    __func__);
    951 			if (vcp->ev_flags & VMCMD_BASE)
    952 				panic("%s: illegal base & relative vmcmd",
    953 				    __func__);
    954 #endif
    955 			vcp->ev_addr += base_vcp->ev_addr;
    956 		}
    957 		error = (*vcp->ev_proc)(l, vcp);
    958 #ifdef DEBUG_EXEC
    959 		if (error) {
    960 			size_t j;
    961 			struct exec_vmcmd *vp =
    962 			    &data->ed_pack.ep_vmcmds.evs_cmds[0];
    963 			DPRINTF(("vmcmds %zu/%u, error %d\n", i,
    964 			    data->ed_pack.ep_vmcmds.evs_used, error));
    965 			for (j = 0; j < data->ed_pack.ep_vmcmds.evs_used; j++) {
    966 				DPRINTF(("vmcmd[%zu] = vmcmd_map_%s %#"
    967 				    PRIxVADDR"/%#"PRIxVSIZE" fd@%#"
    968 				    PRIxVSIZE" prot=0%o flags=%d\n", j,
    969 				    vp[j].ev_proc == vmcmd_map_pagedvn ?
    970 				    "pagedvn" :
    971 				    vp[j].ev_proc == vmcmd_map_readvn ?
    972 				    "readvn" :
    973 				    vp[j].ev_proc == vmcmd_map_zero ?
    974 				    "zero" : "*unknown*",
    975 				    vp[j].ev_addr, vp[j].ev_len,
    976 				    vp[j].ev_offset, vp[j].ev_prot,
    977 				    vp[j].ev_flags));
    978 				if (j == i)
    979 					DPRINTF(("     ^--- failed\n"));
    980 			}
    981 		}
    982 #endif /* DEBUG_EXEC */
    983 		if (vcp->ev_flags & VMCMD_BASE)
    984 			base_vcp = vcp;
    985 	}
    986 
    987 	/* free the vmspace-creation commands, and release their references */
    988 	kill_vmcmds(&data->ed_pack.ep_vmcmds);
    989 
    990 	vn_lock(data->ed_pack.ep_vp, LK_EXCLUSIVE | LK_RETRY);
    991 	VOP_CLOSE(data->ed_pack.ep_vp, FREAD, l->l_cred);
    992 	vput(data->ed_pack.ep_vp);
    993 
    994 	/* if an error happened, deallocate and punt */
    995 	if (error) {
    996 		DPRINTF(("%s: vmcmd %zu failed: %d\n", __func__, i - 1, error));
    997 		goto exec_abort;
    998 	}
    999 
   1000 	/* remember information about the process */
   1001 	data->ed_arginfo.ps_nargvstr = data->ed_argc;
   1002 	data->ed_arginfo.ps_nenvstr = data->ed_envc;
   1003 
   1004 	/* set command name & other accounting info */
   1005 	commandname = strrchr(data->ed_pack.ep_resolvedname, '/');
   1006 	if (commandname != NULL) {
   1007 		commandname++;
   1008 	} else {
   1009 		commandname = data->ed_pack.ep_resolvedname;
   1010 	}
   1011 	i = min(strlen(commandname), MAXCOMLEN);
   1012 	(void)memcpy(p->p_comm, commandname, i);
   1013 	p->p_comm[i] = '\0';
   1014 
   1015 	dp = PNBUF_GET();
   1016 	/*
   1017 	 * If the path starts with /, we don't need to do any work.
   1018 	 * This handles the majority of the cases.
   1019 	 * In the future perhaps we could canonicalize it?
   1020 	 */
   1021 	if (data->ed_pathstring[0] == '/')
   1022 		(void)strlcpy(data->ed_pack.ep_path = dp, data->ed_pathstring,
   1023 		    MAXPATHLEN);
   1024 #ifdef notyet
   1025 	/*
   1026 	 * Although this works most of the time [since the entry was just
   1027 	 * entered in the cache] we don't use it because it theoretically
   1028 	 * can fail and it is not the cleanest interface, because there
   1029 	 * could be races. When the namei cache is re-written, this can
   1030 	 * be changed to use the appropriate function.
   1031 	 */
   1032 	else if (!(error = vnode_to_path(dp, MAXPATHLEN, p->p_textvp, l, p)))
   1033 		data->ed_pack.ep_path = dp;
   1034 #endif
   1035 	else {
   1036 #ifdef notyet
   1037 		printf("Cannot get path for pid %d [%s] (error %d)",
   1038 		    (int)p->p_pid, p->p_comm, error);
   1039 #endif
   1040 		data->ed_pack.ep_path = NULL;
   1041 		PNBUF_PUT(dp);
   1042 	}
   1043 
   1044 	stack = (char *)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
   1045 		STACK_PTHREADSPACE + data->ed_ps_strings_sz + data->ed_szsigcode),
   1046 		data->ed_pack.ep_ssize - (data->ed_ps_strings_sz + data->ed_szsigcode));
   1047 
   1048 #ifdef __MACHINE_STACK_GROWS_UP
   1049 	/*
   1050 	 * The copyargs call always copies into lower addresses
   1051 	 * first, moving towards higher addresses, starting with
   1052 	 * the stack pointer that we give.  When the stack grows
   1053 	 * down, this puts argc/argv/envp very shallow on the
   1054 	 * stack, right at the first user stack pointer.
   1055 	 * When the stack grows up, the situation is reversed.
   1056 	 *
   1057 	 * Normally, this is no big deal.  But the ld_elf.so _rtld()
   1058 	 * function expects to be called with a single pointer to
   1059 	 * a region that has a few words it can stash values into,
   1060 	 * followed by argc/argv/envp.  When the stack grows down,
   1061 	 * it's easy to decrement the stack pointer a little bit to
   1062 	 * allocate the space for these few words and pass the new
   1063 	 * stack pointer to _rtld.  When the stack grows up, however,
   1064 	 * a few words before argc is part of the signal trampoline, XXX
   1065 	 * so we have a problem.
   1066 	 *
   1067 	 * Instead of changing how _rtld works, we take the easy way
   1068 	 * out and steal 32 bytes before we call copyargs.
   1069 	 * This extra space was allowed for when 'pack.ep_ssize' was calculated.
   1070 	 */
   1071 	stack += RTLD_GAP;
   1072 #endif /* __MACHINE_STACK_GROWS_UP */
   1073 
   1074 	/* Now copy argc, args & environ to new stack */
   1075 	error = (*data->ed_pack.ep_esch->es_copyargs)(l, &data->ed_pack,
   1076 	    &data->ed_arginfo, &stack, data->ed_argp);
   1077 
   1078 	if (data->ed_pack.ep_path) {
   1079 		PNBUF_PUT(data->ed_pack.ep_path);
   1080 		data->ed_pack.ep_path = NULL;
   1081 	}
   1082 	if (error) {
   1083 		DPRINTF(("%s: copyargs failed %d\n", __func__, error));
   1084 		goto exec_abort;
   1085 	}
   1086 	/* Move the stack back to original point */
   1087 	stack = (char *)STACK_GROW(vm->vm_minsaddr, data->ed_pack.ep_ssize);
   1088 
   1089 	/* fill process ps_strings info */
   1090 	p->p_psstrp = (vaddr_t)STACK_ALLOC(STACK_GROW(vm->vm_minsaddr,
   1091 	    STACK_PTHREADSPACE), data->ed_ps_strings_sz);
   1092 
   1093 	if (data->ed_pack.ep_flags & EXEC_32) {
   1094 		arginfo32.ps_argvstr = (vaddr_t)data->ed_arginfo.ps_argvstr;
   1095 		arginfo32.ps_nargvstr = data->ed_arginfo.ps_nargvstr;
   1096 		arginfo32.ps_envstr = (vaddr_t)data->ed_arginfo.ps_envstr;
   1097 		arginfo32.ps_nenvstr = data->ed_arginfo.ps_nenvstr;
   1098 	}
   1099 
   1100 	/* copy out the process's ps_strings structure */
   1101 	if ((error = copyout(aip, (void *)p->p_psstrp, data->ed_ps_strings_sz))
   1102 	    != 0) {
   1103 		DPRINTF(("%s: ps_strings copyout %p->%p size %zu failed\n",
   1104 		    __func__, aip, (void *)p->p_psstrp, data->ed_ps_strings_sz));
   1105 		goto exec_abort;
   1106 	}
   1107 
   1108 	cwdexec(p);
   1109 	fd_closeexec();		/* handle close on exec */
   1110 
   1111 	if (__predict_false(ktrace_on))
   1112 		fd_ktrexecfd();
   1113 
   1114 	execsigs(p);		/* reset catched signals */
   1115 
   1116 	l->l_ctxlink = NULL;	/* reset ucontext link */
   1117 
   1118 
   1119 	p->p_acflag &= ~AFORK;
   1120 	mutex_enter(p->p_lock);
   1121 	p->p_flag |= PK_EXEC;
   1122 	mutex_exit(p->p_lock);
   1123 
   1124 	/*
   1125 	 * Stop profiling.
   1126 	 */
   1127 	if ((p->p_stflag & PST_PROFIL) != 0) {
   1128 		mutex_spin_enter(&p->p_stmutex);
   1129 		stopprofclock(p);
   1130 		mutex_spin_exit(&p->p_stmutex);
   1131 	}
   1132 
   1133 	/*
   1134 	 * It's OK to test PL_PPWAIT unlocked here, as other LWPs have
   1135 	 * exited and exec()/exit() are the only places it will be cleared.
   1136 	 */
   1137 	if ((p->p_lflag & PL_PPWAIT) != 0) {
   1138 		mutex_enter(proc_lock);
   1139 		l->l_lwpctl = NULL; /* was on loan from blocked parent */
   1140 		p->p_lflag &= ~PL_PPWAIT;
   1141 		cv_broadcast(&p->p_pptr->p_waitcv);
   1142 		mutex_exit(proc_lock);
   1143 	}
   1144 
   1145 	/*
   1146 	 * Deal with set[ug]id.  MNT_NOSUID has already been used to disable
   1147 	 * s[ug]id.  It's OK to check for PSL_TRACED here as we have blocked
   1148 	 * out additional references on the process for the moment.
   1149 	 */
   1150 	if ((p->p_slflag & PSL_TRACED) == 0 &&
   1151 
   1152 	    (((data->ed_attr.va_mode & S_ISUID) != 0 &&
   1153 	      kauth_cred_geteuid(l->l_cred) != data->ed_attr.va_uid) ||
   1154 
   1155 	     ((data->ed_attr.va_mode & S_ISGID) != 0 &&
   1156 	      kauth_cred_getegid(l->l_cred) != data->ed_attr.va_gid))) {
   1157 		/*
   1158 		 * Mark the process as SUGID before we do
   1159 		 * anything that might block.
   1160 		 */
   1161 		proc_crmod_enter();
   1162 		proc_crmod_leave(NULL, NULL, true);
   1163 
   1164 		/* Make sure file descriptors 0..2 are in use. */
   1165 		if ((error = fd_checkstd()) != 0) {
   1166 			DPRINTF(("%s: fdcheckstd failed %d\n",
   1167 			    __func__, error));
   1168 			goto exec_abort;
   1169 		}
   1170 
   1171 		/*
   1172 		 * Copy the credential so other references don't see our
   1173 		 * changes.
   1174 		 */
   1175 		l->l_cred = kauth_cred_copy(l->l_cred);
   1176 #ifdef KTRACE
   1177 		/*
   1178 		 * If the persistent trace flag isn't set, turn off.
   1179 		 */
   1180 		if (p->p_tracep) {
   1181 			mutex_enter(&ktrace_lock);
   1182 			if (!(p->p_traceflag & KTRFAC_PERSISTENT))
   1183 				ktrderef(p);
   1184 			mutex_exit(&ktrace_lock);
   1185 		}
   1186 #endif
   1187 		if (data->ed_attr.va_mode & S_ISUID)
   1188 			kauth_cred_seteuid(l->l_cred, data->ed_attr.va_uid);
   1189 		if (data->ed_attr.va_mode & S_ISGID)
   1190 			kauth_cred_setegid(l->l_cred, data->ed_attr.va_gid);
   1191 	} else {
   1192 		if (kauth_cred_geteuid(l->l_cred) ==
   1193 		    kauth_cred_getuid(l->l_cred) &&
   1194 		    kauth_cred_getegid(l->l_cred) ==
   1195 		    kauth_cred_getgid(l->l_cred))
   1196 			p->p_flag &= ~PK_SUGID;
   1197 	}
   1198 
   1199 	/*
   1200 	 * Copy the credential so other references don't see our changes.
   1201 	 * Test to see if this is necessary first, since in the common case
   1202 	 * we won't need a private reference.
   1203 	 */
   1204 	if (kauth_cred_geteuid(l->l_cred) != kauth_cred_getsvuid(l->l_cred) ||
   1205 	    kauth_cred_getegid(l->l_cred) != kauth_cred_getsvgid(l->l_cred)) {
   1206 		l->l_cred = kauth_cred_copy(l->l_cred);
   1207 		kauth_cred_setsvuid(l->l_cred, kauth_cred_geteuid(l->l_cred));
   1208 		kauth_cred_setsvgid(l->l_cred, kauth_cred_getegid(l->l_cred));
   1209 	}
   1210 
   1211 	/* Update the master credentials. */
   1212 	if (l->l_cred != p->p_cred) {
   1213 		kauth_cred_t ocred;
   1214 
   1215 		kauth_cred_hold(l->l_cred);
   1216 		mutex_enter(p->p_lock);
   1217 		ocred = p->p_cred;
   1218 		p->p_cred = l->l_cred;
   1219 		mutex_exit(p->p_lock);
   1220 		kauth_cred_free(ocred);
   1221 	}
   1222 
   1223 #if defined(__HAVE_RAS)
   1224 	/*
   1225 	 * Remove all RASs from the address space.
   1226 	 */
   1227 	ras_purgeall();
   1228 #endif
   1229 
   1230 	doexechooks(p);
   1231 
   1232 	/* setup new registers and do misc. setup. */
   1233 	(*data->ed_pack.ep_esch->es_emul->e_setregs)(l, &data->ed_pack,
   1234 	     (vaddr_t)stack);
   1235 	if (data->ed_pack.ep_esch->es_setregs)
   1236 		(*data->ed_pack.ep_esch->es_setregs)(l, &data->ed_pack,
   1237 		    (vaddr_t)stack);
   1238 
   1239 	/* Provide a consistent LWP private setting */
   1240 	(void)lwp_setprivate(l, NULL);
   1241 
   1242 	/* Discard all PCU state; need to start fresh */
   1243 	pcu_discard_all(l);
   1244 
   1245 	/* map the process's signal trampoline code */
   1246 	if ((error = exec_sigcode_map(p, data->ed_pack.ep_esch->es_emul)) != 0) {
   1247 		DPRINTF(("%s: map sigcode failed %d\n", __func__, error));
   1248 		goto exec_abort;
   1249 	}
   1250 
   1251 	pool_put(&exec_pool, data->ed_argp);
   1252 
   1253 	/* notify others that we exec'd */
   1254 	KNOTE(&p->p_klist, NOTE_EXEC);
   1255 
   1256 	kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
   1257 
   1258 	SDT_PROBE(proc,,,exec_success, data->ed_pack.ep_name, 0, 0, 0, 0);
   1259 
   1260 	/* The emulation root will usually have been found when we looked
   1261 	 * for the elf interpreter (or similar), if not look now. */
   1262 	if (data->ed_pack.ep_esch->es_emul->e_path != NULL &&
   1263 	    data->ed_pack.ep_emul_root == NULL)
   1264 		emul_find_root(l, &data->ed_pack);
   1265 
   1266 	/* Any old emulation root got removed by fdcloseexec */
   1267 	rw_enter(&p->p_cwdi->cwdi_lock, RW_WRITER);
   1268 	p->p_cwdi->cwdi_edir = data->ed_pack.ep_emul_root;
   1269 	rw_exit(&p->p_cwdi->cwdi_lock);
   1270 	data->ed_pack.ep_emul_root = NULL;
   1271 	if (data->ed_pack.ep_interp != NULL)
   1272 		vrele(data->ed_pack.ep_interp);
   1273 
   1274 	/*
   1275 	 * Call emulation specific exec hook. This can setup per-process
   1276 	 * p->p_emuldata or do any other per-process stuff an emulation needs.
   1277 	 *
   1278 	 * If we are executing process of different emulation than the
   1279 	 * original forked process, call e_proc_exit() of the old emulation
   1280 	 * first, then e_proc_exec() of new emulation. If the emulation is
   1281 	 * same, the exec hook code should deallocate any old emulation
   1282 	 * resources held previously by this process.
   1283 	 */
   1284 	if (p->p_emul && p->p_emul->e_proc_exit
   1285 	    && p->p_emul != data->ed_pack.ep_esch->es_emul)
   1286 		(*p->p_emul->e_proc_exit)(p);
   1287 
   1288 	/*
   1289 	 * This is now LWP 1.
   1290 	 */
   1291 	mutex_enter(p->p_lock);
   1292 	p->p_nlwpid = 1;
   1293 	l->l_lid = 1;
   1294 	mutex_exit(p->p_lock);
   1295 
   1296 	/*
   1297 	 * Call exec hook. Emulation code may NOT store reference to anything
   1298 	 * from &pack.
   1299 	 */
   1300 	if (data->ed_pack.ep_esch->es_emul->e_proc_exec)
   1301 		(*data->ed_pack.ep_esch->es_emul->e_proc_exec)(p, &data->ed_pack);
   1302 
   1303 	/* update p_emul, the old value is no longer needed */
   1304 	p->p_emul = data->ed_pack.ep_esch->es_emul;
   1305 
   1306 	/* ...and the same for p_execsw */
   1307 	p->p_execsw = data->ed_pack.ep_esch;
   1308 
   1309 #ifdef __HAVE_SYSCALL_INTERN
   1310 	(*p->p_emul->e_syscall_intern)(p);
   1311 #endif
   1312 	ktremul();
   1313 
   1314 	/* Allow new references from the debugger/procfs. */
   1315 	if (!proc_is_new)
   1316 		rw_exit(&p->p_reflock);
   1317 	rw_exit(&exec_lock);
   1318 
   1319 	mutex_enter(proc_lock);
   1320 
   1321 	if ((p->p_slflag & (PSL_TRACED|PSL_SYSCALL)) == PSL_TRACED) {
   1322 		KSI_INIT_EMPTY(&ksi);
   1323 		ksi.ksi_signo = SIGTRAP;
   1324 		ksi.ksi_lid = l->l_lid;
   1325 		kpsignal(p, &ksi, NULL);
   1326 	}
   1327 
   1328 	if (p->p_sflag & PS_STOPEXEC) {
   1329 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
   1330 		p->p_pptr->p_nstopchild++;
   1331 		p->p_pptr->p_waited = 0;
   1332 		mutex_enter(p->p_lock);
   1333 		ksiginfo_queue_init(&kq);
   1334 		sigclearall(p, &contsigmask, &kq);
   1335 		lwp_lock(l);
   1336 		l->l_stat = LSSTOP;
   1337 		p->p_stat = SSTOP;
   1338 		p->p_nrlwps--;
   1339 		lwp_unlock(l);
   1340 		mutex_exit(p->p_lock);
   1341 		mutex_exit(proc_lock);
   1342 		lwp_lock(l);
   1343 		mi_switch(l);
   1344 		ksiginfo_queue_drain(&kq);
   1345 		KERNEL_LOCK(l->l_biglocks, l);
   1346 	} else {
   1347 		mutex_exit(proc_lock);
   1348 	}
   1349 
   1350 	pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
   1351 	pathbuf_destroy(data->ed_pathbuf);
   1352 	PNBUF_PUT(data->ed_resolvedpathbuf);
   1353 	DPRINTF(("%s finished\n", __func__));
   1354 	return (EJUSTRETURN);
   1355 
   1356  exec_abort:
   1357 	SDT_PROBE(proc,,,exec_failure, error, 0, 0, 0, 0);
   1358 	rw_exit(&p->p_reflock);
   1359 	rw_exit(&exec_lock);
   1360 
   1361 	pathbuf_stringcopy_put(data->ed_pathbuf, data->ed_pathstring);
   1362 	pathbuf_destroy(data->ed_pathbuf);
   1363 	PNBUF_PUT(data->ed_resolvedpathbuf);
   1364 
   1365 	/*
   1366 	 * the old process doesn't exist anymore.  exit gracefully.
   1367 	 * get rid of the (new) address space we have created, if any, get rid
   1368 	 * of our namei data and vnode, and exit noting failure
   1369 	 */
   1370 	uvm_deallocate(&vm->vm_map, VM_MIN_ADDRESS,
   1371 		VM_MAXUSER_ADDRESS - VM_MIN_ADDRESS);
   1372 	exec_free_emul_arg(&data->ed_pack);
   1373 	pool_put(&exec_pool, data->ed_argp);
   1374 	kmem_free(data->ed_pack.ep_hdr, data->ed_pack.ep_hdrlen);
   1375 	if (data->ed_pack.ep_emul_root != NULL)
   1376 		vrele(data->ed_pack.ep_emul_root);
   1377 	if (data->ed_pack.ep_interp != NULL)
   1378 		vrele(data->ed_pack.ep_interp);
   1379 
   1380 	/* Acquire the sched-state mutex (exit1() will release it). */
   1381 	if (!proc_is_new) {
   1382 		mutex_enter(p->p_lock);
   1383 		exit1(l, W_EXITCODE(error, SIGABRT));
   1384 	}
   1385 
   1386 	/* NOTREACHED */
   1387 	return 0;
   1388 }
   1389 
   1390 int
   1391 execve1(struct lwp *l, const char *path, char * const *args,
   1392     char * const *envs, execve_fetch_element_t fetch_element)
   1393 {
   1394 	struct execve_data data;
   1395 	int error;
   1396 
   1397 	error = execve_loadvm(l, path, args, envs, fetch_element, &data);
   1398 	if (error)
   1399 		return error;
   1400 	error = execve_runproc(l, &data);
   1401 	return error;
   1402 }
   1403 
   1404 int
   1405 copyargs(struct lwp *l, struct exec_package *pack, struct ps_strings *arginfo,
   1406     char **stackp, void *argp)
   1407 {
   1408 	char	**cpp, *dp, *sp;
   1409 	size_t	len;
   1410 	void	*nullp;
   1411 	long	argc, envc;
   1412 	int	error;
   1413 
   1414 	cpp = (char **)*stackp;
   1415 	nullp = NULL;
   1416 	argc = arginfo->ps_nargvstr;
   1417 	envc = arginfo->ps_nenvstr;
   1418 	if ((error = copyout(&argc, cpp++, sizeof(argc))) != 0) {
   1419 		COPYPRINTF("", cpp - 1, sizeof(argc));
   1420 		return error;
   1421 	}
   1422 
   1423 	dp = (char *) (cpp + argc + envc + 2 + pack->ep_esch->es_arglen);
   1424 	sp = argp;
   1425 
   1426 	/* XXX don't copy them out, remap them! */
   1427 	arginfo->ps_argvstr = cpp; /* remember location of argv for later */
   1428 
   1429 	for (; --argc >= 0; sp += len, dp += len) {
   1430 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) {
   1431 			COPYPRINTF("", cpp - 1, sizeof(dp));
   1432 			return error;
   1433 		}
   1434 		if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) {
   1435 			COPYPRINTF("str", dp, (size_t)ARG_MAX);
   1436 			return error;
   1437 		}
   1438 	}
   1439 
   1440 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) {
   1441 		COPYPRINTF("", cpp - 1, sizeof(nullp));
   1442 		return error;
   1443 	}
   1444 
   1445 	arginfo->ps_envstr = cpp; /* remember location of envp for later */
   1446 
   1447 	for (; --envc >= 0; sp += len, dp += len) {
   1448 		if ((error = copyout(&dp, cpp++, sizeof(dp))) != 0) {
   1449 			COPYPRINTF("", cpp - 1, sizeof(dp));
   1450 			return error;
   1451 		}
   1452 		if ((error = copyoutstr(sp, dp, ARG_MAX, &len)) != 0) {
   1453 			COPYPRINTF("str", dp, (size_t)ARG_MAX);
   1454 			return error;
   1455 		}
   1456 
   1457 	}
   1458 
   1459 	if ((error = copyout(&nullp, cpp++, sizeof(nullp))) != 0) {
   1460 		COPYPRINTF("", cpp - 1, sizeof(nullp));
   1461 		return error;
   1462 	}
   1463 
   1464 	*stackp = (char *)cpp;
   1465 	return 0;
   1466 }
   1467 
   1468 
   1469 /*
   1470  * Add execsw[] entries.
   1471  */
   1472 int
   1473 exec_add(struct execsw *esp, int count)
   1474 {
   1475 	struct exec_entry	*it;
   1476 	int			i;
   1477 
   1478 	if (count == 0) {
   1479 		return 0;
   1480 	}
   1481 
   1482 	/* Check for duplicates. */
   1483 	rw_enter(&exec_lock, RW_WRITER);
   1484 	for (i = 0; i < count; i++) {
   1485 		LIST_FOREACH(it, &ex_head, ex_list) {
   1486 			/* assume unique (makecmds, probe_func, emulation) */
   1487 			if (it->ex_sw->es_makecmds == esp[i].es_makecmds &&
   1488 			    it->ex_sw->u.elf_probe_func ==
   1489 			    esp[i].u.elf_probe_func &&
   1490 			    it->ex_sw->es_emul == esp[i].es_emul) {
   1491 				rw_exit(&exec_lock);
   1492 				return EEXIST;
   1493 			}
   1494 		}
   1495 	}
   1496 
   1497 	/* Allocate new entries. */
   1498 	for (i = 0; i < count; i++) {
   1499 		it = kmem_alloc(sizeof(*it), KM_SLEEP);
   1500 		it->ex_sw = &esp[i];
   1501 		LIST_INSERT_HEAD(&ex_head, it, ex_list);
   1502 	}
   1503 
   1504 	/* update execsw[] */
   1505 	exec_init(0);
   1506 	rw_exit(&exec_lock);
   1507 	return 0;
   1508 }
   1509 
   1510 /*
   1511  * Remove execsw[] entry.
   1512  */
   1513 int
   1514 exec_remove(struct execsw *esp, int count)
   1515 {
   1516 	struct exec_entry	*it, *next;
   1517 	int			i;
   1518 	const struct proclist_desc *pd;
   1519 	proc_t			*p;
   1520 
   1521 	if (count == 0) {
   1522 		return 0;
   1523 	}
   1524 
   1525 	/* Abort if any are busy. */
   1526 	rw_enter(&exec_lock, RW_WRITER);
   1527 	for (i = 0; i < count; i++) {
   1528 		mutex_enter(proc_lock);
   1529 		for (pd = proclists; pd->pd_list != NULL; pd++) {
   1530 			PROCLIST_FOREACH(p, pd->pd_list) {
   1531 				if (p->p_execsw == &esp[i]) {
   1532 					mutex_exit(proc_lock);
   1533 					rw_exit(&exec_lock);
   1534 					return EBUSY;
   1535 				}
   1536 			}
   1537 		}
   1538 		mutex_exit(proc_lock);
   1539 	}
   1540 
   1541 	/* None are busy, so remove them all. */
   1542 	for (i = 0; i < count; i++) {
   1543 		for (it = LIST_FIRST(&ex_head); it != NULL; it = next) {
   1544 			next = LIST_NEXT(it, ex_list);
   1545 			if (it->ex_sw == &esp[i]) {
   1546 				LIST_REMOVE(it, ex_list);
   1547 				kmem_free(it, sizeof(*it));
   1548 				break;
   1549 			}
   1550 		}
   1551 	}
   1552 
   1553 	/* update execsw[] */
   1554 	exec_init(0);
   1555 	rw_exit(&exec_lock);
   1556 	return 0;
   1557 }
   1558 
   1559 /*
   1560  * Initialize exec structures. If init_boot is true, also does necessary
   1561  * one-time initialization (it's called from main() that way).
   1562  * Once system is multiuser, this should be called with exec_lock held,
   1563  * i.e. via exec_{add|remove}().
   1564  */
   1565 int
   1566 exec_init(int init_boot)
   1567 {
   1568 	const struct execsw 	**sw;
   1569 	struct exec_entry	*ex;
   1570 	SLIST_HEAD(,exec_entry)	first;
   1571 	SLIST_HEAD(,exec_entry)	any;
   1572 	SLIST_HEAD(,exec_entry)	last;
   1573 	int			i, sz;
   1574 
   1575 	if (init_boot) {
   1576 		/* do one-time initializations */
   1577 		rw_init(&exec_lock);
   1578 		mutex_init(&sigobject_lock, MUTEX_DEFAULT, IPL_NONE);
   1579 		pool_init(&exec_pool, NCARGS, 0, 0, PR_NOALIGN|PR_NOTOUCH,
   1580 		    "execargs", &exec_palloc, IPL_NONE);
   1581 		pool_sethardlimit(&exec_pool, maxexec, "should not happen", 0);
   1582 	} else {
   1583 		KASSERT(rw_write_held(&exec_lock));
   1584 	}
   1585 
   1586 	/* Sort each entry onto the appropriate queue. */
   1587 	SLIST_INIT(&first);
   1588 	SLIST_INIT(&any);
   1589 	SLIST_INIT(&last);
   1590 	sz = 0;
   1591 	LIST_FOREACH(ex, &ex_head, ex_list) {
   1592 		switch(ex->ex_sw->es_prio) {
   1593 		case EXECSW_PRIO_FIRST:
   1594 			SLIST_INSERT_HEAD(&first, ex, ex_slist);
   1595 			break;
   1596 		case EXECSW_PRIO_ANY:
   1597 			SLIST_INSERT_HEAD(&any, ex, ex_slist);
   1598 			break;
   1599 		case EXECSW_PRIO_LAST:
   1600 			SLIST_INSERT_HEAD(&last, ex, ex_slist);
   1601 			break;
   1602 		default:
   1603 			panic("%s", __func__);
   1604 			break;
   1605 		}
   1606 		sz++;
   1607 	}
   1608 
   1609 	/*
   1610 	 * Create new execsw[].  Ensure we do not try a zero-sized
   1611 	 * allocation.
   1612 	 */
   1613 	sw = kmem_alloc(sz * sizeof(struct execsw *) + 1, KM_SLEEP);
   1614 	i = 0;
   1615 	SLIST_FOREACH(ex, &first, ex_slist) {
   1616 		sw[i++] = ex->ex_sw;
   1617 	}
   1618 	SLIST_FOREACH(ex, &any, ex_slist) {
   1619 		sw[i++] = ex->ex_sw;
   1620 	}
   1621 	SLIST_FOREACH(ex, &last, ex_slist) {
   1622 		sw[i++] = ex->ex_sw;
   1623 	}
   1624 
   1625 	/* Replace old execsw[] and free used memory. */
   1626 	if (execsw != NULL) {
   1627 		kmem_free(__UNCONST(execsw),
   1628 		    nexecs * sizeof(struct execsw *) + 1);
   1629 	}
   1630 	execsw = sw;
   1631 	nexecs = sz;
   1632 
   1633 	/* Figure out the maximum size of an exec header. */
   1634 	exec_maxhdrsz = sizeof(int);
   1635 	for (i = 0; i < nexecs; i++) {
   1636 		if (execsw[i]->es_hdrsz > exec_maxhdrsz)
   1637 			exec_maxhdrsz = execsw[i]->es_hdrsz;
   1638 	}
   1639 
   1640 	return 0;
   1641 }
   1642 
   1643 static int
   1644 exec_sigcode_map(struct proc *p, const struct emul *e)
   1645 {
   1646 	vaddr_t va;
   1647 	vsize_t sz;
   1648 	int error;
   1649 	struct uvm_object *uobj;
   1650 
   1651 	sz = (vaddr_t)e->e_esigcode - (vaddr_t)e->e_sigcode;
   1652 
   1653 	if (e->e_sigobject == NULL || sz == 0) {
   1654 		return 0;
   1655 	}
   1656 
   1657 	/*
   1658 	 * If we don't have a sigobject for this emulation, create one.
   1659 	 *
   1660 	 * sigobject is an anonymous memory object (just like SYSV shared
   1661 	 * memory) that we keep a permanent reference to and that we map
   1662 	 * in all processes that need this sigcode. The creation is simple,
   1663 	 * we create an object, add a permanent reference to it, map it in
   1664 	 * kernel space, copy out the sigcode to it and unmap it.
   1665 	 * We map it with PROT_READ|PROT_EXEC into the process just
   1666 	 * the way sys_mmap() would map it.
   1667 	 */
   1668 
   1669 	uobj = *e->e_sigobject;
   1670 	if (uobj == NULL) {
   1671 		mutex_enter(&sigobject_lock);
   1672 		if ((uobj = *e->e_sigobject) == NULL) {
   1673 			uobj = uao_create(sz, 0);
   1674 			(*uobj->pgops->pgo_reference)(uobj);
   1675 			va = vm_map_min(kernel_map);
   1676 			if ((error = uvm_map(kernel_map, &va, round_page(sz),
   1677 			    uobj, 0, 0,
   1678 			    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
   1679 			    UVM_INH_SHARE, UVM_ADV_RANDOM, 0)))) {
   1680 				printf("kernel mapping failed %d\n", error);
   1681 				(*uobj->pgops->pgo_detach)(uobj);
   1682 				mutex_exit(&sigobject_lock);
   1683 				return (error);
   1684 			}
   1685 			memcpy((void *)va, e->e_sigcode, sz);
   1686 #ifdef PMAP_NEED_PROCWR
   1687 			pmap_procwr(&proc0, va, sz);
   1688 #endif
   1689 			uvm_unmap(kernel_map, va, va + round_page(sz));
   1690 			*e->e_sigobject = uobj;
   1691 		}
   1692 		mutex_exit(&sigobject_lock);
   1693 	}
   1694 
   1695 	/* Just a hint to uvm_map where to put it. */
   1696 	va = e->e_vm_default_addr(p, (vaddr_t)p->p_vmspace->vm_daddr,
   1697 	    round_page(sz));
   1698 
   1699 #ifdef __alpha__
   1700 	/*
   1701 	 * Tru64 puts /sbin/loader at the end of user virtual memory,
   1702 	 * which causes the above calculation to put the sigcode at
   1703 	 * an invalid address.  Put it just below the text instead.
   1704 	 */
   1705 	if (va == (vaddr_t)vm_map_max(&p->p_vmspace->vm_map)) {
   1706 		va = (vaddr_t)p->p_vmspace->vm_taddr - round_page(sz);
   1707 	}
   1708 #endif
   1709 
   1710 	(*uobj->pgops->pgo_reference)(uobj);
   1711 	error = uvm_map(&p->p_vmspace->vm_map, &va, round_page(sz),
   1712 			uobj, 0, 0,
   1713 			UVM_MAPFLAG(UVM_PROT_RX, UVM_PROT_RX, UVM_INH_SHARE,
   1714 				    UVM_ADV_RANDOM, 0));
   1715 	if (error) {
   1716 		DPRINTF(("%s, %d: map %p "
   1717 		    "uvm_map %#"PRIxVSIZE"@%#"PRIxVADDR" failed %d\n",
   1718 		    __func__, __LINE__, &p->p_vmspace->vm_map, round_page(sz),
   1719 		    va, error));
   1720 		(*uobj->pgops->pgo_detach)(uobj);
   1721 		return (error);
   1722 	}
   1723 	p->p_sigctx.ps_sigcode = (void *)va;
   1724 	return (0);
   1725 }
   1726 
   1727 /*
   1728  * A child lwp of a posix_spawn operation starts here and ends up in
   1729  * cpu_spawn_return, dealing with all filedescriptor and scheduler
   1730  * manipulations in between.
   1731  */
   1732 static void
   1733 spawn_return(void *arg)
   1734 {
   1735 	struct spawn_exec_data *spawn_data = arg;
   1736 	struct lwp *l = curlwp;
   1737 	int error, newfd;
   1738 	size_t i;
   1739 	const struct posix_spawn_file_actions_entry *fae;
   1740 	register_t retval;
   1741 
   1742 	error = 0;
   1743 	/* handle posix_spawn_file_actions */
   1744 	if (spawn_data->sed_actions != NULL) {
   1745 		for (i = 0; i < spawn_data->sed_actions_len; i++) {
   1746 			fae = &spawn_data->sed_actions[i];
   1747 			switch (fae->fae_action) {
   1748 			case FAE_OPEN:
   1749 				if (fd_getfile(fae->fae_fildes) != NULL) {
   1750 					error = fd_close(fae->fae_fildes);
   1751 					if (error)
   1752 						break;
   1753 				}
   1754 				error = fd_open(fae->fae_path, fae->fae_oflag,
   1755 				    fae->fae_mode, &newfd);
   1756  				if (error)
   1757  					break;
   1758 				if (newfd != fae->fae_fildes) {
   1759 					error = dodup(l, newfd,
   1760 					    fae->fae_fildes, 0, &retval);
   1761 					if (fd_getfile(newfd) != NULL)
   1762 						fd_close(newfd);
   1763 				}
   1764 				break;
   1765 			case FAE_DUP2:
   1766 				error = dodup(l, fae->fae_fildes,
   1767 				    fae->fae_newfildes, 0, &retval);
   1768 				break;
   1769 			case FAE_CLOSE:
   1770 				if (fd_getfile(fae->fae_fildes) == NULL) {
   1771 					error = EBADF;
   1772 					break;
   1773 				}
   1774 				error = fd_close(fae->fae_fildes);
   1775 				break;
   1776 			}
   1777 			if (error)
   1778 				goto report_error;
   1779 		}
   1780 	}
   1781 
   1782 	/* handle posix_spawnattr */
   1783 	if (spawn_data->sed_attrs != NULL) {
   1784 		struct sigaction sigact;
   1785 		sigact._sa_u._sa_handler = SIG_DFL;
   1786 		sigact.sa_flags = 0;
   1787 
   1788 		/*
   1789 		 * set state to SSTOP so that this proc can be found by pid.
   1790 		 * see proc_enterprp, do_sched_setparam below
   1791 		 */
   1792 		l->l_proc->p_stat = SSTOP;
   1793 
   1794 		/* Set process group */
   1795 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETPGROUP) {
   1796 			pid_t mypid = l->l_proc->p_pid,
   1797 			     pgrp = spawn_data->sed_attrs->sa_pgroup;
   1798 
   1799 			if (pgrp == 0)
   1800 				pgrp = mypid;
   1801 
   1802 			error = proc_enterpgrp(spawn_data->sed_parent,
   1803 			    mypid, pgrp, false);
   1804 			if (error)
   1805 				goto report_error;
   1806 		}
   1807 
   1808 		/* Set scheduler policy */
   1809 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSCHEDULER)
   1810 			error = do_sched_setparam(l->l_proc->p_pid, 0,
   1811 			    spawn_data->sed_attrs->sa_schedpolicy,
   1812 			    &spawn_data->sed_attrs->sa_schedparam);
   1813 		else if (spawn_data->sed_attrs->sa_flags
   1814 		    & POSIX_SPAWN_SETSCHEDPARAM) {
   1815 			error = do_sched_setparam(spawn_data->sed_parent->p_pid, 0,
   1816 			    SCHED_NONE, &spawn_data->sed_attrs->sa_schedparam);
   1817 		}
   1818 		if (error)
   1819 			goto report_error;
   1820 
   1821 		/* Reset user ID's */
   1822 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_RESETIDS) {
   1823 			error = do_setresuid(l, -1,
   1824 			     kauth_cred_getgid(l->l_cred), -1,
   1825 			     ID_E_EQ_R | ID_E_EQ_S);
   1826 			if (error)
   1827 				goto report_error;
   1828 			error = do_setresuid(l, -1,
   1829 			    kauth_cred_getuid(l->l_cred), -1,
   1830 			    ID_E_EQ_R | ID_E_EQ_S);
   1831 			if (error)
   1832 				goto report_error;
   1833 		}
   1834 
   1835 		/* Set signal masks/defaults */
   1836 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSIGMASK) {
   1837 			mutex_enter(l->l_proc->p_lock);
   1838 			error = sigprocmask1(l, SIG_SETMASK,
   1839 			    &spawn_data->sed_attrs->sa_sigmask, NULL);
   1840 			mutex_exit(l->l_proc->p_lock);
   1841 			if (error)
   1842 				goto report_error;
   1843 		}
   1844 
   1845 		if (spawn_data->sed_attrs->sa_flags & POSIX_SPAWN_SETSIGDEF) {
   1846 			for (i = 1; i <= NSIG; i++) {
   1847 				if (sigismember(
   1848 				    &spawn_data->sed_attrs->sa_sigdefault, i))
   1849 					sigaction1(l, i, &sigact, NULL, NULL,
   1850 					    0);
   1851 			}
   1852 		}
   1853 	}
   1854 
   1855 	if (spawn_data->sed_actions != NULL) {
   1856 		for (i = 0; i < spawn_data->sed_actions_len; i++) {
   1857 			fae = &spawn_data->sed_actions[i];
   1858 			if (fae->fae_action == FAE_OPEN)
   1859 				kmem_free(fae->fae_path,
   1860 				    strlen(fae->fae_path)+1);
   1861 		}
   1862 	}
   1863 
   1864 	/* now do the real exec */
   1865 	rw_enter(&exec_lock, RW_READER);
   1866 	error = execve_runproc(l, &spawn_data->sed_exec);
   1867 	if (error == EJUSTRETURN)
   1868 		error = 0;
   1869 	else if (error)
   1870 		goto report_error;
   1871 
   1872 	/* done, signal parent */
   1873 	mutex_enter(&spawn_data->sed_mtx_child);
   1874 	cv_signal(&spawn_data->sed_cv_child_ready);
   1875 	mutex_exit(&spawn_data->sed_mtx_child);
   1876 
   1877 	/* and finaly: leave to userland for the first time */
   1878 	cpu_spawn_return(l);
   1879 
   1880 	/* NOTREACHED */
   1881 	return;
   1882 
   1883  report_error:
   1884 	if (spawn_data->sed_actions != NULL) {
   1885 		for (i = 0; i < spawn_data->sed_actions_len; i++) {
   1886 			fae = &spawn_data->sed_actions[i];
   1887 			if (fae->fae_action == FAE_OPEN)
   1888 				kmem_free(fae->fae_path,
   1889 				    strlen(fae->fae_path)+1);
   1890 		}
   1891 	}
   1892 
   1893  	/*
   1894  	 * Set error value for parent to pick up (and take over ownership
   1895  	 * of spawn_data again), signal parent and exit this process.
   1896  	 */
   1897 	mutex_enter(&spawn_data->sed_mtx_child);
   1898 	spawn_data->sed_error = error;
   1899 	cv_signal(&spawn_data->sed_cv_child_ready);
   1900 	mutex_exit(&spawn_data->sed_mtx_child);
   1901 	mutex_enter(l->l_proc->p_lock);
   1902 	exit1(l, W_EXITCODE(error, SIGABRT));
   1903 }
   1904 
   1905 int
   1906 sys_posix_spawn(struct lwp *l1, const struct sys_posix_spawn_args *uap,
   1907     register_t *retval)
   1908 {
   1909 	/* {
   1910 		syscallarg(pid_t *) pid;
   1911 		syscallarg(const char *) path;
   1912 		syscallarg(const struct posix_spawn_file_actions *) file_actions;
   1913 		syscallarg(const struct posix_spawnattr *) attrp;
   1914 		syscallarg(char *const *) argv;
   1915 		syscallarg(char *const *) envp;
   1916 	} */
   1917 
   1918 	struct proc *p1, *p2;
   1919 	struct plimit *p1_lim;
   1920 	struct lwp *l2;
   1921 	int error = 0, tnprocs, count, i;
   1922 	struct posix_spawn_file_actions *fa = NULL;
   1923 	struct posix_spawnattr *sa = NULL;
   1924 	struct posix_spawn_file_actions_entry *ufa;
   1925 	struct spawn_exec_data *spawn_data;
   1926 	uid_t uid;
   1927 	vaddr_t uaddr;
   1928 	pid_t pid;
   1929 	bool have_exec_lock = false;
   1930 
   1931 	p1 = l1->l_proc;
   1932 	uid = kauth_cred_getuid(l1->l_cred);
   1933 	tnprocs = atomic_inc_uint_nv(&nprocs);
   1934 
   1935 	/*
   1936 	 * Although process entries are dynamically created, we still keep
   1937 	 * a global limit on the maximum number we will create.
   1938 	 */
   1939 	if (__predict_false(tnprocs >= maxproc))
   1940 		error = -1;
   1941 	else
   1942 		error = kauth_authorize_process(l1->l_cred,
   1943 		    KAUTH_PROCESS_FORK, p1, KAUTH_ARG(tnprocs), NULL, NULL);
   1944 
   1945 	if (error) {
   1946 		atomic_dec_uint(&nprocs);
   1947 		*retval = EAGAIN;
   1948 		return 0;
   1949 	}
   1950 
   1951 	/*
   1952 	 * Enforce limits.
   1953 	 */
   1954 	count = chgproccnt(uid, 1);
   1955 	if (kauth_authorize_generic(l1->l_cred, KAUTH_GENERIC_ISSUSER, NULL) !=
   1956 	    0 && __predict_false(count > p1->p_rlimit[RLIMIT_NPROC].rlim_cur)) {
   1957 		error = EAGAIN;
   1958 		goto error_exit;
   1959 	}
   1960 
   1961 	/* copy in file_actions struct */
   1962 	if (SCARG(uap, file_actions) != NULL) {
   1963 		fa = kmem_alloc(sizeof(struct posix_spawn_file_actions),
   1964 		    KM_SLEEP);
   1965 		error = copyin(SCARG(uap, file_actions), fa,
   1966 		    sizeof(struct posix_spawn_file_actions));
   1967 		if (error) {
   1968 			fa->fae = NULL;
   1969 			goto error_exit;
   1970 		}
   1971 		ufa = fa->fae;
   1972 		fa->fae = kmem_alloc(fa->len *
   1973 		    sizeof(struct posix_spawn_file_actions_entry), KM_SLEEP);
   1974 		error = copyin(ufa, fa->fae,
   1975 		    fa->len * sizeof(struct posix_spawn_file_actions_entry));
   1976 		if (error)
   1977 			goto error_exit;
   1978 		for (i = 0; i < fa->len; i++) {
   1979 			if (fa->fae[i].fae_action == FAE_OPEN) {
   1980 				char buf[PATH_MAX];
   1981 				error = copyinstr(fa->fae[i].fae_path, buf,
   1982 				     sizeof(buf), NULL);
   1983 				if (error)
   1984 					break;
   1985 				fa->fae[i].fae_path = kmem_alloc(strlen(buf)+1,
   1986 				     KM_SLEEP);
   1987 				if (fa->fae[i].fae_path == NULL) {
   1988 					error = ENOMEM;
   1989 					break;
   1990 				}
   1991 				strcpy(fa->fae[i].fae_path, buf);
   1992 			}
   1993 		}
   1994 	}
   1995 
   1996 	/* copyin posix_spawnattr struct */
   1997 	sa = NULL;
   1998 	if (SCARG(uap, attrp) != NULL) {
   1999 		sa = kmem_alloc(sizeof(struct posix_spawnattr), KM_SLEEP);
   2000 		error = copyin(SCARG(uap, attrp), sa,
   2001 		    sizeof(struct posix_spawnattr));
   2002 		if (error)
   2003 			goto error_exit;
   2004 	}
   2005 
   2006 
   2007 	/*
   2008 	 * Do the first part of the exec now, collect state
   2009 	 * in spawn_data.
   2010 	 */
   2011 	spawn_data = kmem_zalloc(sizeof(*spawn_data), KM_SLEEP);
   2012 	error = execve_loadvm(l1, SCARG(uap, path), SCARG(uap, argv),
   2013 	    SCARG(uap, envp), execve_fetch_element, &spawn_data->sed_exec);
   2014 	if (error == EJUSTRETURN)
   2015 		error = 0;
   2016 	else if (error)
   2017 		goto error_exit;
   2018 
   2019 	have_exec_lock = true;
   2020 
   2021 	/*
   2022 	 * Allocate virtual address space for the U-area now, while it
   2023 	 * is still easy to abort the fork operation if we're out of
   2024 	 * kernel virtual address space.
   2025 	 */
   2026 	uaddr = uvm_uarea_alloc();
   2027 	if (__predict_false(uaddr == 0)) {
   2028 		error = ENOMEM;
   2029 		goto error_exit;
   2030 	}
   2031 
   2032 	/*
   2033 	 * Allocate new proc. Leave it's p_vmspace NULL for now.
   2034 	 * This is a point of no return, we will have to go through
   2035 	 * the child proc to properly clean it up past this point.
   2036 	 */
   2037 	p2 = proc_alloc();
   2038 	pid = p2->p_pid;
   2039 
   2040 	/*
   2041 	 * Make a proc table entry for the new process.
   2042 	 * Start by zeroing the section of proc that is zero-initialized,
   2043 	 * then copy the section that is copied directly from the parent.
   2044 	 */
   2045 	memset(&p2->p_startzero, 0,
   2046 	    (unsigned) ((char *)&p2->p_endzero - (char *)&p2->p_startzero));
   2047 	memcpy(&p2->p_startcopy, &p1->p_startcopy,
   2048 	    (unsigned) ((char *)&p2->p_endcopy - (char *)&p2->p_startcopy));
   2049 	p2->p_vmspace = NULL;
   2050 
   2051 	CIRCLEQ_INIT(&p2->p_sigpend.sp_info);
   2052 
   2053 	LIST_INIT(&p2->p_lwps);
   2054 	LIST_INIT(&p2->p_sigwaiters);
   2055 
   2056 	/*
   2057 	 * Duplicate sub-structures as needed.
   2058 	 * Increase reference counts on shared objects.
   2059 	 * Inherit flags we want to keep.  The flags related to SIGCHLD
   2060 	 * handling are important in order to keep a consistent behaviour
   2061 	 * for the child after the fork.  If we are a 32-bit process, the
   2062 	 * child will be too.
   2063 	 */
   2064 	p2->p_flag =
   2065 	    p1->p_flag & (PK_SUGID | PK_NOCLDWAIT | PK_CLDSIGIGN | PK_32);
   2066 	p2->p_emul = p1->p_emul;
   2067 	p2->p_execsw = p1->p_execsw;
   2068 
   2069 	mutex_init(&p2->p_stmutex, MUTEX_DEFAULT, IPL_HIGH);
   2070 	mutex_init(&p2->p_auxlock, MUTEX_DEFAULT, IPL_NONE);
   2071 	rw_init(&p2->p_reflock);
   2072 	cv_init(&p2->p_waitcv, "wait");
   2073 	cv_init(&p2->p_lwpcv, "lwpwait");
   2074 
   2075 	p2->p_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   2076 
   2077 	kauth_proc_fork(p1, p2);
   2078 
   2079 	p2->p_raslist = NULL;
   2080 	p2->p_fd = fd_copy();
   2081 
   2082 	/* XXX racy */
   2083 	p2->p_mqueue_cnt = p1->p_mqueue_cnt;
   2084 
   2085 	p2->p_cwdi = cwdinit();
   2086 
   2087 	/*
   2088 	 * Note: p_limit (rlimit stuff) is copy-on-write, so normally
   2089 	 * we just need increase pl_refcnt.
   2090 	 */
   2091 	p1_lim = p1->p_limit;
   2092 	if (!p1_lim->pl_writeable) {
   2093 		lim_addref(p1_lim);
   2094 		p2->p_limit = p1_lim;
   2095 	} else {
   2096 		p2->p_limit = lim_copy(p1->p_limit);
   2097 	}
   2098 
   2099 	p2->p_lflag = 0;
   2100 	p2->p_sflag = 0;
   2101 	p2->p_slflag = 0;
   2102 	p2->p_pptr = p1;
   2103 	p2->p_ppid = p1->p_pid;
   2104 	LIST_INIT(&p2->p_children);
   2105 
   2106 	p2->p_aio = NULL;
   2107 
   2108 #ifdef KTRACE
   2109 	/*
   2110 	 * Copy traceflag and tracefile if enabled.
   2111 	 * If not inherited, these were zeroed above.
   2112 	 */
   2113 	if (p1->p_traceflag & KTRFAC_INHERIT) {
   2114 		mutex_enter(&ktrace_lock);
   2115 		p2->p_traceflag = p1->p_traceflag;
   2116 		if ((p2->p_tracep = p1->p_tracep) != NULL)
   2117 			ktradref(p2);
   2118 		mutex_exit(&ktrace_lock);
   2119 	}
   2120 #endif
   2121 
   2122 	/*
   2123 	 * Create signal actions for the child process.
   2124 	 */
   2125 	p2->p_sigacts = sigactsinit(p1, 0);
   2126 	mutex_enter(p1->p_lock);
   2127 	p2->p_sflag |=
   2128 	    (p1->p_sflag & (PS_STOPFORK | PS_STOPEXEC | PS_NOCLDSTOP));
   2129 	sched_proc_fork(p1, p2);
   2130 	mutex_exit(p1->p_lock);
   2131 
   2132 	p2->p_stflag = p1->p_stflag;
   2133 
   2134 	/*
   2135 	 * p_stats.
   2136 	 * Copy parts of p_stats, and zero out the rest.
   2137 	 */
   2138 	p2->p_stats = pstatscopy(p1->p_stats);
   2139 
   2140 	/* copy over machdep flags to the new proc */
   2141 	cpu_proc_fork(p1, p2);
   2142 
   2143 	/*
   2144 	 * Prepare remaining parts of spawn data
   2145 	 */
   2146 	if (fa != NULL) {
   2147 		spawn_data->sed_actions_len = fa->len;
   2148 		spawn_data->sed_actions = fa->fae;
   2149 		kmem_free(fa, sizeof(*fa));
   2150 		fa = NULL;
   2151 	}
   2152 	if (sa != NULL) {
   2153 		spawn_data->sed_attrs = sa;
   2154 		sa = NULL;
   2155 	}
   2156 
   2157 	spawn_data->sed_parent = p1;
   2158 	cv_init(&spawn_data->sed_cv_child_ready, "pspawn");
   2159 	mutex_init(&spawn_data->sed_mtx_child, MUTEX_DEFAULT, IPL_NONE);
   2160 	mutex_enter(&spawn_data->sed_mtx_child);
   2161 
   2162 	/* create LWP */
   2163 	lwp_create(l1, p2, uaddr, 0, NULL, 0, spawn_return, spawn_data,
   2164 	    &l2, l1->l_class);
   2165 	l2->l_ctxlink = NULL;	/* reset ucontext link */
   2166 
   2167 	/*
   2168 	 * Copy the credential so other references don't see our changes.
   2169 	 * Test to see if this is necessary first, since in the common case
   2170 	 * we won't need a private reference.
   2171 	 */
   2172 	if (kauth_cred_geteuid(l2->l_cred) != kauth_cred_getsvuid(l2->l_cred) ||
   2173 	    kauth_cred_getegid(l2->l_cred) != kauth_cred_getsvgid(l2->l_cred)) {
   2174 		l2->l_cred = kauth_cred_copy(l2->l_cred);
   2175 		kauth_cred_setsvuid(l2->l_cred, kauth_cred_geteuid(l2->l_cred));
   2176 		kauth_cred_setsvgid(l2->l_cred, kauth_cred_getegid(l2->l_cred));
   2177 	}
   2178 
   2179 	/* Update the master credentials. */
   2180 	if (l2->l_cred != p2->p_cred) {
   2181 		kauth_cred_t ocred;
   2182 
   2183 		kauth_cred_hold(l2->l_cred);
   2184 		mutex_enter(p2->p_lock);
   2185 		ocred = p2->p_cred;
   2186 		p2->p_cred = l2->l_cred;
   2187 		mutex_exit(p2->p_lock);
   2188 		kauth_cred_free(ocred);
   2189 	}
   2190 
   2191 	/*
   2192 	 * It's now safe for the scheduler and other processes to see the
   2193 	 * child process.
   2194 	 */
   2195 	mutex_enter(proc_lock);
   2196 
   2197 	if (p1->p_session->s_ttyvp != NULL && p1->p_lflag & PL_CONTROLT)
   2198 		p2->p_lflag |= PL_CONTROLT;
   2199 
   2200 	LIST_INSERT_HEAD(&p1->p_children, p2, p_sibling);
   2201 	p2->p_exitsig = SIGCHLD;	/* signal for parent on exit */
   2202 
   2203 	LIST_INSERT_AFTER(p1, p2, p_pglist);
   2204 	LIST_INSERT_HEAD(&allproc, p2, p_list);
   2205 
   2206 	p2->p_trace_enabled = trace_is_enabled(p2);
   2207 #ifdef __HAVE_SYSCALL_INTERN
   2208 	(*p2->p_emul->e_syscall_intern)(p2);
   2209 #endif
   2210 	rw_exit(&p1->p_reflock);
   2211 
   2212 	/*
   2213 	 * Make child runnable, set start time, and add to run queue except
   2214 	 * if the parent requested the child to start in SSTOP state.
   2215 	 */
   2216 	mutex_enter(p2->p_lock);
   2217 
   2218 	getmicrotime(&p2->p_stats->p_start);
   2219 
   2220 	lwp_lock(l2);
   2221 	KASSERT(p2->p_nrlwps == 1);
   2222 	p2->p_nrlwps = 1;
   2223 	p2->p_stat = SACTIVE;
   2224 	l2->l_stat = LSRUN;
   2225 	sched_enqueue(l2, false);
   2226 	lwp_unlock(l2);
   2227 
   2228 	mutex_exit(p2->p_lock);
   2229 	mutex_exit(proc_lock);
   2230 
   2231 	cv_wait(&spawn_data->sed_cv_child_ready, &spawn_data->sed_mtx_child);
   2232 	mutex_exit(&spawn_data->sed_mtx_child);
   2233 	error = spawn_data->sed_error;
   2234 
   2235 	rw_exit(&exec_lock);
   2236 	have_exec_lock = false;
   2237 
   2238 	if (spawn_data->sed_actions != NULL)
   2239 		kmem_free(spawn_data->sed_actions,
   2240 		    spawn_data->sed_actions_len * sizeof(*spawn_data->sed_actions));
   2241 
   2242 	if (spawn_data->sed_attrs != NULL)
   2243 		kmem_free(spawn_data->sed_attrs, sizeof(*spawn_data->sed_attrs));
   2244 
   2245 	cv_destroy(&spawn_data->sed_cv_child_ready);
   2246 	mutex_destroy(&spawn_data->sed_mtx_child);
   2247 
   2248 	kmem_free(spawn_data, sizeof(*spawn_data));
   2249 
   2250 	if (error == 0 && SCARG(uap, pid) != NULL)
   2251 		error = copyout(&pid, SCARG(uap, pid), sizeof(pid));
   2252 
   2253 	*retval = error;
   2254 	return 0;
   2255 
   2256  error_exit:
   2257  	if (have_exec_lock)
   2258  		rw_exit(&exec_lock);
   2259 
   2260 	if (fa != NULL) {
   2261 		if (fa->fae != NULL)
   2262 			kmem_free(fa->fae, fa->len * sizeof(*fa->fae));
   2263 		kmem_free(fa, sizeof(*fa));
   2264 	}
   2265 
   2266 	if (sa != NULL)
   2267 		kmem_free(sa, sizeof(*sa));
   2268 
   2269 	(void)chgproccnt(uid, -1);
   2270 	atomic_dec_uint(&nprocs);
   2271 
   2272 	*retval = error;
   2273 	return 0;
   2274 }
   2275 
   2276 void
   2277 exec_free_emul_arg(struct exec_package *epp)
   2278 {
   2279 	if (epp->ep_emul_arg_free != NULL) {
   2280 		KASSERT(epp->ep_emul_arg != NULL);
   2281 		(*epp->ep_emul_arg_free)(epp->ep_emul_arg);
   2282 		epp->ep_emul_arg_free = NULL;
   2283 		epp->ep_emul_arg = NULL;
   2284 	} else {
   2285 		KASSERT(epp->ep_emul_arg == NULL);
   2286 	}
   2287 }
   2288