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