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