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