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