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