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