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