xref: /freebsd/sys/kern/kern_exec.c (revision 4a5216a6dc0c3ce4cf5f2d3ee8af0c3ff3402c4f)
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_hwpmc_hooks.h"
31 #include "opt_kdtrace.h"
32 #include "opt_ktrace.h"
33 #include "opt_mac.h"
34 #include "opt_vm.h"
35 
36 #include <sys/param.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/sdt.h>
59 #include <sys/sf_buf.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysent.h>
62 #include <sys/shm.h>
63 #include <sys/sysctl.h>
64 #include <sys/vnode.h>
65 #include <sys/stat.h>
66 #ifdef KTRACE
67 #include <sys/ktrace.h>
68 #endif
69 
70 #include <vm/vm.h>
71 #include <vm/vm_param.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_page.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_extern.h>
77 #include <vm/vm_object.h>
78 #include <vm/vm_pager.h>
79 
80 #ifdef	HWPMC_HOOKS
81 #include <sys/pmckern.h>
82 #endif
83 
84 #include <machine/reg.h>
85 
86 #include <security/audit/audit.h>
87 #include <security/mac/mac_framework.h>
88 
89 #ifdef KDTRACE_HOOKS
90 #include <sys/dtrace_bsd.h>
91 dtrace_execexit_func_t	dtrace_fasttrap_exec;
92 #endif
93 
94 SDT_PROVIDER_DECLARE(proc);
95 SDT_PROBE_DEFINE(proc, kernel, , exec);
96 SDT_PROBE_ARGTYPE(proc, kernel, , exec, 0, "char *");
97 SDT_PROBE_DEFINE(proc, kernel, , exec_failure);
98 SDT_PROBE_ARGTYPE(proc, kernel, , exec_failure, 0, "int");
99 SDT_PROBE_DEFINE(proc, kernel, , exec_success);
100 SDT_PROBE_ARGTYPE(proc, kernel, , exec_success, 0, "char *");
101 
102 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
103 
104 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
105 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
106 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
107 static int do_execve(struct thread *td, struct image_args *args,
108     struct mac *mac_p);
109 static void exec_free_args(struct image_args *);
110 
111 /* XXX This should be vm_size_t. */
112 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
113     NULL, 0, sysctl_kern_ps_strings, "LU", "");
114 
115 /* XXX This should be vm_size_t. */
116 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD,
117     NULL, 0, sysctl_kern_usrstack, "LU", "");
118 
119 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
120     NULL, 0, sysctl_kern_stackprot, "I", "");
121 
122 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
123 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
124     &ps_arg_cache_limit, 0, "");
125 
126 static int
127 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
128 {
129 	struct proc *p;
130 	int error;
131 
132 	p = curproc;
133 #ifdef SCTL_MASK32
134 	if (req->flags & SCTL_MASK32) {
135 		unsigned int val;
136 		val = (unsigned int)p->p_sysent->sv_psstrings;
137 		error = SYSCTL_OUT(req, &val, sizeof(val));
138 	} else
139 #endif
140 		error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
141 		   sizeof(p->p_sysent->sv_psstrings));
142 	return error;
143 }
144 
145 static int
146 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
147 {
148 	struct proc *p;
149 	int error;
150 
151 	p = curproc;
152 #ifdef SCTL_MASK32
153 	if (req->flags & SCTL_MASK32) {
154 		unsigned int val;
155 		val = (unsigned int)p->p_sysent->sv_usrstack;
156 		error = SYSCTL_OUT(req, &val, sizeof(val));
157 	} else
158 #endif
159 		error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
160 		    sizeof(p->p_sysent->sv_usrstack));
161 	return error;
162 }
163 
164 static int
165 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
166 {
167 	struct proc *p;
168 
169 	p = curproc;
170 	return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
171 	    sizeof(p->p_sysent->sv_stackprot)));
172 }
173 
174 /*
175  * Each of the items is a pointer to a `const struct execsw', hence the
176  * double pointer here.
177  */
178 static const struct execsw **execsw;
179 
180 #ifndef _SYS_SYSPROTO_H_
181 struct execve_args {
182 	char    *fname;
183 	char    **argv;
184 	char    **envv;
185 };
186 #endif
187 
188 int
189 execve(td, uap)
190 	struct thread *td;
191 	struct execve_args /* {
192 		char *fname;
193 		char **argv;
194 		char **envv;
195 	} */ *uap;
196 {
197 	int error;
198 	struct image_args args;
199 
200 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
201 	    uap->argv, uap->envv);
202 	if (error == 0)
203 		error = kern_execve(td, &args, NULL);
204 	return (error);
205 }
206 
207 #ifndef _SYS_SYSPROTO_H_
208 struct fexecve_args {
209 	int	fd;
210 	char	**argv;
211 	char	**envv;
212 }
213 #endif
214 int
215 fexecve(struct thread *td, struct fexecve_args *uap)
216 {
217 	int error;
218 	struct image_args args;
219 
220 	error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
221 	    uap->argv, uap->envv);
222 	if (error == 0) {
223 		args.fd = uap->fd;
224 		error = kern_execve(td, &args, NULL);
225 	}
226 	return (error);
227 }
228 
229 #ifndef _SYS_SYSPROTO_H_
230 struct __mac_execve_args {
231 	char	*fname;
232 	char	**argv;
233 	char	**envv;
234 	struct mac	*mac_p;
235 };
236 #endif
237 
238 int
239 __mac_execve(td, uap)
240 	struct thread *td;
241 	struct __mac_execve_args /* {
242 		char *fname;
243 		char **argv;
244 		char **envv;
245 		struct mac *mac_p;
246 	} */ *uap;
247 {
248 #ifdef MAC
249 	int error;
250 	struct image_args args;
251 
252 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
253 	    uap->argv, uap->envv);
254 	if (error == 0)
255 		error = kern_execve(td, &args, uap->mac_p);
256 	return (error);
257 #else
258 	return (ENOSYS);
259 #endif
260 }
261 
262 /*
263  * XXX: kern_execve has the astonishing property of not always returning to
264  * the caller.  If sufficiently bad things happen during the call to
265  * do_execve(), it can end up calling exit1(); as a result, callers must
266  * avoid doing anything which they might need to undo (e.g., allocating
267  * memory).
268  */
269 int
270 kern_execve(td, args, mac_p)
271 	struct thread *td;
272 	struct image_args *args;
273 	struct mac *mac_p;
274 {
275 	struct proc *p = td->td_proc;
276 	int error;
277 
278 	AUDIT_ARG(argv, args->begin_argv, args->argc,
279 	    args->begin_envv - args->begin_argv);
280 	AUDIT_ARG(envv, args->begin_envv, args->envc,
281 	    args->endp - args->begin_envv);
282 	if (p->p_flag & P_HADTHREADS) {
283 		PROC_LOCK(p);
284 		if (thread_single(SINGLE_BOUNDARY)) {
285 			PROC_UNLOCK(p);
286 	       		exec_free_args(args);
287 			return (ERESTART);	/* Try again later. */
288 		}
289 		PROC_UNLOCK(p);
290 	}
291 
292 	error = do_execve(td, args, mac_p);
293 
294 	if (p->p_flag & P_HADTHREADS) {
295 		PROC_LOCK(p);
296 		/*
297 		 * If success, we upgrade to SINGLE_EXIT state to
298 		 * force other threads to suicide.
299 		 */
300 		if (error == 0)
301 			thread_single(SINGLE_EXIT);
302 		else
303 			thread_single_end();
304 		PROC_UNLOCK(p);
305 	}
306 
307 	return (error);
308 }
309 
310 /*
311  * In-kernel implementation of execve().  All arguments are assumed to be
312  * userspace pointers from the passed thread.
313  */
314 static int
315 do_execve(td, args, mac_p)
316 	struct thread *td;
317 	struct image_args *args;
318 	struct mac *mac_p;
319 {
320 	struct proc *p = td->td_proc;
321 	struct nameidata nd, *ndp;
322 	struct ucred *newcred = NULL, *oldcred;
323 	struct uidinfo *euip;
324 	register_t *stack_base;
325 	int error, len = 0, i;
326 	struct image_params image_params, *imgp;
327 	struct vattr attr;
328 	int (*img_first)(struct image_params *);
329 	struct pargs *oldargs = NULL, *newargs = NULL;
330 	struct sigacts *oldsigacts, *newsigacts;
331 #ifdef KTRACE
332 	struct vnode *tracevp = NULL;
333 	struct ucred *tracecred = NULL;
334 #endif
335 	struct vnode *textvp = NULL, *binvp = NULL;
336 	int credential_changing;
337 	int vfslocked;
338 	int textset;
339 #ifdef MAC
340 	struct label *interpvplabel = NULL;
341 	int will_transition;
342 #endif
343 #ifdef HWPMC_HOOKS
344 	struct pmckern_procexec pe;
345 #endif
346 	static const char fexecv_proc_title[] = "(fexecv)";
347 
348 	vfslocked = 0;
349 	imgp = &image_params;
350 
351 	/*
352 	 * Lock the process and set the P_INEXEC flag to indicate that
353 	 * it should be left alone until we're done here.  This is
354 	 * necessary to avoid race conditions - e.g. in ptrace() -
355 	 * that might allow a local user to illicitly obtain elevated
356 	 * privileges.
357 	 */
358 	PROC_LOCK(p);
359 	KASSERT((p->p_flag & P_INEXEC) == 0,
360 	    ("%s(): process already has P_INEXEC flag", __func__));
361 	p->p_flag |= P_INEXEC;
362 	PROC_UNLOCK(p);
363 
364 	/*
365 	 * Initialize part of the common data
366 	 */
367 	imgp->proc = p;
368 	imgp->execlabel = NULL;
369 	imgp->attr = &attr;
370 	imgp->entry_addr = 0;
371 	imgp->vmspace_destroyed = 0;
372 	imgp->interpreted = 0;
373 	imgp->opened = 0;
374 	imgp->interpreter_name = args->buf + PATH_MAX + ARG_MAX;
375 	imgp->auxargs = NULL;
376 	imgp->vp = NULL;
377 	imgp->object = NULL;
378 	imgp->firstpage = NULL;
379 	imgp->ps_strings = 0;
380 	imgp->auxarg_size = 0;
381 	imgp->args = args;
382 
383 #ifdef MAC
384 	error = mac_execve_enter(imgp, mac_p);
385 	if (error)
386 		goto exec_fail;
387 #endif
388 
389 	imgp->image_header = NULL;
390 
391 	SDT_PROBE(proc, kernel, , exec, args->fname, 0, 0, 0, 0 );
392 
393 	/*
394 	 * Translate the file name. namei() returns a vnode pointer
395 	 *	in ni_vp amoung other things.
396 	 *
397 	 * XXXAUDIT: It would be desirable to also audit the name of the
398 	 * interpreter if this is an interpreted binary.
399 	 */
400 	if (args->fname != NULL) {
401 		ndp = &nd;
402 		NDINIT(ndp, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
403 		    | MPSAFE | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
404 	}
405 
406 interpret:
407 	if (args->fname != NULL) {
408 		error = namei(ndp);
409 		if (error)
410 			goto exec_fail;
411 
412 		vfslocked = NDHASGIANT(ndp);
413 		binvp  = ndp->ni_vp;
414 		imgp->vp = binvp;
415 	} else {
416 		AUDIT_ARG(fd, args->fd);
417 		error = fgetvp(td, args->fd, &binvp);
418 		if (error)
419 			goto exec_fail;
420 		vfslocked = VFS_LOCK_GIANT(binvp->v_mount);
421 		vn_lock(binvp, LK_EXCLUSIVE | LK_RETRY);
422 		AUDIT_ARG(vnode, binvp, ARG_VNODE1);
423 		imgp->vp = binvp;
424 	}
425 
426 	/*
427 	 * Check file permissions (also 'opens' file)
428 	 */
429 	error = exec_check_permissions(imgp);
430 	if (error)
431 		goto exec_fail_dealloc;
432 
433 	imgp->object = imgp->vp->v_object;
434 	if (imgp->object != NULL)
435 		vm_object_reference(imgp->object);
436 
437 	/*
438 	 * Set VV_TEXT now so no one can write to the executable while we're
439 	 * activating it.
440 	 *
441 	 * Remember if this was set before and unset it in case this is not
442 	 * actually an executable image.
443 	 */
444 	textset = imgp->vp->v_vflag & VV_TEXT;
445 	imgp->vp->v_vflag |= VV_TEXT;
446 
447 	error = exec_map_first_page(imgp);
448 	if (error)
449 		goto exec_fail_dealloc;
450 
451 	imgp->proc->p_osrel = 0;
452 	/*
453 	 *	If the current process has a special image activator it
454 	 *	wants to try first, call it.   For example, emulating shell
455 	 *	scripts differently.
456 	 */
457 	error = -1;
458 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
459 		error = img_first(imgp);
460 
461 	/*
462 	 *	Loop through the list of image activators, calling each one.
463 	 *	An activator returns -1 if there is no match, 0 on success,
464 	 *	and an error otherwise.
465 	 */
466 	for (i = 0; error == -1 && execsw[i]; ++i) {
467 		if (execsw[i]->ex_imgact == NULL ||
468 		    execsw[i]->ex_imgact == img_first) {
469 			continue;
470 		}
471 		error = (*execsw[i]->ex_imgact)(imgp);
472 	}
473 
474 	if (error) {
475 		if (error == -1) {
476 			if (textset == 0)
477 				imgp->vp->v_vflag &= ~VV_TEXT;
478 			error = ENOEXEC;
479 		}
480 		goto exec_fail_dealloc;
481 	}
482 
483 	/*
484 	 * Special interpreter operation, cleanup and loop up to try to
485 	 * activate the interpreter.
486 	 */
487 	if (imgp->interpreted) {
488 		exec_unmap_first_page(imgp);
489 		/*
490 		 * VV_TEXT needs to be unset for scripts.  There is a short
491 		 * period before we determine that something is a script where
492 		 * VV_TEXT will be set. The vnode lock is held over this
493 		 * entire period so nothing should illegitimately be blocked.
494 		 */
495 		imgp->vp->v_vflag &= ~VV_TEXT;
496 		/* free name buffer and old vnode */
497 		if (args->fname != NULL)
498 			NDFREE(ndp, NDF_ONLY_PNBUF);
499 #ifdef MAC
500 		mac_execve_interpreter_enter(binvp, &interpvplabel);
501 #endif
502 		if (imgp->opened) {
503 			VOP_CLOSE(binvp, FREAD, td->td_ucred, td);
504 			imgp->opened = 0;
505 		}
506 		vput(binvp);
507 		vm_object_deallocate(imgp->object);
508 		imgp->object = NULL;
509 		VFS_UNLOCK_GIANT(vfslocked);
510 		vfslocked = 0;
511 		/* set new name to that of the interpreter */
512 		NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME | MPSAFE,
513 		    UIO_SYSSPACE, imgp->interpreter_name, td);
514 		args->fname = imgp->interpreter_name;
515 		goto interpret;
516 	}
517 
518 	/*
519 	 * NB: We unlock the vnode here because it is believed that none
520 	 * of the sv_copyout_strings/sv_fixup operations require the vnode.
521 	 */
522 	VOP_UNLOCK(imgp->vp, 0);
523 	/*
524 	 * Copy out strings (args and env) and initialize stack base
525 	 */
526 	if (p->p_sysent->sv_copyout_strings)
527 		stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
528 	else
529 		stack_base = exec_copyout_strings(imgp);
530 
531 	/*
532 	 * If custom stack fixup routine present for this process
533 	 * let it do the stack setup.
534 	 * Else stuff argument count as first item on stack
535 	 */
536 	if (p->p_sysent->sv_fixup != NULL)
537 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
538 	else
539 		suword(--stack_base, imgp->args->argc);
540 
541 	/*
542 	 * For security and other reasons, the file descriptor table cannot
543 	 * be shared after an exec.
544 	 */
545 	fdunshare(p, td);
546 
547 	/*
548 	 * Malloc things before we need locks.
549 	 */
550 	newcred = crget();
551 	euip = uifind(attr.va_uid);
552 	i = imgp->args->begin_envv - imgp->args->begin_argv;
553 	/* Cache arguments if they fit inside our allowance */
554 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
555 		newargs = pargs_alloc(i);
556 		bcopy(imgp->args->begin_argv, newargs->ar_args, i);
557 	}
558 
559 	/* close files on exec */
560 	fdcloseexec(td);
561 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
562 
563 	/* Get a reference to the vnode prior to locking the proc */
564 	VREF(binvp);
565 
566 	/*
567 	 * For security and other reasons, signal handlers cannot
568 	 * be shared after an exec. The new process gets a copy of the old
569 	 * handlers. In execsigs(), the new process will have its signals
570 	 * reset.
571 	 */
572 	PROC_LOCK(p);
573 	if (sigacts_shared(p->p_sigacts)) {
574 		oldsigacts = p->p_sigacts;
575 		PROC_UNLOCK(p);
576 		newsigacts = sigacts_alloc();
577 		sigacts_copy(newsigacts, oldsigacts);
578 		PROC_LOCK(p);
579 		p->p_sigacts = newsigacts;
580 	} else
581 		oldsigacts = NULL;
582 
583 	/* Stop profiling */
584 	stopprofclock(p);
585 
586 	/* reset caught signals */
587 	execsigs(p);
588 
589 	/* name this process - nameiexec(p, ndp) */
590 	if (args->fname) {
591 		len = min(ndp->ni_cnd.cn_namelen,MAXCOMLEN);
592 		bcopy(ndp->ni_cnd.cn_nameptr, p->p_comm, len);
593 	} else {
594 		len = MAXCOMLEN;
595 		if (vn_commname(binvp, p->p_comm, MAXCOMLEN + 1) == 0)
596 			len = MAXCOMLEN;
597 		else {
598 			len = sizeof(fexecv_proc_title);
599 			bcopy(fexecv_proc_title, p->p_comm, len);
600 		}
601 	}
602 	p->p_comm[len] = 0;
603 	bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
604 
605 	/*
606 	 * mark as execed, wakeup the process that vforked (if any) and tell
607 	 * it that it now has its own resources back
608 	 */
609 	p->p_flag |= P_EXEC;
610 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
611 		p->p_flag &= ~P_PPWAIT;
612 		wakeup(p->p_pptr);
613 	}
614 
615 	/*
616 	 * Implement image setuid/setgid.
617 	 *
618 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
619 	 * the process is being traced.
620 	 *
621 	 * XXXMAC: For the time being, use NOSUID to also prohibit
622 	 * transitions on the file system.
623 	 */
624 	oldcred = p->p_ucred;
625 	credential_changing = 0;
626 	credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
627 	    attr.va_uid;
628 	credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
629 	    attr.va_gid;
630 #ifdef MAC
631 	will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
632 	    interpvplabel, imgp);
633 	credential_changing |= will_transition;
634 #endif
635 
636 	if (credential_changing &&
637 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
638 	    (p->p_flag & P_TRACED) == 0) {
639 		/*
640 		 * Turn off syscall tracing for set-id programs, except for
641 		 * root.  Record any set-id flags first to make sure that
642 		 * we do not regain any tracing during a possible block.
643 		 */
644 		setsugid(p);
645 
646 #ifdef KTRACE
647 		if (p->p_tracevp != NULL &&
648 		    priv_check_cred(oldcred, PRIV_DEBUG_DIFFCRED, 0)) {
649 			mtx_lock(&ktrace_mtx);
650 			p->p_traceflag = 0;
651 			tracevp = p->p_tracevp;
652 			p->p_tracevp = NULL;
653 			tracecred = p->p_tracecred;
654 			p->p_tracecred = NULL;
655 			mtx_unlock(&ktrace_mtx);
656 		}
657 #endif
658 		/*
659 		 * Close any file descriptors 0..2 that reference procfs,
660 		 * then make sure file descriptors 0..2 are in use.
661 		 *
662 		 * setugidsafety() may call closef() and then pfind()
663 		 * which may grab the process lock.
664 		 * fdcheckstd() may call falloc() which may block to
665 		 * allocate memory, so temporarily drop the process lock.
666 		 */
667 		PROC_UNLOCK(p);
668 		setugidsafety(td);
669 		VOP_UNLOCK(imgp->vp, 0);
670 		error = fdcheckstd(td);
671 		vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
672 		if (error != 0)
673 			goto done1;
674 		PROC_LOCK(p);
675 		/*
676 		 * Set the new credentials.
677 		 */
678 		crcopy(newcred, oldcred);
679 		if (attr.va_mode & S_ISUID)
680 			change_euid(newcred, euip);
681 		if (attr.va_mode & S_ISGID)
682 			change_egid(newcred, attr.va_gid);
683 #ifdef MAC
684 		if (will_transition) {
685 			mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
686 			    interpvplabel, imgp);
687 		}
688 #endif
689 		/*
690 		 * Implement correct POSIX saved-id behavior.
691 		 *
692 		 * XXXMAC: Note that the current logic will save the
693 		 * uid and gid if a MAC domain transition occurs, even
694 		 * though maybe it shouldn't.
695 		 */
696 		change_svuid(newcred, newcred->cr_uid);
697 		change_svgid(newcred, newcred->cr_gid);
698 		p->p_ucred = newcred;
699 		newcred = NULL;
700 	} else {
701 		if (oldcred->cr_uid == oldcred->cr_ruid &&
702 		    oldcred->cr_gid == oldcred->cr_rgid)
703 			p->p_flag &= ~P_SUGID;
704 		/*
705 		 * Implement correct POSIX saved-id behavior.
706 		 *
707 		 * XXX: It's not clear that the existing behavior is
708 		 * POSIX-compliant.  A number of sources indicate that the
709 		 * saved uid/gid should only be updated if the new ruid is
710 		 * not equal to the old ruid, or the new euid is not equal
711 		 * to the old euid and the new euid is not equal to the old
712 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
713 		 * Also, this code uses the new (replaced) euid and egid as
714 		 * the source, which may or may not be the right ones to use.
715 		 */
716 		if (oldcred->cr_svuid != oldcred->cr_uid ||
717 		    oldcred->cr_svgid != oldcred->cr_gid) {
718 			crcopy(newcred, oldcred);
719 			change_svuid(newcred, newcred->cr_uid);
720 			change_svgid(newcred, newcred->cr_gid);
721 			p->p_ucred = newcred;
722 			newcred = NULL;
723 		}
724 	}
725 
726 	/*
727 	 * Store the vp for use in procfs.  This vnode was referenced prior
728 	 * to locking the proc lock.
729 	 */
730 	textvp = p->p_textvp;
731 	p->p_textvp = binvp;
732 
733 #ifdef KDTRACE_HOOKS
734 	/*
735 	 * Tell the DTrace fasttrap provider about the exec if it
736 	 * has declared an interest.
737 	 */
738 	if (dtrace_fasttrap_exec)
739 		dtrace_fasttrap_exec(p);
740 #endif
741 
742 	/*
743 	 * Notify others that we exec'd, and clear the P_INEXEC flag
744 	 * as we're now a bona fide freshly-execed process.
745 	 */
746 	KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
747 	p->p_flag &= ~P_INEXEC;
748 
749 	/*
750 	 * If tracing the process, trap to debugger so breakpoints
751 	 * can be set before the program executes.
752 	 * Use tdsignal to deliver signal to current thread, use
753 	 * psignal may cause the signal to be delivered to wrong thread
754 	 * because that thread will exit, remember we are going to enter
755 	 * single thread mode.
756 	 */
757 	if (p->p_flag & P_TRACED)
758 		tdsignal(p, td, SIGTRAP, NULL);
759 
760 	/* clear "fork but no exec" flag, as we _are_ execing */
761 	p->p_acflag &= ~AFORK;
762 
763 	/*
764 	 * Free any previous argument cache and replace it with
765 	 * the new argument cache, if any.
766 	 */
767 	oldargs = p->p_args;
768 	p->p_args = newargs;
769 	newargs = NULL;
770 
771 #ifdef	HWPMC_HOOKS
772 	/*
773 	 * Check if system-wide sampling is in effect or if the
774 	 * current process is using PMCs.  If so, do exec() time
775 	 * processing.  This processing needs to happen AFTER the
776 	 * P_INEXEC flag is cleared.
777 	 *
778 	 * The proc lock needs to be released before taking the PMC
779 	 * SX.
780 	 */
781 	if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
782 		PROC_UNLOCK(p);
783 		pe.pm_credentialschanged = credential_changing;
784 		pe.pm_entryaddr = imgp->entry_addr;
785 
786 		PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
787 	} else
788 		PROC_UNLOCK(p);
789 #else  /* !HWPMC_HOOKS */
790 	PROC_UNLOCK(p);
791 #endif
792 
793 	/* Set values passed into the program in registers. */
794 	if (p->p_sysent->sv_setregs)
795 		(*p->p_sysent->sv_setregs)(td, imgp->entry_addr,
796 		    (u_long)(uintptr_t)stack_base, imgp->ps_strings);
797 	else
798 		exec_setregs(td, imgp->entry_addr,
799 		    (u_long)(uintptr_t)stack_base, imgp->ps_strings);
800 
801 	vfs_mark_atime(imgp->vp, td->td_ucred);
802 
803 done1:
804 
805 	/*
806 	 * Free any resources malloc'd earlier that we didn't use.
807 	 */
808 	uifree(euip);
809 	if (newcred == NULL)
810 		crfree(oldcred);
811 	else
812 		crfree(newcred);
813 	VOP_UNLOCK(imgp->vp, 0);
814 
815 	SDT_PROBE(proc, kernel, , exec_success, args->fname, 0, 0, 0, 0);
816 
817 	/*
818 	 * Handle deferred decrement of ref counts.
819 	 */
820 	if (textvp != NULL) {
821 		int tvfslocked;
822 
823 		tvfslocked = VFS_LOCK_GIANT(textvp->v_mount);
824 		vrele(textvp);
825 		VFS_UNLOCK_GIANT(tvfslocked);
826 	}
827 	if (binvp && error != 0)
828 		vrele(binvp);
829 #ifdef KTRACE
830 	if (tracevp != NULL) {
831 		int tvfslocked;
832 
833 		tvfslocked = VFS_LOCK_GIANT(tracevp->v_mount);
834 		vrele(tracevp);
835 		VFS_UNLOCK_GIANT(tvfslocked);
836 	}
837 	if (tracecred != NULL)
838 		crfree(tracecred);
839 #endif
840 	vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
841 	pargs_drop(oldargs);
842 	pargs_drop(newargs);
843 	if (oldsigacts != NULL)
844 		sigacts_free(oldsigacts);
845 
846 exec_fail_dealloc:
847 
848 	/*
849 	 * free various allocated resources
850 	 */
851 	if (imgp->firstpage != NULL)
852 		exec_unmap_first_page(imgp);
853 
854 	if (imgp->vp != NULL) {
855 		if (args->fname)
856 			NDFREE(ndp, NDF_ONLY_PNBUF);
857 		if (imgp->opened)
858 			VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
859 		vput(imgp->vp);
860 	}
861 
862 	if (imgp->object != NULL)
863 		vm_object_deallocate(imgp->object);
864 
865 	if (error == 0) {
866 		/*
867 		 * Stop the process here if its stop event mask has
868 		 * the S_EXEC bit set.
869 		 */
870 		STOPEVENT(p, S_EXEC, 0);
871 		goto done2;
872 	}
873 
874 exec_fail:
875 	/* we're done here, clear P_INEXEC */
876 	PROC_LOCK(p);
877 	p->p_flag &= ~P_INEXEC;
878 	PROC_UNLOCK(p);
879 
880 	SDT_PROBE(proc, kernel, , exec_failure, error, 0, 0, 0, 0);
881 
882 done2:
883 #ifdef MAC
884 	mac_execve_exit(imgp);
885 	mac_execve_interpreter_exit(interpvplabel);
886 #endif
887 	VFS_UNLOCK_GIANT(vfslocked);
888 	exec_free_args(args);
889 
890 	if (error && imgp->vmspace_destroyed) {
891 		/* sorry, no more process anymore. exit gracefully */
892 		exit1(td, W_EXITCODE(0, SIGABRT));
893 		/* NOT REACHED */
894 	}
895 	return (error);
896 }
897 
898 int
899 exec_map_first_page(imgp)
900 	struct image_params *imgp;
901 {
902 	int rv, i;
903 	int initial_pagein;
904 	vm_page_t ma[VM_INITIAL_PAGEIN];
905 	vm_object_t object;
906 
907 	if (imgp->firstpage != NULL)
908 		exec_unmap_first_page(imgp);
909 
910 	object = imgp->vp->v_object;
911 	if (object == NULL)
912 		return (EACCES);
913 	VM_OBJECT_LOCK(object);
914 #if VM_NRESERVLEVEL > 0
915 	if ((object->flags & OBJ_COLORED) == 0) {
916 		object->flags |= OBJ_COLORED;
917 		object->pg_color = 0;
918 	}
919 #endif
920 	ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
921 	if ((ma[0]->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
922 		initial_pagein = VM_INITIAL_PAGEIN;
923 		if (initial_pagein > object->size)
924 			initial_pagein = object->size;
925 		for (i = 1; i < initial_pagein; i++) {
926 			if ((ma[i] = vm_page_lookup(object, i)) != NULL) {
927 				if (ma[i]->valid)
928 					break;
929 				if ((ma[i]->oflags & VPO_BUSY) || ma[i]->busy)
930 					break;
931 				vm_page_busy(ma[i]);
932 			} else {
933 				ma[i] = vm_page_alloc(object, i,
934 				    VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
935 				if (ma[i] == NULL)
936 					break;
937 			}
938 		}
939 		initial_pagein = i;
940 		rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
941 		ma[0] = vm_page_lookup(object, 0);
942 		if ((rv != VM_PAGER_OK) || (ma[0] == NULL) ||
943 		    (ma[0]->valid == 0)) {
944 			if (ma[0]) {
945 				vm_page_lock_queues();
946 				vm_page_free(ma[0]);
947 				vm_page_unlock_queues();
948 			}
949 			VM_OBJECT_UNLOCK(object);
950 			return (EIO);
951 		}
952 	}
953 	vm_page_lock_queues();
954 	vm_page_hold(ma[0]);
955 	vm_page_unlock_queues();
956 	vm_page_wakeup(ma[0]);
957 	VM_OBJECT_UNLOCK(object);
958 
959 	imgp->firstpage = sf_buf_alloc(ma[0], 0);
960 	imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
961 
962 	return (0);
963 }
964 
965 void
966 exec_unmap_first_page(imgp)
967 	struct image_params *imgp;
968 {
969 	vm_page_t m;
970 
971 	if (imgp->firstpage != NULL) {
972 		m = sf_buf_page(imgp->firstpage);
973 		sf_buf_free(imgp->firstpage);
974 		imgp->firstpage = NULL;
975 		vm_page_lock_queues();
976 		vm_page_unhold(m);
977 		vm_page_unlock_queues();
978 	}
979 }
980 
981 /*
982  * Destroy old address space, and allocate a new stack
983  *	The new stack is only SGROWSIZ large because it is grown
984  *	automatically in trap.c.
985  */
986 int
987 exec_new_vmspace(imgp, sv)
988 	struct image_params *imgp;
989 	struct sysentvec *sv;
990 {
991 	int error;
992 	struct proc *p = imgp->proc;
993 	struct vmspace *vmspace = p->p_vmspace;
994 	vm_offset_t stack_addr;
995 	vm_map_t map;
996 	u_long ssiz;
997 
998 	imgp->vmspace_destroyed = 1;
999 	imgp->sysent = sv;
1000 
1001 	/* May be called with Giant held */
1002 	EVENTHANDLER_INVOKE(process_exec, p, imgp);
1003 
1004 	/*
1005 	 * Blow away entire process VM, if address space not shared,
1006 	 * otherwise, create a new VM space so that other threads are
1007 	 * not disrupted
1008 	 */
1009 	map = &vmspace->vm_map;
1010 	if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv->sv_minuser &&
1011 	    vm_map_max(map) == sv->sv_maxuser) {
1012 		shmexit(vmspace);
1013 		pmap_remove_pages(vmspace_pmap(vmspace));
1014 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1015 	} else {
1016 		error = vmspace_exec(p, sv->sv_minuser, sv->sv_maxuser);
1017 		if (error)
1018 			return (error);
1019 		vmspace = p->p_vmspace;
1020 		map = &vmspace->vm_map;
1021 	}
1022 
1023 	/* Allocate a new stack */
1024 	if (sv->sv_maxssiz != NULL)
1025 		ssiz = *sv->sv_maxssiz;
1026 	else
1027 		ssiz = maxssiz;
1028 	stack_addr = sv->sv_usrstack - ssiz;
1029 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1030 	    sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1031 	if (error)
1032 		return (error);
1033 
1034 #ifdef __ia64__
1035 	/* Allocate a new register stack */
1036 	stack_addr = IA64_BACKINGSTORE;
1037 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1038 	    sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_UP);
1039 	if (error)
1040 		return (error);
1041 #endif
1042 
1043 	/* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
1044 	 * VM_STACK case, but they are still used to monitor the size of the
1045 	 * process stack so we can check the stack rlimit.
1046 	 */
1047 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1048 	vmspace->vm_maxsaddr = (char *)sv->sv_usrstack - ssiz;
1049 
1050 	return (0);
1051 }
1052 
1053 /*
1054  * Copy out argument and environment strings from the old process address
1055  * space into the temporary string buffer.
1056  */
1057 int
1058 exec_copyin_args(struct image_args *args, char *fname,
1059     enum uio_seg segflg, char **argv, char **envv)
1060 {
1061 	char *argp, *envp;
1062 	int error;
1063 	size_t length;
1064 
1065 	error = 0;
1066 
1067 	bzero(args, sizeof(*args));
1068 	if (argv == NULL)
1069 		return (EFAULT);
1070 	/*
1071 	 * Allocate temporary demand zeroed space for argument and
1072 	 *	environment strings:
1073 	 *
1074 	 * o ARG_MAX for argument and environment;
1075 	 * o MAXSHELLCMDLEN for the name of interpreters.
1076 	 */
1077 	args->buf = (char *) kmem_alloc_wait(exec_map,
1078 	    PATH_MAX + ARG_MAX + MAXSHELLCMDLEN);
1079 	if (args->buf == NULL)
1080 		return (ENOMEM);
1081 	args->begin_argv = args->buf;
1082 	args->endp = args->begin_argv;
1083 	args->stringspace = ARG_MAX;
1084 	/*
1085 	 * Copy the file name.
1086 	 */
1087 	if (fname != NULL) {
1088 		args->fname = args->buf + ARG_MAX;
1089 		error = (segflg == UIO_SYSSPACE) ?
1090 		    copystr(fname, args->fname, PATH_MAX, &length) :
1091 		    copyinstr(fname, args->fname, PATH_MAX, &length);
1092 		if (error != 0)
1093 			goto err_exit;
1094 	} else
1095 		args->fname = NULL;
1096 
1097 	/*
1098 	 * extract arguments first
1099 	 */
1100 	while ((argp = (caddr_t) (intptr_t) fuword(argv++))) {
1101 		if (argp == (caddr_t) -1) {
1102 			error = EFAULT;
1103 			goto err_exit;
1104 		}
1105 		if ((error = copyinstr(argp, args->endp,
1106 		    args->stringspace, &length))) {
1107 			if (error == ENAMETOOLONG)
1108 				error = E2BIG;
1109 			goto err_exit;
1110 		}
1111 		args->stringspace -= length;
1112 		args->endp += length;
1113 		args->argc++;
1114 	}
1115 
1116 	args->begin_envv = args->endp;
1117 
1118 	/*
1119 	 * extract environment strings
1120 	 */
1121 	if (envv) {
1122 		while ((envp = (caddr_t)(intptr_t)fuword(envv++))) {
1123 			if (envp == (caddr_t)-1) {
1124 				error = EFAULT;
1125 				goto err_exit;
1126 			}
1127 			if ((error = copyinstr(envp, args->endp,
1128 			    args->stringspace, &length))) {
1129 				if (error == ENAMETOOLONG)
1130 					error = E2BIG;
1131 				goto err_exit;
1132 			}
1133 			args->stringspace -= length;
1134 			args->endp += length;
1135 			args->envc++;
1136 		}
1137 	}
1138 
1139 	return (0);
1140 
1141 err_exit:
1142 	exec_free_args(args);
1143 	return (error);
1144 }
1145 
1146 static void
1147 exec_free_args(struct image_args *args)
1148 {
1149 
1150 	if (args->buf) {
1151 		kmem_free_wakeup(exec_map, (vm_offset_t)args->buf,
1152 		    PATH_MAX + ARG_MAX + MAXSHELLCMDLEN);
1153 		args->buf = NULL;
1154 	}
1155 }
1156 
1157 /*
1158  * Copy strings out to the new process address space, constructing new arg
1159  * and env vector tables. Return a pointer to the base so that it can be used
1160  * as the initial stack pointer.
1161  */
1162 register_t *
1163 exec_copyout_strings(imgp)
1164 	struct image_params *imgp;
1165 {
1166 	int argc, envc;
1167 	char **vectp;
1168 	char *stringp, *destp;
1169 	register_t *stack_base;
1170 	struct ps_strings *arginfo;
1171 	struct proc *p;
1172 	int szsigcode;
1173 
1174 	/*
1175 	 * Calculate string base and vector table pointers.
1176 	 * Also deal with signal trampoline code for this exec type.
1177 	 */
1178 	p = imgp->proc;
1179 	szsigcode = 0;
1180 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1181 	if (p->p_sysent->sv_szsigcode != NULL)
1182 		szsigcode = *(p->p_sysent->sv_szsigcode);
1183 	destp =	(caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
1184 	    roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *));
1185 
1186 	/*
1187 	 * install sigcode
1188 	 */
1189 	if (szsigcode)
1190 		copyout(p->p_sysent->sv_sigcode, ((caddr_t)arginfo -
1191 		    szsigcode), szsigcode);
1192 
1193 	/*
1194 	 * If we have a valid auxargs ptr, prepare some room
1195 	 * on the stack.
1196 	 */
1197 	if (imgp->auxargs) {
1198 		/*
1199 		 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1200 		 * lower compatibility.
1201 		 */
1202 		imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1203 		    (AT_COUNT * 2);
1204 		/*
1205 		 * The '+ 2' is for the null pointers at the end of each of
1206 		 * the arg and env vector sets,and imgp->auxarg_size is room
1207 		 * for argument of Runtime loader.
1208 		 */
1209 		vectp = (char **)(destp - (imgp->args->argc +
1210 		    imgp->args->envc + 2 + imgp->auxarg_size) *
1211 		    sizeof(char *));
1212 
1213 	} else {
1214 		/*
1215 		 * The '+ 2' is for the null pointers at the end of each of
1216 		 * the arg and env vector sets
1217 		 */
1218 		vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2) *
1219 		    sizeof(char *));
1220 	}
1221 
1222 	/*
1223 	 * vectp also becomes our initial stack base
1224 	 */
1225 	stack_base = (register_t *)vectp;
1226 
1227 	stringp = imgp->args->begin_argv;
1228 	argc = imgp->args->argc;
1229 	envc = imgp->args->envc;
1230 
1231 	/*
1232 	 * Copy out strings - arguments and environment.
1233 	 */
1234 	copyout(stringp, destp, ARG_MAX - imgp->args->stringspace);
1235 
1236 	/*
1237 	 * Fill in "ps_strings" struct for ps, w, etc.
1238 	 */
1239 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1240 	suword(&arginfo->ps_nargvstr, argc);
1241 
1242 	/*
1243 	 * Fill in argument portion of vector table.
1244 	 */
1245 	for (; argc > 0; --argc) {
1246 		suword(vectp++, (long)(intptr_t)destp);
1247 		while (*stringp++ != 0)
1248 			destp++;
1249 		destp++;
1250 	}
1251 
1252 	/* a null vector table pointer separates the argp's from the envp's */
1253 	suword(vectp++, 0);
1254 
1255 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1256 	suword(&arginfo->ps_nenvstr, envc);
1257 
1258 	/*
1259 	 * Fill in environment portion of vector table.
1260 	 */
1261 	for (; envc > 0; --envc) {
1262 		suword(vectp++, (long)(intptr_t)destp);
1263 		while (*stringp++ != 0)
1264 			destp++;
1265 		destp++;
1266 	}
1267 
1268 	/* end of vector table is a null pointer */
1269 	suword(vectp, 0);
1270 
1271 	return (stack_base);
1272 }
1273 
1274 /*
1275  * Check permissions of file to execute.
1276  *	Called with imgp->vp locked.
1277  *	Return 0 for success or error code on failure.
1278  */
1279 int
1280 exec_check_permissions(imgp)
1281 	struct image_params *imgp;
1282 {
1283 	struct vnode *vp = imgp->vp;
1284 	struct vattr *attr = imgp->attr;
1285 	struct thread *td;
1286 	int error;
1287 
1288 	td = curthread;
1289 
1290 	/* Get file attributes */
1291 	error = VOP_GETATTR(vp, attr, td->td_ucred);
1292 	if (error)
1293 		return (error);
1294 
1295 #ifdef MAC
1296 	error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1297 	if (error)
1298 		return (error);
1299 #endif
1300 
1301 	/*
1302 	 * 1) Check if file execution is disabled for the filesystem that this
1303 	 *	file resides on.
1304 	 * 2) Insure that at least one execute bit is on - otherwise root
1305 	 *	will always succeed, and we don't want to happen unless the
1306 	 *	file really is executable.
1307 	 * 3) Insure that the file is a regular file.
1308 	 */
1309 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1310 	    ((attr->va_mode & 0111) == 0) ||
1311 	    (attr->va_type != VREG))
1312 		return (EACCES);
1313 
1314 	/*
1315 	 * Zero length files can't be exec'd
1316 	 */
1317 	if (attr->va_size == 0)
1318 		return (ENOEXEC);
1319 
1320 	/*
1321 	 *  Check for execute permission to file based on current credentials.
1322 	 */
1323 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1324 	if (error)
1325 		return (error);
1326 
1327 	/*
1328 	 * Check number of open-for-writes on the file and deny execution
1329 	 * if there are any.
1330 	 */
1331 	if (vp->v_writecount)
1332 		return (ETXTBSY);
1333 
1334 	/*
1335 	 * Call filesystem specific open routine (which does nothing in the
1336 	 * general case).
1337 	 */
1338 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1339 	if (error == 0)
1340 		imgp->opened = 1;
1341 	return (error);
1342 }
1343 
1344 /*
1345  * Exec handler registration
1346  */
1347 int
1348 exec_register(execsw_arg)
1349 	const struct execsw *execsw_arg;
1350 {
1351 	const struct execsw **es, **xs, **newexecsw;
1352 	int count = 2;	/* New slot and trailing NULL */
1353 
1354 	if (execsw)
1355 		for (es = execsw; *es; es++)
1356 			count++;
1357 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1358 	if (newexecsw == NULL)
1359 		return (ENOMEM);
1360 	xs = newexecsw;
1361 	if (execsw)
1362 		for (es = execsw; *es; es++)
1363 			*xs++ = *es;
1364 	*xs++ = execsw_arg;
1365 	*xs = NULL;
1366 	if (execsw)
1367 		free(execsw, M_TEMP);
1368 	execsw = newexecsw;
1369 	return (0);
1370 }
1371 
1372 int
1373 exec_unregister(execsw_arg)
1374 	const struct execsw *execsw_arg;
1375 {
1376 	const struct execsw **es, **xs, **newexecsw;
1377 	int count = 1;
1378 
1379 	if (execsw == NULL)
1380 		panic("unregister with no handlers left?\n");
1381 
1382 	for (es = execsw; *es; es++) {
1383 		if (*es == execsw_arg)
1384 			break;
1385 	}
1386 	if (*es == NULL)
1387 		return (ENOENT);
1388 	for (es = execsw; *es; es++)
1389 		if (*es != execsw_arg)
1390 			count++;
1391 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1392 	if (newexecsw == NULL)
1393 		return (ENOMEM);
1394 	xs = newexecsw;
1395 	for (es = execsw; *es; es++)
1396 		if (*es != execsw_arg)
1397 			*xs++ = *es;
1398 	*xs = NULL;
1399 	if (execsw)
1400 		free(execsw, M_TEMP);
1401 	execsw = newexecsw;
1402 	return (0);
1403 }
1404