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