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