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