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