Fix a bug in signal translation introduced in last revision. This effects
[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.14 2003/11/12 01:00:33 daver Exp $
28  */
29
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/sysproto.h>
33 #include <sys/kernel.h>
34 #include <sys/mount.h>
35 #include <sys/filedesc.h>
36 #include <sys/fcntl.h>
37 #include <sys/acct.h>
38 #include <sys/exec.h>
39 #include <sys/imgact.h>
40 #include <sys/imgact_elf.h>
41 #include <sys/kern_syscall.h>
42 #include <sys/wait.h>
43 #include <sys/malloc.h>
44 #include <sys/proc.h>
45 #include <sys/signalvar.h>
46 #include <sys/pioctl.h>
47 #include <sys/namei.h>
48 #include <sys/sysent.h>
49 #include <sys/shm.h>
50 #include <sys/sysctl.h>
51 #include <sys/vnode.h>
52 #include <sys/aio.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_param.h>
56 #include <sys/lock.h>
57 #include <vm/pmap.h>
58 #include <vm/vm_page.h>
59 #include <vm/vm_map.h>
60 #include <vm/vm_kern.h>
61 #include <vm/vm_extern.h>
62 #include <vm/vm_object.h>
63 #include <vm/vm_pager.h>
64
65 #include <sys/user.h>
66 #include <machine/reg.h>
67
68 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
69
70 static register_t *exec_copyout_strings (struct image_params *);
71
72 /* XXX This should be vm_size_t. */
73 static u_long ps_strings = PS_STRINGS;
74 SYSCTL_ULONG(_kern, KERN_PS_STRINGS, ps_strings, CTLFLAG_RD, &ps_strings, 0, "");
75
76 /* XXX This should be vm_size_t. */
77 static u_long usrstack = USRSTACK;
78 SYSCTL_ULONG(_kern, KERN_USRSTACK, usrstack, CTLFLAG_RD, &usrstack, 0, "");
79
80 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
81 SYSCTL_LONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
82     &ps_arg_cache_limit, 0, "");
83
84 int ps_argsopen = 1;
85 SYSCTL_INT(_kern, OID_AUTO, ps_argsopen, CTLFLAG_RW, &ps_argsopen, 0, "");
86
87 void print_execve_args(struct image_args *args);
88 int debug_execve_args = 0;
89 SYSCTL_INT(_kern, OID_AUTO, debug_execve_args, CTLFLAG_RW, &debug_execve_args,
90     0, "");
91
92 void
93 print_execve_args(struct image_args *args)
94 {
95         char *cp;
96         int ndx;
97
98         cp = args->begin_argv;
99         for (ndx = 0; ndx < args->argc; ndx++) {
100                 printf("\targv[%d]: %s\n", ndx, cp);
101                 while (*cp++ != '\0');
102         }
103         for (ndx = 0; ndx < args->envc; ndx++) {
104                 printf("\tenvv[%d]: %s\n", ndx, cp);
105                 while (*cp++ != '\0');
106         }
107 }
108
109 /*
110  * Each of the items is a pointer to a `const struct execsw', hence the
111  * double pointer here.
112  */
113 static const struct execsw **execsw;
114
115 int
116 kern_execve(struct nameidata *ndp, struct image_args *args)
117 {
118         struct thread *td = curthread;
119         struct proc *p = td->td_proc;
120         register_t *stack_base;
121         int error, len, i;
122         struct image_params image_params, *imgp;
123         struct vattr attr;
124         int (*img_first) (struct image_params *);
125
126         if (debug_execve_args) {
127                 printf("%s()\n", __func__);
128                 print_execve_args(args);
129         }
130
131         KKASSERT(p);
132         imgp = &image_params;
133
134         /*
135          * Lock the process and set the P_INEXEC flag to indicate that
136          * it should be left alone until we're done here.  This is
137          * necessary to avoid race conditions - e.g. in ptrace() -
138          * that might allow a local user to illicitly obtain elevated
139          * privileges.
140          */
141         p->p_flag |= P_INEXEC;
142
143         /*
144          * Initialize part of the common data
145          */
146         imgp->proc = p;
147         imgp->args = args;
148         imgp->attr = &attr;
149         imgp->entry_addr = 0;
150         imgp->vmspace_destroyed = 0;
151         imgp->interpreted = 0;
152         imgp->auxargs = NULL;
153         imgp->vp = NULL;
154         imgp->firstpage = NULL;
155         imgp->ps_strings = 0;
156
157         /*
158          * Allocate temporary demand zeroed space for argument and
159          *      environment strings
160          */
161         imgp->image_header = (char *)kmem_alloc_wait(exec_map, PAGE_SIZE);
162         if (imgp->image_header == NULL) {
163                 error = ENOMEM;
164                 goto exec_fail;
165         }
166
167 interpret:
168
169         /*
170          * Translate the file name. namei() returns a vnode pointer
171          *      in ni_vp amoung other things.
172          */
173         error = namei(ndp);
174         if (error) {
175                 kmem_free_wakeup(exec_map, (vm_offset_t)imgp->image_header,
176                     PAGE_SIZE);
177                 goto exec_fail;
178         }
179
180         imgp->vp = ndp->ni_vp;
181
182         /*
183          * Check file permissions (also 'opens' file)
184          */
185         error = exec_check_permissions(imgp);
186         if (error) {
187                 VOP_UNLOCK(imgp->vp, 0, td);
188                 goto exec_fail_dealloc;
189         }
190
191         error = exec_map_first_page(imgp);
192         VOP_UNLOCK(imgp->vp, 0, td);
193         if (error)
194                 goto exec_fail_dealloc;
195
196         if (debug_execve_args && imgp->interpreted) {
197                 printf("    target is interpreted -- recursive pass\n");
198                 printf("    interpreter: %s\n", imgp->interpreter_name);
199                 print_execve_args(args);
200         }
201
202         /*
203          *      If the current process has a special image activator it
204          *      wants to try first, call it.   For example, emulating shell 
205          *      scripts differently.
206          */
207         error = -1;
208         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
209                 error = img_first(imgp);
210
211         /*
212          *      Loop through the list of image activators, calling each one.
213          *      An activator returns -1 if there is no match, 0 on success,
214          *      and an error otherwise.
215          */
216         for (i = 0; error == -1 && execsw[i]; ++i) {
217                 if (execsw[i]->ex_imgact == NULL ||
218                     execsw[i]->ex_imgact == img_first) {
219                         continue;
220                 }
221                 error = (*execsw[i]->ex_imgact)(imgp);
222         }
223
224         if (error) {
225                 if (error == -1)
226                         error = ENOEXEC;
227                 goto exec_fail_dealloc;
228         }
229
230         /*
231          * Special interpreter operation, cleanup and loop up to try to
232          * activate the interpreter.
233          */
234         if (imgp->interpreted) {
235                 exec_unmap_first_page(imgp);
236                 /* free name buffer and old vnode */
237                 NDFREE(ndp, NDF_ONLY_PNBUF);
238                 vrele(ndp->ni_vp);
239                 /* set new name to that of the interpreter */
240                 NDINIT(ndp, NAMEI_LOOKUP, 
241                     CNP_LOCKLEAF | CNP_FOLLOW | CNP_SAVENAME,
242                     UIO_SYSSPACE, imgp->interpreter_name, td);
243                 goto interpret;
244         }
245
246         /*
247          * Copy out strings (args and env) and initialize stack base
248          */
249         stack_base = exec_copyout_strings(imgp);
250         p->p_vmspace->vm_minsaddr = (char *)stack_base;
251
252         /*
253          * If custom stack fixup routine present for this process
254          * let it do the stack setup.
255          * Else stuff argument count as first item on stack
256          */
257         if (p->p_sysent->sv_fixup)
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->image_header != NULL)
435                 kmem_free_wakeup(exec_map, (vm_offset_t)imgp->image_header,
436                     PAGE_SIZE);
437
438         if (imgp->vp) {
439                 NDFREE(ndp, NDF_ONLY_PNBUF);
440                 vrele(imgp->vp);
441         }
442
443         if (error == 0)
444                 return (0);
445
446 exec_fail:
447         /* we're done here, clear P_INEXEC */
448         p->p_flag &= ~P_INEXEC;
449         if (imgp->vmspace_destroyed) {
450                 /* sorry, no more process anymore. exit gracefully */
451                 exit1(W_EXITCODE(0, SIGABRT));
452                 /* NOT REACHED */
453                 return(0);
454         } else {
455                 return(error);
456         }
457 }
458
459 /*
460  * execve() system call.
461  */
462 int
463 execve(struct execve_args *uap)
464 {
465         struct thread *td = curthread;
466         struct nameidata nd;
467         struct image_args args;
468         int error;
469
470         NDINIT(&nd, NAMEI_LOOKUP, CNP_LOCKLEAF | CNP_FOLLOW | CNP_SAVENAME,
471             UIO_USERSPACE, uap->fname, td);
472
473         error = exec_copyin_args(&args, uap->fname, PATH_USERSPACE,
474             uap->argv, uap->envv);
475         if (error)
476                 return (error);
477
478         error = kern_execve(&nd, &args);
479
480         exec_free_args(&args);
481
482         /*
483          * The syscall result is returned in registers to the new program.
484          * Linux will register %edx as an atexit function and we must be
485          * sure to set it to 0.  XXX
486          */
487         if (error == 0)
488                 uap->sysmsg_result64 = 0;
489
490         return (error);
491 }
492
493 int
494 exec_map_first_page(struct image_params *imgp)
495 {
496         int s, rv, i;
497         int initial_pagein;
498         vm_page_t ma[VM_INITIAL_PAGEIN];
499         vm_object_t object;
500
501
502         if (imgp->firstpage) {
503                 exec_unmap_first_page(imgp);
504         }
505
506         VOP_GETVOBJECT(imgp->vp, &object);
507         s = splvm();
508
509         ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
510
511         if ((ma[0]->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
512                 initial_pagein = VM_INITIAL_PAGEIN;
513                 if (initial_pagein > object->size)
514                         initial_pagein = object->size;
515                 for (i = 1; i < initial_pagein; i++) {
516                         if ((ma[i] = vm_page_lookup(object, i)) != NULL) {
517                                 if ((ma[i]->flags & PG_BUSY) || ma[i]->busy)
518                                         break;
519                                 if (ma[i]->valid)
520                                         break;
521                                 vm_page_busy(ma[i]);
522                         } else {
523                                 ma[i] = vm_page_alloc(object, i, VM_ALLOC_NORMAL);
524                                 if (ma[i] == NULL)
525                                         break;
526                         }
527                 }
528                 initial_pagein = i;
529
530                 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
531                 ma[0] = vm_page_lookup(object, 0);
532
533                 if ((rv != VM_PAGER_OK) || (ma[0] == NULL) || (ma[0]->valid == 0)) {
534                         if (ma[0]) {
535                                 vm_page_protect(ma[0], VM_PROT_NONE);
536                                 vm_page_free(ma[0]);
537                         }
538                         splx(s);
539                         return EIO;
540                 }
541         }
542
543         vm_page_wire(ma[0]);
544         vm_page_wakeup(ma[0]);
545         splx(s);
546
547         pmap_kenter((vm_offset_t) imgp->image_header, VM_PAGE_TO_PHYS(ma[0]));
548         imgp->firstpage = ma[0];
549
550         return 0;
551 }
552
553 void
554 exec_unmap_first_page(imgp)
555         struct image_params *imgp;
556 {
557         if (imgp->firstpage) {
558                 pmap_kremove((vm_offset_t) imgp->image_header);
559                 vm_page_unwire(imgp->firstpage, 1);
560                 imgp->firstpage = NULL;
561         }
562 }
563
564 /*
565  * Destroy old address space, and allocate a new stack
566  *      The new stack is only SGROWSIZ large because it is grown
567  *      automatically in trap.c.
568  */
569 int
570 exec_new_vmspace(imgp)
571         struct image_params *imgp;
572 {
573         int error;
574         struct vmspace *vmspace = imgp->proc->p_vmspace;
575         vm_offset_t stack_addr = USRSTACK - maxssiz;
576         vm_map_t map = &vmspace->vm_map;
577
578         imgp->vmspace_destroyed = 1;
579
580         /*
581          * Prevent a pending AIO from modifying the new address space.
582          */
583         aio_proc_rundown(imgp->proc);
584
585         /*
586          * Blow away entire process VM, if address space not shared,
587          * otherwise, create a new VM space so that other threads are
588          * not disrupted
589          */
590         if (vmspace->vm_refcnt == 1) {
591                 shmexit(vmspace);
592                 pmap_remove_pages(vmspace_pmap(vmspace), 0, VM_MAXUSER_ADDRESS);
593                 vm_map_remove(map, 0, VM_MAXUSER_ADDRESS);
594         } else {
595                 vmspace_exec(imgp->proc);
596                 vmspace = imgp->proc->p_vmspace;
597                 map = &vmspace->vm_map;
598         }
599
600         /* Allocate a new stack */
601         error = vm_map_stack(&vmspace->vm_map, stack_addr, (vm_size_t)maxssiz,
602             VM_PROT_ALL, VM_PROT_ALL, 0);
603         if (error)
604                 return (error);
605
606         /* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
607          * VM_STACK case, but they are still used to monitor the size of the
608          * process stack so we can check the stack rlimit.
609          */
610         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
611         vmspace->vm_maxsaddr = (char *)USRSTACK - maxssiz;
612
613         return(0);
614 }
615
616 /*
617  * Copy out argument and environment strings from the old process
618  *      address space into the temporary string buffer.
619  */
620 int
621 exec_copyin_args(struct image_args *args, char *fname,
622     enum exec_path_segflg segflg, char **argv, char **envv)
623 {
624         char    *argp, *envp;
625         int     error = 0;
626         size_t  length;
627
628         args->buf = (char *) kmem_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
629         if (args->buf == NULL)
630                 return (ENOMEM);
631         args->begin_argv = args->buf;
632         args->endp = args->begin_argv;
633         args->space = ARG_MAX;
634         args->argc = 0;
635         args->envc = 0;
636
637         args->fname = args->buf + ARG_MAX;
638
639         /*
640          * Copy the file name.
641          */
642         if (segflg == PATH_SYSSPACE) {
643                 error = copystr(fname, args->fname, PATH_MAX, &length);
644         } else if (segflg == PATH_USERSPACE) {
645                 error = copyinstr(fname, args->fname, PATH_MAX, &length);
646         }
647
648         /*
649          * extract argument strings
650          */
651
652         if (argv) {
653                 argp = (caddr_t) (intptr_t) fuword(argv);
654                 /*
655                  * First argument is a special case.  If it is a null
656                  * string, we must copy the file name into the string
657                  * buffer as the first argument.  This guarantees that
658                  * the interpreter knows what file to open in the case
659                  * that we exec an interpreted file.
660                  */
661                 while ((argp = (caddr_t) (intptr_t) fuword(argv++))) {
662                         if (argp == (caddr_t) -1) {
663                                 error = EFAULT;
664                                 goto cleanup;
665                         }
666                         error = copyinstr(argp, args->endp,
667                             args->space, &length);
668                         if (error == ENAMETOOLONG)
669                                 error = E2BIG;
670                         if (error)
671                                 goto cleanup;
672                         args->space -= length;
673                         args->endp += length;
674                         args->argc++;
675                 }
676         }       
677
678         args->begin_envv = args->endp;
679
680         /*
681          * extract environment strings
682          */
683
684         if (envv) {
685                 while ((envp = (caddr_t) (intptr_t) fuword(envv++))) {
686                         if (envp == (caddr_t) -1) {
687                                 error = EFAULT;
688                                 goto cleanup;
689                         }
690                         error = copyinstr(envp, args->endp, args->space,
691                             &length);
692                         if (error == ENAMETOOLONG)
693                                 error = E2BIG;
694                         if (error)
695                                 goto cleanup;
696                         args->space -= length;
697                         args->endp += length;
698                         args->envc++;
699                 }
700         }
701
702 cleanup:
703         if (error)
704                 exec_free_args(args);
705         return (error);
706 }
707
708 void
709 exec_free_args(struct image_args *args)
710 {
711         kmem_free_wakeup(exec_map, (vm_offset_t)args->buf, PATH_MAX + ARG_MAX);
712 }
713
714 /*
715  * Copy strings out to the new process address space, constructing
716  *      new arg and env vector tables. Return a pointer to the base
717  *      so that it can be used as the initial stack pointer.
718  */
719 register_t *
720 exec_copyout_strings(struct image_params *imgp)
721 {
722         int argc, envc;
723         char **vectp;
724         char *stringp, *destp;
725         register_t *stack_base;
726         struct ps_strings *arginfo;
727         int szsigcode;
728
729         /*
730          * Calculate string base and vector table pointers.
731          * Also deal with signal trampoline code for this exec type.
732          */
733         arginfo = (struct ps_strings *)PS_STRINGS;
734         szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);
735         destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
736             roundup((ARG_MAX - imgp->args->space), sizeof(char *));
737
738         /*
739          * install sigcode
740          */
741         if (szsigcode)
742                 copyout(imgp->proc->p_sysent->sv_sigcode,
743                     ((caddr_t)arginfo - szsigcode), szsigcode);
744
745         /*
746          * If we have a valid auxargs ptr, prepare some room
747          * on the stack.
748          */
749         if (imgp->auxargs)
750         /*
751          * The '+ 2' is for the null pointers at the end of each of the
752          * arg and env vector sets, and 'AT_COUNT*2' is room for the
753          * ELF Auxargs data.
754          */
755                 vectp = (char **)(destp - (imgp->args->argc +
756                     imgp->args->envc + 2 + AT_COUNT*2) * sizeof(char*));
757         else 
758         /*
759          * The '+ 2' is for the null pointers at the end of each of the
760          * arg and env vector sets
761          */
762                 vectp = (char **)
763                     (destp - (imgp->args->argc + imgp->args->envc + 2) *
764                     sizeof(char*));
765
766         /*
767          * vectp also becomes our initial stack base
768          */
769         stack_base = (register_t *)vectp;
770
771         stringp = imgp->args->begin_argv;
772         argc = imgp->args->argc;
773         envc = imgp->args->envc;
774
775         /*
776          * Copy out strings - arguments and environment.
777          */
778         copyout(stringp, destp, ARG_MAX - imgp->args->space);
779
780         /*
781          * Fill in "ps_strings" struct for ps, w, etc.
782          */
783         suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
784         suword(&arginfo->ps_nargvstr, argc);
785
786         /*
787          * Fill in argument portion of vector table.
788          */
789         for (; argc > 0; --argc) {
790                 suword(vectp++, (long)(intptr_t)destp);
791                 while (*stringp++ != 0)
792                         destp++;
793                 destp++;
794         }
795
796         /* a null vector table pointer seperates the argp's from the envp's */
797         suword(vectp++, 0);
798
799         suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
800         suword(&arginfo->ps_nenvstr, envc);
801
802         /*
803          * Fill in environment portion of vector table.
804          */
805         for (; envc > 0; --envc) {
806                 suword(vectp++, (long)(intptr_t)destp);
807                 while (*stringp++ != 0)
808                         destp++;
809                 destp++;
810         }
811
812         /* end of vector table is a null pointer */
813         suword(vectp, 0);
814
815         return (stack_base);
816 }
817
818 /*
819  * Check permissions of file to execute.
820  *      Return 0 for success or error code on failure.
821  */
822 int
823 exec_check_permissions(imgp)
824         struct image_params *imgp;
825 {
826         struct proc *p = imgp->proc;
827         struct vnode *vp = imgp->vp;
828         struct vattr *attr = imgp->attr;
829         struct thread *td = p->p_thread;
830         int error;
831
832         /* Get file attributes */
833         error = VOP_GETATTR(vp, attr, td);
834         if (error)
835                 return (error);
836
837         /*
838          * 1) Check if file execution is disabled for the filesystem that this
839          *      file resides on.
840          * 2) Insure that at least one execute bit is on - otherwise root
841          *      will always succeed, and we don't want to happen unless the
842          *      file really is executable.
843          * 3) Insure that the file is a regular file.
844          */
845         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
846             ((attr->va_mode & 0111) == 0) ||
847             (attr->va_type != VREG)) {
848                 return (EACCES);
849         }
850
851         /*
852          * Zero length files can't be exec'd
853          */
854         if (attr->va_size == 0)
855                 return (ENOEXEC);
856
857         /*
858          *  Check for execute permission to file based on current credentials.
859          */
860         error = VOP_ACCESS(vp, VEXEC, p->p_ucred, td);
861         if (error)
862                 return (error);
863
864         /*
865          * Check number of open-for-writes on the file and deny execution
866          * if there are any.
867          */
868         if (vp->v_writecount)
869                 return (ETXTBSY);
870
871         /*
872          * Call filesystem specific open routine (which does nothing in the
873          * general case).
874          */
875         error = VOP_OPEN(vp, FREAD, p->p_ucred, td);
876         if (error)
877                 return (error);
878
879         return (0);
880 }
881
882 /*
883  * Exec handler registration
884  */
885 int
886 exec_register(execsw_arg)
887         const struct execsw *execsw_arg;
888 {
889         const struct execsw **es, **xs, **newexecsw;
890         int count = 2;  /* New slot and trailing NULL */
891
892         if (execsw)
893                 for (es = execsw; *es; es++)
894                         count++;
895         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
896         if (newexecsw == NULL)
897                 return ENOMEM;
898         xs = newexecsw;
899         if (execsw)
900                 for (es = execsw; *es; es++)
901                         *xs++ = *es;
902         *xs++ = execsw_arg;
903         *xs = NULL;
904         if (execsw)
905                 free(execsw, M_TEMP);
906         execsw = newexecsw;
907         return 0;
908 }
909
910 int
911 exec_unregister(execsw_arg)
912         const struct execsw *execsw_arg;
913 {
914         const struct execsw **es, **xs, **newexecsw;
915         int count = 1;
916
917         if (execsw == NULL)
918                 panic("unregister with no handlers left?\n");
919
920         for (es = execsw; *es; es++) {
921                 if (*es == execsw_arg)
922                         break;
923         }
924         if (*es == NULL)
925                 return ENOENT;
926         for (es = execsw; *es; es++)
927                 if (*es != execsw_arg)
928                         count++;
929         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
930         if (newexecsw == NULL)
931                 return ENOMEM;
932         xs = newexecsw;
933         for (es = execsw; *es; es++)
934                 if (*es != execsw_arg)
935                         *xs++ = *es;
936         *xs = NULL;
937         if (execsw)
938                 free(execsw, M_TEMP);
939         execsw = newexecsw;
940         return 0;
941 }