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