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