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