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