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