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