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