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