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