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