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