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