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