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