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