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