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