2 * Copyright (c) 1993, David Greenman
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
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.2 2003/06/17 04:28:41 dillon Exp $
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>
39 #include <sys/imgact.h>
40 #include <sys/imgact_elf.h>
42 #include <sys/malloc.h>
44 #include <sys/signalvar.h>
45 #include <sys/pioctl.h>
46 #include <sys/namei.h>
47 #include <sys/sysent.h>
49 #include <sys/sysctl.h>
50 #include <sys/vnode.h>
54 #include <vm/vm_param.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>
65 #include <machine/reg.h>
67 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
69 static register_t *exec_copyout_strings __P((struct image_params *));
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, "");
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, "");
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, "");
84 SYSCTL_INT(_kern, OID_AUTO, ps_argsopen, CTLFLAG_RW, &ps_argsopen, 0, "");
87 * Each of the items is a pointer to a `const struct execsw', hence the
88 * double pointer here.
90 static const struct execsw **execsw;
92 #ifndef _SYS_SYSPROTO_H_
101 * execve() system call.
106 register struct execve_args *uap;
108 struct nameidata nd, *ndp;
109 register_t *stack_base;
111 struct image_params image_params, *imgp;
113 int (*img_first) __P((struct image_params *));
115 imgp = &image_params;
118 * Lock the process and set the P_INEXEC flag to indicate that
119 * it should be left alone until we're done here. This is
120 * necessary to avoid race conditions - e.g. in ptrace() -
121 * that might allow a local user to illicitly obtain elevated
124 p->p_flag |= P_INEXEC;
127 * Initialize part of the common data
132 imgp->argc = imgp->envc = 0;
134 imgp->entry_addr = 0;
135 imgp->vmspace_destroyed = 0;
136 imgp->interpreted = 0;
137 imgp->interpreter_name[0] = '\0';
138 imgp->auxargs = NULL;
140 imgp->firstpage = NULL;
141 imgp->ps_strings = 0;
144 * Allocate temporary demand zeroed space for argument and
145 * environment strings
147 imgp->stringbase = (char *)kmem_alloc_wait(exec_map, ARG_MAX + PAGE_SIZE);
148 if (imgp->stringbase == NULL) {
152 imgp->stringp = imgp->stringbase;
153 imgp->stringspace = ARG_MAX;
154 imgp->image_header = imgp->stringbase + ARG_MAX;
157 * Translate the file name. namei() returns a vnode pointer
158 * in ni_vp amoung other things.
161 NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
162 UIO_USERSPACE, uap->fname, p);
168 kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase,
169 ARG_MAX + PAGE_SIZE);
173 imgp->vp = ndp->ni_vp;
174 imgp->fname = uap->fname;
177 * Check file permissions (also 'opens' file)
179 error = exec_check_permissions(imgp);
181 VOP_UNLOCK(imgp->vp, 0, p);
182 goto exec_fail_dealloc;
185 error = exec_map_first_page(imgp);
186 VOP_UNLOCK(imgp->vp, 0, p);
188 goto exec_fail_dealloc;
191 * If the current process has a special image activator it
192 * wants to try first, call it. For example, emulating shell
193 * scripts differently.
196 if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
197 error = img_first(imgp);
200 * Loop through the list of image activators, calling each one.
201 * An activator returns -1 if there is no match, 0 on success,
202 * and an error otherwise.
204 for (i = 0; error == -1 && execsw[i]; ++i) {
205 if (execsw[i]->ex_imgact == NULL ||
206 execsw[i]->ex_imgact == img_first) {
209 error = (*execsw[i]->ex_imgact)(imgp);
215 goto exec_fail_dealloc;
219 * Special interpreter operation, cleanup and loop up to try to
220 * activate the interpreter.
222 if (imgp->interpreted) {
223 exec_unmap_first_page(imgp);
224 /* free name buffer and old vnode */
225 NDFREE(ndp, NDF_ONLY_PNBUF);
227 /* set new name to that of the interpreter */
228 NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
229 UIO_SYSSPACE, imgp->interpreter_name, p);
234 * Copy out strings (args and env) and initialize stack base
236 stack_base = exec_copyout_strings(imgp);
237 p->p_vmspace->vm_minsaddr = (char *)stack_base;
240 * If custom stack fixup routine present for this process
241 * let it do the stack setup.
242 * Else stuff argument count as first item on stack
244 if (p->p_sysent->sv_fixup)
245 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
247 suword(--stack_base, imgp->argc);
250 * For security and other reasons, the file descriptor table cannot
251 * be shared after an exec.
253 if (p->p_fd->fd_refcnt > 1) {
254 struct filedesc *tmp;
262 * For security and other reasons, signal handlers cannot
263 * be shared after an exec. The new proces gets a copy of the old
264 * handlers. In execsigs(), the new process will have its signals
267 if (p->p_procsig->ps_refcnt > 1) {
268 struct procsig *newprocsig;
270 MALLOC(newprocsig, struct procsig *, sizeof(struct procsig),
271 M_SUBPROC, M_WAITOK);
272 bcopy(p->p_procsig, newprocsig, sizeof(*newprocsig));
273 p->p_procsig->ps_refcnt--;
274 p->p_procsig = newprocsig;
275 p->p_procsig->ps_refcnt = 1;
276 if (p->p_sigacts == &p->p_addr->u_sigacts)
277 panic("shared procsig but private sigacts?");
279 p->p_addr->u_sigacts = *p->p_sigacts;
280 p->p_sigacts = &p->p_addr->u_sigacts;
286 /* close files on exec */
289 /* reset caught signals */
292 /* name this process - nameiexec(p, ndp) */
293 len = min(ndp->ni_cnd.cn_namelen,MAXCOMLEN);
294 bcopy(ndp->ni_cnd.cn_nameptr, p->p_comm, len);
298 * mark as execed, wakeup the process that vforked (if any) and tell
299 * it that it now has its own resources back
302 if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
303 p->p_flag &= ~P_PPWAIT;
304 wakeup((caddr_t)p->p_pptr);
308 * Implement image setuid/setgid.
310 * Don't honor setuid/setgid if the filesystem prohibits it or if
311 * the process is being traced.
313 if ((((attr.va_mode & VSUID) && p->p_ucred->cr_uid != attr.va_uid) ||
314 ((attr.va_mode & VSGID) && p->p_ucred->cr_gid != attr.va_gid)) &&
315 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
316 (p->p_flag & P_TRACED) == 0) {
318 * Turn off syscall tracing for set-id programs, except for
319 * root. Record any set-id flags first to make sure that
320 * we do not regain any tracing during a possible block.
323 if (p->p_tracep && suser(p)) {
326 if ((vtmp = p->p_tracep) != NULL) {
332 /* Close any file descriptors 0..2 that reference procfs */
334 /* Make sure file descriptors 0..2 are in use. */
335 error = fdcheckstd(p);
337 goto exec_fail_dealloc;
339 * Set the new credentials.
341 p->p_ucred = crcopy(p->p_ucred);
342 if (attr.va_mode & VSUID)
343 change_euid(p, attr.va_uid);
344 if (attr.va_mode & VSGID)
345 p->p_ucred->cr_gid = attr.va_gid;
347 if (p->p_ucred->cr_uid == p->p_cred->p_ruid &&
348 p->p_ucred->cr_gid == p->p_cred->p_rgid)
349 p->p_flag &= ~P_SUGID;
353 * Implement correct POSIX saved-id behavior.
355 p->p_cred->p_svuid = p->p_ucred->cr_uid;
356 p->p_cred->p_svgid = p->p_ucred->cr_gid;
359 * Store the vp for use in procfs
361 if (p->p_textvp) /* release old reference */
364 p->p_textvp = ndp->ni_vp;
367 * Notify others that we exec'd, and clear the P_INEXEC flag
368 * as we're now a bona fide freshly-execed process.
370 KNOTE(&p->p_klist, NOTE_EXEC);
371 p->p_flag &= ~P_INEXEC;
374 * If tracing the process, trap to debugger so breakpoints
375 * can be set before the program executes.
377 STOPEVENT(p, S_EXEC, 0);
379 if (p->p_flag & P_TRACED)
382 /* clear "fork but no exec" flag, as we _are_ execing */
383 p->p_acflag &= ~AFORK;
385 /* Set values passed into the program in registers. */
386 setregs(p, imgp->entry_addr, (u_long)(uintptr_t)stack_base,
389 /* Free any previous argument cache */
390 if (p->p_args && --p->p_args->ar_ref == 0)
391 FREE(p->p_args, M_PARGS);
394 /* Cache arguments if they fit inside our allowance */
395 i = imgp->endargs - imgp->stringbase;
396 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
397 MALLOC(p->p_args, struct pargs *, sizeof(struct pargs) + i,
399 p->p_args->ar_ref = 1;
400 p->p_args->ar_length = i;
401 bcopy(imgp->stringbase, p->p_args->ar_args, i);
407 * free various allocated resources
410 exec_unmap_first_page(imgp);
412 if (imgp->stringbase != NULL)
413 kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase,
414 ARG_MAX + PAGE_SIZE);
417 NDFREE(ndp, NDF_ONLY_PNBUF);
425 /* we're done here, clear P_INEXEC */
426 p->p_flag &= ~P_INEXEC;
427 if (imgp->vmspace_destroyed) {
428 /* sorry, no more process anymore. exit gracefully */
429 exit1(p, W_EXITCODE(0, SIGABRT));
438 exec_map_first_page(imgp)
439 struct image_params *imgp;
443 vm_page_t ma[VM_INITIAL_PAGEIN];
447 if (imgp->firstpage) {
448 exec_unmap_first_page(imgp);
451 VOP_GETVOBJECT(imgp->vp, &object);
454 ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
456 if ((ma[0]->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
457 initial_pagein = VM_INITIAL_PAGEIN;
458 if (initial_pagein > object->size)
459 initial_pagein = object->size;
460 for (i = 1; i < initial_pagein; i++) {
461 if ((ma[i] = vm_page_lookup(object, i)) != NULL) {
462 if ((ma[i]->flags & PG_BUSY) || ma[i]->busy)
468 ma[i] = vm_page_alloc(object, i, VM_ALLOC_NORMAL);
475 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
476 ma[0] = vm_page_lookup(object, 0);
478 if ((rv != VM_PAGER_OK) || (ma[0] == NULL) || (ma[0]->valid == 0)) {
480 vm_page_protect(ma[0], VM_PROT_NONE);
489 vm_page_wakeup(ma[0]);
492 pmap_kenter((vm_offset_t) imgp->image_header, VM_PAGE_TO_PHYS(ma[0]));
493 imgp->firstpage = ma[0];
499 exec_unmap_first_page(imgp)
500 struct image_params *imgp;
502 if (imgp->firstpage) {
503 pmap_kremove((vm_offset_t) imgp->image_header);
504 vm_page_unwire(imgp->firstpage, 1);
505 imgp->firstpage = NULL;
510 * Destroy old address space, and allocate a new stack
511 * The new stack is only SGROWSIZ large because it is grown
512 * automatically in trap.c.
515 exec_new_vmspace(imgp)
516 struct image_params *imgp;
519 struct vmspace *vmspace = imgp->proc->p_vmspace;
520 vm_offset_t stack_addr = USRSTACK - maxssiz;
521 vm_map_t map = &vmspace->vm_map;
523 imgp->vmspace_destroyed = 1;
526 * Prevent a pending AIO from modifying the new address space.
528 aio_proc_rundown(imgp->proc);
531 * Blow away entire process VM, if address space not shared,
532 * otherwise, create a new VM space so that other threads are
535 if (vmspace->vm_refcnt == 1) {
538 pmap_remove_pages(vmspace_pmap(vmspace), 0, VM_MAXUSER_ADDRESS);
539 vm_map_remove(map, 0, VM_MAXUSER_ADDRESS);
541 vmspace_exec(imgp->proc);
542 vmspace = imgp->proc->p_vmspace;
543 map = &vmspace->vm_map;
546 /* Allocate a new stack */
547 error = vm_map_stack(&vmspace->vm_map, stack_addr, (vm_size_t)maxssiz,
548 VM_PROT_ALL, VM_PROT_ALL, 0);
552 /* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
553 * VM_STACK case, but they are still used to monitor the size of the
554 * process stack so we can check the stack rlimit.
556 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
557 vmspace->vm_maxsaddr = (char *)USRSTACK - maxssiz;
563 * Copy out argument and environment strings from the old process
564 * address space into the temporary string buffer.
567 exec_extract_strings(imgp)
568 struct image_params *imgp;
576 * extract arguments first
579 argv = imgp->uap->argv;
582 argp = (caddr_t) (intptr_t) fuword(argv);
583 if (argp == (caddr_t) -1)
591 if (argp == (caddr_t) -1)
593 if ((error = copyinstr(argp, imgp->stringp,
594 imgp->stringspace, &length))) {
595 if (error == ENAMETOOLONG)
599 imgp->stringspace -= length;
600 imgp->stringp += length;
602 } while ((argp = (caddr_t) (intptr_t) fuword(argv++)));
606 imgp->endargs = imgp->stringp;
609 * extract environment strings
612 envv = imgp->uap->envv;
615 while ((envp = (caddr_t) (intptr_t) fuword(envv++))) {
616 if (envp == (caddr_t) -1)
618 if ((error = copyinstr(envp, imgp->stringp,
619 imgp->stringspace, &length))) {
620 if (error == ENAMETOOLONG)
624 imgp->stringspace -= length;
625 imgp->stringp += length;
634 * Copy strings out to the new process address space, constructing
635 * new arg and env vector tables. Return a pointer to the base
636 * so that it can be used as the initial stack pointer.
639 exec_copyout_strings(imgp)
640 struct image_params *imgp;
644 char *stringp, *destp;
645 register_t *stack_base;
646 struct ps_strings *arginfo;
650 * Calculate string base and vector table pointers.
651 * Also deal with signal trampoline code for this exec type.
653 arginfo = (struct ps_strings *)PS_STRINGS;
654 szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);
655 destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
656 roundup((ARG_MAX - imgp->stringspace), sizeof(char *));
662 copyout(imgp->proc->p_sysent->sv_sigcode,
663 ((caddr_t)arginfo - szsigcode), szsigcode);
666 * If we have a valid auxargs ptr, prepare some room
671 * The '+ 2' is for the null pointers at the end of each of the
672 * arg and env vector sets, and 'AT_COUNT*2' is room for the
675 vectp = (char **)(destp - (imgp->argc + imgp->envc + 2 +
676 AT_COUNT*2) * sizeof(char*));
679 * The '+ 2' is for the null pointers at the end of each of the
680 * arg and env vector sets
683 (destp - (imgp->argc + imgp->envc + 2) * sizeof(char*));
686 * vectp also becomes our initial stack base
688 stack_base = (register_t *)vectp;
690 stringp = imgp->stringbase;
695 * Copy out strings - arguments and environment.
697 copyout(stringp, destp, ARG_MAX - imgp->stringspace);
700 * Fill in "ps_strings" struct for ps, w, etc.
702 suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
703 suword(&arginfo->ps_nargvstr, argc);
706 * Fill in argument portion of vector table.
708 for (; argc > 0; --argc) {
709 suword(vectp++, (long)(intptr_t)destp);
710 while (*stringp++ != 0)
715 /* a null vector table pointer seperates the argp's from the envp's */
718 suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
719 suword(&arginfo->ps_nenvstr, envc);
722 * Fill in environment portion of vector table.
724 for (; envc > 0; --envc) {
725 suword(vectp++, (long)(intptr_t)destp);
726 while (*stringp++ != 0)
731 /* end of vector table is a null pointer */
738 * Check permissions of file to execute.
739 * Return 0 for success or error code on failure.
742 exec_check_permissions(imgp)
743 struct image_params *imgp;
745 struct proc *p = imgp->proc;
746 struct vnode *vp = imgp->vp;
747 struct vattr *attr = imgp->attr;
750 /* Get file attributes */
751 error = VOP_GETATTR(vp, attr, p->p_ucred, p);
756 * 1) Check if file execution is disabled for the filesystem that this
758 * 2) Insure that at least one execute bit is on - otherwise root
759 * will always succeed, and we don't want to happen unless the
760 * file really is executable.
761 * 3) Insure that the file is a regular file.
763 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
764 ((attr->va_mode & 0111) == 0) ||
765 (attr->va_type != VREG)) {
770 * Zero length files can't be exec'd
772 if (attr->va_size == 0)
776 * Check for execute permission to file based on current credentials.
778 error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p);
783 * Check number of open-for-writes on the file and deny execution
786 if (vp->v_writecount)
790 * Call filesystem specific open routine (which does nothing in the
793 error = VOP_OPEN(vp, FREAD, p->p_ucred, p);
801 * Exec handler registration
804 exec_register(execsw_arg)
805 const struct execsw *execsw_arg;
807 const struct execsw **es, **xs, **newexecsw;
808 int count = 2; /* New slot and trailing NULL */
811 for (es = execsw; *es; es++)
813 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
814 if (newexecsw == NULL)
818 for (es = execsw; *es; es++)
823 free(execsw, M_TEMP);
829 exec_unregister(execsw_arg)
830 const struct execsw *execsw_arg;
832 const struct execsw **es, **xs, **newexecsw;
836 panic("unregister with no handlers left?\n");
838 for (es = execsw; *es; es++) {
839 if (*es == execsw_arg)
844 for (es = execsw; *es; es++)
845 if (*es != execsw_arg)
847 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
848 if (newexecsw == NULL)
851 for (es = execsw; *es; es++)
852 if (*es != execsw_arg)
856 free(execsw, M_TEMP);