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