Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[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.64 2008/10/26 04:29:19 sephe 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/priv.h>
46 #include <sys/ktrace.h>
47 #include <sys/signalvar.h>
48 #include <sys/pioctl.h>
49 #include <sys/nlookup.h>
50 #include <sys/sysent.h>
51 #include <sys/shm.h>
52 #include <sys/sysctl.h>
53 #include <sys/vnode.h>
54 #include <sys/vmmeter.h>
55 #include <sys/libkern.h>
56
57 #include <cpu/lwbuf.h>
58
59 #include <vm/vm.h>
60 #include <vm/vm_param.h>
61 #include <sys/lock.h>
62 #include <vm/pmap.h>
63 #include <vm/vm_page.h>
64 #include <vm/vm_map.h>
65 #include <vm/vm_kern.h>
66 #include <vm/vm_extern.h>
67 #include <vm/vm_object.h>
68 #include <vm/vnode_pager.h>
69 #include <vm/vm_pager.h>
70
71 #include <sys/user.h>
72 #include <sys/reg.h>
73
74 #include <sys/refcount.h>
75 #include <sys/thread2.h>
76 #include <sys/mplock2.h>
77
78 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
79 MALLOC_DEFINE(M_EXECARGS, "exec-args", "Exec arguments");
80
81 static register_t *exec_copyout_strings (struct image_params *);
82
83 /* XXX This should be vm_size_t. */
84 static u_long ps_strings = PS_STRINGS;
85 SYSCTL_ULONG(_kern, KERN_PS_STRINGS, ps_strings, CTLFLAG_RD, &ps_strings, 0, "");
86
87 /* XXX This should be vm_size_t. */
88 static u_long usrstack = USRSTACK;
89 SYSCTL_ULONG(_kern, KERN_USRSTACK, usrstack, CTLFLAG_RD, &usrstack, 0, "");
90
91 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
92 SYSCTL_LONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
93     &ps_arg_cache_limit, 0, "");
94
95 int ps_argsopen = 1;
96 SYSCTL_INT(_kern, OID_AUTO, ps_argsopen, CTLFLAG_RW, &ps_argsopen, 0, "");
97
98 static int ktrace_suid = 0;
99 SYSCTL_INT(_kern, OID_AUTO, ktrace_suid, CTLFLAG_RW, &ktrace_suid, 0, "");
100
101 void print_execve_args(struct image_args *args);
102 int debug_execve_args = 0;
103 SYSCTL_INT(_kern, OID_AUTO, debug_execve_args, CTLFLAG_RW, &debug_execve_args,
104     0, "");
105
106 /*
107  * Exec arguments object cache
108  */
109 static struct objcache *exec_objcache;
110
111 static
112 void
113 exec_objcache_init(void *arg __unused)
114 {
115         int cluster_limit;
116
117         cluster_limit = 16;     /* up to this many objects */
118         exec_objcache = objcache_create_mbacked(
119                                         M_EXECARGS, PATH_MAX + ARG_MAX,
120                                         &cluster_limit,
121                                         2,      /* minimal magazine capacity */
122                                         NULL, NULL, NULL);
123 }
124 SYSINIT(exec_objcache, SI_BOOT2_MACHDEP, SI_ORDER_ANY, exec_objcache_init, 0);
125
126 /*
127  * stackgap_random specifies if the stackgap should have a random size added
128  * to it.  It must be a power of 2.  If non-zero, the stack gap will be 
129  * calculated as: ALIGN(karc4random() & (stackgap_random - 1)).
130  */
131 static int stackgap_random = 1024;
132 static int
133 sysctl_kern_stackgap(SYSCTL_HANDLER_ARGS)
134 {
135         int error, new_val;
136         new_val = stackgap_random;
137         error = sysctl_handle_int(oidp, &new_val, 0, req);
138         if (error != 0 || req->newptr == NULL)
139                 return (error);
140         if ((new_val < 0) || (new_val > 16 * PAGE_SIZE) || ! powerof2(new_val))
141                 return (EINVAL);
142         stackgap_random = new_val;
143
144         return(0);
145 }
146
147 SYSCTL_PROC(_kern, OID_AUTO, stackgap_random, CTLFLAG_RW|CTLTYPE_UINT, 
148         0, 0, sysctl_kern_stackgap, "IU", "Max random stack gap (power of 2)");
149         
150 void
151 print_execve_args(struct image_args *args)
152 {
153         char *cp;
154         int ndx;
155
156         cp = args->begin_argv;
157         for (ndx = 0; ndx < args->argc; ndx++) {
158                 kprintf("\targv[%d]: %s\n", ndx, cp);
159                 while (*cp++ != '\0');
160         }
161         for (ndx = 0; ndx < args->envc; ndx++) {
162                 kprintf("\tenvv[%d]: %s\n", ndx, cp);
163                 while (*cp++ != '\0');
164         }
165 }
166
167 /*
168  * Each of the items is a pointer to a `const struct execsw', hence the
169  * double pointer here.
170  */
171 static const struct execsw **execsw;
172
173 /*
174  * Replace current vmspace with a new binary.
175  * Returns 0 on success, > 0 on recoverable error (use as errno).
176  * Returns -1 on lethal error which demands killing of the current
177  * process!
178  */
179 int
180 kern_execve(struct nlookupdata *nd, struct image_args *args)
181 {
182         struct thread *td = curthread;
183         struct lwp *lp = td->td_lwp;
184         struct proc *p = td->td_proc;
185         register_t *stack_base;
186         struct pargs *pa;
187         struct sigacts *ops;
188         struct sigacts *nps;
189         int error, len, i;
190         struct image_params image_params, *imgp;
191         struct vattr attr;
192         int (*img_first) (struct image_params *);
193
194         if (debug_execve_args) {
195                 kprintf("%s()\n", __func__);
196                 print_execve_args(args);
197         }
198
199         KKASSERT(p);
200         lwkt_gettoken(&p->p_token);
201         imgp = &image_params;
202
203         /*
204          * NOTE: P_INEXEC is handled by exec_new_vmspace() now.  We make
205          * no modifications to the process at all until we get there.
206          *
207          * Note that multiple threads may be trying to exec at the same
208          * time.  exec_new_vmspace() handles that too.
209          */
210
211         /*
212          * Initialize part of the common data
213          */
214         imgp->proc = p;
215         imgp->args = args;
216         imgp->attr = &attr;
217         imgp->entry_addr = 0;
218         imgp->resident = 0;
219         imgp->vmspace_destroyed = 0;
220         imgp->interpreted = 0;
221         imgp->interpreter_name[0] = 0;
222         imgp->auxargs = NULL;
223         imgp->vp = NULL;
224         imgp->firstpage = NULL;
225         imgp->ps_strings = 0;
226         imgp->image_header = NULL;
227
228 interpret:
229
230         /*
231          * Translate the file name to a vnode.  Unlock the cache entry to
232          * improve parallelism for programs exec'd in parallel.
233          */
234         if ((error = nlookup(nd)) != 0)
235                 goto exec_fail;
236         error = cache_vget(&nd->nl_nch, nd->nl_cred, LK_EXCLUSIVE, &imgp->vp);
237         KKASSERT(nd->nl_flags & NLC_NCPISLOCKED);
238         nd->nl_flags &= ~NLC_NCPISLOCKED;
239         cache_unlock(&nd->nl_nch);
240         if (error)
241                 goto exec_fail;
242
243         /*
244          * Check file permissions (also 'opens' file).
245          * Include also the top level mount in the check.
246          */
247         error = exec_check_permissions(imgp, nd->nl_nch.mount);
248         if (error) {
249                 vn_unlock(imgp->vp);
250                 goto exec_fail_dealloc;
251         }
252
253         error = exec_map_first_page(imgp);
254         vn_unlock(imgp->vp);
255         if (error)
256                 goto exec_fail_dealloc;
257
258         if (debug_execve_args && imgp->interpreted) {
259                 kprintf("    target is interpreted -- recursive pass\n");
260                 kprintf("    interpreter: %s\n", imgp->interpreter_name);
261                 print_execve_args(args);
262         }
263
264         /*
265          *      If the current process has a special image activator it
266          *      wants to try first, call it.   For example, emulating shell 
267          *      scripts differently.
268          */
269         error = -1;
270         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
271                 error = img_first(imgp);
272
273         /*
274          *      If the vnode has a registered vmspace, exec the vmspace
275          */
276         if (error == -1 && imgp->vp->v_resident) {
277                 error = exec_resident_imgact(imgp);
278         }
279
280         /*
281          *      Loop through the list of image activators, calling each one.
282          *      An activator returns -1 if there is no match, 0 on success,
283          *      and an error otherwise.
284          */
285         for (i = 0; error == -1 && execsw[i]; ++i) {
286                 if (execsw[i]->ex_imgact == NULL ||
287                     execsw[i]->ex_imgact == img_first) {
288                         continue;
289                 }
290                 error = (*execsw[i]->ex_imgact)(imgp);
291         }
292
293         if (error) {
294                 if (error == -1)
295                         error = ENOEXEC;
296                 goto exec_fail_dealloc;
297         }
298
299         /*
300          * Special interpreter operation, cleanup and loop up to try to
301          * activate the interpreter.
302          */
303         if (imgp->interpreted) {
304                 exec_unmap_first_page(imgp);
305                 nlookup_done(nd);
306                 vrele(imgp->vp);
307                 imgp->vp = NULL;
308                 error = nlookup_init(nd, imgp->interpreter_name, UIO_SYSSPACE,
309                                         NLC_FOLLOW);
310                 if (error)
311                         goto exec_fail;
312                 goto interpret;
313         }
314
315         /*
316          * Copy out strings (args and env) and initialize stack base
317          */
318         stack_base = exec_copyout_strings(imgp);
319         p->p_vmspace->vm_minsaddr = (char *)stack_base;
320
321         /*
322          * If custom stack fixup routine present for this process
323          * let it do the stack setup.  If we are running a resident
324          * image there is no auxinfo or other image activator context
325          * so don't try to add fixups to the stack.
326          *
327          * Else stuff argument count as first item on stack
328          */
329         if (p->p_sysent->sv_fixup && imgp->resident == 0)
330                 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
331         else
332                 suword(--stack_base, imgp->args->argc);
333
334         /*
335          * For security and other reasons, the file descriptor table cannot
336          * be shared after an exec.
337          */
338         if (p->p_fd->fd_refcnt > 1) {
339                 struct filedesc *tmp;
340
341                 error = fdcopy(p, &tmp);
342                 if (error != 0)
343                         goto exec_fail;
344                 fdfree(p, tmp);
345         }
346
347         /*
348          * For security and other reasons, signal handlers cannot
349          * be shared after an exec. The new proces gets a copy of the old
350          * handlers. In execsigs(), the new process will have its signals
351          * reset.
352          */
353         ops = p->p_sigacts;
354         if (ops->ps_refcnt > 1) {
355                 nps = kmalloc(sizeof(*nps), M_SUBPROC, M_WAITOK);
356                 bcopy(ops, nps, sizeof(*nps));
357                 refcount_init(&nps->ps_refcnt, 1);
358                 p->p_sigacts = nps;
359                 if (refcount_release(&ops->ps_refcnt)) {
360                         kfree(ops, M_SUBPROC);
361                         ops = NULL;
362                 }
363         }
364
365         /*
366          * For security and other reasons virtual kernels cannot be
367          * inherited by an exec.  This also allows a virtual kernel
368          * to fork/exec unrelated applications.
369          */
370         if (p->p_vkernel)
371                 vkernel_exit(p);
372
373         /* Stop profiling */
374         stopprofclock(p);
375
376         /* close files on exec */
377         fdcloseexec(p);
378
379         /* reset caught signals */
380         execsigs(p);
381
382         /* name this process - nameiexec(p, ndp) */
383         len = min(nd->nl_nch.ncp->nc_nlen, MAXCOMLEN);
384         bcopy(nd->nl_nch.ncp->nc_name, p->p_comm, len);
385         p->p_comm[len] = 0;
386         bcopy(p->p_comm, lp->lwp_thread->td_comm, MAXCOMLEN+1);
387
388         /*
389          * mark as execed, wakeup the process that vforked (if any) and tell
390          * it that it now has its own resources back
391          */
392         p->p_flag |= P_EXEC;
393         if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
394                 p->p_flag &= ~P_PPWAIT;
395                 wakeup((caddr_t)p->p_pptr);
396         }
397
398         /*
399          * Implement image setuid/setgid.
400          *
401          * Don't honor setuid/setgid if the filesystem prohibits it or if
402          * the process is being traced.
403          */
404         if ((((attr.va_mode & VSUID) && p->p_ucred->cr_uid != attr.va_uid) ||
405              ((attr.va_mode & VSGID) && p->p_ucred->cr_gid != attr.va_gid)) &&
406             (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
407             (p->p_flag & P_TRACED) == 0) {
408                 /*
409                  * Turn off syscall tracing for set-id programs, except for
410                  * root.  Record any set-id flags first to make sure that
411                  * we do not regain any tracing during a possible block.
412                  */
413                 setsugid();
414                 if (p->p_tracenode && ktrace_suid == 0 &&
415                     priv_check(td, PRIV_ROOT) != 0) {
416                         ktrdestroy(&p->p_tracenode);
417                         p->p_traceflag = 0;
418                 }
419                 /* Close any file descriptors 0..2 that reference procfs */
420                 setugidsafety(p);
421                 /* Make sure file descriptors 0..2 are in use. */
422                 error = fdcheckstd(lp);
423                 if (error != 0)
424                         goto exec_fail_dealloc;
425                 /*
426                  * Set the new credentials.
427                  */
428                 cratom(&p->p_ucred);
429                 if (attr.va_mode & VSUID)
430                         change_euid(attr.va_uid);
431                 if (attr.va_mode & VSGID)
432                         p->p_ucred->cr_gid = attr.va_gid;
433
434                 /*
435                  * Clear local varsym variables
436                  */
437                 varsymset_clean(&p->p_varsymset);
438         } else {
439                 if (p->p_ucred->cr_uid == p->p_ucred->cr_ruid &&
440                     p->p_ucred->cr_gid == p->p_ucred->cr_rgid)
441                         p->p_flag &= ~P_SUGID;
442         }
443
444         /*
445          * Implement correct POSIX saved-id behavior.
446          */
447         if (p->p_ucred->cr_svuid != p->p_ucred->cr_uid ||
448             p->p_ucred->cr_svgid != p->p_ucred->cr_gid) {
449                 cratom(&p->p_ucred);
450                 p->p_ucred->cr_svuid = p->p_ucred->cr_uid;
451                 p->p_ucred->cr_svgid = p->p_ucred->cr_gid;
452         }
453
454         /*
455          * Store the vp for use in procfs
456          */
457         if (p->p_textvp)                /* release old reference */
458                 vrele(p->p_textvp);
459         p->p_textvp = imgp->vp;
460         vref(p->p_textvp);
461
462         /* Release old namecache handle to text file */
463         if (p->p_textnch.ncp)
464                 cache_drop(&p->p_textnch);
465
466         if (nd->nl_nch.mount)
467                 cache_copy(&nd->nl_nch, &p->p_textnch);
468
469         /*
470          * Notify others that we exec'd, and clear the P_INEXEC flag
471          * as we're now a bona fide freshly-execed process.
472          */
473         KNOTE(&p->p_klist, NOTE_EXEC);
474         p->p_flag &= ~P_INEXEC;
475
476         /*
477          * If tracing the process, trap to debugger so breakpoints
478          *      can be set before the program executes.
479          */
480         STOPEVENT(p, S_EXEC, 0);
481
482         if (p->p_flag & P_TRACED)
483                 ksignal(p, SIGTRAP);
484
485         /* clear "fork but no exec" flag, as we _are_ execing */
486         p->p_acflag &= ~AFORK;
487
488         /* Set values passed into the program in registers. */
489         exec_setregs(imgp->entry_addr, (u_long)(uintptr_t)stack_base,
490             imgp->ps_strings);
491
492         /* Set the access time on the vnode */
493         vn_mark_atime(imgp->vp, td);
494
495         /*
496          * Free any previous argument cache
497          */
498         pa = p->p_args;
499         p->p_args = NULL;
500         if (pa && refcount_release(&pa->ar_ref)) {
501                 kfree(pa, M_PARGS);
502                 pa = NULL;
503         }
504
505         /*
506          * Cache arguments if they fit inside our allowance
507          */
508         i = imgp->args->begin_envv - imgp->args->begin_argv;
509         if (sizeof(struct pargs) + i <= ps_arg_cache_limit) {
510                 pa = kmalloc(sizeof(struct pargs) + i, M_PARGS, M_WAITOK);
511                 refcount_init(&pa->ar_ref, 1);
512                 pa->ar_length = i;
513                 bcopy(imgp->args->begin_argv, pa->ar_args, i);
514                 KKASSERT(p->p_args == NULL);
515                 p->p_args = pa;
516         }
517
518 exec_fail_dealloc:
519
520         /*
521          * free various allocated resources
522          */
523         if (imgp->firstpage)
524                 exec_unmap_first_page(imgp);
525
526         if (imgp->vp) {
527                 vrele(imgp->vp);
528                 imgp->vp = NULL;
529         }
530
531         if (error == 0) {
532                 ++mycpu->gd_cnt.v_exec;
533                 lwkt_reltoken(&p->p_token);
534                 return (0);
535         }
536
537 exec_fail:
538         /*
539          * we're done here, clear P_INEXEC if we were the ones that
540          * set it.  Otherwise if vmspace_destroyed is still set we
541          * raced another thread and that thread is responsible for
542          * clearing it.
543          */
544         if (imgp->vmspace_destroyed & 2)
545                 p->p_flag &= ~P_INEXEC;
546         lwkt_reltoken(&p->p_token);
547         if (imgp->vmspace_destroyed) {
548                 /*
549                  * Sorry, no more process anymore. exit gracefully.
550                  * However we can't die right here, because our
551                  * caller might have to clean up, so indicate a
552                  * lethal error by returning -1.
553                  */
554                 return(-1);
555         } else {
556                 return(error);
557         }
558 }
559
560 /*
561  * execve() system call.
562  *
563  * MPALMOSTSAFE
564  */
565 int
566 sys_execve(struct execve_args *uap)
567 {
568         struct nlookupdata nd;
569         struct image_args args;
570         int error;
571
572         bzero(&args, sizeof(args));
573
574         get_mplock();
575         error = nlookup_init(&nd, uap->fname, UIO_USERSPACE, NLC_FOLLOW);
576         if (error == 0) {
577                 error = exec_copyin_args(&args, uap->fname, PATH_USERSPACE,
578                                         uap->argv, uap->envv);
579         }
580         if (error == 0)
581                 error = kern_execve(&nd, &args);
582         nlookup_done(&nd);
583         exec_free_args(&args);
584
585         if (error < 0) {
586                 /* We hit a lethal error condition.  Let's die now. */
587                 exit1(W_EXITCODE(0, SIGABRT));
588                 /* NOTREACHED */
589         }
590         rel_mplock();
591
592         /*
593          * The syscall result is returned in registers to the new program.
594          * Linux will register %edx as an atexit function and we must be
595          * sure to set it to 0.  XXX
596          */
597         if (error == 0)
598                 uap->sysmsg_result64 = 0;
599
600         return (error);
601 }
602
603 int
604 exec_map_page(struct image_params *imgp, vm_pindex_t pageno,
605               struct lwbuf **plwb, const char **pdata)
606 {
607         int rv;
608         vm_page_t ma;
609         vm_page_t m;
610         vm_object_t object;
611
612         /*
613          * The file has to be mappable.
614          */
615         if ((object = imgp->vp->v_object) == NULL)
616                 return (EIO);
617
618         if (pageno >= object->size)
619                 return (EIO);
620
621         m = vm_page_grab(object, pageno, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
622
623         lwkt_gettoken(&vm_token);
624         while ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
625                 ma = m;
626
627                 /*
628                  * get_pages unbusies all the requested pages except the
629                  * primary page (at index 0 in this case).  The primary
630                  * page may have been wired during the pagein (e.g. by
631                  * the buffer cache) so vnode_pager_freepage() must be
632                  * used to properly release it.
633                  */
634                 rv = vm_pager_get_page(object, &ma, 1);
635                 m = vm_page_lookup(object, pageno);
636
637                 if (rv != VM_PAGER_OK || m == NULL || m->valid == 0) {
638                         if (m) {
639                                 vm_page_protect(m, VM_PROT_NONE);
640                                 vnode_pager_freepage(m);
641                         }
642                         lwkt_reltoken(&vm_token);
643                         return EIO;
644                 }
645         }
646         vm_page_hold(m);        /* requires vm_token to be held */
647         vm_page_wakeup(m);      /* unbusy the page */
648         lwkt_reltoken(&vm_token);
649
650         *plwb = lwbuf_alloc(m, *plwb);
651         *pdata = (void *)lwbuf_kva(*plwb);
652
653         return (0);
654 }
655
656 int
657 exec_map_first_page(struct image_params *imgp)
658 {
659         int err;
660
661         if (imgp->firstpage)
662                 exec_unmap_first_page(imgp);
663
664         imgp->firstpage = &imgp->firstpage_cache;
665         err = exec_map_page(imgp, 0, &imgp->firstpage, &imgp->image_header);
666
667         if (err)
668                 return err;
669
670         return 0;
671 }
672
673 void
674 exec_unmap_page(struct lwbuf *lwb)
675 {
676         vm_page_t m;
677
678         crit_enter();
679         if (lwb != NULL) {
680                 m = lwbuf_page(lwb);
681                 lwbuf_free(lwb);
682                 vm_page_unhold(m);
683         }
684         crit_exit();
685 }
686
687 void
688 exec_unmap_first_page(struct image_params *imgp)
689 {
690         exec_unmap_page(imgp->firstpage);
691         imgp->firstpage = NULL;
692         imgp->image_header = NULL;
693 }
694
695 /*
696  * Destroy old address space, and allocate a new stack
697  *      The new stack is only SGROWSIZ large because it is grown
698  *      automatically in trap.c.
699  *
700  * This is the point of no return.
701  */
702 int
703 exec_new_vmspace(struct image_params *imgp, struct vmspace *vmcopy)
704 {
705         struct vmspace *vmspace = imgp->proc->p_vmspace;
706         vm_offset_t stack_addr = USRSTACK - maxssiz;
707         struct proc *p;
708         vm_map_t map;
709         int error;
710
711         /*
712          * Indicate that we cannot gracefully error out any more, kill
713          * any other threads present, and set P_INEXEC to indicate that
714          * we are now messing with the process structure proper.
715          *
716          * If killalllwps() races return an error which coupled with
717          * vmspace_destroyed will cause us to exit.  This is what we
718          * want since another thread is patiently waiting for us to exit
719          * in that case.
720          */
721         p = curproc;
722         imgp->vmspace_destroyed = 1;
723
724         if (curthread->td_proc->p_nthreads > 1) {
725                 error = killalllwps(1);
726                 if (error)
727                         return (error);
728         }
729         imgp->vmspace_destroyed |= 2;   /* we are responsible for P_INEXEC */
730         p->p_flag |= P_INEXEC;
731
732         /*
733          * Blow away entire process VM, if address space not shared,
734          * otherwise, create a new VM space so that other threads are
735          * not disrupted.  If we are execing a resident vmspace we
736          * create a duplicate of it and remap the stack.
737          *
738          * The exitingcnt test is not strictly necessary but has been
739          * included for code sanity (to make the code more deterministic).
740          */
741         map = &vmspace->vm_map;
742         if (vmcopy) {
743                 vmspace_exec(imgp->proc, vmcopy);
744                 vmspace = imgp->proc->p_vmspace;
745                 pmap_remove_pages(vmspace_pmap(vmspace), stack_addr, USRSTACK);
746                 map = &vmspace->vm_map;
747         } else if (vmspace->vm_sysref.refcnt == 1 &&
748                    vmspace->vm_exitingcnt == 0) {
749                 shmexit(vmspace);
750                 if (vmspace->vm_upcalls)
751                         upc_release(vmspace, ONLY_LWP_IN_PROC(imgp->proc));
752                 pmap_remove_pages(vmspace_pmap(vmspace),
753                         0, VM_MAX_USER_ADDRESS);
754                 vm_map_remove(map, 0, VM_MAX_USER_ADDRESS);
755         } else {
756                 vmspace_exec(imgp->proc, NULL);
757                 vmspace = imgp->proc->p_vmspace;
758                 map = &vmspace->vm_map;
759         }
760
761         /* Allocate a new stack */
762         error = vm_map_stack(&vmspace->vm_map, stack_addr, (vm_size_t)maxssiz,
763                              0, VM_PROT_ALL, VM_PROT_ALL, 0);
764         if (error)
765                 return (error);
766
767         /* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
768          * VM_STACK case, but they are still used to monitor the size of the
769          * process stack so we can check the stack rlimit.
770          */
771         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
772         vmspace->vm_maxsaddr = (char *)USRSTACK - maxssiz;
773
774         return(0);
775 }
776
777 /*
778  * Copy out argument and environment strings from the old process
779  *      address space into the temporary string buffer.
780  */
781 int
782 exec_copyin_args(struct image_args *args, char *fname,
783                 enum exec_path_segflg segflg, char **argv, char **envv)
784 {
785         char    *argp, *envp;
786         int     error = 0;
787         size_t  length;
788
789         args->buf = objcache_get(exec_objcache, M_WAITOK);
790         if (args->buf == NULL)
791                 return (ENOMEM);
792         args->begin_argv = args->buf;
793         args->endp = args->begin_argv;
794         args->space = ARG_MAX;
795
796         args->fname = args->buf + ARG_MAX;
797
798         /*
799          * Copy the file name.
800          */
801         if (segflg == PATH_SYSSPACE) {
802                 error = copystr(fname, args->fname, PATH_MAX, &length);
803         } else if (segflg == PATH_USERSPACE) {
804                 error = copyinstr(fname, args->fname, PATH_MAX, &length);
805         }
806
807         /*
808          * Extract argument strings.  argv may not be NULL.  The argv
809          * array is terminated by a NULL entry.  We special-case the
810          * situation where argv[0] is NULL by passing { filename, NULL }
811          * to the new program to guarentee that the interpreter knows what
812          * file to open in case we exec an interpreted file.   Note that
813          * a NULL argv[0] terminates the argv[] array.
814          *
815          * XXX the special-casing of argv[0] is historical and needs to be
816          * revisited.
817          */
818         if (argv == NULL)
819                 error = EFAULT;
820         if (error == 0) {
821                 while ((argp = (caddr_t)(intptr_t)fuword(argv++)) != NULL) {
822                         if (argp == (caddr_t)-1) {
823                                 error = EFAULT;
824                                 break;
825                         }
826                         error = copyinstr(argp, args->endp,
827                                             args->space, &length);
828                         if (error) {
829                                 if (error == ENAMETOOLONG)
830                                         error = E2BIG;
831                                 break;
832                         }
833                         args->space -= length;
834                         args->endp += length;
835                         args->argc++;
836                 }
837                 if (args->argc == 0 && error == 0) {
838                         length = strlen(args->fname) + 1;
839                         if (length > args->space) {
840                                 error = E2BIG;
841                         } else {
842                                 bcopy(args->fname, args->endp, length);
843                                 args->space -= length;
844                                 args->endp += length;
845                                 args->argc++;
846                         }
847                 }
848         }       
849
850         args->begin_envv = args->endp;
851
852         /*
853          * extract environment strings.  envv may be NULL.
854          */
855         if (envv && error == 0) {
856                 while ((envp = (caddr_t) (intptr_t) fuword(envv++))) {
857                         if (envp == (caddr_t) -1) {
858                                 error = EFAULT;
859                                 break;
860                         }
861                         error = copyinstr(envp, args->endp, args->space,
862                             &length);
863                         if (error) {
864                                 if (error == ENAMETOOLONG)
865                                         error = E2BIG;
866                                 break;
867                         }
868                         args->space -= length;
869                         args->endp += length;
870                         args->envc++;
871                 }
872         }
873         return (error);
874 }
875
876 void
877 exec_free_args(struct image_args *args)
878 {
879         if (args->buf) {
880                 objcache_put(exec_objcache, args->buf);
881                 args->buf = NULL;
882         }
883 }
884
885 /*
886  * Copy strings out to the new process address space, constructing
887  *      new arg and env vector tables. Return a pointer to the base
888  *      so that it can be used as the initial stack pointer.
889  */
890 register_t *
891 exec_copyout_strings(struct image_params *imgp)
892 {
893         int argc, envc, sgap;
894         char **vectp;
895         char *stringp, *destp;
896         register_t *stack_base;
897         struct ps_strings *arginfo;
898         int szsigcode;
899
900         /*
901          * Calculate string base and vector table pointers.
902          * Also deal with signal trampoline code for this exec type.
903          */
904         arginfo = (struct ps_strings *)PS_STRINGS;
905         szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);
906         if (stackgap_random != 0)
907                 sgap = ALIGN(karc4random() & (stackgap_random - 1));
908         else
909                 sgap = 0;
910         destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE - sgap -
911             roundup((ARG_MAX - imgp->args->space), sizeof(char *));
912
913         /*
914          * install sigcode
915          */
916         if (szsigcode)
917                 copyout(imgp->proc->p_sysent->sv_sigcode,
918                     ((caddr_t)arginfo - szsigcode), szsigcode);
919
920         /*
921          * If we have a valid auxargs ptr, prepare some room
922          * on the stack.
923          *
924          * The '+ 2' is for the null pointers at the end of each of the
925          * arg and env vector sets, and 'AT_COUNT*2' is room for the
926          * ELF Auxargs data.
927          */
928         if (imgp->auxargs) {
929                 vectp = (char **)(destp - (imgp->args->argc +
930                         imgp->args->envc + 2 + AT_COUNT * 2) * sizeof(char*));
931         } else {
932                 vectp = (char **)(destp - (imgp->args->argc +
933                         imgp->args->envc + 2) * sizeof(char*));
934         }
935
936         /*
937          * NOTE: don't bother aligning the stack here for GCC 2.x, it will
938          * be done in crt1.o.  Note that GCC 3.x aligns the stack in main.
939          */
940
941         /*
942          * vectp also becomes our initial stack base
943          */
944         stack_base = (register_t *)vectp;
945
946         stringp = imgp->args->begin_argv;
947         argc = imgp->args->argc;
948         envc = imgp->args->envc;
949
950         /*
951          * Copy out strings - arguments and environment.
952          */
953         copyout(stringp, destp, ARG_MAX - imgp->args->space);
954
955         /*
956          * Fill in "ps_strings" struct for ps, w, etc.
957          */
958         suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
959         suword(&arginfo->ps_nargvstr, argc);
960
961         /*
962          * Fill in argument portion of vector table.
963          */
964         for (; argc > 0; --argc) {
965                 suword(vectp++, (long)(intptr_t)destp);
966                 while (*stringp++ != 0)
967                         destp++;
968                 destp++;
969         }
970
971         /* a null vector table pointer separates the argp's from the envp's */
972         suword(vectp++, 0);
973
974         suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
975         suword(&arginfo->ps_nenvstr, envc);
976
977         /*
978          * Fill in environment portion of vector table.
979          */
980         for (; envc > 0; --envc) {
981                 suword(vectp++, (long)(intptr_t)destp);
982                 while (*stringp++ != 0)
983                         destp++;
984                 destp++;
985         }
986
987         /* end of vector table is a null pointer */
988         suword(vectp, 0);
989
990         return (stack_base);
991 }
992
993 /*
994  * Check permissions of file to execute.
995  *      Return 0 for success or error code on failure.
996  */
997 int
998 exec_check_permissions(struct image_params *imgp, struct mount *topmnt)
999 {
1000         struct proc *p = imgp->proc;
1001         struct vnode *vp = imgp->vp;
1002         struct vattr *attr = imgp->attr;
1003         int error;
1004
1005         /* Get file attributes */
1006         error = VOP_GETATTR(vp, attr);
1007         if (error)
1008                 return (error);
1009
1010         /*
1011          * 1) Check if file execution is disabled for the filesystem that this
1012          *      file resides on.
1013          * 2) Insure that at least one execute bit is on - otherwise root
1014          *      will always succeed, and we don't want to happen unless the
1015          *      file really is executable.
1016          * 3) Insure that the file is a regular file.
1017          */
1018         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1019             ((topmnt != NULL) && (topmnt->mnt_flag & MNT_NOEXEC)) ||
1020             ((attr->va_mode & 0111) == 0) ||
1021             (attr->va_type != VREG)) {
1022                 return (EACCES);
1023         }
1024
1025         /*
1026          * Zero length files can't be exec'd
1027          */
1028         if (attr->va_size == 0)
1029                 return (ENOEXEC);
1030
1031         /*
1032          *  Check for execute permission to file based on current credentials.
1033          */
1034         error = VOP_EACCESS(vp, VEXEC, p->p_ucred);
1035         if (error)
1036                 return (error);
1037
1038         /*
1039          * Check number of open-for-writes on the file and deny execution
1040          * if there are any.
1041          */
1042         if (vp->v_writecount)
1043                 return (ETXTBSY);
1044
1045         /*
1046          * Call filesystem specific open routine, which allows us to read,
1047          * write, and mmap the file.  Without the VOP_OPEN we can only
1048          * stat the file.
1049          */
1050         error = VOP_OPEN(vp, FREAD, p->p_ucred, NULL);
1051         if (error)
1052                 return (error);
1053
1054         return (0);
1055 }
1056
1057 /*
1058  * Exec handler registration
1059  */
1060 int
1061 exec_register(const struct execsw *execsw_arg)
1062 {
1063         const struct execsw **es, **xs, **newexecsw;
1064         int count = 2;  /* New slot and trailing NULL */
1065
1066         if (execsw)
1067                 for (es = execsw; *es; es++)
1068                         count++;
1069         newexecsw = kmalloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1070         xs = newexecsw;
1071         if (execsw)
1072                 for (es = execsw; *es; es++)
1073                         *xs++ = *es;
1074         *xs++ = execsw_arg;
1075         *xs = NULL;
1076         if (execsw)
1077                 kfree(execsw, M_TEMP);
1078         execsw = newexecsw;
1079         return 0;
1080 }
1081
1082 int
1083 exec_unregister(const struct execsw *execsw_arg)
1084 {
1085         const struct execsw **es, **xs, **newexecsw;
1086         int count = 1;
1087
1088         if (execsw == NULL)
1089                 panic("unregister with no handlers left?");
1090
1091         for (es = execsw; *es; es++) {
1092                 if (*es == execsw_arg)
1093                         break;
1094         }
1095         if (*es == NULL)
1096                 return ENOENT;
1097         for (es = execsw; *es; es++)
1098                 if (*es != execsw_arg)
1099                         count++;
1100         newexecsw = kmalloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1101         xs = newexecsw;
1102         for (es = execsw; *es; es++)
1103                 if (*es != execsw_arg)
1104                         *xs++ = *es;
1105         *xs = NULL;
1106         if (execsw)
1107                 kfree(execsw, M_TEMP);
1108         execsw = newexecsw;
1109         return 0;
1110 }