2 * Copyright (c) 1993, David Greenman
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include "opt_capsicum.h"
31 #include "opt_hwpmc_hooks.h"
32 #include "opt_ktrace.h"
35 #include <sys/param.h>
36 #include <sys/capsicum.h>
37 #include <sys/systm.h>
38 #include <sys/eventhandler.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>
49 #include <sys/imgact.h>
50 #include <sys/imgact_elf.h>
52 #include <sys/malloc.h>
55 #include <sys/pioctl.h>
56 #include <sys/namei.h>
57 #include <sys/resourcevar.h>
58 #include <sys/rwlock.h>
59 #include <sys/sched.h>
61 #include <sys/sf_buf.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysent.h>
65 #include <sys/sysctl.h>
66 #include <sys/vnode.h>
69 #include <sys/ktrace.h>
73 #include <vm/vm_param.h>
75 #include <vm/vm_page.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_extern.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_pager.h>
83 #include <sys/pmckern.h>
86 #include <machine/reg.h>
88 #include <security/audit/audit.h>
89 #include <security/mac/mac_framework.h>
92 #include <sys/dtrace_bsd.h>
93 dtrace_execexit_func_t dtrace_fasttrap_exec;
96 SDT_PROVIDER_DECLARE(proc);
97 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
98 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
99 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
101 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
103 int coredump_pack_fileinfo = 1;
104 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
105 &coredump_pack_fileinfo, 0,
106 "Enable file path packing in 'procstat -f' coredump notes");
108 int coredump_pack_vmmapinfo = 1;
109 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
110 &coredump_pack_vmmapinfo, 0,
111 "Enable file path packing in 'procstat -v' coredump notes");
113 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
114 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
115 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
116 static int do_execve(struct thread *td, struct image_args *args,
119 /* XXX This should be vm_size_t. */
120 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
121 NULL, 0, sysctl_kern_ps_strings, "LU", "");
123 /* XXX This should be vm_size_t. */
124 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
125 CTLFLAG_CAPRD, NULL, 0, sysctl_kern_usrstack, "LU", "");
127 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
128 NULL, 0, sysctl_kern_stackprot, "I", "");
130 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
131 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
132 &ps_arg_cache_limit, 0, "");
134 static int disallow_high_osrel;
135 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
136 &disallow_high_osrel, 0,
137 "Disallow execution of binaries built for higher version of the world");
139 static int map_at_zero = 0;
140 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
141 "Permit processes to map an object at virtual address 0.");
144 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
151 if (req->flags & SCTL_MASK32) {
153 val = (unsigned int)p->p_sysent->sv_psstrings;
154 error = SYSCTL_OUT(req, &val, sizeof(val));
157 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
158 sizeof(p->p_sysent->sv_psstrings));
163 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
170 if (req->flags & SCTL_MASK32) {
172 val = (unsigned int)p->p_sysent->sv_usrstack;
173 error = SYSCTL_OUT(req, &val, sizeof(val));
176 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
177 sizeof(p->p_sysent->sv_usrstack));
182 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
187 return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
188 sizeof(p->p_sysent->sv_stackprot)));
192 * Each of the items is a pointer to a `const struct execsw', hence the
193 * double pointer here.
195 static const struct execsw **execsw;
197 #ifndef _SYS_SYSPROTO_H_
206 sys_execve(struct thread *td, struct execve_args *uap)
208 struct image_args args;
209 struct vmspace *oldvmspace;
212 error = pre_execve(td, &oldvmspace);
215 error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
216 uap->argv, uap->envv);
218 error = kern_execve(td, &args, NULL);
219 post_execve(td, error, oldvmspace);
223 #ifndef _SYS_SYSPROTO_H_
224 struct fexecve_args {
231 sys_fexecve(struct thread *td, struct fexecve_args *uap)
233 struct image_args args;
234 struct vmspace *oldvmspace;
237 error = pre_execve(td, &oldvmspace);
240 error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
241 uap->argv, uap->envv);
244 error = kern_execve(td, &args, NULL);
246 post_execve(td, error, oldvmspace);
250 #ifndef _SYS_SYSPROTO_H_
251 struct __mac_execve_args {
260 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
263 struct image_args args;
264 struct vmspace *oldvmspace;
267 error = pre_execve(td, &oldvmspace);
270 error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
271 uap->argv, uap->envv);
273 error = kern_execve(td, &args, uap->mac_p);
274 post_execve(td, error, oldvmspace);
282 pre_execve(struct thread *td, struct vmspace **oldvmspace)
287 KASSERT(td == curthread, ("non-current thread %p", td));
290 if ((p->p_flag & P_HADTHREADS) != 0) {
292 if (thread_single(p, SINGLE_BOUNDARY) != 0)
296 KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
298 *oldvmspace = p->p_vmspace;
303 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
307 KASSERT(td == curthread, ("non-current thread %p", td));
309 if ((p->p_flag & P_HADTHREADS) != 0) {
312 * If success, we upgrade to SINGLE_EXIT state to
313 * force other threads to suicide.
316 thread_single(p, SINGLE_EXIT);
318 thread_single_end(p, SINGLE_BOUNDARY);
321 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
322 KASSERT(p->p_vmspace != oldvmspace,
323 ("oldvmspace still used"));
324 vmspace_free(oldvmspace);
325 td->td_pflags &= ~TDP_EXECVMSPC;
330 * XXX: kern_execve has the astonishing property of not always returning to
331 * the caller. If sufficiently bad things happen during the call to
332 * do_execve(), it can end up calling exit1(); as a result, callers must
333 * avoid doing anything which they might need to undo (e.g., allocating
337 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p)
340 AUDIT_ARG_ARGV(args->begin_argv, args->argc,
341 args->begin_envv - args->begin_argv);
342 AUDIT_ARG_ENVV(args->begin_envv, args->envc,
343 args->endp - args->begin_envv);
344 return (do_execve(td, args, mac_p));
348 * In-kernel implementation of execve(). All arguments are assumed to be
349 * userspace pointers from the passed thread.
352 do_execve(td, args, mac_p)
354 struct image_args *args;
357 struct proc *p = td->td_proc;
359 struct ucred *newcred = NULL, *oldcred;
360 struct uidinfo *euip = NULL;
361 register_t *stack_base;
363 struct image_params image_params, *imgp;
365 int (*img_first)(struct image_params *);
366 struct pargs *oldargs = NULL, *newargs = NULL;
367 struct sigacts *oldsigacts, *newsigacts;
369 struct vnode *tracevp = NULL;
370 struct ucred *tracecred = NULL;
372 struct vnode *oldtextvp = NULL, *newtextvp;
374 int credential_changing;
377 struct label *interpvplabel = NULL;
381 struct pmckern_procexec pe;
383 static const char fexecv_proc_title[] = "(fexecv)";
385 imgp = &image_params;
388 * Lock the process and set the P_INEXEC flag to indicate that
389 * it should be left alone until we're done here. This is
390 * necessary to avoid race conditions - e.g. in ptrace() -
391 * that might allow a local user to illicitly obtain elevated
395 KASSERT((p->p_flag & P_INEXEC) == 0,
396 ("%s(): process already has P_INEXEC flag", __func__));
397 p->p_flag |= P_INEXEC;
401 * Initialize part of the common data
403 bzero(imgp, sizeof(*imgp));
409 error = mac_execve_enter(imgp, mac_p);
415 * Translate the file name. namei() returns a vnode pointer
416 * in ni_vp amoung other things.
418 * XXXAUDIT: It would be desirable to also audit the name of the
419 * interpreter if this is an interpreted binary.
421 if (args->fname != NULL) {
422 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
423 | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
426 SDT_PROBE1(proc, , , exec, args->fname);
429 if (args->fname != NULL) {
430 #ifdef CAPABILITY_MODE
432 * While capability mode can't reach this point via direct
433 * path arguments to execve(), we also don't allow
434 * interpreters to be used in capability mode (for now).
435 * Catch indirect lookups and return a permissions error.
437 if (IN_CAPABILITY_MODE(td)) {
446 newtextvp = nd.ni_vp;
447 imgp->vp = newtextvp;
449 AUDIT_ARG_FD(args->fd);
451 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
453 error = fgetvp_exec(td, args->fd,
454 cap_rights_init(&rights, CAP_FEXECVE), &newtextvp);
457 vn_lock(newtextvp, LK_EXCLUSIVE | LK_RETRY);
458 AUDIT_ARG_VNODE1(newtextvp);
459 imgp->vp = newtextvp;
463 * Check file permissions (also 'opens' file)
465 error = exec_check_permissions(imgp);
467 goto exec_fail_dealloc;
469 imgp->object = imgp->vp->v_object;
470 if (imgp->object != NULL)
471 vm_object_reference(imgp->object);
474 * Set VV_TEXT now so no one can write to the executable while we're
477 * Remember if this was set before and unset it in case this is not
478 * actually an executable image.
480 textset = VOP_IS_TEXT(imgp->vp);
481 VOP_SET_TEXT(imgp->vp);
483 error = exec_map_first_page(imgp);
485 goto exec_fail_dealloc;
487 imgp->proc->p_osrel = 0;
489 * If the current process has a special image activator it
490 * wants to try first, call it. For example, emulating shell
491 * scripts differently.
494 if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
495 error = img_first(imgp);
498 * Loop through the list of image activators, calling each one.
499 * An activator returns -1 if there is no match, 0 on success,
500 * and an error otherwise.
502 for (i = 0; error == -1 && execsw[i]; ++i) {
503 if (execsw[i]->ex_imgact == NULL ||
504 execsw[i]->ex_imgact == img_first) {
507 error = (*execsw[i]->ex_imgact)(imgp);
513 VOP_UNSET_TEXT(imgp->vp);
516 goto exec_fail_dealloc;
520 * Special interpreter operation, cleanup and loop up to try to
521 * activate the interpreter.
523 if (imgp->interpreted) {
524 exec_unmap_first_page(imgp);
526 * VV_TEXT needs to be unset for scripts. There is a short
527 * period before we determine that something is a script where
528 * VV_TEXT will be set. The vnode lock is held over this
529 * entire period so nothing should illegitimately be blocked.
531 VOP_UNSET_TEXT(imgp->vp);
532 /* free name buffer and old vnode */
533 if (args->fname != NULL)
534 NDFREE(&nd, NDF_ONLY_PNBUF);
536 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
539 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
543 vm_object_deallocate(imgp->object);
545 /* set new name to that of the interpreter */
546 NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
547 UIO_SYSSPACE, imgp->interpreter_name, td);
548 args->fname = imgp->interpreter_name;
553 * NB: We unlock the vnode here because it is believed that none
554 * of the sv_copyout_strings/sv_fixup operations require the vnode.
556 VOP_UNLOCK(imgp->vp, 0);
559 * Do the best to calculate the full path to the image file.
561 if (imgp->auxargs != NULL &&
562 ((args->fname != NULL && args->fname[0] == '/') ||
563 vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
564 imgp->execpath = args->fname;
566 if (disallow_high_osrel &&
567 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
569 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
570 imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
571 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
572 goto exec_fail_dealloc;
575 /* ABI enforces the use of Capsicum. Switch into capabilities mode. */
576 if (SV_PROC_FLAG(p, SV_CAPSICUM))
577 sys_cap_enter(td, NULL);
580 * Copy out strings (args and env) and initialize stack base
582 if (p->p_sysent->sv_copyout_strings)
583 stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
585 stack_base = exec_copyout_strings(imgp);
588 * If custom stack fixup routine present for this process
589 * let it do the stack setup.
590 * Else stuff argument count as first item on stack
592 if (p->p_sysent->sv_fixup != NULL)
593 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
595 suword(--stack_base, imgp->args->argc);
597 if (args->fdp != NULL) {
598 /* Install a brand new file descriptor table. */
599 fdinstall_remapped(td, args->fdp);
603 * Keep on using the existing file descriptor table. For
604 * security and other reasons, the file descriptor table
605 * cannot be shared after an exec.
608 /* close files on exec */
613 * Malloc things before we need locks.
615 i = imgp->args->begin_envv - imgp->args->begin_argv;
616 /* Cache arguments if they fit inside our allowance */
617 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
618 newargs = pargs_alloc(i);
619 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
622 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
625 * For security and other reasons, signal handlers cannot
626 * be shared after an exec. The new process gets a copy of the old
627 * handlers. In execsigs(), the new process will have its signals
630 if (sigacts_shared(p->p_sigacts)) {
631 oldsigacts = p->p_sigacts;
632 newsigacts = sigacts_alloc();
633 sigacts_copy(newsigacts, oldsigacts);
636 newsigacts = NULL; /* satisfy gcc */
641 p->p_sigacts = newsigacts;
642 oldcred = p->p_ucred;
646 /* reset caught signals */
649 /* name this process - nameiexec(p, ndp) */
650 bzero(p->p_comm, sizeof(p->p_comm));
652 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
653 min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
654 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
655 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
656 bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
658 sched_clear_tdname(td);
662 * mark as execed, wakeup the process that vforked (if any) and tell
663 * it that it now has its own resources back
666 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
667 p->p_flag2 &= ~P2_NOTRACE;
668 if (p->p_flag & P_PPWAIT) {
669 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
670 cv_broadcast(&p->p_pwait);
674 * Implement image setuid/setgid.
676 * Don't honor setuid/setgid if the filesystem prohibits it or if
677 * the process is being traced.
679 * We disable setuid/setgid/etc in compatibility mode on the basis
680 * that most setugid applications are not written with that
681 * environment in mind, and will therefore almost certainly operate
682 * incorrectly. In principle there's no reason that setugid
683 * applications might not be useful in capability mode, so we may want
684 * to reconsider this conservative design choice in the future.
686 * XXXMAC: For the time being, use NOSUID to also prohibit
687 * transitions on the file system.
689 credential_changing = 0;
690 credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
692 credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
695 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
696 interpvplabel, imgp);
697 credential_changing |= will_transition;
700 if (credential_changing &&
701 #ifdef CAPABILITY_MODE
702 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
704 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
705 (p->p_flag & P_TRACED) == 0) {
707 * Turn off syscall tracing for set-id programs, except for
708 * root. Record any set-id flags first to make sure that
709 * we do not regain any tracing during a possible block.
714 if (p->p_tracecred != NULL &&
715 priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
716 ktrprocexec(p, &tracecred, &tracevp);
719 * Close any file descriptors 0..2 that reference procfs,
720 * then make sure file descriptors 0..2 are in use.
722 * Both fdsetugidsafety() and fdcheckstd() may call functions
723 * taking sleepable locks, so temporarily drop our locks.
726 VOP_UNLOCK(imgp->vp, 0);
728 error = fdcheckstd(td);
731 newcred = crdup(oldcred);
732 euip = uifind(attr.va_uid);
733 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
736 * Set the new credentials.
738 if (attr.va_mode & S_ISUID)
739 change_euid(newcred, euip);
740 if (attr.va_mode & S_ISGID)
741 change_egid(newcred, attr.va_gid);
743 if (will_transition) {
744 mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
745 interpvplabel, imgp);
749 * Implement correct POSIX saved-id behavior.
751 * XXXMAC: Note that the current logic will save the
752 * uid and gid if a MAC domain transition occurs, even
753 * though maybe it shouldn't.
755 change_svuid(newcred, newcred->cr_uid);
756 change_svgid(newcred, newcred->cr_gid);
757 proc_set_cred(p, newcred);
759 if (oldcred->cr_uid == oldcred->cr_ruid &&
760 oldcred->cr_gid == oldcred->cr_rgid)
761 p->p_flag &= ~P_SUGID;
763 * Implement correct POSIX saved-id behavior.
765 * XXX: It's not clear that the existing behavior is
766 * POSIX-compliant. A number of sources indicate that the
767 * saved uid/gid should only be updated if the new ruid is
768 * not equal to the old ruid, or the new euid is not equal
769 * to the old euid and the new euid is not equal to the old
770 * ruid. The FreeBSD code always updates the saved uid/gid.
771 * Also, this code uses the new (replaced) euid and egid as
772 * the source, which may or may not be the right ones to use.
774 if (oldcred->cr_svuid != oldcred->cr_uid ||
775 oldcred->cr_svgid != oldcred->cr_gid) {
777 VOP_UNLOCK(imgp->vp, 0);
778 newcred = crdup(oldcred);
779 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
781 change_svuid(newcred, newcred->cr_uid);
782 change_svgid(newcred, newcred->cr_gid);
783 proc_set_cred(p, newcred);
788 * Store the vp for use in procfs. This vnode was referenced by namei
791 oldtextvp = p->p_textvp;
792 p->p_textvp = newtextvp;
796 * Tell the DTrace fasttrap provider about the exec if it
797 * has declared an interest.
799 if (dtrace_fasttrap_exec)
800 dtrace_fasttrap_exec(p);
804 * Notify others that we exec'd, and clear the P_INEXEC flag
805 * as we're now a bona fide freshly-execed process.
807 KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
808 p->p_flag &= ~P_INEXEC;
810 /* clear "fork but no exec" flag, as we _are_ execing */
811 p->p_acflag &= ~AFORK;
814 * Free any previous argument cache and replace it with
815 * the new argument cache, if any.
823 * Check if system-wide sampling is in effect or if the
824 * current process is using PMCs. If so, do exec() time
825 * processing. This processing needs to happen AFTER the
826 * P_INEXEC flag is cleared.
828 * The proc lock needs to be released before taking the PMC
831 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
833 VOP_UNLOCK(imgp->vp, 0);
834 pe.pm_credentialschanged = credential_changing;
835 pe.pm_entryaddr = imgp->entry_addr;
837 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
838 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
841 #else /* !HWPMC_HOOKS */
845 /* Set values passed into the program in registers. */
846 if (p->p_sysent->sv_setregs)
847 (*p->p_sysent->sv_setregs)(td, imgp,
848 (u_long)(uintptr_t)stack_base);
850 exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
852 vfs_mark_atime(imgp->vp, td->td_ucred);
854 SDT_PROBE1(proc, , , exec__success, args->fname);
856 VOP_UNLOCK(imgp->vp, 0);
859 * Free any resources malloc'd earlier that we didn't use.
867 * Handle deferred decrement of ref counts.
869 if (oldtextvp != NULL)
874 if (tracecred != NULL)
877 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
880 if (oldsigacts != NULL)
881 sigacts_free(oldsigacts);
886 * free various allocated resources
888 if (imgp->firstpage != NULL)
889 exec_unmap_first_page(imgp);
891 if (imgp->vp != NULL) {
893 NDFREE(&nd, NDF_ONLY_PNBUF);
895 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
899 VOP_UNLOCK(imgp->vp, 0);
902 if (imgp->object != NULL)
903 vm_object_deallocate(imgp->object);
905 free(imgp->freepath, M_TEMP);
909 td->td_dbgflags |= TDB_EXEC;
913 * Stop the process here if its stop event mask has
914 * the S_EXEC bit set.
916 STOPEVENT(p, S_EXEC, 0);
921 /* we're done here, clear P_INEXEC */
923 p->p_flag &= ~P_INEXEC;
926 SDT_PROBE1(proc, , , exec__failure, error);
930 mac_execve_exit(imgp);
931 mac_execve_interpreter_exit(interpvplabel);
933 exec_free_args(args);
935 if (error && imgp->vmspace_destroyed) {
936 /* sorry, no more process anymore. exit gracefully */
937 exit1(td, 0, SIGABRT);
950 exec_map_first_page(imgp)
951 struct image_params *imgp;
953 int rv, i, after, initial_pagein;
954 vm_page_t ma[VM_INITIAL_PAGEIN];
957 if (imgp->firstpage != NULL)
958 exec_unmap_first_page(imgp);
960 object = imgp->vp->v_object;
963 VM_OBJECT_WLOCK(object);
964 #if VM_NRESERVLEVEL > 0
965 vm_object_color(object, 0);
967 ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
968 if (ma[0]->valid != VM_PAGE_BITS_ALL) {
969 if (!vm_pager_has_page(object, 0, NULL, &after)) {
972 vm_page_unlock(ma[0]);
973 vm_page_xunbusy(ma[0]);
974 VM_OBJECT_WUNLOCK(object);
977 initial_pagein = min(after, VM_INITIAL_PAGEIN);
978 KASSERT(initial_pagein <= object->size,
979 ("%s: initial_pagein %d object->size %ju",
980 __func__, initial_pagein, (uintmax_t )object->size));
981 for (i = 1; i < initial_pagein; i++) {
982 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
985 if (vm_page_tryxbusy(ma[i]))
988 ma[i] = vm_page_alloc(object, i,
989 VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
995 rv = vm_pager_get_pages(object, ma, initial_pagein, NULL, NULL);
996 if (rv != VM_PAGER_OK) {
997 for (i = 0; i < initial_pagein; i++) {
1000 vm_page_unlock(ma[i]);
1001 vm_page_xunbusy(ma[i]);
1003 VM_OBJECT_WUNLOCK(object);
1006 for (i = 1; i < initial_pagein; i++)
1007 vm_page_readahead_finish(ma[i]);
1009 vm_page_xunbusy(ma[0]);
1010 vm_page_lock(ma[0]);
1011 vm_page_hold(ma[0]);
1012 vm_page_activate(ma[0]);
1013 vm_page_unlock(ma[0]);
1014 VM_OBJECT_WUNLOCK(object);
1016 imgp->firstpage = sf_buf_alloc(ma[0], 0);
1017 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1023 exec_unmap_first_page(imgp)
1024 struct image_params *imgp;
1028 if (imgp->firstpage != NULL) {
1029 m = sf_buf_page(imgp->firstpage);
1030 sf_buf_free(imgp->firstpage);
1031 imgp->firstpage = NULL;
1039 * Destroy old address space, and allocate a new stack
1040 * The new stack is only SGROWSIZ large because it is grown
1041 * automatically in trap.c.
1044 exec_new_vmspace(imgp, sv)
1045 struct image_params *imgp;
1046 struct sysentvec *sv;
1049 struct proc *p = imgp->proc;
1050 struct vmspace *vmspace = p->p_vmspace;
1052 struct rlimit rlim_stack;
1053 vm_offset_t sv_minuser, stack_addr;
1057 imgp->vmspace_destroyed = 1;
1060 /* May be called with Giant held */
1061 EVENTHANDLER_INVOKE(process_exec, p, imgp);
1064 * Blow away entire process VM, if address space not shared,
1065 * otherwise, create a new VM space so that other threads are
1068 map = &vmspace->vm_map;
1070 sv_minuser = sv->sv_minuser;
1072 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1073 if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1074 vm_map_max(map) == sv->sv_maxuser) {
1076 pmap_remove_pages(vmspace_pmap(vmspace));
1077 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1079 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1082 vmspace = p->p_vmspace;
1083 map = &vmspace->vm_map;
1086 /* Map a shared page */
1087 obj = sv->sv_shared_page_obj;
1089 vm_object_reference(obj);
1090 error = vm_map_fixed(map, obj, 0,
1091 sv->sv_shared_page_base, sv->sv_shared_page_len,
1092 VM_PROT_READ | VM_PROT_EXECUTE,
1093 VM_PROT_READ | VM_PROT_EXECUTE,
1094 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1096 vm_object_deallocate(obj);
1101 /* Allocate a new stack */
1102 if (imgp->stack_sz != 0) {
1103 ssiz = trunc_page(imgp->stack_sz);
1105 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1107 if (ssiz > rlim_stack.rlim_max)
1108 ssiz = rlim_stack.rlim_max;
1109 if (ssiz > rlim_stack.rlim_cur) {
1110 rlim_stack.rlim_cur = ssiz;
1111 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1113 } else if (sv->sv_maxssiz != NULL) {
1114 ssiz = *sv->sv_maxssiz;
1118 stack_addr = sv->sv_usrstack - ssiz;
1119 error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1120 obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1122 VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1127 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1128 * are still used to enforce the stack rlimit on the process stack.
1130 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1131 vmspace->vm_maxsaddr = (char *)stack_addr;
1137 * Copy out argument and environment strings from the old process address
1138 * space into the temporary string buffer.
1141 exec_copyin_args(struct image_args *args, char *fname,
1142 enum uio_seg segflg, char **argv, char **envv)
1148 bzero(args, sizeof(*args));
1153 * Allocate demand-paged memory for the file name, argument, and
1154 * environment strings.
1156 error = exec_alloc_args(args);
1161 * Copy the file name.
1163 if (fname != NULL) {
1164 args->fname = args->buf;
1165 error = (segflg == UIO_SYSSPACE) ?
1166 copystr(fname, args->fname, PATH_MAX, &length) :
1167 copyinstr(fname, args->fname, PATH_MAX, &length);
1173 args->begin_argv = args->buf + length;
1174 args->endp = args->begin_argv;
1175 args->stringspace = ARG_MAX;
1178 * extract arguments first
1181 error = fueword(argv++, &argp);
1188 error = copyinstr((void *)(uintptr_t)argp, args->endp,
1189 args->stringspace, &length);
1191 if (error == ENAMETOOLONG)
1195 args->stringspace -= length;
1196 args->endp += length;
1200 args->begin_envv = args->endp;
1203 * extract environment strings
1207 error = fueword(envv++, &envp);
1214 error = copyinstr((void *)(uintptr_t)envp,
1215 args->endp, args->stringspace, &length);
1217 if (error == ENAMETOOLONG)
1221 args->stringspace -= length;
1222 args->endp += length;
1230 exec_free_args(args);
1235 exec_copyin_data_fds(struct thread *td, struct image_args *args,
1236 const void *data, size_t datalen, const int *fds, size_t fdslen)
1238 struct filedesc *ofdp;
1243 memset(args, '\0', sizeof(*args));
1244 ofdp = td->td_proc->p_fd;
1245 if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
1247 error = exec_alloc_args(args);
1251 args->begin_argv = args->buf;
1252 args->stringspace = ARG_MAX;
1256 * Argument buffer has been provided. Copy it into the
1257 * kernel as a single string and add a terminating null
1260 error = copyin(data, args->begin_argv, datalen);
1263 args->begin_argv[datalen] = '\0';
1264 args->endp = args->begin_argv + datalen + 1;
1265 args->stringspace -= datalen + 1;
1268 * Traditional argument counting. Count the number of
1271 for (p = args->begin_argv; p < args->endp; ++p)
1275 /* No argument buffer provided. */
1276 args->endp = args->begin_argv;
1278 /* There are no environment variables. */
1279 args->begin_envv = args->endp;
1281 /* Create new file descriptor table. */
1282 kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
1283 error = copyin(fds, kfds, fdslen * sizeof(int));
1288 error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
1295 exec_free_args(args);
1300 * Allocate temporary demand-paged, zero-filled memory for the file name,
1301 * argument, and environment strings. Returns zero if the allocation succeeds
1302 * and ENOMEM otherwise.
1305 exec_alloc_args(struct image_args *args)
1308 args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1309 return (args->buf != NULL ? 0 : ENOMEM);
1313 exec_free_args(struct image_args *args)
1316 if (args->buf != NULL) {
1317 kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
1318 PATH_MAX + ARG_MAX);
1321 if (args->fname_buf != NULL) {
1322 free(args->fname_buf, M_TEMP);
1323 args->fname_buf = NULL;
1325 if (args->fdp != NULL)
1326 fdescfree_remapped(args->fdp);
1330 * Copy strings out to the new process address space, constructing new arg
1331 * and env vector tables. Return a pointer to the base so that it can be used
1332 * as the initial stack pointer.
1335 exec_copyout_strings(imgp)
1336 struct image_params *imgp;
1342 register_t *stack_base;
1343 struct ps_strings *arginfo;
1345 size_t execpath_len;
1346 int szsigcode, szps;
1347 char canary[sizeof(long) * 8];
1349 szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1351 * Calculate string base and vector table pointers.
1352 * Also deal with signal trampoline code for this exec type.
1354 if (imgp->execpath != NULL && imgp->auxargs != NULL)
1355 execpath_len = strlen(imgp->execpath) + 1;
1360 arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1361 if (p->p_sysent->sv_sigcode_base == 0) {
1362 if (p->p_sysent->sv_szsigcode != NULL)
1363 szsigcode = *(p->p_sysent->sv_szsigcode);
1365 destp = (uintptr_t)arginfo;
1370 if (szsigcode != 0) {
1372 destp = rounddown2(destp, sizeof(void *));
1373 copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
1377 * Copy the image path for the rtld.
1379 if (execpath_len != 0) {
1380 destp -= execpath_len;
1381 imgp->execpathp = destp;
1382 copyout(imgp->execpath, (void *)destp, execpath_len);
1386 * Prepare the canary for SSP.
1388 arc4rand(canary, sizeof(canary), 0);
1389 destp -= sizeof(canary);
1390 imgp->canary = destp;
1391 copyout(canary, (void *)destp, sizeof(canary));
1392 imgp->canarylen = sizeof(canary);
1395 * Prepare the pagesizes array.
1398 destp = rounddown2(destp, sizeof(void *));
1399 imgp->pagesizes = destp;
1400 copyout(pagesizes, (void *)destp, szps);
1401 imgp->pagesizeslen = szps;
1403 destp -= ARG_MAX - imgp->args->stringspace;
1404 destp = rounddown2(destp, sizeof(void *));
1407 * If we have a valid auxargs ptr, prepare some room
1410 if (imgp->auxargs) {
1412 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1413 * lower compatibility.
1415 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1418 * The '+ 2' is for the null pointers at the end of each of
1419 * the arg and env vector sets,and imgp->auxarg_size is room
1420 * for argument of Runtime loader.
1422 vectp = (char **)(destp - (imgp->args->argc +
1423 imgp->args->envc + 2 + imgp->auxarg_size)
1427 * The '+ 2' is for the null pointers at the end of each of
1428 * the arg and env vector sets
1430 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
1431 + 2) * sizeof(char *));
1435 * vectp also becomes our initial stack base
1437 stack_base = (register_t *)vectp;
1439 stringp = imgp->args->begin_argv;
1440 argc = imgp->args->argc;
1441 envc = imgp->args->envc;
1444 * Copy out strings - arguments and environment.
1446 copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
1449 * Fill in "ps_strings" struct for ps, w, etc.
1451 suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1452 suword32(&arginfo->ps_nargvstr, argc);
1455 * Fill in argument portion of vector table.
1457 for (; argc > 0; --argc) {
1458 suword(vectp++, (long)(intptr_t)destp);
1459 while (*stringp++ != 0)
1464 /* a null vector table pointer separates the argp's from the envp's */
1467 suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1468 suword32(&arginfo->ps_nenvstr, envc);
1471 * Fill in environment portion of vector table.
1473 for (; envc > 0; --envc) {
1474 suword(vectp++, (long)(intptr_t)destp);
1475 while (*stringp++ != 0)
1480 /* end of vector table is a null pointer */
1483 return (stack_base);
1487 * Check permissions of file to execute.
1488 * Called with imgp->vp locked.
1489 * Return 0 for success or error code on failure.
1492 exec_check_permissions(imgp)
1493 struct image_params *imgp;
1495 struct vnode *vp = imgp->vp;
1496 struct vattr *attr = imgp->attr;
1498 int error, writecount;
1502 /* Get file attributes */
1503 error = VOP_GETATTR(vp, attr, td->td_ucred);
1508 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1514 * 1) Check if file execution is disabled for the filesystem that
1515 * this file resides on.
1516 * 2) Ensure that at least one execute bit is on. Otherwise, a
1517 * privileged user will always succeed, and we don't want this
1518 * to happen unless the file really is executable.
1519 * 3) Ensure that the file is a regular file.
1521 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1522 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1523 (attr->va_type != VREG))
1527 * Zero length files can't be exec'd
1529 if (attr->va_size == 0)
1533 * Check for execute permission to file based on current credentials.
1535 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1540 * Check number of open-for-writes on the file and deny execution
1543 error = VOP_GET_WRITECOUNT(vp, &writecount);
1546 if (writecount != 0)
1550 * Call filesystem specific open routine (which does nothing in the
1553 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1560 * Exec handler registration
1563 exec_register(execsw_arg)
1564 const struct execsw *execsw_arg;
1566 const struct execsw **es, **xs, **newexecsw;
1567 int count = 2; /* New slot and trailing NULL */
1570 for (es = execsw; *es; es++)
1572 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1573 if (newexecsw == NULL)
1577 for (es = execsw; *es; es++)
1582 free(execsw, M_TEMP);
1588 exec_unregister(execsw_arg)
1589 const struct execsw *execsw_arg;
1591 const struct execsw **es, **xs, **newexecsw;
1595 panic("unregister with no handlers left?\n");
1597 for (es = execsw; *es; es++) {
1598 if (*es == execsw_arg)
1603 for (es = execsw; *es; es++)
1604 if (*es != execsw_arg)
1606 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1607 if (newexecsw == NULL)
1610 for (es = execsw; *es; es++)
1611 if (*es != execsw_arg)
1615 free(execsw, M_TEMP);