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, kernel, , exec, "char *");
98 SDT_PROBE_DEFINE1(proc, kernel, , exec__failure, "int");
99 SDT_PROBE_DEFINE1(proc, kernel, , 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, kernel, , 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, kernel, , 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, kernel, , 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;
955 vm_page_t ma[VM_INITIAL_PAGEIN];
958 if (imgp->firstpage != NULL)
959 exec_unmap_first_page(imgp);
961 object = imgp->vp->v_object;
964 VM_OBJECT_WLOCK(object);
965 #if VM_NRESERVLEVEL > 0
966 vm_object_color(object, 0);
968 ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
969 if (ma[0]->valid != VM_PAGE_BITS_ALL) {
970 initial_pagein = VM_INITIAL_PAGEIN;
971 if (initial_pagein > object->size)
972 initial_pagein = object->size;
973 for (i = 1; i < initial_pagein; i++) {
974 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
977 if (vm_page_tryxbusy(ma[i]))
980 ma[i] = vm_page_alloc(object, i,
981 VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
987 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
988 if (rv != VM_PAGER_OK) {
991 vm_page_unlock(ma[0]);
992 VM_OBJECT_WUNLOCK(object);
996 vm_page_xunbusy(ma[0]);
999 vm_page_activate(ma[0]);
1000 vm_page_unlock(ma[0]);
1001 VM_OBJECT_WUNLOCK(object);
1003 imgp->firstpage = sf_buf_alloc(ma[0], 0);
1004 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1010 exec_unmap_first_page(imgp)
1011 struct image_params *imgp;
1015 if (imgp->firstpage != NULL) {
1016 m = sf_buf_page(imgp->firstpage);
1017 sf_buf_free(imgp->firstpage);
1018 imgp->firstpage = NULL;
1026 * Destroy old address space, and allocate a new stack
1027 * The new stack is only SGROWSIZ large because it is grown
1028 * automatically in trap.c.
1031 exec_new_vmspace(imgp, sv)
1032 struct image_params *imgp;
1033 struct sysentvec *sv;
1036 struct proc *p = imgp->proc;
1037 struct vmspace *vmspace = p->p_vmspace;
1039 struct rlimit rlim_stack;
1040 vm_offset_t sv_minuser, stack_addr;
1044 imgp->vmspace_destroyed = 1;
1047 /* May be called with Giant held */
1048 EVENTHANDLER_INVOKE(process_exec, p, imgp);
1051 * Blow away entire process VM, if address space not shared,
1052 * otherwise, create a new VM space so that other threads are
1055 map = &vmspace->vm_map;
1057 sv_minuser = sv->sv_minuser;
1059 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1060 if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1061 vm_map_max(map) == sv->sv_maxuser) {
1063 pmap_remove_pages(vmspace_pmap(vmspace));
1064 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1066 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1069 vmspace = p->p_vmspace;
1070 map = &vmspace->vm_map;
1073 /* Map a shared page */
1074 obj = sv->sv_shared_page_obj;
1076 vm_object_reference(obj);
1077 error = vm_map_fixed(map, obj, 0,
1078 sv->sv_shared_page_base, sv->sv_shared_page_len,
1079 VM_PROT_READ | VM_PROT_EXECUTE,
1080 VM_PROT_READ | VM_PROT_EXECUTE,
1081 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1083 vm_object_deallocate(obj);
1088 /* Allocate a new stack */
1089 if (imgp->stack_sz != 0) {
1090 ssiz = trunc_page(imgp->stack_sz);
1092 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1094 if (ssiz > rlim_stack.rlim_max)
1095 ssiz = rlim_stack.rlim_max;
1096 if (ssiz > rlim_stack.rlim_cur) {
1097 rlim_stack.rlim_cur = ssiz;
1098 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1100 } else if (sv->sv_maxssiz != NULL) {
1101 ssiz = *sv->sv_maxssiz;
1105 stack_addr = sv->sv_usrstack - ssiz;
1106 error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1107 obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1109 VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1114 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1115 * are still used to enforce the stack rlimit on the process stack.
1117 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1118 vmspace->vm_maxsaddr = (char *)stack_addr;
1124 * Copy out argument and environment strings from the old process address
1125 * space into the temporary string buffer.
1128 exec_copyin_args(struct image_args *args, char *fname,
1129 enum uio_seg segflg, char **argv, char **envv)
1135 bzero(args, sizeof(*args));
1140 * Allocate demand-paged memory for the file name, argument, and
1141 * environment strings.
1143 error = exec_alloc_args(args);
1148 * Copy the file name.
1150 if (fname != NULL) {
1151 args->fname = args->buf;
1152 error = (segflg == UIO_SYSSPACE) ?
1153 copystr(fname, args->fname, PATH_MAX, &length) :
1154 copyinstr(fname, args->fname, PATH_MAX, &length);
1160 args->begin_argv = args->buf + length;
1161 args->endp = args->begin_argv;
1162 args->stringspace = ARG_MAX;
1165 * extract arguments first
1168 error = fueword(argv++, &argp);
1175 error = copyinstr((void *)(uintptr_t)argp, args->endp,
1176 args->stringspace, &length);
1178 if (error == ENAMETOOLONG)
1182 args->stringspace -= length;
1183 args->endp += length;
1187 args->begin_envv = args->endp;
1190 * extract environment strings
1194 error = fueword(envv++, &envp);
1201 error = copyinstr((void *)(uintptr_t)envp,
1202 args->endp, args->stringspace, &length);
1204 if (error == ENAMETOOLONG)
1208 args->stringspace -= length;
1209 args->endp += length;
1217 exec_free_args(args);
1222 exec_copyin_data_fds(struct thread *td, struct image_args *args,
1223 const void *data, size_t datalen, const int *fds, size_t fdslen)
1225 struct filedesc *ofdp;
1230 memset(args, '\0', sizeof(*args));
1231 ofdp = td->td_proc->p_fd;
1232 if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
1234 error = exec_alloc_args(args);
1238 args->begin_argv = args->buf;
1239 args->stringspace = ARG_MAX;
1243 * Argument buffer has been provided. Copy it into the
1244 * kernel as a single string and add a terminating null
1247 error = copyin(data, args->begin_argv, datalen);
1250 args->begin_argv[datalen] = '\0';
1251 args->endp = args->begin_argv + datalen + 1;
1252 args->stringspace -= datalen + 1;
1255 * Traditional argument counting. Count the number of
1258 for (p = args->begin_argv; p < args->endp; ++p)
1262 /* No argument buffer provided. */
1263 args->endp = args->begin_argv;
1265 /* There are no environment variables. */
1266 args->begin_envv = args->endp;
1268 /* Create new file descriptor table. */
1269 kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
1270 error = copyin(fds, kfds, fdslen * sizeof(int));
1275 error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
1282 exec_free_args(args);
1287 * Allocate temporary demand-paged, zero-filled memory for the file name,
1288 * argument, and environment strings. Returns zero if the allocation succeeds
1289 * and ENOMEM otherwise.
1292 exec_alloc_args(struct image_args *args)
1295 args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1296 return (args->buf != NULL ? 0 : ENOMEM);
1300 exec_free_args(struct image_args *args)
1303 if (args->buf != NULL) {
1304 kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
1305 PATH_MAX + ARG_MAX);
1308 if (args->fname_buf != NULL) {
1309 free(args->fname_buf, M_TEMP);
1310 args->fname_buf = NULL;
1312 if (args->fdp != NULL)
1313 fdescfree_remapped(args->fdp);
1317 * Copy strings out to the new process address space, constructing new arg
1318 * and env vector tables. Return a pointer to the base so that it can be used
1319 * as the initial stack pointer.
1322 exec_copyout_strings(imgp)
1323 struct image_params *imgp;
1329 register_t *stack_base;
1330 struct ps_strings *arginfo;
1332 size_t execpath_len;
1333 int szsigcode, szps;
1334 char canary[sizeof(long) * 8];
1336 szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1338 * Calculate string base and vector table pointers.
1339 * Also deal with signal trampoline code for this exec type.
1341 if (imgp->execpath != NULL && imgp->auxargs != NULL)
1342 execpath_len = strlen(imgp->execpath) + 1;
1347 arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1348 if (p->p_sysent->sv_sigcode_base == 0) {
1349 if (p->p_sysent->sv_szsigcode != NULL)
1350 szsigcode = *(p->p_sysent->sv_szsigcode);
1352 destp = (uintptr_t)arginfo;
1357 if (szsigcode != 0) {
1359 destp = rounddown2(destp, sizeof(void *));
1360 copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
1364 * Copy the image path for the rtld.
1366 if (execpath_len != 0) {
1367 destp -= execpath_len;
1368 imgp->execpathp = destp;
1369 copyout(imgp->execpath, (void *)destp, execpath_len);
1373 * Prepare the canary for SSP.
1375 arc4rand(canary, sizeof(canary), 0);
1376 destp -= sizeof(canary);
1377 imgp->canary = destp;
1378 copyout(canary, (void *)destp, sizeof(canary));
1379 imgp->canarylen = sizeof(canary);
1382 * Prepare the pagesizes array.
1385 destp = rounddown2(destp, sizeof(void *));
1386 imgp->pagesizes = destp;
1387 copyout(pagesizes, (void *)destp, szps);
1388 imgp->pagesizeslen = szps;
1390 destp -= ARG_MAX - imgp->args->stringspace;
1391 destp = rounddown2(destp, sizeof(void *));
1394 * If we have a valid auxargs ptr, prepare some room
1397 if (imgp->auxargs) {
1399 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1400 * lower compatibility.
1402 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1405 * The '+ 2' is for the null pointers at the end of each of
1406 * the arg and env vector sets,and imgp->auxarg_size is room
1407 * for argument of Runtime loader.
1409 vectp = (char **)(destp - (imgp->args->argc +
1410 imgp->args->envc + 2 + imgp->auxarg_size)
1414 * The '+ 2' is for the null pointers at the end of each of
1415 * the arg and env vector sets
1417 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
1418 + 2) * sizeof(char *));
1422 * vectp also becomes our initial stack base
1424 stack_base = (register_t *)vectp;
1426 stringp = imgp->args->begin_argv;
1427 argc = imgp->args->argc;
1428 envc = imgp->args->envc;
1431 * Copy out strings - arguments and environment.
1433 copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
1436 * Fill in "ps_strings" struct for ps, w, etc.
1438 suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1439 suword32(&arginfo->ps_nargvstr, argc);
1442 * Fill in argument portion of vector table.
1444 for (; argc > 0; --argc) {
1445 suword(vectp++, (long)(intptr_t)destp);
1446 while (*stringp++ != 0)
1451 /* a null vector table pointer separates the argp's from the envp's */
1454 suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1455 suword32(&arginfo->ps_nenvstr, envc);
1458 * Fill in environment portion of vector table.
1460 for (; envc > 0; --envc) {
1461 suword(vectp++, (long)(intptr_t)destp);
1462 while (*stringp++ != 0)
1467 /* end of vector table is a null pointer */
1470 return (stack_base);
1474 * Check permissions of file to execute.
1475 * Called with imgp->vp locked.
1476 * Return 0 for success or error code on failure.
1479 exec_check_permissions(imgp)
1480 struct image_params *imgp;
1482 struct vnode *vp = imgp->vp;
1483 struct vattr *attr = imgp->attr;
1485 int error, writecount;
1489 /* Get file attributes */
1490 error = VOP_GETATTR(vp, attr, td->td_ucred);
1495 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1501 * 1) Check if file execution is disabled for the filesystem that
1502 * this file resides on.
1503 * 2) Ensure that at least one execute bit is on. Otherwise, a
1504 * privileged user will always succeed, and we don't want this
1505 * to happen unless the file really is executable.
1506 * 3) Ensure that the file is a regular file.
1508 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1509 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1510 (attr->va_type != VREG))
1514 * Zero length files can't be exec'd
1516 if (attr->va_size == 0)
1520 * Check for execute permission to file based on current credentials.
1522 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1527 * Check number of open-for-writes on the file and deny execution
1530 error = VOP_GET_WRITECOUNT(vp, &writecount);
1533 if (writecount != 0)
1537 * Call filesystem specific open routine (which does nothing in the
1540 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1547 * Exec handler registration
1550 exec_register(execsw_arg)
1551 const struct execsw *execsw_arg;
1553 const struct execsw **es, **xs, **newexecsw;
1554 int count = 2; /* New slot and trailing NULL */
1557 for (es = execsw; *es; es++)
1559 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1560 if (newexecsw == NULL)
1564 for (es = execsw; *es; es++)
1569 free(execsw, M_TEMP);
1575 exec_unregister(execsw_arg)
1576 const struct execsw *execsw_arg;
1578 const struct execsw **es, **xs, **newexecsw;
1582 panic("unregister with no handlers left?\n");
1584 for (es = execsw; *es; es++) {
1585 if (*es == execsw_arg)
1590 for (es = execsw; *es; es++)
1591 if (*es != execsw_arg)
1593 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1594 if (newexecsw == NULL)
1597 for (es = execsw; *es; es++)
1598 if (*es != execsw_arg)
1602 free(execsw, M_TEMP);