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