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