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