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