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