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