xref: /freebsd/sys/kern/kern_exec.c (revision 29cf6a79acb7c28586ce39473e9ea1f2f1cd1ed4)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1993, David Greenman
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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_capsicum.h"
33 #include "opt_hwpmc_hooks.h"
34 #include "opt_ktrace.h"
35 #include "opt_vm.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/acct.h>
40 #include <sys/asan.h>
41 #include <sys/capsicum.h>
42 #include <sys/compressor.h>
43 #include <sys/eventhandler.h>
44 #include <sys/exec.h>
45 #include <sys/fcntl.h>
46 #include <sys/filedesc.h>
47 #include <sys/imgact.h>
48 #include <sys/imgact_elf.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mman.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/namei.h>
56 #include <sys/priv.h>
57 #include <sys/proc.h>
58 #include <sys/ptrace.h>
59 #include <sys/reg.h>
60 #include <sys/resourcevar.h>
61 #include <sys/rwlock.h>
62 #include <sys/sched.h>
63 #include <sys/sdt.h>
64 #include <sys/sf_buf.h>
65 #include <sys/shm.h>
66 #include <sys/signalvar.h>
67 #include <sys/smp.h>
68 #include <sys/stat.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysent.h>
72 #include <sys/sysproto.h>
73 #include <sys/timers.h>
74 #include <sys/umtxvar.h>
75 #include <sys/vnode.h>
76 #include <sys/wait.h>
77 #ifdef KTRACE
78 #include <sys/ktrace.h>
79 #endif
80 
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_extern.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_pager.h>
90 
91 #ifdef	HWPMC_HOOKS
92 #include <sys/pmckern.h>
93 #endif
94 
95 #include <security/audit/audit.h>
96 #include <security/mac/mac_framework.h>
97 
98 #ifdef KDTRACE_HOOKS
99 #include <sys/dtrace_bsd.h>
100 dtrace_execexit_func_t	dtrace_fasttrap_exec;
101 #endif
102 
103 SDT_PROVIDER_DECLARE(proc);
104 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
105 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
106 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
107 
108 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
109 
110 int coredump_pack_fileinfo = 1;
111 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
112     &coredump_pack_fileinfo, 0,
113     "Enable file path packing in 'procstat -f' coredump notes");
114 
115 int coredump_pack_vmmapinfo = 1;
116 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
117     &coredump_pack_vmmapinfo, 0,
118     "Enable file path packing in 'procstat -v' coredump notes");
119 
120 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
121 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
122 static int sysctl_kern_stacktop(SYSCTL_HANDLER_ARGS);
123 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
124 static int do_execve(struct thread *td, struct image_args *args,
125     struct mac *mac_p, struct vmspace *oldvmspace);
126 
127 /* XXX This should be vm_size_t. */
128 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD|
129     CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_ps_strings, "LU",
130     "Location of process' ps_strings structure");
131 
132 /* XXX This should be vm_size_t. */
133 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
134     CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_usrstack, "LU",
135     "Top of process stack");
136 
137 SYSCTL_PROC(_kern, KERN_STACKTOP, stacktop, CTLTYPE_ULONG | CTLFLAG_RD |
138     CTLFLAG_CAPRD | CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_stacktop, "LU",
139     "Top of process stack with stack gap.");
140 
141 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_MPSAFE,
142     NULL, 0, sysctl_kern_stackprot, "I",
143     "Stack memory permissions");
144 
145 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
146 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
147     &ps_arg_cache_limit, 0,
148     "Process' command line characters cache limit");
149 
150 static int disallow_high_osrel;
151 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
152     &disallow_high_osrel, 0,
153     "Disallow execution of binaries built for higher version of the world");
154 
155 static int map_at_zero = 0;
156 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
157     "Permit processes to map an object at virtual address 0.");
158 
159 static int core_dump_can_intr = 1;
160 SYSCTL_INT(_kern, OID_AUTO, core_dump_can_intr, CTLFLAG_RWTUN,
161     &core_dump_can_intr, 0,
162     "Core dumping interruptible with SIGKILL");
163 
164 static int
165 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
166 {
167 	struct proc *p;
168 	int error;
169 
170 	p = curproc;
171 #ifdef SCTL_MASK32
172 	if (req->flags & SCTL_MASK32) {
173 		unsigned int val;
174 		val = (unsigned int)p->p_sysent->sv_psstrings;
175 		error = SYSCTL_OUT(req, &val, sizeof(val));
176 	} else
177 #endif
178 		error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
179 		   sizeof(p->p_sysent->sv_psstrings));
180 	return error;
181 }
182 
183 static int
184 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
185 {
186 	struct proc *p;
187 	int error;
188 
189 	p = curproc;
190 #ifdef SCTL_MASK32
191 	if (req->flags & SCTL_MASK32) {
192 		unsigned int val;
193 		val = (unsigned int)p->p_sysent->sv_usrstack;
194 		error = SYSCTL_OUT(req, &val, sizeof(val));
195 	} else
196 #endif
197 		error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
198 		    sizeof(p->p_sysent->sv_usrstack));
199 	return (error);
200 }
201 
202 static int
203 sysctl_kern_stacktop(SYSCTL_HANDLER_ARGS)
204 {
205 	vm_offset_t stacktop;
206 	struct proc *p;
207 	int error;
208 
209 	p = curproc;
210 #ifdef SCTL_MASK32
211 	if (req->flags & SCTL_MASK32) {
212 		unsigned int val;
213 
214 		val = (unsigned int)(p->p_sysent->sv_usrstack -
215 		    p->p_vmspace->vm_stkgap);
216 		error = SYSCTL_OUT(req, &val, sizeof(val));
217 	} else
218 #endif
219 	{
220 		stacktop = p->p_sysent->sv_usrstack - p->p_vmspace->vm_stkgap;
221 		error = SYSCTL_OUT(req, &stacktop, sizeof(stacktop));
222 	}
223 	return (error);
224 }
225 
226 static int
227 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
228 {
229 	struct proc *p;
230 
231 	p = curproc;
232 	return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
233 	    sizeof(p->p_sysent->sv_stackprot)));
234 }
235 
236 /*
237  * Each of the items is a pointer to a `const struct execsw', hence the
238  * double pointer here.
239  */
240 static const struct execsw **execsw;
241 
242 #ifndef _SYS_SYSPROTO_H_
243 struct execve_args {
244 	char    *fname;
245 	char    **argv;
246 	char    **envv;
247 };
248 #endif
249 
250 int
251 sys_execve(struct thread *td, struct execve_args *uap)
252 {
253 	struct image_args args;
254 	struct vmspace *oldvmspace;
255 	int error;
256 
257 	error = pre_execve(td, &oldvmspace);
258 	if (error != 0)
259 		return (error);
260 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
261 	    uap->argv, uap->envv);
262 	if (error == 0)
263 		error = kern_execve(td, &args, NULL, oldvmspace);
264 	post_execve(td, error, oldvmspace);
265 	AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
266 	return (error);
267 }
268 
269 #ifndef _SYS_SYSPROTO_H_
270 struct fexecve_args {
271 	int	fd;
272 	char	**argv;
273 	char	**envv;
274 };
275 #endif
276 int
277 sys_fexecve(struct thread *td, struct fexecve_args *uap)
278 {
279 	struct image_args args;
280 	struct vmspace *oldvmspace;
281 	int error;
282 
283 	error = pre_execve(td, &oldvmspace);
284 	if (error != 0)
285 		return (error);
286 	error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
287 	    uap->argv, uap->envv);
288 	if (error == 0) {
289 		args.fd = uap->fd;
290 		error = kern_execve(td, &args, NULL, oldvmspace);
291 	}
292 	post_execve(td, error, oldvmspace);
293 	AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
294 	return (error);
295 }
296 
297 #ifndef _SYS_SYSPROTO_H_
298 struct __mac_execve_args {
299 	char	*fname;
300 	char	**argv;
301 	char	**envv;
302 	struct mac	*mac_p;
303 };
304 #endif
305 
306 int
307 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
308 {
309 #ifdef MAC
310 	struct image_args args;
311 	struct vmspace *oldvmspace;
312 	int error;
313 
314 	error = pre_execve(td, &oldvmspace);
315 	if (error != 0)
316 		return (error);
317 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
318 	    uap->argv, uap->envv);
319 	if (error == 0)
320 		error = kern_execve(td, &args, uap->mac_p, oldvmspace);
321 	post_execve(td, error, oldvmspace);
322 	AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
323 	return (error);
324 #else
325 	return (ENOSYS);
326 #endif
327 }
328 
329 int
330 pre_execve(struct thread *td, struct vmspace **oldvmspace)
331 {
332 	struct proc *p;
333 	int error;
334 
335 	KASSERT(td == curthread, ("non-current thread %p", td));
336 	error = 0;
337 	p = td->td_proc;
338 	if ((p->p_flag & P_HADTHREADS) != 0) {
339 		PROC_LOCK(p);
340 		if (thread_single(p, SINGLE_BOUNDARY) != 0)
341 			error = ERESTART;
342 		PROC_UNLOCK(p);
343 	}
344 	KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
345 	    ("nested execve"));
346 	*oldvmspace = p->p_vmspace;
347 	return (error);
348 }
349 
350 void
351 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
352 {
353 	struct proc *p;
354 
355 	KASSERT(td == curthread, ("non-current thread %p", td));
356 	p = td->td_proc;
357 	if ((p->p_flag & P_HADTHREADS) != 0) {
358 		PROC_LOCK(p);
359 		/*
360 		 * If success, we upgrade to SINGLE_EXIT state to
361 		 * force other threads to suicide.
362 		 */
363 		if (error == EJUSTRETURN)
364 			thread_single(p, SINGLE_EXIT);
365 		else
366 			thread_single_end(p, SINGLE_BOUNDARY);
367 		PROC_UNLOCK(p);
368 	}
369 	exec_cleanup(td, oldvmspace);
370 }
371 
372 /*
373  * kern_execve() has the astonishing property of not always returning to
374  * the caller.  If sufficiently bad things happen during the call to
375  * do_execve(), it can end up calling exit1(); as a result, callers must
376  * avoid doing anything which they might need to undo (e.g., allocating
377  * memory).
378  */
379 int
380 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
381     struct vmspace *oldvmspace)
382 {
383 
384 	TSEXEC(td->td_proc->p_pid, args->begin_argv);
385 	AUDIT_ARG_ARGV(args->begin_argv, args->argc,
386 	    exec_args_get_begin_envv(args) - args->begin_argv);
387 	AUDIT_ARG_ENVV(exec_args_get_begin_envv(args), args->envc,
388 	    args->endp - exec_args_get_begin_envv(args));
389 	return (do_execve(td, args, mac_p, oldvmspace));
390 }
391 
392 static void
393 execve_nosetid(struct image_params *imgp)
394 {
395 	imgp->credential_setid = false;
396 	if (imgp->newcred != NULL) {
397 		crfree(imgp->newcred);
398 		imgp->newcred = NULL;
399 	}
400 }
401 
402 /*
403  * In-kernel implementation of execve().  All arguments are assumed to be
404  * userspace pointers from the passed thread.
405  */
406 static int
407 do_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
408     struct vmspace *oldvmspace)
409 {
410 	struct proc *p = td->td_proc;
411 	struct nameidata nd;
412 	struct ucred *oldcred;
413 	struct uidinfo *euip = NULL;
414 	uintptr_t stack_base;
415 	struct image_params image_params, *imgp;
416 	struct vattr attr;
417 	int (*img_first)(struct image_params *);
418 	struct pargs *oldargs = NULL, *newargs = NULL;
419 	struct sigacts *oldsigacts = NULL, *newsigacts = NULL;
420 #ifdef KTRACE
421 	struct ktr_io_params *kiop;
422 #endif
423 	struct vnode *oldtextvp, *newtextvp;
424 	struct vnode *oldtextdvp, *newtextdvp;
425 	char *oldbinname, *newbinname;
426 	bool credential_changing;
427 #ifdef MAC
428 	struct label *interpvplabel = NULL;
429 	bool will_transition;
430 #endif
431 #ifdef HWPMC_HOOKS
432 	struct pmckern_procexec pe;
433 #endif
434 	int error, i, orig_osrel;
435 	uint32_t orig_fctl0;
436 	Elf_Brandinfo *orig_brandinfo;
437 	size_t freepath_size;
438 	static const char fexecv_proc_title[] = "(fexecv)";
439 
440 	imgp = &image_params;
441 	oldtextvp = oldtextdvp = NULL;
442 	newtextvp = newtextdvp = NULL;
443 	newbinname = oldbinname = NULL;
444 #ifdef KTRACE
445 	kiop = NULL;
446 #endif
447 
448 	/*
449 	 * Lock the process and set the P_INEXEC flag to indicate that
450 	 * it should be left alone until we're done here.  This is
451 	 * necessary to avoid race conditions - e.g. in ptrace() -
452 	 * that might allow a local user to illicitly obtain elevated
453 	 * privileges.
454 	 */
455 	PROC_LOCK(p);
456 	KASSERT((p->p_flag & P_INEXEC) == 0,
457 	    ("%s(): process already has P_INEXEC flag", __func__));
458 	p->p_flag |= P_INEXEC;
459 	PROC_UNLOCK(p);
460 
461 	/*
462 	 * Initialize part of the common data
463 	 */
464 	bzero(imgp, sizeof(*imgp));
465 	imgp->proc = p;
466 	imgp->attr = &attr;
467 	imgp->args = args;
468 	oldcred = p->p_ucred;
469 	orig_osrel = p->p_osrel;
470 	orig_fctl0 = p->p_fctl0;
471 	orig_brandinfo = p->p_elf_brandinfo;
472 
473 #ifdef MAC
474 	error = mac_execve_enter(imgp, mac_p);
475 	if (error)
476 		goto exec_fail;
477 #endif
478 
479 	SDT_PROBE1(proc, , , exec, args->fname);
480 
481 interpret:
482 	if (args->fname != NULL) {
483 #ifdef CAPABILITY_MODE
484 		/*
485 		 * While capability mode can't reach this point via direct
486 		 * path arguments to execve(), we also don't allow
487 		 * interpreters to be used in capability mode (for now).
488 		 * Catch indirect lookups and return a permissions error.
489 		 */
490 		if (IN_CAPABILITY_MODE(td)) {
491 			error = ECAPMODE;
492 			goto exec_fail;
493 		}
494 #endif
495 
496 		/*
497 		 * Translate the file name. namei() returns a vnode
498 		 * pointer in ni_vp among other things.
499 		 */
500 		NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
501 		    SAVENAME | AUDITVNODE1 | WANTPARENT, UIO_SYSSPACE,
502 		    args->fname, td);
503 
504 		error = namei(&nd);
505 		if (error)
506 			goto exec_fail;
507 
508 		newtextvp = nd.ni_vp;
509 		newtextdvp = nd.ni_dvp;
510 		nd.ni_dvp = NULL;
511 		newbinname = malloc(nd.ni_cnd.cn_namelen + 1, M_PARGS,
512 		    M_WAITOK);
513 		memcpy(newbinname, nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen);
514 		newbinname[nd.ni_cnd.cn_namelen] = '\0';
515 		imgp->vp = newtextvp;
516 
517 		/*
518 		 * Do the best to calculate the full path to the image file.
519 		 */
520 		if (args->fname[0] == '/') {
521 			imgp->execpath = args->fname;
522 		} else {
523 			VOP_UNLOCK(imgp->vp);
524 			freepath_size = MAXPATHLEN;
525 			if (vn_fullpath_hardlink(newtextvp, newtextdvp,
526 			    newbinname, nd.ni_cnd.cn_namelen, &imgp->execpath,
527 			    &imgp->freepath, &freepath_size) != 0)
528 				imgp->execpath = args->fname;
529 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
530 		}
531 	} else {
532 		AUDIT_ARG_FD(args->fd);
533 		/*
534 		 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
535 		 */
536 		error = fgetvp_exec(td, args->fd, &cap_fexecve_rights,
537 		    &newtextvp);
538 		if (error)
539 			goto exec_fail;
540 		if (vn_fullpath(imgp->vp, &imgp->execpath,
541 		    &imgp->freepath) != 0)
542 			imgp->execpath = args->fname;
543 		vn_lock(newtextvp, LK_SHARED | LK_RETRY);
544 		AUDIT_ARG_VNODE1(newtextvp);
545 		imgp->vp = newtextvp;
546 	}
547 
548 	/*
549 	 * Check file permissions.  Also 'opens' file and sets its vnode to
550 	 * text mode.
551 	 */
552 	error = exec_check_permissions(imgp);
553 	if (error)
554 		goto exec_fail_dealloc;
555 
556 	imgp->object = imgp->vp->v_object;
557 	if (imgp->object != NULL)
558 		vm_object_reference(imgp->object);
559 
560 	error = exec_map_first_page(imgp);
561 	if (error)
562 		goto exec_fail_dealloc;
563 
564 	imgp->proc->p_osrel = 0;
565 	imgp->proc->p_fctl0 = 0;
566 	imgp->proc->p_elf_brandinfo = NULL;
567 
568 	/*
569 	 * Implement image setuid/setgid.
570 	 *
571 	 * Determine new credentials before attempting image activators
572 	 * so that it can be used by process_exec handlers to determine
573 	 * credential/setid changes.
574 	 *
575 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
576 	 * the process is being traced.
577 	 *
578 	 * We disable setuid/setgid/etc in capability mode on the basis
579 	 * that most setugid applications are not written with that
580 	 * environment in mind, and will therefore almost certainly operate
581 	 * incorrectly. In principle there's no reason that setugid
582 	 * applications might not be useful in capability mode, so we may want
583 	 * to reconsider this conservative design choice in the future.
584 	 *
585 	 * XXXMAC: For the time being, use NOSUID to also prohibit
586 	 * transitions on the file system.
587 	 */
588 	credential_changing = false;
589 	credential_changing |= (attr.va_mode & S_ISUID) &&
590 	    oldcred->cr_uid != attr.va_uid;
591 	credential_changing |= (attr.va_mode & S_ISGID) &&
592 	    oldcred->cr_gid != attr.va_gid;
593 #ifdef MAC
594 	will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
595 	    interpvplabel, imgp) != 0;
596 	credential_changing |= will_transition;
597 #endif
598 
599 	/* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */
600 	if (credential_changing)
601 		imgp->proc->p_pdeathsig = 0;
602 
603 	if (credential_changing &&
604 #ifdef CAPABILITY_MODE
605 	    ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
606 #endif
607 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
608 	    (p->p_flag & P_TRACED) == 0) {
609 		imgp->credential_setid = true;
610 		VOP_UNLOCK(imgp->vp);
611 		imgp->newcred = crdup(oldcred);
612 		if (attr.va_mode & S_ISUID) {
613 			euip = uifind(attr.va_uid);
614 			change_euid(imgp->newcred, euip);
615 		}
616 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
617 		if (attr.va_mode & S_ISGID)
618 			change_egid(imgp->newcred, attr.va_gid);
619 		/*
620 		 * Implement correct POSIX saved-id behavior.
621 		 *
622 		 * XXXMAC: Note that the current logic will save the
623 		 * uid and gid if a MAC domain transition occurs, even
624 		 * though maybe it shouldn't.
625 		 */
626 		change_svuid(imgp->newcred, imgp->newcred->cr_uid);
627 		change_svgid(imgp->newcred, imgp->newcred->cr_gid);
628 	} else {
629 		/*
630 		 * Implement correct POSIX saved-id behavior.
631 		 *
632 		 * XXX: It's not clear that the existing behavior is
633 		 * POSIX-compliant.  A number of sources indicate that the
634 		 * saved uid/gid should only be updated if the new ruid is
635 		 * not equal to the old ruid, or the new euid is not equal
636 		 * to the old euid and the new euid is not equal to the old
637 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
638 		 * Also, this code uses the new (replaced) euid and egid as
639 		 * the source, which may or may not be the right ones to use.
640 		 */
641 		if (oldcred->cr_svuid != oldcred->cr_uid ||
642 		    oldcred->cr_svgid != oldcred->cr_gid) {
643 			VOP_UNLOCK(imgp->vp);
644 			imgp->newcred = crdup(oldcred);
645 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
646 			change_svuid(imgp->newcred, imgp->newcred->cr_uid);
647 			change_svgid(imgp->newcred, imgp->newcred->cr_gid);
648 		}
649 	}
650 	/* The new credentials are installed into the process later. */
651 
652 	/*
653 	 *	If the current process has a special image activator it
654 	 *	wants to try first, call it.   For example, emulating shell
655 	 *	scripts differently.
656 	 */
657 	error = -1;
658 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
659 		error = img_first(imgp);
660 
661 	/*
662 	 *	Loop through the list of image activators, calling each one.
663 	 *	An activator returns -1 if there is no match, 0 on success,
664 	 *	and an error otherwise.
665 	 */
666 	for (i = 0; error == -1 && execsw[i]; ++i) {
667 		if (execsw[i]->ex_imgact == NULL ||
668 		    execsw[i]->ex_imgact == img_first) {
669 			continue;
670 		}
671 		error = (*execsw[i]->ex_imgact)(imgp);
672 	}
673 
674 	if (error) {
675 		if (error == -1)
676 			error = ENOEXEC;
677 		goto exec_fail_dealloc;
678 	}
679 
680 	/*
681 	 * Special interpreter operation, cleanup and loop up to try to
682 	 * activate the interpreter.
683 	 */
684 	if (imgp->interpreted) {
685 		exec_unmap_first_page(imgp);
686 		/*
687 		 * The text reference needs to be removed for scripts.
688 		 * There is a short period before we determine that
689 		 * something is a script where text reference is active.
690 		 * The vnode lock is held over this entire period
691 		 * so nothing should illegitimately be blocked.
692 		 */
693 		MPASS(imgp->textset);
694 		VOP_UNSET_TEXT_CHECKED(newtextvp);
695 		imgp->textset = false;
696 		/* free name buffer and old vnode */
697 #ifdef MAC
698 		mac_execve_interpreter_enter(newtextvp, &interpvplabel);
699 #endif
700 		if (imgp->opened) {
701 			VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
702 			imgp->opened = false;
703 		}
704 		vput(newtextvp);
705 		imgp->vp = newtextvp = NULL;
706 		if (args->fname != NULL) {
707 			if (newtextdvp != NULL) {
708 				vrele(newtextdvp);
709 				newtextdvp = NULL;
710 			}
711 			NDFREE(&nd, NDF_ONLY_PNBUF);
712 			free(newbinname, M_PARGS);
713 			newbinname = NULL;
714 		}
715 		vm_object_deallocate(imgp->object);
716 		imgp->object = NULL;
717 		execve_nosetid(imgp);
718 		imgp->execpath = NULL;
719 		free(imgp->freepath, M_TEMP);
720 		imgp->freepath = NULL;
721 		/* set new name to that of the interpreter */
722 		args->fname = imgp->interpreter_name;
723 		goto interpret;
724 	}
725 
726 	/*
727 	 * NB: We unlock the vnode here because it is believed that none
728 	 * of the sv_copyout_strings/sv_fixup operations require the vnode.
729 	 */
730 	VOP_UNLOCK(imgp->vp);
731 
732 	if (disallow_high_osrel &&
733 	    P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
734 		error = ENOEXEC;
735 		uprintf("Osrel %d for image %s too high\n", p->p_osrel,
736 		    imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
737 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
738 		goto exec_fail_dealloc;
739 	}
740 
741 	/*
742 	 * Copy out strings (args and env) and initialize stack base.
743 	 */
744 	error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base);
745 	if (error != 0) {
746 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
747 		goto exec_fail_dealloc;
748 	}
749 
750 	/*
751 	 * Stack setup.
752 	 */
753 	error = (*p->p_sysent->sv_fixup)(&stack_base, imgp);
754 	if (error != 0) {
755 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
756 		goto exec_fail_dealloc;
757 	}
758 
759 	/*
760 	 * For security and other reasons, the file descriptor table cannot be
761 	 * shared after an exec.
762 	 */
763 	fdunshare(td);
764 	pdunshare(td);
765 	/* close files on exec */
766 	fdcloseexec(td);
767 
768 	/*
769 	 * Malloc things before we need locks.
770 	 */
771 	i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv;
772 	/* Cache arguments if they fit inside our allowance */
773 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
774 		newargs = pargs_alloc(i);
775 		bcopy(imgp->args->begin_argv, newargs->ar_args, i);
776 	}
777 
778 	/*
779 	 * For security and other reasons, signal handlers cannot
780 	 * be shared after an exec. The new process gets a copy of the old
781 	 * handlers. In execsigs(), the new process will have its signals
782 	 * reset.
783 	 */
784 	if (sigacts_shared(p->p_sigacts)) {
785 		oldsigacts = p->p_sigacts;
786 		newsigacts = sigacts_alloc();
787 		sigacts_copy(newsigacts, oldsigacts);
788 	}
789 
790 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
791 
792 	PROC_LOCK(p);
793 	if (oldsigacts)
794 		p->p_sigacts = newsigacts;
795 	/* Stop profiling */
796 	stopprofclock(p);
797 
798 	/* reset caught signals */
799 	execsigs(p);
800 
801 	/* name this process - nameiexec(p, ndp) */
802 	bzero(p->p_comm, sizeof(p->p_comm));
803 	if (args->fname)
804 		bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
805 		    min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
806 	else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
807 		bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
808 	bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
809 #ifdef KTR
810 	sched_clear_tdname(td);
811 #endif
812 
813 	/*
814 	 * mark as execed, wakeup the process that vforked (if any) and tell
815 	 * it that it now has its own resources back
816 	 */
817 	p->p_flag |= P_EXEC;
818 	if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
819 		p->p_flag2 &= ~P2_NOTRACE;
820 	if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
821 		p->p_flag2 &= ~P2_STKGAP_DISABLE;
822 	if (p->p_flag & P_PPWAIT) {
823 		p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
824 		cv_broadcast(&p->p_pwait);
825 		/* STOPs are no longer ignored, arrange for AST */
826 		signotify(td);
827 	}
828 
829 	if ((imgp->sysent->sv_setid_allowed != NULL &&
830 	    !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
831 	    (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
832 		execve_nosetid(imgp);
833 
834 	/*
835 	 * Implement image setuid/setgid installation.
836 	 */
837 	if (imgp->credential_setid) {
838 		/*
839 		 * Turn off syscall tracing for set-id programs, except for
840 		 * root.  Record any set-id flags first to make sure that
841 		 * we do not regain any tracing during a possible block.
842 		 */
843 		setsugid(p);
844 #ifdef KTRACE
845 		kiop = ktrprocexec(p);
846 #endif
847 		/*
848 		 * Close any file descriptors 0..2 that reference procfs,
849 		 * then make sure file descriptors 0..2 are in use.
850 		 *
851 		 * Both fdsetugidsafety() and fdcheckstd() may call functions
852 		 * taking sleepable locks, so temporarily drop our locks.
853 		 */
854 		PROC_UNLOCK(p);
855 		VOP_UNLOCK(imgp->vp);
856 		fdsetugidsafety(td);
857 		error = fdcheckstd(td);
858 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
859 		if (error != 0)
860 			goto exec_fail_dealloc;
861 		PROC_LOCK(p);
862 #ifdef MAC
863 		if (will_transition) {
864 			mac_vnode_execve_transition(oldcred, imgp->newcred,
865 			    imgp->vp, interpvplabel, imgp);
866 		}
867 #endif
868 	} else {
869 		if (oldcred->cr_uid == oldcred->cr_ruid &&
870 		    oldcred->cr_gid == oldcred->cr_rgid)
871 			p->p_flag &= ~P_SUGID;
872 	}
873 	/*
874 	 * Set the new credentials.
875 	 */
876 	if (imgp->newcred != NULL) {
877 		proc_set_cred(p, imgp->newcred);
878 		crfree(oldcred);
879 		oldcred = NULL;
880 	}
881 
882 	/*
883 	 * Store the vp for use in kern.proc.pathname.  This vnode was
884 	 * referenced by namei() or fgetvp_exec().
885 	 */
886 	oldtextvp = p->p_textvp;
887 	p->p_textvp = newtextvp;
888 	oldtextdvp = p->p_textdvp;
889 	p->p_textdvp = newtextdvp;
890 	newtextdvp = NULL;
891 	oldbinname = p->p_binname;
892 	p->p_binname = newbinname;
893 	newbinname = NULL;
894 
895 #ifdef KDTRACE_HOOKS
896 	/*
897 	 * Tell the DTrace fasttrap provider about the exec if it
898 	 * has declared an interest.
899 	 */
900 	if (dtrace_fasttrap_exec)
901 		dtrace_fasttrap_exec(p);
902 #endif
903 
904 	/*
905 	 * Notify others that we exec'd, and clear the P_INEXEC flag
906 	 * as we're now a bona fide freshly-execed process.
907 	 */
908 	KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
909 	p->p_flag &= ~P_INEXEC;
910 
911 	/* clear "fork but no exec" flag, as we _are_ execing */
912 	p->p_acflag &= ~AFORK;
913 
914 	/*
915 	 * Free any previous argument cache and replace it with
916 	 * the new argument cache, if any.
917 	 */
918 	oldargs = p->p_args;
919 	p->p_args = newargs;
920 	newargs = NULL;
921 
922 	PROC_UNLOCK(p);
923 
924 #ifdef	HWPMC_HOOKS
925 	/*
926 	 * Check if system-wide sampling is in effect or if the
927 	 * current process is using PMCs.  If so, do exec() time
928 	 * processing.  This processing needs to happen AFTER the
929 	 * P_INEXEC flag is cleared.
930 	 */
931 	if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
932 		VOP_UNLOCK(imgp->vp);
933 		pe.pm_credentialschanged = credential_changing;
934 		pe.pm_entryaddr = imgp->entry_addr;
935 
936 		PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
937 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
938 	}
939 #endif
940 
941 	/* Set values passed into the program in registers. */
942 	(*p->p_sysent->sv_setregs)(td, imgp, stack_base);
943 
944 	VOP_MMAPPED(imgp->vp);
945 
946 	SDT_PROBE1(proc, , , exec__success, args->fname);
947 
948 exec_fail_dealloc:
949 	if (error != 0) {
950 		p->p_osrel = orig_osrel;
951 		p->p_fctl0 = orig_fctl0;
952 		p->p_elf_brandinfo = orig_brandinfo;
953 	}
954 
955 	if (imgp->firstpage != NULL)
956 		exec_unmap_first_page(imgp);
957 
958 	if (imgp->vp != NULL) {
959 		if (imgp->opened)
960 			VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
961 		if (imgp->textset)
962 			VOP_UNSET_TEXT_CHECKED(imgp->vp);
963 		if (error != 0)
964 			vput(imgp->vp);
965 		else
966 			VOP_UNLOCK(imgp->vp);
967 		if (args->fname != NULL)
968 			NDFREE(&nd, NDF_ONLY_PNBUF);
969 		if (newtextdvp != NULL)
970 			vrele(newtextdvp);
971 		free(newbinname, M_PARGS);
972 	}
973 
974 	if (imgp->object != NULL)
975 		vm_object_deallocate(imgp->object);
976 
977 	free(imgp->freepath, M_TEMP);
978 
979 	if (error == 0) {
980 		if (p->p_ptevents & PTRACE_EXEC) {
981 			PROC_LOCK(p);
982 			if (p->p_ptevents & PTRACE_EXEC)
983 				td->td_dbgflags |= TDB_EXEC;
984 			PROC_UNLOCK(p);
985 		}
986 	} else {
987 exec_fail:
988 		/* we're done here, clear P_INEXEC */
989 		PROC_LOCK(p);
990 		p->p_flag &= ~P_INEXEC;
991 		PROC_UNLOCK(p);
992 
993 		SDT_PROBE1(proc, , , exec__failure, error);
994 	}
995 
996 	if (imgp->newcred != NULL && oldcred != NULL)
997 		crfree(imgp->newcred);
998 
999 #ifdef MAC
1000 	mac_execve_exit(imgp);
1001 	mac_execve_interpreter_exit(interpvplabel);
1002 #endif
1003 	exec_free_args(args);
1004 
1005 	/*
1006 	 * Handle deferred decrement of ref counts.
1007 	 */
1008 	if (oldtextvp != NULL)
1009 		vrele(oldtextvp);
1010 	if (oldtextdvp != NULL)
1011 		vrele(oldtextdvp);
1012 	free(oldbinname, M_PARGS);
1013 #ifdef KTRACE
1014 	ktr_io_params_free(kiop);
1015 #endif
1016 	pargs_drop(oldargs);
1017 	pargs_drop(newargs);
1018 	if (oldsigacts != NULL)
1019 		sigacts_free(oldsigacts);
1020 	if (euip != NULL)
1021 		uifree(euip);
1022 
1023 	if (error && imgp->vmspace_destroyed) {
1024 		/* sorry, no more process anymore. exit gracefully */
1025 		exec_cleanup(td, oldvmspace);
1026 		exit1(td, 0, SIGABRT);
1027 		/* NOT REACHED */
1028 	}
1029 
1030 #ifdef KTRACE
1031 	if (error == 0)
1032 		ktrprocctor(p);
1033 #endif
1034 
1035 	/*
1036 	 * We don't want cpu_set_syscall_retval() to overwrite any of
1037 	 * the register values put in place by exec_setregs().
1038 	 * Implementations of cpu_set_syscall_retval() will leave
1039 	 * registers unmodified when returning EJUSTRETURN.
1040 	 */
1041 	return (error == 0 ? EJUSTRETURN : error);
1042 }
1043 
1044 void
1045 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1046 {
1047 	if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1048 		KASSERT(td->td_proc->p_vmspace != oldvmspace,
1049 		    ("oldvmspace still used"));
1050 		vmspace_free(oldvmspace);
1051 		td->td_pflags &= ~TDP_EXECVMSPC;
1052 	}
1053 }
1054 
1055 int
1056 exec_map_first_page(struct image_params *imgp)
1057 {
1058 	vm_object_t object;
1059 	vm_page_t m;
1060 	int error;
1061 
1062 	if (imgp->firstpage != NULL)
1063 		exec_unmap_first_page(imgp);
1064 
1065 	object = imgp->vp->v_object;
1066 	if (object == NULL)
1067 		return (EACCES);
1068 #if VM_NRESERVLEVEL > 0
1069 	if ((object->flags & OBJ_COLORED) == 0) {
1070 		VM_OBJECT_WLOCK(object);
1071 		vm_object_color(object, 0);
1072 		VM_OBJECT_WUNLOCK(object);
1073 	}
1074 #endif
1075 	error = vm_page_grab_valid_unlocked(&m, object, 0,
1076 	    VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1077 	    VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1078 
1079 	if (error != VM_PAGER_OK)
1080 		return (EIO);
1081 	imgp->firstpage = sf_buf_alloc(m, 0);
1082 	imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1083 
1084 	return (0);
1085 }
1086 
1087 void
1088 exec_unmap_first_page(struct image_params *imgp)
1089 {
1090 	vm_page_t m;
1091 
1092 	if (imgp->firstpage != NULL) {
1093 		m = sf_buf_page(imgp->firstpage);
1094 		sf_buf_free(imgp->firstpage);
1095 		imgp->firstpage = NULL;
1096 		vm_page_unwire(m, PQ_ACTIVE);
1097 	}
1098 }
1099 
1100 void
1101 exec_onexec_old(struct thread *td)
1102 {
1103 	sigfastblock_clear(td);
1104 	umtx_exec(td->td_proc);
1105 }
1106 
1107 /*
1108  * This is an optimization which removes the unmanaged shared page
1109  * mapping. In combination with pmap_remove_pages(), which cleans all
1110  * managed mappings in the process' vmspace pmap, no work will be left
1111  * for pmap_remove(min, max).
1112  */
1113 void
1114 exec_free_abi_mappings(struct proc *p)
1115 {
1116 	struct vmspace *vmspace;
1117 	struct sysentvec *sv;
1118 
1119 	vmspace = p->p_vmspace;
1120 	if (refcount_load(&vmspace->vm_refcnt) != 1)
1121 		return;
1122 
1123 	sv = p->p_sysent;
1124 	if (sv->sv_shared_page_obj == NULL)
1125 		return;
1126 
1127 	pmap_remove(vmspace_pmap(vmspace), sv->sv_shared_page_base,
1128 	    sv->sv_shared_page_base + sv->sv_shared_page_len);
1129 }
1130 
1131 /*
1132  * Destroy old address space, and allocate a new stack.
1133  *	The new stack is only sgrowsiz large because it is grown
1134  *	automatically on a page fault.
1135  */
1136 int
1137 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1138 {
1139 	int error;
1140 	struct proc *p = imgp->proc;
1141 	struct vmspace *vmspace = p->p_vmspace;
1142 	struct thread *td = curthread;
1143 	vm_object_t obj;
1144 	struct rlimit rlim_stack;
1145 	vm_offset_t sv_minuser, stack_addr;
1146 	vm_map_t map;
1147 	vm_prot_t stack_prot;
1148 	u_long ssiz;
1149 
1150 	imgp->vmspace_destroyed = true;
1151 	imgp->sysent = sv;
1152 
1153 	if (p->p_sysent->sv_onexec_old != NULL)
1154 		p->p_sysent->sv_onexec_old(td);
1155 	itimers_exec(p);
1156 
1157 	EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1158 
1159 	/*
1160 	 * Blow away entire process VM, if address space not shared,
1161 	 * otherwise, create a new VM space so that other threads are
1162 	 * not disrupted
1163 	 */
1164 	map = &vmspace->vm_map;
1165 	if (map_at_zero)
1166 		sv_minuser = sv->sv_minuser;
1167 	else
1168 		sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1169 	if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1170 	    vm_map_min(map) == sv_minuser &&
1171 	    vm_map_max(map) == sv->sv_maxuser &&
1172 	    cpu_exec_vmspace_reuse(p, map)) {
1173 		exec_free_abi_mappings(p);
1174 		shmexit(vmspace);
1175 		pmap_remove_pages(vmspace_pmap(vmspace));
1176 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1177 		/*
1178 		 * An exec terminates mlockall(MCL_FUTURE).
1179 		 * ASLR and W^X states must be re-evaluated.
1180 		 */
1181 		vm_map_lock(map);
1182 		vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1183 		    MAP_ASLR_IGNSTART | MAP_WXORX);
1184 		vm_map_unlock(map);
1185 	} else {
1186 		error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1187 		if (error)
1188 			return (error);
1189 		vmspace = p->p_vmspace;
1190 		map = &vmspace->vm_map;
1191 	}
1192 	map->flags |= imgp->map_flags;
1193 
1194 	/* Map a shared page */
1195 	obj = sv->sv_shared_page_obj;
1196 	if (obj != NULL) {
1197 		vm_object_reference(obj);
1198 		error = vm_map_fixed(map, obj, 0,
1199 		    sv->sv_shared_page_base, sv->sv_shared_page_len,
1200 		    VM_PROT_READ | VM_PROT_EXECUTE,
1201 		    VM_PROT_READ | VM_PROT_EXECUTE,
1202 		    MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1203 		if (error != KERN_SUCCESS) {
1204 			vm_object_deallocate(obj);
1205 			return (vm_mmap_to_errno(error));
1206 		}
1207 	}
1208 
1209 	/* Allocate a new stack */
1210 	if (imgp->stack_sz != 0) {
1211 		ssiz = trunc_page(imgp->stack_sz);
1212 		PROC_LOCK(p);
1213 		lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1214 		PROC_UNLOCK(p);
1215 		if (ssiz > rlim_stack.rlim_max)
1216 			ssiz = rlim_stack.rlim_max;
1217 		if (ssiz > rlim_stack.rlim_cur) {
1218 			rlim_stack.rlim_cur = ssiz;
1219 			kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1220 		}
1221 	} else if (sv->sv_maxssiz != NULL) {
1222 		ssiz = *sv->sv_maxssiz;
1223 	} else {
1224 		ssiz = maxssiz;
1225 	}
1226 	imgp->eff_stack_sz = lim_cur(curthread, RLIMIT_STACK);
1227 	if (ssiz < imgp->eff_stack_sz)
1228 		imgp->eff_stack_sz = ssiz;
1229 	stack_addr = sv->sv_usrstack - ssiz;
1230 	stack_prot = obj != NULL && imgp->stack_prot != 0 ?
1231 	    imgp->stack_prot : sv->sv_stackprot;
1232 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz, stack_prot,
1233 	    VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1234 	if (error != KERN_SUCCESS) {
1235 		uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1236 		    "failed mach error %d errno %d\n", (uintmax_t)ssiz,
1237 		    stack_prot, error, vm_mmap_to_errno(error));
1238 		return (vm_mmap_to_errno(error));
1239 	}
1240 	vmspace->vm_stkgap = 0;
1241 
1242 	/*
1243 	 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1244 	 * are still used to enforce the stack rlimit on the process stack.
1245 	 */
1246 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1247 	vmspace->vm_maxsaddr = (char *)stack_addr;
1248 
1249 	return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1250 }
1251 
1252 /*
1253  * Copy out argument and environment strings from the old process address
1254  * space into the temporary string buffer.
1255  */
1256 int
1257 exec_copyin_args(struct image_args *args, const char *fname,
1258     enum uio_seg segflg, char **argv, char **envv)
1259 {
1260 	u_long arg, env;
1261 	int error;
1262 
1263 	bzero(args, sizeof(*args));
1264 	if (argv == NULL)
1265 		return (EFAULT);
1266 
1267 	/*
1268 	 * Allocate demand-paged memory for the file name, argument, and
1269 	 * environment strings.
1270 	 */
1271 	error = exec_alloc_args(args);
1272 	if (error != 0)
1273 		return (error);
1274 
1275 	/*
1276 	 * Copy the file name.
1277 	 */
1278 	error = exec_args_add_fname(args, fname, segflg);
1279 	if (error != 0)
1280 		goto err_exit;
1281 
1282 	/*
1283 	 * extract arguments first
1284 	 */
1285 	for (;;) {
1286 		error = fueword(argv++, &arg);
1287 		if (error == -1) {
1288 			error = EFAULT;
1289 			goto err_exit;
1290 		}
1291 		if (arg == 0)
1292 			break;
1293 		error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1294 		    UIO_USERSPACE);
1295 		if (error != 0)
1296 			goto err_exit;
1297 	}
1298 
1299 	/*
1300 	 * extract environment strings
1301 	 */
1302 	if (envv) {
1303 		for (;;) {
1304 			error = fueword(envv++, &env);
1305 			if (error == -1) {
1306 				error = EFAULT;
1307 				goto err_exit;
1308 			}
1309 			if (env == 0)
1310 				break;
1311 			error = exec_args_add_env(args,
1312 			    (char *)(uintptr_t)env, UIO_USERSPACE);
1313 			if (error != 0)
1314 				goto err_exit;
1315 		}
1316 	}
1317 
1318 	return (0);
1319 
1320 err_exit:
1321 	exec_free_args(args);
1322 	return (error);
1323 }
1324 
1325 struct exec_args_kva {
1326 	vm_offset_t addr;
1327 	u_int gen;
1328 	SLIST_ENTRY(exec_args_kva) next;
1329 };
1330 
1331 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1332 
1333 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1334 static struct mtx exec_args_kva_mtx;
1335 static u_int exec_args_gen;
1336 
1337 static void
1338 exec_prealloc_args_kva(void *arg __unused)
1339 {
1340 	struct exec_args_kva *argkva;
1341 	u_int i;
1342 
1343 	SLIST_INIT(&exec_args_kva_freelist);
1344 	mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1345 	for (i = 0; i < exec_map_entries; i++) {
1346 		argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1347 		argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size);
1348 		argkva->gen = exec_args_gen;
1349 		SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1350 	}
1351 }
1352 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1353 
1354 static vm_offset_t
1355 exec_alloc_args_kva(void **cookie)
1356 {
1357 	struct exec_args_kva *argkva;
1358 
1359 	argkva = (void *)atomic_readandclear_ptr(
1360 	    (uintptr_t *)DPCPU_PTR(exec_args_kva));
1361 	if (argkva == NULL) {
1362 		mtx_lock(&exec_args_kva_mtx);
1363 		while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1364 			(void)mtx_sleep(&exec_args_kva_freelist,
1365 			    &exec_args_kva_mtx, 0, "execkva", 0);
1366 		SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1367 		mtx_unlock(&exec_args_kva_mtx);
1368 	}
1369 	kasan_mark((void *)argkva->addr, exec_map_entry_size,
1370 	    exec_map_entry_size, 0);
1371 	*(struct exec_args_kva **)cookie = argkva;
1372 	return (argkva->addr);
1373 }
1374 
1375 static void
1376 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1377 {
1378 	vm_offset_t base;
1379 
1380 	base = argkva->addr;
1381 	kasan_mark((void *)argkva->addr, 0, exec_map_entry_size,
1382 	    KASAN_EXEC_ARGS_FREED);
1383 	if (argkva->gen != gen) {
1384 		(void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1385 		    MADV_FREE);
1386 		argkva->gen = gen;
1387 	}
1388 	if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1389 	    (uintptr_t)NULL, (uintptr_t)argkva)) {
1390 		mtx_lock(&exec_args_kva_mtx);
1391 		SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1392 		wakeup_one(&exec_args_kva_freelist);
1393 		mtx_unlock(&exec_args_kva_mtx);
1394 	}
1395 }
1396 
1397 static void
1398 exec_free_args_kva(void *cookie)
1399 {
1400 
1401 	exec_release_args_kva(cookie, exec_args_gen);
1402 }
1403 
1404 static void
1405 exec_args_kva_lowmem(void *arg __unused)
1406 {
1407 	SLIST_HEAD(, exec_args_kva) head;
1408 	struct exec_args_kva *argkva;
1409 	u_int gen;
1410 	int i;
1411 
1412 	gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1413 
1414 	/*
1415 	 * Force an madvise of each KVA range. Any currently allocated ranges
1416 	 * will have MADV_FREE applied once they are freed.
1417 	 */
1418 	SLIST_INIT(&head);
1419 	mtx_lock(&exec_args_kva_mtx);
1420 	SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1421 	mtx_unlock(&exec_args_kva_mtx);
1422 	while ((argkva = SLIST_FIRST(&head)) != NULL) {
1423 		SLIST_REMOVE_HEAD(&head, next);
1424 		exec_release_args_kva(argkva, gen);
1425 	}
1426 
1427 	CPU_FOREACH(i) {
1428 		argkva = (void *)atomic_readandclear_ptr(
1429 		    (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1430 		if (argkva != NULL)
1431 			exec_release_args_kva(argkva, gen);
1432 	}
1433 }
1434 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1435     EVENTHANDLER_PRI_ANY);
1436 
1437 /*
1438  * Allocate temporary demand-paged, zero-filled memory for the file name,
1439  * argument, and environment strings.
1440  */
1441 int
1442 exec_alloc_args(struct image_args *args)
1443 {
1444 
1445 	args->buf = (char *)exec_alloc_args_kva(&args->bufkva);
1446 	return (0);
1447 }
1448 
1449 void
1450 exec_free_args(struct image_args *args)
1451 {
1452 
1453 	if (args->buf != NULL) {
1454 		exec_free_args_kva(args->bufkva);
1455 		args->buf = NULL;
1456 	}
1457 	if (args->fname_buf != NULL) {
1458 		free(args->fname_buf, M_TEMP);
1459 		args->fname_buf = NULL;
1460 	}
1461 }
1462 
1463 /*
1464  * A set to functions to fill struct image args.
1465  *
1466  * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1467  * fname) before the other functions.  All exec_args_add_arg() calls must
1468  * be made before any exec_args_add_env() calls.  exec_args_adjust_args()
1469  * may be called any time after exec_args_add_fname().
1470  *
1471  * exec_args_add_fname() - install path to be executed
1472  * exec_args_add_arg() - append an argument string
1473  * exec_args_add_env() - append an env string
1474  * exec_args_adjust_args() - adjust location of the argument list to
1475  *                           allow new arguments to be prepended
1476  */
1477 int
1478 exec_args_add_fname(struct image_args *args, const char *fname,
1479     enum uio_seg segflg)
1480 {
1481 	int error;
1482 	size_t length;
1483 
1484 	KASSERT(args->fname == NULL, ("fname already appended"));
1485 	KASSERT(args->endp == NULL, ("already appending to args"));
1486 
1487 	if (fname != NULL) {
1488 		args->fname = args->buf;
1489 		error = segflg == UIO_SYSSPACE ?
1490 		    copystr(fname, args->fname, PATH_MAX, &length) :
1491 		    copyinstr(fname, args->fname, PATH_MAX, &length);
1492 		if (error != 0)
1493 			return (error == ENAMETOOLONG ? E2BIG : error);
1494 	} else
1495 		length = 0;
1496 
1497 	/* Set up for _arg_*()/_env_*() */
1498 	args->endp = args->buf + length;
1499 	/* begin_argv must be set and kept updated */
1500 	args->begin_argv = args->endp;
1501 	KASSERT(exec_map_entry_size - length >= ARG_MAX,
1502 	    ("too little space remaining for arguments %zu < %zu",
1503 	    exec_map_entry_size - length, (size_t)ARG_MAX));
1504 	args->stringspace = ARG_MAX;
1505 
1506 	return (0);
1507 }
1508 
1509 static int
1510 exec_args_add_str(struct image_args *args, const char *str,
1511     enum uio_seg segflg, int *countp)
1512 {
1513 	int error;
1514 	size_t length;
1515 
1516 	KASSERT(args->endp != NULL, ("endp not initialized"));
1517 	KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1518 
1519 	error = (segflg == UIO_SYSSPACE) ?
1520 	    copystr(str, args->endp, args->stringspace, &length) :
1521 	    copyinstr(str, args->endp, args->stringspace, &length);
1522 	if (error != 0)
1523 		return (error == ENAMETOOLONG ? E2BIG : error);
1524 	args->stringspace -= length;
1525 	args->endp += length;
1526 	(*countp)++;
1527 
1528 	return (0);
1529 }
1530 
1531 int
1532 exec_args_add_arg(struct image_args *args, const char *argp,
1533     enum uio_seg segflg)
1534 {
1535 
1536 	KASSERT(args->envc == 0, ("appending args after env"));
1537 
1538 	return (exec_args_add_str(args, argp, segflg, &args->argc));
1539 }
1540 
1541 int
1542 exec_args_add_env(struct image_args *args, const char *envp,
1543     enum uio_seg segflg)
1544 {
1545 
1546 	if (args->envc == 0)
1547 		args->begin_envv = args->endp;
1548 
1549 	return (exec_args_add_str(args, envp, segflg, &args->envc));
1550 }
1551 
1552 int
1553 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1554 {
1555 	ssize_t offset;
1556 
1557 	KASSERT(args->endp != NULL, ("endp not initialized"));
1558 	KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1559 
1560 	offset = extend - consume;
1561 	if (args->stringspace < offset)
1562 		return (E2BIG);
1563 	memmove(args->begin_argv + extend, args->begin_argv + consume,
1564 	    args->endp - args->begin_argv + consume);
1565 	if (args->envc > 0)
1566 		args->begin_envv += offset;
1567 	args->endp += offset;
1568 	args->stringspace -= offset;
1569 	return (0);
1570 }
1571 
1572 char *
1573 exec_args_get_begin_envv(struct image_args *args)
1574 {
1575 
1576 	KASSERT(args->endp != NULL, ("endp not initialized"));
1577 
1578 	if (args->envc > 0)
1579 		return (args->begin_envv);
1580 	return (args->endp);
1581 }
1582 
1583 void
1584 exec_stackgap(struct image_params *imgp, uintptr_t *dp)
1585 {
1586 	struct proc *p = imgp->proc;
1587 
1588 	if (imgp->sysent->sv_stackgap == NULL ||
1589 	    (p->p_fctl0 & (NT_FREEBSD_FCTL_ASLR_DISABLE |
1590 	    NT_FREEBSD_FCTL_ASG_DISABLE)) != 0 ||
1591 	    (imgp->map_flags & MAP_ASLR) == 0) {
1592 		p->p_vmspace->vm_stkgap = 0;
1593 		return;
1594 	}
1595 	p->p_vmspace->vm_stkgap = imgp->sysent->sv_stackgap(imgp, dp);
1596 }
1597 
1598 /*
1599  * Copy strings out to the new process address space, constructing new arg
1600  * and env vector tables. Return a pointer to the base so that it can be used
1601  * as the initial stack pointer.
1602  */
1603 int
1604 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1605 {
1606 	int argc, envc;
1607 	char **vectp;
1608 	char *stringp;
1609 	uintptr_t destp, ustringp;
1610 	struct ps_strings *arginfo;
1611 	struct proc *p;
1612 	size_t execpath_len;
1613 	int error, szsigcode, szps;
1614 	char canary[sizeof(long) * 8];
1615 
1616 	szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1617 	/*
1618 	 * Calculate string base and vector table pointers.
1619 	 * Also deal with signal trampoline code for this exec type.
1620 	 */
1621 	if (imgp->execpath != NULL && imgp->auxargs != NULL)
1622 		execpath_len = strlen(imgp->execpath) + 1;
1623 	else
1624 		execpath_len = 0;
1625 	p = imgp->proc;
1626 	szsigcode = 0;
1627 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1628 	imgp->ps_strings = arginfo;
1629 	if (p->p_sysent->sv_sigcode_base == 0) {
1630 		if (p->p_sysent->sv_szsigcode != NULL)
1631 			szsigcode = *(p->p_sysent->sv_szsigcode);
1632 	}
1633 	destp =	(uintptr_t)arginfo;
1634 
1635 	/*
1636 	 * install sigcode
1637 	 */
1638 	if (szsigcode != 0) {
1639 		destp -= szsigcode;
1640 		destp = rounddown2(destp, sizeof(void *));
1641 		error = copyout(p->p_sysent->sv_sigcode, (void *)destp,
1642 		    szsigcode);
1643 		if (error != 0)
1644 			return (error);
1645 	}
1646 
1647 	/*
1648 	 * Copy the image path for the rtld.
1649 	 */
1650 	if (execpath_len != 0) {
1651 		destp -= execpath_len;
1652 		destp = rounddown2(destp, sizeof(void *));
1653 		imgp->execpathp = (void *)destp;
1654 		error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1655 		if (error != 0)
1656 			return (error);
1657 	}
1658 
1659 	/*
1660 	 * Prepare the canary for SSP.
1661 	 */
1662 	arc4rand(canary, sizeof(canary), 0);
1663 	destp -= sizeof(canary);
1664 	imgp->canary = (void *)destp;
1665 	error = copyout(canary, imgp->canary, sizeof(canary));
1666 	if (error != 0)
1667 		return (error);
1668 	imgp->canarylen = sizeof(canary);
1669 
1670 	/*
1671 	 * Prepare the pagesizes array.
1672 	 */
1673 	destp -= szps;
1674 	destp = rounddown2(destp, sizeof(void *));
1675 	imgp->pagesizes = (void *)destp;
1676 	error = copyout(pagesizes, imgp->pagesizes, szps);
1677 	if (error != 0)
1678 		return (error);
1679 	imgp->pagesizeslen = szps;
1680 
1681 	/*
1682 	 * Allocate room for the argument and environment strings.
1683 	 */
1684 	destp -= ARG_MAX - imgp->args->stringspace;
1685 	destp = rounddown2(destp, sizeof(void *));
1686 	ustringp = destp;
1687 
1688 	exec_stackgap(imgp, &destp);
1689 
1690 	if (imgp->auxargs) {
1691 		/*
1692 		 * Allocate room on the stack for the ELF auxargs
1693 		 * array.  It has up to AT_COUNT entries.
1694 		 */
1695 		destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1696 		destp = rounddown2(destp, sizeof(void *));
1697 	}
1698 
1699 	vectp = (char **)destp;
1700 
1701 	/*
1702 	 * Allocate room for the argv[] and env vectors including the
1703 	 * terminating NULL pointers.
1704 	 */
1705 	vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1706 
1707 	/*
1708 	 * vectp also becomes our initial stack base
1709 	 */
1710 	*stack_base = (uintptr_t)vectp;
1711 
1712 	stringp = imgp->args->begin_argv;
1713 	argc = imgp->args->argc;
1714 	envc = imgp->args->envc;
1715 
1716 	/*
1717 	 * Copy out strings - arguments and environment.
1718 	 */
1719 	error = copyout(stringp, (void *)ustringp,
1720 	    ARG_MAX - imgp->args->stringspace);
1721 	if (error != 0)
1722 		return (error);
1723 
1724 	/*
1725 	 * Fill in "ps_strings" struct for ps, w, etc.
1726 	 */
1727 	imgp->argv = vectp;
1728 	if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1729 	    suword32(&arginfo->ps_nargvstr, argc) != 0)
1730 		return (EFAULT);
1731 
1732 	/*
1733 	 * Fill in argument portion of vector table.
1734 	 */
1735 	for (; argc > 0; --argc) {
1736 		if (suword(vectp++, ustringp) != 0)
1737 			return (EFAULT);
1738 		while (*stringp++ != 0)
1739 			ustringp++;
1740 		ustringp++;
1741 	}
1742 
1743 	/* a null vector table pointer separates the argp's from the envp's */
1744 	if (suword(vectp++, 0) != 0)
1745 		return (EFAULT);
1746 
1747 	imgp->envv = vectp;
1748 	if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1749 	    suword32(&arginfo->ps_nenvstr, envc) != 0)
1750 		return (EFAULT);
1751 
1752 	/*
1753 	 * Fill in environment portion of vector table.
1754 	 */
1755 	for (; envc > 0; --envc) {
1756 		if (suword(vectp++, ustringp) != 0)
1757 			return (EFAULT);
1758 		while (*stringp++ != 0)
1759 			ustringp++;
1760 		ustringp++;
1761 	}
1762 
1763 	/* end of vector table is a null pointer */
1764 	if (suword(vectp, 0) != 0)
1765 		return (EFAULT);
1766 
1767 	if (imgp->auxargs) {
1768 		vectp++;
1769 		error = imgp->sysent->sv_copyout_auxargs(imgp,
1770 		    (uintptr_t)vectp);
1771 		if (error != 0)
1772 			return (error);
1773 	}
1774 
1775 	return (0);
1776 }
1777 
1778 /*
1779  * Check permissions of file to execute.
1780  *	Called with imgp->vp locked.
1781  *	Return 0 for success or error code on failure.
1782  */
1783 int
1784 exec_check_permissions(struct image_params *imgp)
1785 {
1786 	struct vnode *vp = imgp->vp;
1787 	struct vattr *attr = imgp->attr;
1788 	struct thread *td;
1789 	int error;
1790 
1791 	td = curthread;
1792 
1793 	/* Get file attributes */
1794 	error = VOP_GETATTR(vp, attr, td->td_ucred);
1795 	if (error)
1796 		return (error);
1797 
1798 #ifdef MAC
1799 	error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1800 	if (error)
1801 		return (error);
1802 #endif
1803 
1804 	/*
1805 	 * 1) Check if file execution is disabled for the filesystem that
1806 	 *    this file resides on.
1807 	 * 2) Ensure that at least one execute bit is on. Otherwise, a
1808 	 *    privileged user will always succeed, and we don't want this
1809 	 *    to happen unless the file really is executable.
1810 	 * 3) Ensure that the file is a regular file.
1811 	 */
1812 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1813 	    (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1814 	    (attr->va_type != VREG))
1815 		return (EACCES);
1816 
1817 	/*
1818 	 * Zero length files can't be exec'd
1819 	 */
1820 	if (attr->va_size == 0)
1821 		return (ENOEXEC);
1822 
1823 	/*
1824 	 *  Check for execute permission to file based on current credentials.
1825 	 */
1826 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1827 	if (error)
1828 		return (error);
1829 
1830 	/*
1831 	 * Check number of open-for-writes on the file and deny execution
1832 	 * if there are any.
1833 	 *
1834 	 * Add a text reference now so no one can write to the
1835 	 * executable while we're activating it.
1836 	 *
1837 	 * Remember if this was set before and unset it in case this is not
1838 	 * actually an executable image.
1839 	 */
1840 	error = VOP_SET_TEXT(vp);
1841 	if (error != 0)
1842 		return (error);
1843 	imgp->textset = true;
1844 
1845 	/*
1846 	 * Call filesystem specific open routine (which does nothing in the
1847 	 * general case).
1848 	 */
1849 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1850 	if (error == 0)
1851 		imgp->opened = true;
1852 	return (error);
1853 }
1854 
1855 /*
1856  * Exec handler registration
1857  */
1858 int
1859 exec_register(const struct execsw *execsw_arg)
1860 {
1861 	const struct execsw **es, **xs, **newexecsw;
1862 	u_int count = 2;	/* New slot and trailing NULL */
1863 
1864 	if (execsw)
1865 		for (es = execsw; *es; es++)
1866 			count++;
1867 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1868 	xs = newexecsw;
1869 	if (execsw)
1870 		for (es = execsw; *es; es++)
1871 			*xs++ = *es;
1872 	*xs++ = execsw_arg;
1873 	*xs = NULL;
1874 	if (execsw)
1875 		free(execsw, M_TEMP);
1876 	execsw = newexecsw;
1877 	return (0);
1878 }
1879 
1880 int
1881 exec_unregister(const struct execsw *execsw_arg)
1882 {
1883 	const struct execsw **es, **xs, **newexecsw;
1884 	int count = 1;
1885 
1886 	if (execsw == NULL)
1887 		panic("unregister with no handlers left?\n");
1888 
1889 	for (es = execsw; *es; es++) {
1890 		if (*es == execsw_arg)
1891 			break;
1892 	}
1893 	if (*es == NULL)
1894 		return (ENOENT);
1895 	for (es = execsw; *es; es++)
1896 		if (*es != execsw_arg)
1897 			count++;
1898 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1899 	xs = newexecsw;
1900 	for (es = execsw; *es; es++)
1901 		if (*es != execsw_arg)
1902 			*xs++ = *es;
1903 	*xs = NULL;
1904 	if (execsw)
1905 		free(execsw, M_TEMP);
1906 	execsw = newexecsw;
1907 	return (0);
1908 }
1909 
1910 /*
1911  * Write out a core segment to the compression stream.
1912  */
1913 static int
1914 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
1915 {
1916 	size_t chunk_len;
1917 	int error;
1918 
1919 	while (len > 0) {
1920 		chunk_len = MIN(len, CORE_BUF_SIZE);
1921 
1922 		/*
1923 		 * We can get EFAULT error here.
1924 		 * In that case zero out the current chunk of the segment.
1925 		 */
1926 		error = copyin(base, buf, chunk_len);
1927 		if (error != 0)
1928 			bzero(buf, chunk_len);
1929 		error = compressor_write(cp->comp, buf, chunk_len);
1930 		if (error != 0)
1931 			break;
1932 		base += chunk_len;
1933 		len -= chunk_len;
1934 	}
1935 	return (error);
1936 }
1937 
1938 int
1939 core_write(struct coredump_params *cp, const void *base, size_t len,
1940     off_t offset, enum uio_seg seg, size_t *resid)
1941 {
1942 
1943 	return (vn_rdwr_inchunks(UIO_WRITE, cp->vp, __DECONST(void *, base),
1944 	    len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1945 	    cp->active_cred, cp->file_cred, resid, cp->td));
1946 }
1947 
1948 int
1949 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
1950     void *tmpbuf)
1951 {
1952 	vm_map_t map;
1953 	struct mount *mp;
1954 	size_t resid, runlen;
1955 	int error;
1956 	bool success;
1957 
1958 	KASSERT((uintptr_t)base % PAGE_SIZE == 0,
1959 	    ("%s: user address %p is not page-aligned", __func__, base));
1960 
1961 	if (cp->comp != NULL)
1962 		return (compress_chunk(cp, base, tmpbuf, len));
1963 
1964 	map = &cp->td->td_proc->p_vmspace->vm_map;
1965 	for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
1966 		/*
1967 		 * Attempt to page in all virtual pages in the range.  If a
1968 		 * virtual page is not backed by the pager, it is represented as
1969 		 * a hole in the file.  This can occur with zero-filled
1970 		 * anonymous memory or truncated files, for example.
1971 		 */
1972 		for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
1973 			if (core_dump_can_intr && curproc_sigkilled())
1974 				return (EINTR);
1975 			error = vm_fault(map, (uintptr_t)base + runlen,
1976 			    VM_PROT_READ, VM_FAULT_NOFILL, NULL);
1977 			if (runlen == 0)
1978 				success = error == KERN_SUCCESS;
1979 			else if ((error == KERN_SUCCESS) != success)
1980 				break;
1981 		}
1982 
1983 		if (success) {
1984 			error = core_write(cp, base, runlen, offset,
1985 			    UIO_USERSPACE, &resid);
1986 			if (error != 0) {
1987 				if (error != EFAULT)
1988 					break;
1989 
1990 				/*
1991 				 * EFAULT may be returned if the user mapping
1992 				 * could not be accessed, e.g., because a mapped
1993 				 * file has been truncated.  Skip the page if no
1994 				 * progress was made, to protect against a
1995 				 * hypothetical scenario where vm_fault() was
1996 				 * successful but core_write() returns EFAULT
1997 				 * anyway.
1998 				 */
1999 				runlen -= resid;
2000 				if (runlen == 0) {
2001 					success = false;
2002 					runlen = PAGE_SIZE;
2003 				}
2004 			}
2005 		}
2006 		if (!success) {
2007 			error = vn_start_write(cp->vp, &mp, V_WAIT);
2008 			if (error != 0)
2009 				break;
2010 			vn_lock(cp->vp, LK_EXCLUSIVE | LK_RETRY);
2011 			error = vn_truncate_locked(cp->vp, offset + runlen,
2012 			    false, cp->td->td_ucred);
2013 			VOP_UNLOCK(cp->vp);
2014 			vn_finished_write(mp);
2015 			if (error != 0)
2016 				break;
2017 		}
2018 	}
2019 	return (error);
2020 }
2021 
2022 /*
2023  * Drain into a core file.
2024  */
2025 int
2026 sbuf_drain_core_output(void *arg, const char *data, int len)
2027 {
2028 	struct coredump_params *cp;
2029 	struct proc *p;
2030 	int error, locked;
2031 
2032 	cp = arg;
2033 	p = cp->td->td_proc;
2034 
2035 	/*
2036 	 * Some kern_proc out routines that print to this sbuf may
2037 	 * call us with the process lock held. Draining with the
2038 	 * non-sleepable lock held is unsafe. The lock is needed for
2039 	 * those routines when dumping a live process. In our case we
2040 	 * can safely release the lock before draining and acquire
2041 	 * again after.
2042 	 */
2043 	locked = PROC_LOCKED(p);
2044 	if (locked)
2045 		PROC_UNLOCK(p);
2046 	if (cp->comp != NULL)
2047 		error = compressor_write(cp->comp, __DECONST(char *, data),
2048 		    len);
2049 	else
2050 		error = core_write(cp, __DECONST(void *, data), len, cp->offset,
2051 		    UIO_SYSSPACE, NULL);
2052 	if (locked)
2053 		PROC_LOCK(p);
2054 	if (error != 0)
2055 		return (-error);
2056 	cp->offset += len;
2057 	return (len);
2058 }
2059