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