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