]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_exec.c
This commit was generated by cvs2svn to compensate for changes in r153667,
[FreeBSD/FreeBSD.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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_hwpmc_hooks.h"
31 #include "opt_ktrace.h"
32 #include "opt_mac.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/eventhandler.h>
37 #include <sys/lock.h>
38 #include <sys/mutex.h>
39 #include <sys/sysproto.h>
40 #include <sys/signalvar.h>
41 #include <sys/kernel.h>
42 #include <sys/mac.h>
43 #include <sys/mount.h>
44 #include <sys/filedesc.h>
45 #include <sys/fcntl.h>
46 #include <sys/acct.h>
47 #include <sys/exec.h>
48 #include <sys/imgact.h>
49 #include <sys/imgact_elf.h>
50 #include <sys/wait.h>
51 #include <sys/malloc.h>
52 #include <sys/proc.h>
53 #include <sys/pioctl.h>
54 #include <sys/namei.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sf_buf.h>
57 #include <sys/syscallsubr.h>
58 #include <sys/sysent.h>
59 #include <sys/shm.h>
60 #include <sys/sysctl.h>
61 #include <sys/vnode.h>
62 #ifdef KTRACE
63 #include <sys/ktrace.h>
64 #endif
65
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <vm/pmap.h>
69 #include <vm/vm_page.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_extern.h>
73 #include <vm/vm_object.h>
74 #include <vm/vm_pager.h>
75
76 #ifdef  HWPMC_HOOKS
77 #include <sys/pmckern.h>
78 #endif
79
80 #include <machine/reg.h>
81
82 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
83
84 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
85 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
86 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
87 static int do_execve(struct thread *td, struct image_args *args,
88     struct mac *mac_p);
89
90 /* XXX This should be vm_size_t. */
91 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
92     NULL, 0, sysctl_kern_ps_strings, "LU", "");
93
94 /* XXX This should be vm_size_t. */
95 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD,
96     NULL, 0, sysctl_kern_usrstack, "LU", "");
97
98 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
99     NULL, 0, sysctl_kern_stackprot, "I", "");
100
101 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
102 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
103     &ps_arg_cache_limit, 0, "");
104
105 static int
106 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
107 {
108         struct proc *p;
109         int error;
110
111         p = curproc;
112 #ifdef SCTL_MASK32
113         if (req->flags & SCTL_MASK32) {
114                 unsigned int val;
115                 val = (unsigned int)p->p_sysent->sv_psstrings;
116                 error = SYSCTL_OUT(req, &val, sizeof(val));
117         } else
118 #endif
119                 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
120                    sizeof(p->p_sysent->sv_psstrings));
121         return error;
122 }
123
124 static int
125 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
126 {
127         struct proc *p;
128         int error;
129
130         p = curproc;
131 #ifdef SCTL_MASK32
132         if (req->flags & SCTL_MASK32) {
133                 unsigned int val;
134                 val = (unsigned int)p->p_sysent->sv_usrstack;
135                 error = SYSCTL_OUT(req, &val, sizeof(val));
136         } else
137 #endif
138                 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
139                     sizeof(p->p_sysent->sv_usrstack));
140         return error;
141 }
142
143 static int
144 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
145 {
146         struct proc *p;
147
148         p = curproc;
149         return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
150             sizeof(p->p_sysent->sv_stackprot)));
151 }
152
153 /*
154  * Each of the items is a pointer to a `const struct execsw', hence the
155  * double pointer here.
156  */
157 static const struct execsw **execsw;
158
159 #ifndef _SYS_SYSPROTO_H_
160 struct execve_args {
161         char    *fname; 
162         char    **argv;
163         char    **envv; 
164 };
165 #endif
166
167 /*
168  * MPSAFE
169  */
170 int
171 execve(td, uap)
172         struct thread *td;
173         struct execve_args /* {
174                 char *fname;
175                 char **argv;
176                 char **envv;
177         } */ *uap;
178 {
179         int error;
180         struct image_args args;
181
182         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
183             uap->argv, uap->envv);
184
185         if (error == 0)
186                 error = kern_execve(td, &args, NULL);
187
188         exec_free_args(&args);
189
190         return (error);
191 }
192
193 #ifndef _SYS_SYSPROTO_H_
194 struct __mac_execve_args {
195         char    *fname;
196         char    **argv;
197         char    **envv;
198         struct mac      *mac_p;
199 };
200 #endif
201
202 /*
203  * MPSAFE
204  */
205 int
206 __mac_execve(td, uap)
207         struct thread *td;
208         struct __mac_execve_args /* {
209                 char *fname;
210                 char **argv;
211                 char **envv;
212                 struct mac *mac_p;
213         } */ *uap;
214 {
215 #ifdef MAC
216         int error;
217         struct image_args args;
218
219         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
220             uap->argv, uap->envv);
221
222         if (error == 0)
223                 error = kern_execve(td, &args, uap->mac_p);
224
225         exec_free_args(&args);
226
227         return (error);
228 #else
229         return (ENOSYS);
230 #endif
231 }
232
233 /*
234  * XXX: kern_execve has the astonishing property of not always
235  * returning to the caller.  If sufficiently bad things happen during
236  * the call to do_execve(), it can end up calling exit1(); as a result,
237  * callers must avoid doing anything which they might need to undo
238  * (e.g., allocating memory).
239  */
240 int
241 kern_execve(td, args, mac_p)
242         struct thread *td;
243         struct image_args *args;
244         struct mac *mac_p;
245 {
246         struct proc *p = td->td_proc;
247         int error;
248
249         if (p->p_flag & P_HADTHREADS) {
250                 PROC_LOCK(p);
251                 if (thread_single(SINGLE_BOUNDARY)) {
252                         PROC_UNLOCK(p);
253                         return (ERESTART);      /* Try again later. */
254                 }
255                 PROC_UNLOCK(p);
256         }
257
258         error = do_execve(td, args, mac_p);
259
260         if (p->p_flag & P_HADTHREADS) {
261                 PROC_LOCK(p);
262                 /*
263                  * If success, we upgrade to SINGLE_EXIT state to
264                  * force other threads to suicide.
265                  */
266                 if (error == 0)
267                         thread_single(SINGLE_EXIT);
268                 else
269                         thread_single_end();
270                 PROC_UNLOCK(p);
271         }
272
273         return (error);
274 }
275
276 /*
277  * In-kernel implementation of execve().  All arguments are assumed to be
278  * userspace pointers from the passed thread.
279  *
280  * MPSAFE
281  */
282 static int
283 do_execve(td, args, mac_p)
284         struct thread *td;
285         struct image_args *args;
286         struct mac *mac_p;
287 {
288         struct proc *p = td->td_proc;
289         struct nameidata nd, *ndp;
290         struct ucred *newcred = NULL, *oldcred;
291         struct uidinfo *euip;
292         register_t *stack_base;
293         int error, len, i;
294         struct image_params image_params, *imgp;
295         struct vattr attr;
296         int (*img_first)(struct image_params *);
297         struct pargs *oldargs = NULL, *newargs = NULL;
298         struct sigacts *oldsigacts, *newsigacts;
299 #ifdef KTRACE
300         struct vnode *tracevp = NULL;
301         struct ucred *tracecred = NULL;
302 #endif
303         struct vnode *textvp = NULL;
304         int credential_changing;
305         int vfslocked;
306         int textset;
307 #ifdef MAC
308         struct label *interplabel = NULL;
309         int will_transition;
310 #endif
311 #ifdef HWPMC_HOOKS
312         struct pmckern_procexec pe;
313 #endif
314
315         vfslocked = 0;
316         imgp = &image_params;
317
318         /*
319          * Lock the process and set the P_INEXEC flag to indicate that
320          * it should be left alone until we're done here.  This is
321          * necessary to avoid race conditions - e.g. in ptrace() -
322          * that might allow a local user to illicitly obtain elevated
323          * privileges.
324          */
325         PROC_LOCK(p);
326         KASSERT((p->p_flag & P_INEXEC) == 0,
327             ("%s(): process already has P_INEXEC flag", __func__));
328         p->p_flag |= P_INEXEC;
329         PROC_UNLOCK(p);
330
331         /*
332          * Initialize part of the common data
333          */
334         imgp->proc = p;
335         imgp->execlabel = NULL;
336         imgp->attr = &attr;
337         imgp->entry_addr = 0;
338         imgp->vmspace_destroyed = 0;
339         imgp->interpreted = 0;
340         imgp->interpreter_name = args->buf + PATH_MAX + ARG_MAX;
341         imgp->auxargs = NULL;
342         imgp->vp = NULL;
343         imgp->object = NULL;
344         imgp->firstpage = NULL;
345         imgp->ps_strings = 0;
346         imgp->auxarg_size = 0;
347         imgp->args = args;
348
349 #ifdef MAC
350         error = mac_execve_enter(imgp, mac_p);
351         if (error)
352                 goto exec_fail;
353 #endif
354
355         imgp->image_header = NULL;
356
357         /*
358          * Translate the file name. namei() returns a vnode pointer
359          *      in ni_vp amoung other things.
360          */
361         ndp = &nd;
362         NDINIT(ndp, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME | MPSAFE,
363             UIO_SYSSPACE, args->fname, td);
364
365 interpret:
366         error = namei(ndp);
367         if (error)
368                 goto exec_fail;
369
370         vfslocked = NDHASGIANT(ndp);
371         imgp->vp = ndp->ni_vp;
372
373         /*
374          * Check file permissions (also 'opens' file)
375          */
376         error = exec_check_permissions(imgp);
377         if (error)
378                 goto exec_fail_dealloc;
379
380         imgp->object = imgp->vp->v_object;
381         if (imgp->object != NULL)
382                 vm_object_reference(imgp->object);
383
384         /*
385          * Set VV_TEXT now so no one can write to the executable while we're
386          * activating it.
387          *
388          * Remember if this was set before and unset it in case this is not
389          * actually an executable image.
390          */
391         textset = imgp->vp->v_vflag & VV_TEXT;
392         imgp->vp->v_vflag |= VV_TEXT;
393
394         error = exec_map_first_page(imgp);
395         if (error)
396                 goto exec_fail_dealloc;
397
398         /*
399          *      If the current process has a special image activator it
400          *      wants to try first, call it.   For example, emulating shell
401          *      scripts differently.
402          */
403         error = -1;
404         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
405                 error = img_first(imgp);
406
407         /*
408          *      Loop through the list of image activators, calling each one.
409          *      An activator returns -1 if there is no match, 0 on success,
410          *      and an error otherwise.
411          */
412         for (i = 0; error == -1 && execsw[i]; ++i) {
413                 if (execsw[i]->ex_imgact == NULL ||
414                     execsw[i]->ex_imgact == img_first) {
415                         continue;
416                 }
417                 error = (*execsw[i]->ex_imgact)(imgp);
418         }
419
420         if (error) {
421                 if (error == -1) {
422                         if (textset == 0)
423                                 imgp->vp->v_vflag &= ~VV_TEXT;
424                         error = ENOEXEC;
425                 }
426                 goto exec_fail_dealloc;
427         }
428
429         /*
430          * Special interpreter operation, cleanup and loop up to try to
431          * activate the interpreter.
432          */
433         if (imgp->interpreted) {
434                 exec_unmap_first_page(imgp);
435                 /*
436                  * VV_TEXT needs to be unset for scripts.  There is a short
437                  * period before we determine that something is a script where
438                  * VV_TEXT will be set. The vnode lock is held over this
439                  * entire period so nothing should illegitimately be blocked.
440                  */
441                 imgp->vp->v_vflag &= ~VV_TEXT;
442                 /* free name buffer and old vnode */
443                 NDFREE(ndp, NDF_ONLY_PNBUF);
444 #ifdef MAC
445                 interplabel = mac_vnode_label_alloc();
446                 mac_copy_vnode_label(ndp->ni_vp->v_label, interplabel);
447 #endif
448                 vput(ndp->ni_vp);
449                 vm_object_deallocate(imgp->object);
450                 imgp->object = NULL;
451                 VFS_UNLOCK_GIANT(vfslocked);
452                 vfslocked = 0;
453                 /* set new name to that of the interpreter */
454                 NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME | MPSAFE,
455                     UIO_SYSSPACE, imgp->interpreter_name, td);
456                 goto interpret;
457         }
458
459         /*
460          * Copy out strings (args and env) and initialize stack base
461          */
462         if (p->p_sysent->sv_copyout_strings)
463                 stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
464         else
465                 stack_base = exec_copyout_strings(imgp);
466
467         /*
468          * If custom stack fixup routine present for this process
469          * let it do the stack setup.
470          * Else stuff argument count as first item on stack
471          */
472         if (p->p_sysent->sv_fixup != NULL)
473                 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
474         else
475                 suword(--stack_base, imgp->args->argc);
476
477         /*
478          * For security and other reasons, the file descriptor table cannot
479          * be shared after an exec.
480          */
481         fdunshare(p, td);
482
483         /*
484          * Malloc things before we need locks.
485          */
486         newcred = crget();
487         euip = uifind(attr.va_uid);
488         i = imgp->args->begin_envv - imgp->args->begin_argv;
489         /* Cache arguments if they fit inside our allowance */
490         if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
491                 newargs = pargs_alloc(i);
492                 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
493         }
494
495         /* close files on exec */
496         fdcloseexec(td);
497
498         /* Get a reference to the vnode prior to locking the proc */
499         VREF(ndp->ni_vp);
500
501         /*
502          * For security and other reasons, signal handlers cannot
503          * be shared after an exec. The new process gets a copy of the old
504          * handlers. In execsigs(), the new process will have its signals
505          * reset.
506          */
507         PROC_LOCK(p);
508         if (sigacts_shared(p->p_sigacts)) {
509                 oldsigacts = p->p_sigacts;
510                 PROC_UNLOCK(p);
511                 newsigacts = sigacts_alloc();
512                 sigacts_copy(newsigacts, oldsigacts);
513                 PROC_LOCK(p);
514                 p->p_sigacts = newsigacts;
515         } else
516                 oldsigacts = NULL;
517
518         /* Stop profiling */
519         stopprofclock(p);
520
521         /* reset caught signals */
522         execsigs(p);
523
524         /* name this process - nameiexec(p, ndp) */
525         len = min(ndp->ni_cnd.cn_namelen,MAXCOMLEN);
526         bcopy(ndp->ni_cnd.cn_nameptr, p->p_comm, len);
527         p->p_comm[len] = 0;
528
529         /*
530          * mark as execed, wakeup the process that vforked (if any) and tell
531          * it that it now has its own resources back
532          */
533         p->p_flag |= P_EXEC;
534         if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
535                 p->p_flag &= ~P_PPWAIT;
536                 wakeup(p->p_pptr);
537         }
538
539         /*
540          * Implement image setuid/setgid.
541          *
542          * Don't honor setuid/setgid if the filesystem prohibits it or if
543          * the process is being traced.
544          *
545          * XXXMAC: For the time being, use NOSUID to also prohibit
546          * transitions on the file system.
547          */
548         oldcred = p->p_ucred;
549         credential_changing = 0;
550         credential_changing |= (attr.va_mode & VSUID) && oldcred->cr_uid !=
551             attr.va_uid;
552         credential_changing |= (attr.va_mode & VSGID) && oldcred->cr_gid !=
553             attr.va_gid;
554 #ifdef MAC
555         will_transition = mac_execve_will_transition(oldcred, imgp->vp,
556             interplabel, imgp);
557         credential_changing |= will_transition;
558 #endif
559
560         if (credential_changing &&
561             (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
562             (p->p_flag & P_TRACED) == 0) {
563                 /*
564                  * Turn off syscall tracing for set-id programs, except for
565                  * root.  Record any set-id flags first to make sure that
566                  * we do not regain any tracing during a possible block.
567                  */
568                 setsugid(p);
569 #ifdef KTRACE
570                 if (p->p_tracevp != NULL && suser_cred(oldcred, SUSER_ALLOWJAIL)) {
571                         mtx_lock(&ktrace_mtx);
572                         p->p_traceflag = 0;
573                         tracevp = p->p_tracevp;
574                         p->p_tracevp = NULL;
575                         tracecred = p->p_tracecred;
576                         p->p_tracecred = NULL;
577                         mtx_unlock(&ktrace_mtx);
578                 }
579 #endif
580                 /*
581                  * Close any file descriptors 0..2 that reference procfs,
582                  * then make sure file descriptors 0..2 are in use.
583                  *
584                  * setugidsafety() may call closef() and then pfind()
585                  * which may grab the process lock.
586                  * fdcheckstd() may call falloc() which may block to
587                  * allocate memory, so temporarily drop the process lock.
588                  */
589                 PROC_UNLOCK(p);
590                 setugidsafety(td);
591                 error = fdcheckstd(td);
592                 if (error != 0)
593                         goto done1;
594                 PROC_LOCK(p);
595                 /*
596                  * Set the new credentials.
597                  */
598                 crcopy(newcred, oldcred);
599                 if (attr.va_mode & VSUID)
600                         change_euid(newcred, euip);
601                 if (attr.va_mode & VSGID)
602                         change_egid(newcred, attr.va_gid);
603 #ifdef MAC
604                 if (will_transition) {
605                         mac_execve_transition(oldcred, newcred, imgp->vp,
606                             interplabel, imgp);
607                 }
608 #endif
609                 /*
610                  * Implement correct POSIX saved-id behavior.
611                  *
612                  * XXXMAC: Note that the current logic will save the
613                  * uid and gid if a MAC domain transition occurs, even
614                  * though maybe it shouldn't.
615                  */
616                 change_svuid(newcred, newcred->cr_uid);
617                 change_svgid(newcred, newcred->cr_gid);
618                 p->p_ucred = newcred;
619                 newcred = NULL;
620         } else {
621                 if (oldcred->cr_uid == oldcred->cr_ruid &&
622                     oldcred->cr_gid == oldcred->cr_rgid)
623                         p->p_flag &= ~P_SUGID;
624                 /*
625                  * Implement correct POSIX saved-id behavior.
626                  *
627                  * XXX: It's not clear that the existing behavior is
628                  * POSIX-compliant.  A number of sources indicate that the
629                  * saved uid/gid should only be updated if the new ruid is
630                  * not equal to the old ruid, or the new euid is not equal
631                  * to the old euid and the new euid is not equal to the old
632                  * ruid.  The FreeBSD code always updates the saved uid/gid.
633                  * Also, this code uses the new (replaced) euid and egid as
634                  * the source, which may or may not be the right ones to use.
635                  */
636                 if (oldcred->cr_svuid != oldcred->cr_uid ||
637                     oldcred->cr_svgid != oldcred->cr_gid) {
638                         crcopy(newcred, oldcred);
639                         change_svuid(newcred, newcred->cr_uid);
640                         change_svgid(newcred, newcred->cr_gid);
641                         p->p_ucred = newcred;
642                         newcred = NULL;
643                 }
644         }
645
646         /*
647          * Store the vp for use in procfs.  This vnode was referenced prior
648          * to locking the proc lock.
649          */
650         textvp = p->p_textvp;
651         p->p_textvp = ndp->ni_vp;
652
653         /*
654          * Notify others that we exec'd, and clear the P_INEXEC flag
655          * as we're now a bona fide freshly-execed process.
656          */
657         KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
658         p->p_flag &= ~P_INEXEC;
659
660         /*
661          * If tracing the process, trap to debugger so breakpoints
662          * can be set before the program executes.
663          * Use tdsignal to deliver signal to current thread, use
664          * psignal may cause the signal to be delivered to wrong thread
665          * because that thread will exit, remember we are going to enter
666          * single thread mode.
667          */
668         if (p->p_flag & P_TRACED)
669                 tdsignal(p, td, SIGTRAP, NULL);
670
671         /* clear "fork but no exec" flag, as we _are_ execing */
672         p->p_acflag &= ~AFORK;
673
674         /*
675          * Free any previous argument cache and replace it with
676          * the new argument cache, if any.
677          */
678         oldargs = p->p_args;
679         p->p_args = newargs;
680         newargs = NULL;
681
682 #ifdef  HWPMC_HOOKS
683         /*
684          * Check if system-wide sampling is in effect or if the
685          * current process is using PMCs.  If so, do exec() time
686          * processing.  This processing needs to happen AFTER the
687          * P_INEXEC flag is cleared.
688          *
689          * The proc lock needs to be released before taking the PMC
690          * SX.
691          */
692         if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
693                 PROC_UNLOCK(p);
694                 pe.pm_credentialschanged = credential_changing;
695                 pe.pm_entryaddr = imgp->entry_addr;
696
697                 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
698         } else
699                 PROC_UNLOCK(p);
700 #else  /* !HWPMC_HOOKS */
701         PROC_UNLOCK(p);
702 #endif
703
704         /* Set values passed into the program in registers. */
705         if (p->p_sysent->sv_setregs)
706                 (*p->p_sysent->sv_setregs)(td, imgp->entry_addr,
707                     (u_long)(uintptr_t)stack_base, imgp->ps_strings);
708         else
709                 exec_setregs(td, imgp->entry_addr,
710                     (u_long)(uintptr_t)stack_base, imgp->ps_strings);
711
712         vfs_mark_atime(imgp->vp, td);
713
714 done1:
715         /*
716          * Free any resources malloc'd earlier that we didn't use.
717          */
718         uifree(euip);
719         if (newcred == NULL)
720                 crfree(oldcred);
721         else
722                 crfree(newcred);
723         /*
724          * Handle deferred decrement of ref counts.
725          */
726         if (textvp != NULL)
727                 vrele(textvp);
728         if (ndp->ni_vp && error != 0)
729                 vrele(ndp->ni_vp);
730 #ifdef KTRACE
731         if (tracevp != NULL)
732                 vrele(tracevp);
733         if (tracecred != NULL)
734                 crfree(tracecred);
735 #endif
736         if (oldargs != NULL)
737                 pargs_drop(oldargs);
738         if (newargs != NULL)
739                 pargs_drop(newargs);
740         if (oldsigacts != NULL)
741                 sigacts_free(oldsigacts);
742
743 exec_fail_dealloc:
744
745         /*
746          * free various allocated resources
747          */
748         if (imgp->firstpage != NULL)
749                 exec_unmap_first_page(imgp);
750
751         if (imgp->vp != NULL) {
752                 NDFREE(ndp, NDF_ONLY_PNBUF);
753                 vput(imgp->vp);
754         }
755
756         if (imgp->object != NULL)
757                 vm_object_deallocate(imgp->object);
758
759         if (error == 0) {
760                 /*
761                  * Stop the process here if its stop event mask has
762                  * the S_EXEC bit set.
763                  */
764                 STOPEVENT(p, S_EXEC, 0);
765                 goto done2;
766         }
767
768 exec_fail:
769         /* we're done here, clear P_INEXEC */
770         PROC_LOCK(p);
771         p->p_flag &= ~P_INEXEC;
772         PROC_UNLOCK(p);
773
774         if (imgp->vmspace_destroyed) {
775                 /* sorry, no more process anymore. exit gracefully */
776 #ifdef MAC
777                 mac_execve_exit(imgp);
778                 if (interplabel != NULL)
779                         mac_vnode_label_free(interplabel);
780 #endif
781                 VFS_UNLOCK_GIANT(vfslocked);
782                 exec_free_args(args);
783                 exit1(td, W_EXITCODE(0, SIGABRT));
784                 /* NOT REACHED */
785                 error = 0;
786         }
787 done2:
788 #ifdef MAC
789         mac_execve_exit(imgp);
790         if (interplabel != NULL)
791                 mac_vnode_label_free(interplabel);
792 #endif
793         VFS_UNLOCK_GIANT(vfslocked);
794         return (error);
795 }
796
797 int
798 exec_map_first_page(imgp)
799         struct image_params *imgp;
800 {
801         int rv, i;
802         int initial_pagein;
803         vm_page_t ma[VM_INITIAL_PAGEIN];
804         vm_object_t object;
805
806         if (imgp->firstpage != NULL)
807                 exec_unmap_first_page(imgp);
808
809         object = imgp->vp->v_object;
810         if (object == NULL)
811                 return (EACCES);
812         VM_OBJECT_LOCK(object);
813         ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
814         if ((ma[0]->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
815                 initial_pagein = VM_INITIAL_PAGEIN;
816                 if (initial_pagein > object->size)
817                         initial_pagein = object->size;
818                 for (i = 1; i < initial_pagein; i++) {
819                         if ((ma[i] = vm_page_lookup(object, i)) != NULL) {
820                                 if (ma[i]->valid)
821                                         break;
822                                 if ((ma[i]->flags & PG_BUSY) || ma[i]->busy)
823                                         break;
824                                 vm_page_lock_queues();
825                                 vm_page_busy(ma[i]);
826                                 vm_page_unlock_queues();
827                         } else {
828                                 ma[i] = vm_page_alloc(object, i,
829                                     VM_ALLOC_NORMAL);
830                                 if (ma[i] == NULL)
831                                         break;
832                         }
833                 }
834                 initial_pagein = i;
835                 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
836                 ma[0] = vm_page_lookup(object, 0);
837                 if ((rv != VM_PAGER_OK) || (ma[0] == NULL) ||
838                     (ma[0]->valid == 0)) {
839                         if (ma[0]) {
840                                 vm_page_lock_queues();
841                                 vm_page_free(ma[0]);
842                                 vm_page_unlock_queues();
843                         }
844                         VM_OBJECT_UNLOCK(object);
845                         return (EIO);
846                 }
847         }
848         vm_page_lock_queues();
849         vm_page_hold(ma[0]);
850         vm_page_wakeup(ma[0]);
851         vm_page_unlock_queues();
852         VM_OBJECT_UNLOCK(object);
853
854         imgp->firstpage = sf_buf_alloc(ma[0], 0);
855         imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
856
857         return (0);
858 }
859
860 void
861 exec_unmap_first_page(imgp)
862         struct image_params *imgp;
863 {
864         vm_page_t m;
865
866         if (imgp->firstpage != NULL) {
867                 m = sf_buf_page(imgp->firstpage);
868                 sf_buf_free(imgp->firstpage);
869                 imgp->firstpage = NULL;
870                 vm_page_lock_queues();
871                 vm_page_unhold(m);
872                 vm_page_unlock_queues();
873         }
874 }
875
876 /*
877  * Destroy old address space, and allocate a new stack
878  *      The new stack is only SGROWSIZ large because it is grown
879  *      automatically in trap.c.
880  */
881 int
882 exec_new_vmspace(imgp, sv)
883         struct image_params *imgp;
884         struct sysentvec *sv;
885 {
886         int error;
887         struct proc *p = imgp->proc;
888         struct vmspace *vmspace = p->p_vmspace;
889         vm_offset_t stack_addr;
890         vm_map_t map;
891
892         imgp->vmspace_destroyed = 1;
893
894         /* Called with Giant held, do not depend on it! */
895         EVENTHANDLER_INVOKE(process_exec, p);
896
897         /*
898          * Here is as good a place as any to do any resource limit cleanups.
899          * This is needed if a 64 bit binary exec's a 32 bit binary - the
900          * data size limit may need to be changed to a value that makes
901          * sense for the 32 bit binary.
902          */
903         if (sv->sv_fixlimits != NULL)
904                 sv->sv_fixlimits(p);
905
906         /*
907          * Blow away entire process VM, if address space not shared,
908          * otherwise, create a new VM space so that other threads are
909          * not disrupted
910          */
911         map = &vmspace->vm_map;
912         if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv->sv_minuser &&
913             vm_map_max(map) == sv->sv_maxuser) {
914                 shmexit(vmspace);
915                 pmap_remove_pages(vmspace_pmap(vmspace), vm_map_min(map),
916                     vm_map_max(map));
917                 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
918         } else {
919                 vmspace_exec(p, sv->sv_minuser, sv->sv_maxuser);
920                 vmspace = p->p_vmspace;
921                 map = &vmspace->vm_map;
922         }
923
924         /* Allocate a new stack */
925         stack_addr = sv->sv_usrstack - maxssiz;
926         error = vm_map_stack(map, stack_addr, (vm_size_t)maxssiz,
927             sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
928         if (error)
929                 return (error);
930
931 #ifdef __ia64__
932         /* Allocate a new register stack */
933         stack_addr = IA64_BACKINGSTORE;
934         error = vm_map_stack(map, stack_addr, (vm_size_t)maxssiz,
935             sv->sv_stackprot, VM_PROT_ALL, MAP_STACK_GROWS_UP);
936         if (error)
937                 return (error);
938 #endif
939
940         /* vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
941          * VM_STACK case, but they are still used to monitor the size of the
942          * process stack so we can check the stack rlimit.
943          */
944         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
945         vmspace->vm_maxsaddr = (char *)sv->sv_usrstack - maxssiz;
946
947         return (0);
948 }
949
950 /*
951  * Copy out argument and environment strings from the old process
952  *      address space into the temporary string buffer.
953  */
954 int
955 exec_copyin_args(struct image_args *args, char *fname,
956     enum uio_seg segflg, char **argv, char **envv)
957 {
958         char *argp, *envp;
959         int error;
960         size_t length;
961
962         error = 0;
963
964         bzero(args, sizeof(*args));
965         if (argv == NULL)
966                 return (EFAULT);
967         /*
968          * Allocate temporary demand zeroed space for argument and
969          *      environment strings:
970          *
971          * o ARG_MAX for argument and environment;
972          * o MAXSHELLCMDLEN for the name of interpreters.
973          */
974         args->buf = (char *) kmem_alloc_wait(exec_map,
975             PATH_MAX + ARG_MAX + MAXSHELLCMDLEN);
976         if (args->buf == NULL)
977                 return (ENOMEM);
978         args->begin_argv = args->buf;
979         args->endp = args->begin_argv;
980         args->stringspace = ARG_MAX;
981
982         args->fname = args->buf + ARG_MAX;
983
984         /*
985          * Copy the file name.
986          */
987         error = (segflg == UIO_SYSSPACE) ?
988             copystr(fname, args->fname, PATH_MAX, &length) :
989             copyinstr(fname, args->fname, PATH_MAX, &length);
990         if (error != 0)
991                 return (error);
992
993         /*
994          * extract arguments first
995          */
996         while ((argp = (caddr_t) (intptr_t) fuword(argv++))) {
997                 if (argp == (caddr_t) -1)
998                         return (EFAULT);
999                 if ((error = copyinstr(argp, args->endp,
1000                     args->stringspace, &length))) {
1001                         if (error == ENAMETOOLONG)
1002                                 return (E2BIG);
1003                         return (error);
1004                 }
1005                 args->stringspace -= length;
1006                 args->endp += length;
1007                 args->argc++;
1008         }
1009
1010         args->begin_envv = args->endp;
1011
1012         /*
1013          * extract environment strings
1014          */
1015         if (envv) {
1016                 while ((envp = (caddr_t)(intptr_t)fuword(envv++))) {
1017                         if (envp == (caddr_t)-1)
1018                                 return (EFAULT);
1019                         if ((error = copyinstr(envp, args->endp,
1020                             args->stringspace, &length))) {
1021                                 if (error == ENAMETOOLONG)
1022                                         return (E2BIG);
1023                                 return (error);
1024                         }
1025                         args->stringspace -= length;
1026                         args->endp += length;
1027                         args->envc++;
1028                 }
1029         }
1030
1031         return (0);
1032 }
1033
1034 void
1035 exec_free_args(struct image_args *args)
1036 {
1037
1038         if (args->buf) {
1039                 kmem_free_wakeup(exec_map, (vm_offset_t)args->buf,
1040                     PATH_MAX + ARG_MAX + MAXSHELLCMDLEN);
1041                 args->buf = NULL;
1042         }
1043 }
1044
1045 /*
1046  * Copy strings out to the new process address space, constructing
1047  *      new arg and env vector tables. Return a pointer to the base
1048  *      so that it can be used as the initial stack pointer.
1049  */
1050 register_t *
1051 exec_copyout_strings(imgp)
1052         struct image_params *imgp;
1053 {
1054         int argc, envc;
1055         char **vectp;
1056         char *stringp, *destp;
1057         register_t *stack_base;
1058         struct ps_strings *arginfo;
1059         struct proc *p;
1060         int szsigcode;
1061
1062         /*
1063          * Calculate string base and vector table pointers.
1064          * Also deal with signal trampoline code for this exec type.
1065          */
1066         p = imgp->proc;
1067         szsigcode = 0;
1068         arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1069         if (p->p_sysent->sv_szsigcode != NULL)
1070                 szsigcode = *(p->p_sysent->sv_szsigcode);
1071         destp = (caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
1072             roundup((ARG_MAX - imgp->args->stringspace), sizeof(char *));
1073
1074         /*
1075          * install sigcode
1076          */
1077         if (szsigcode)
1078                 copyout(p->p_sysent->sv_sigcode, ((caddr_t)arginfo -
1079                     szsigcode), szsigcode);
1080
1081         /*
1082          * If we have a valid auxargs ptr, prepare some room
1083          * on the stack.
1084          */
1085         if (imgp->auxargs) {
1086                 /*
1087                  * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1088                  * lower compatibility.
1089                  */
1090                 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1091                     (AT_COUNT * 2);
1092                 /*
1093                  * The '+ 2' is for the null pointers at the end of each of
1094                  * the arg and env vector sets,and imgp->auxarg_size is room
1095                  * for argument of Runtime loader.
1096                  */
1097                 vectp = (char **)(destp - (imgp->args->argc +
1098                     imgp->args->envc + 2 + imgp->auxarg_size) *
1099                     sizeof(char *));
1100
1101         } else {
1102                 /*
1103                  * The '+ 2' is for the null pointers at the end of each of
1104                  * the arg and env vector sets
1105                  */
1106                 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc + 2) *
1107                     sizeof(char *));
1108         }
1109
1110         /*
1111          * vectp also becomes our initial stack base
1112          */
1113         stack_base = (register_t *)vectp;
1114
1115         stringp = imgp->args->begin_argv;
1116         argc = imgp->args->argc;
1117         envc = imgp->args->envc;
1118
1119         /*
1120          * Copy out strings - arguments and environment.
1121          */
1122         copyout(stringp, destp, ARG_MAX - imgp->args->stringspace);
1123
1124         /*
1125          * Fill in "ps_strings" struct for ps, w, etc.
1126          */
1127         suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1128         suword(&arginfo->ps_nargvstr, argc);
1129
1130         /*
1131          * Fill in argument portion of vector table.
1132          */
1133         for (; argc > 0; --argc) {
1134                 suword(vectp++, (long)(intptr_t)destp);
1135                 while (*stringp++ != 0)
1136                         destp++;
1137                 destp++;
1138         }
1139
1140         /* a null vector table pointer separates the argp's from the envp's */
1141         suword(vectp++, 0);
1142
1143         suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1144         suword(&arginfo->ps_nenvstr, envc);
1145
1146         /*
1147          * Fill in environment portion of vector table.
1148          */
1149         for (; envc > 0; --envc) {
1150                 suword(vectp++, (long)(intptr_t)destp);
1151                 while (*stringp++ != 0)
1152                         destp++;
1153                 destp++;
1154         }
1155
1156         /* end of vector table is a null pointer */
1157         suword(vectp, 0);
1158
1159         return (stack_base);
1160 }
1161
1162 /*
1163  * Check permissions of file to execute.
1164  *      Called with imgp->vp locked.
1165  *      Return 0 for success or error code on failure.
1166  */
1167 int
1168 exec_check_permissions(imgp)
1169         struct image_params *imgp;
1170 {
1171         struct vnode *vp = imgp->vp;
1172         struct vattr *attr = imgp->attr;
1173         struct thread *td;
1174         int error;
1175
1176         td = curthread;                 /* XXXKSE */
1177
1178         /* Get file attributes */
1179         error = VOP_GETATTR(vp, attr, td->td_ucred, td);
1180         if (error)
1181                 return (error);
1182
1183 #ifdef MAC
1184         error = mac_check_vnode_exec(td->td_ucred, imgp->vp, imgp);
1185         if (error)
1186                 return (error);
1187 #endif
1188         
1189         /*
1190          * 1) Check if file execution is disabled for the filesystem that this
1191          *      file resides on.
1192          * 2) Insure that at least one execute bit is on - otherwise root
1193          *      will always succeed, and we don't want to happen unless the
1194          *      file really is executable.
1195          * 3) Insure that the file is a regular file.
1196          */
1197         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1198             ((attr->va_mode & 0111) == 0) ||
1199             (attr->va_type != VREG))
1200                 return (EACCES);
1201
1202         /*
1203          * Zero length files can't be exec'd
1204          */
1205         if (attr->va_size == 0)
1206                 return (ENOEXEC);
1207
1208         /*
1209          *  Check for execute permission to file based on current credentials.
1210          */
1211         error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1212         if (error)
1213                 return (error);
1214
1215         /*
1216          * Check number of open-for-writes on the file and deny execution
1217          * if there are any.
1218          */
1219         if (vp->v_writecount)
1220                 return (ETXTBSY);
1221
1222         /*
1223          * Call filesystem specific open routine (which does nothing in the
1224          * general case).
1225          */
1226         error = VOP_OPEN(vp, FREAD, td->td_ucred, td, -1);
1227         return (error);
1228 }
1229
1230 /*
1231  * Exec handler registration
1232  */
1233 int
1234 exec_register(execsw_arg)
1235         const struct execsw *execsw_arg;
1236 {
1237         const struct execsw **es, **xs, **newexecsw;
1238         int count = 2;  /* New slot and trailing NULL */
1239
1240         if (execsw)
1241                 for (es = execsw; *es; es++)
1242                         count++;
1243         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1244         if (newexecsw == NULL)
1245                 return (ENOMEM);
1246         xs = newexecsw;
1247         if (execsw)
1248                 for (es = execsw; *es; es++)
1249                         *xs++ = *es;
1250         *xs++ = execsw_arg;
1251         *xs = NULL;
1252         if (execsw)
1253                 free(execsw, M_TEMP);
1254         execsw = newexecsw;
1255         return (0);
1256 }
1257
1258 int
1259 exec_unregister(execsw_arg)
1260         const struct execsw *execsw_arg;
1261 {
1262         const struct execsw **es, **xs, **newexecsw;
1263         int count = 1;
1264
1265         if (execsw == NULL)
1266                 panic("unregister with no handlers left?\n");
1267
1268         for (es = execsw; *es; es++) {
1269                 if (*es == execsw_arg)
1270                         break;
1271         }
1272         if (*es == NULL)
1273                 return (ENOENT);
1274         for (es = execsw; *es; es++)
1275                 if (*es != execsw_arg)
1276                         count++;
1277         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1278         if (newexecsw == NULL)
1279                 return (ENOMEM);
1280         xs = newexecsw;
1281         for (es = execsw; *es; es++)
1282                 if (*es != execsw_arg)
1283                         *xs++ = *es;
1284         *xs = NULL;
1285         if (execsw)
1286                 free(execsw, M_TEMP);
1287         execsw = newexecsw;
1288         return (0);
1289 }