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