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 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
109 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
110 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
111 static int do_execve(struct thread *td, struct image_args *args,
114 /* XXX This should be vm_size_t. */
115 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
116 NULL, 0, sysctl_kern_ps_strings, "LU", "");
118 /* XXX This should be vm_size_t. */
119 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
120 CTLFLAG_CAPRD, NULL, 0, sysctl_kern_usrstack, "LU", "");
122 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
123 NULL, 0, sysctl_kern_stackprot, "I", "");
125 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
126 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
127 &ps_arg_cache_limit, 0, "");
129 static int disallow_high_osrel;
130 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
131 &disallow_high_osrel, 0,
132 "Disallow execution of binaries built for higher version of the world");
134 static int map_at_zero = 0;
135 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
136 "Permit processes to map an object at virtual address 0.");
139 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
146 if (req->flags & SCTL_MASK32) {
148 val = (unsigned int)p->p_sysent->sv_psstrings;
149 error = SYSCTL_OUT(req, &val, sizeof(val));
152 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
153 sizeof(p->p_sysent->sv_psstrings));
158 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
165 if (req->flags & SCTL_MASK32) {
167 val = (unsigned int)p->p_sysent->sv_usrstack;
168 error = SYSCTL_OUT(req, &val, sizeof(val));
171 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
172 sizeof(p->p_sysent->sv_usrstack));
177 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
182 return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
183 sizeof(p->p_sysent->sv_stackprot)));
187 * Each of the items is a pointer to a `const struct execsw', hence the
188 * double pointer here.
190 static const struct execsw **execsw;
192 #ifndef _SYS_SYSPROTO_H_
201 sys_execve(struct thread *td, struct execve_args *uap)
203 struct image_args args;
204 struct vmspace *oldvmspace;
207 error = pre_execve(td, &oldvmspace);
210 error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
211 uap->argv, uap->envv);
213 error = kern_execve(td, &args, NULL);
214 post_execve(td, error, oldvmspace);
218 #ifndef _SYS_SYSPROTO_H_
219 struct fexecve_args {
226 sys_fexecve(struct thread *td, struct fexecve_args *uap)
228 struct image_args args;
229 struct vmspace *oldvmspace;
232 error = pre_execve(td, &oldvmspace);
235 error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
236 uap->argv, uap->envv);
239 error = kern_execve(td, &args, NULL);
241 post_execve(td, error, oldvmspace);
245 #ifndef _SYS_SYSPROTO_H_
246 struct __mac_execve_args {
255 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
258 struct image_args args;
259 struct vmspace *oldvmspace;
262 error = pre_execve(td, &oldvmspace);
265 error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
266 uap->argv, uap->envv);
268 error = kern_execve(td, &args, uap->mac_p);
269 post_execve(td, error, oldvmspace);
277 pre_execve(struct thread *td, struct vmspace **oldvmspace)
282 KASSERT(td == curthread, ("non-current thread %p", td));
285 if ((p->p_flag & P_HADTHREADS) != 0) {
287 if (thread_single(p, SINGLE_BOUNDARY) != 0)
291 KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
293 *oldvmspace = p->p_vmspace;
298 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
302 KASSERT(td == curthread, ("non-current thread %p", td));
304 if ((p->p_flag & P_HADTHREADS) != 0) {
307 * If success, we upgrade to SINGLE_EXIT state to
308 * force other threads to suicide.
311 thread_single(p, SINGLE_EXIT);
313 thread_single_end(p, SINGLE_BOUNDARY);
316 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
317 KASSERT(p->p_vmspace != oldvmspace,
318 ("oldvmspace still used"));
319 vmspace_free(oldvmspace);
320 td->td_pflags &= ~TDP_EXECVMSPC;
325 * XXX: kern_execve has the astonishing property of not always returning to
326 * the caller. If sufficiently bad things happen during the call to
327 * do_execve(), it can end up calling exit1(); as a result, callers must
328 * avoid doing anything which they might need to undo (e.g., allocating
332 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p)
335 AUDIT_ARG_ARGV(args->begin_argv, args->argc,
336 args->begin_envv - args->begin_argv);
337 AUDIT_ARG_ENVV(args->begin_envv, args->envc,
338 args->endp - args->begin_envv);
339 return (do_execve(td, args, mac_p));
343 * In-kernel implementation of execve(). All arguments are assumed to be
344 * userspace pointers from the passed thread.
347 do_execve(td, args, mac_p)
349 struct image_args *args;
352 struct proc *p = td->td_proc;
354 struct ucred *newcred = NULL, *oldcred;
355 struct uidinfo *euip = NULL;
356 register_t *stack_base;
358 struct image_params image_params, *imgp;
360 int (*img_first)(struct image_params *);
361 struct pargs *oldargs = NULL, *newargs = NULL;
362 struct sigacts *oldsigacts, *newsigacts;
364 struct vnode *tracevp = NULL;
365 struct ucred *tracecred = NULL;
367 struct vnode *oldtextvp = NULL, *newtextvp;
369 int credential_changing;
372 struct label *interpvplabel = NULL;
376 struct pmckern_procexec pe;
378 static const char fexecv_proc_title[] = "(fexecv)";
380 imgp = &image_params;
383 * Lock the process and set the P_INEXEC flag to indicate that
384 * it should be left alone until we're done here. This is
385 * necessary to avoid race conditions - e.g. in ptrace() -
386 * that might allow a local user to illicitly obtain elevated
390 KASSERT((p->p_flag & P_INEXEC) == 0,
391 ("%s(): process already has P_INEXEC flag", __func__));
392 p->p_flag |= P_INEXEC;
396 * Initialize part of the common data
398 bzero(imgp, sizeof(*imgp));
404 error = mac_execve_enter(imgp, mac_p);
410 * Translate the file name. namei() returns a vnode pointer
411 * in ni_vp amoung other things.
413 * XXXAUDIT: It would be desirable to also audit the name of the
414 * interpreter if this is an interpreted binary.
416 if (args->fname != NULL) {
417 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
418 | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
421 SDT_PROBE(proc, kernel, , exec, args->fname, 0, 0, 0, 0 );
424 if (args->fname != NULL) {
425 #ifdef CAPABILITY_MODE
427 * While capability mode can't reach this point via direct
428 * path arguments to execve(), we also don't allow
429 * interpreters to be used in capability mode (for now).
430 * Catch indirect lookups and return a permissions error.
432 if (IN_CAPABILITY_MODE(td)) {
441 newtextvp = nd.ni_vp;
442 imgp->vp = newtextvp;
444 AUDIT_ARG_FD(args->fd);
446 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
448 error = fgetvp_exec(td, args->fd,
449 cap_rights_init(&rights, CAP_FEXECVE), &newtextvp);
452 vn_lock(newtextvp, LK_EXCLUSIVE | LK_RETRY);
453 AUDIT_ARG_VNODE1(newtextvp);
454 imgp->vp = newtextvp;
458 * Check file permissions (also 'opens' file)
460 error = exec_check_permissions(imgp);
462 goto exec_fail_dealloc;
464 imgp->object = imgp->vp->v_object;
465 if (imgp->object != NULL)
466 vm_object_reference(imgp->object);
469 * Set VV_TEXT now so no one can write to the executable while we're
472 * Remember if this was set before and unset it in case this is not
473 * actually an executable image.
475 textset = VOP_IS_TEXT(imgp->vp);
476 VOP_SET_TEXT(imgp->vp);
478 error = exec_map_first_page(imgp);
480 goto exec_fail_dealloc;
482 imgp->proc->p_osrel = 0;
484 * If the current process has a special image activator it
485 * wants to try first, call it. For example, emulating shell
486 * scripts differently.
489 if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
490 error = img_first(imgp);
493 * Loop through the list of image activators, calling each one.
494 * An activator returns -1 if there is no match, 0 on success,
495 * and an error otherwise.
497 for (i = 0; error == -1 && execsw[i]; ++i) {
498 if (execsw[i]->ex_imgact == NULL ||
499 execsw[i]->ex_imgact == img_first) {
502 error = (*execsw[i]->ex_imgact)(imgp);
508 VOP_UNSET_TEXT(imgp->vp);
511 goto exec_fail_dealloc;
515 * Special interpreter operation, cleanup and loop up to try to
516 * activate the interpreter.
518 if (imgp->interpreted) {
519 exec_unmap_first_page(imgp);
521 * VV_TEXT needs to be unset for scripts. There is a short
522 * period before we determine that something is a script where
523 * VV_TEXT will be set. The vnode lock is held over this
524 * entire period so nothing should illegitimately be blocked.
526 VOP_UNSET_TEXT(imgp->vp);
527 /* free name buffer and old vnode */
528 if (args->fname != NULL)
529 NDFREE(&nd, NDF_ONLY_PNBUF);
531 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
534 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
538 vm_object_deallocate(imgp->object);
540 /* set new name to that of the interpreter */
541 NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
542 UIO_SYSSPACE, imgp->interpreter_name, td);
543 args->fname = imgp->interpreter_name;
548 * NB: We unlock the vnode here because it is believed that none
549 * of the sv_copyout_strings/sv_fixup operations require the vnode.
551 VOP_UNLOCK(imgp->vp, 0);
554 * Do the best to calculate the full path to the image file.
556 if (imgp->auxargs != NULL &&
557 ((args->fname != NULL && args->fname[0] == '/') ||
558 vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
559 imgp->execpath = args->fname;
561 if (disallow_high_osrel &&
562 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
564 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
565 imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
566 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
567 goto exec_fail_dealloc;
570 /* ABI enforces the use of Capsicum. Switch into capabilities mode. */
571 if (SV_PROC_FLAG(p, SV_CAPSICUM))
572 sys_cap_enter(td, NULL);
575 * Copy out strings (args and env) and initialize stack base
577 if (p->p_sysent->sv_copyout_strings)
578 stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
580 stack_base = exec_copyout_strings(imgp);
583 * If custom stack fixup routine present for this process
584 * let it do the stack setup.
585 * Else stuff argument count as first item on stack
587 if (p->p_sysent->sv_fixup != NULL)
588 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
590 suword(--stack_base, imgp->args->argc);
592 if (args->fdp != NULL) {
593 /* Install a brand new file descriptor table. */
594 fdinstall_remapped(td, args->fdp);
598 * Keep on using the existing file descriptor table. For
599 * security and other reasons, the file descriptor table
600 * cannot be shared after an exec.
603 /* close files on exec */
608 * Malloc things before we need locks.
610 i = imgp->args->begin_envv - imgp->args->begin_argv;
611 /* Cache arguments if they fit inside our allowance */
612 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
613 newargs = pargs_alloc(i);
614 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
617 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
620 * For security and other reasons, signal handlers cannot
621 * be shared after an exec. The new process gets a copy of the old
622 * handlers. In execsigs(), the new process will have its signals
625 if (sigacts_shared(p->p_sigacts)) {
626 oldsigacts = p->p_sigacts;
627 newsigacts = sigacts_alloc();
628 sigacts_copy(newsigacts, oldsigacts);
631 newsigacts = NULL; /* satisfy gcc */
636 p->p_sigacts = newsigacts;
637 oldcred = p->p_ucred;
641 /* reset caught signals */
644 /* name this process - nameiexec(p, ndp) */
645 bzero(p->p_comm, sizeof(p->p_comm));
647 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
648 min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
649 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
650 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
651 bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
653 sched_clear_tdname(td);
657 * mark as execed, wakeup the process that vforked (if any) and tell
658 * it that it now has its own resources back
661 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
662 p->p_flag2 &= ~P2_NOTRACE;
663 if (p->p_flag & P_PPWAIT) {
664 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
665 cv_broadcast(&p->p_pwait);
669 * Implement image setuid/setgid.
671 * Don't honor setuid/setgid if the filesystem prohibits it or if
672 * the process is being traced.
674 * We disable setuid/setgid/etc in compatibility mode on the basis
675 * that most setugid applications are not written with that
676 * environment in mind, and will therefore almost certainly operate
677 * incorrectly. In principle there's no reason that setugid
678 * applications might not be useful in capability mode, so we may want
679 * to reconsider this conservative design choice in the future.
681 * XXXMAC: For the time being, use NOSUID to also prohibit
682 * transitions on the file system.
684 credential_changing = 0;
685 credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
687 credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
690 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
691 interpvplabel, imgp);
692 credential_changing |= will_transition;
695 if (credential_changing &&
696 #ifdef CAPABILITY_MODE
697 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
699 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
700 (p->p_flag & P_TRACED) == 0) {
702 * Turn off syscall tracing for set-id programs, except for
703 * root. Record any set-id flags first to make sure that
704 * we do not regain any tracing during a possible block.
709 if (p->p_tracecred != NULL &&
710 priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
711 ktrprocexec(p, &tracecred, &tracevp);
714 * Close any file descriptors 0..2 that reference procfs,
715 * then make sure file descriptors 0..2 are in use.
717 * Both fdsetugidsafety() and fdcheckstd() may call functions
718 * taking sleepable locks, so temporarily drop our locks.
721 VOP_UNLOCK(imgp->vp, 0);
723 error = fdcheckstd(td);
726 newcred = crdup(oldcred);
727 euip = uifind(attr.va_uid);
728 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
731 * Set the new credentials.
733 if (attr.va_mode & S_ISUID)
734 change_euid(newcred, euip);
735 if (attr.va_mode & S_ISGID)
736 change_egid(newcred, attr.va_gid);
738 if (will_transition) {
739 mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
740 interpvplabel, imgp);
744 * Implement correct POSIX saved-id behavior.
746 * XXXMAC: Note that the current logic will save the
747 * uid and gid if a MAC domain transition occurs, even
748 * though maybe it shouldn't.
750 change_svuid(newcred, newcred->cr_uid);
751 change_svgid(newcred, newcred->cr_gid);
752 proc_set_cred(p, newcred);
754 if (oldcred->cr_uid == oldcred->cr_ruid &&
755 oldcred->cr_gid == oldcred->cr_rgid)
756 p->p_flag &= ~P_SUGID;
758 * Implement correct POSIX saved-id behavior.
760 * XXX: It's not clear that the existing behavior is
761 * POSIX-compliant. A number of sources indicate that the
762 * saved uid/gid should only be updated if the new ruid is
763 * not equal to the old ruid, or the new euid is not equal
764 * to the old euid and the new euid is not equal to the old
765 * ruid. The FreeBSD code always updates the saved uid/gid.
766 * Also, this code uses the new (replaced) euid and egid as
767 * the source, which may or may not be the right ones to use.
769 if (oldcred->cr_svuid != oldcred->cr_uid ||
770 oldcred->cr_svgid != oldcred->cr_gid) {
772 VOP_UNLOCK(imgp->vp, 0);
773 newcred = crdup(oldcred);
774 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
776 change_svuid(newcred, newcred->cr_uid);
777 change_svgid(newcred, newcred->cr_gid);
778 proc_set_cred(p, newcred);
783 * Store the vp for use in procfs. This vnode was referenced by namei
786 oldtextvp = p->p_textvp;
787 p->p_textvp = newtextvp;
791 * Tell the DTrace fasttrap provider about the exec if it
792 * has declared an interest.
794 if (dtrace_fasttrap_exec)
795 dtrace_fasttrap_exec(p);
799 * Notify others that we exec'd, and clear the P_INEXEC flag
800 * as we're now a bona fide freshly-execed process.
802 KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
803 p->p_flag &= ~P_INEXEC;
805 /* clear "fork but no exec" flag, as we _are_ execing */
806 p->p_acflag &= ~AFORK;
809 * Free any previous argument cache and replace it with
810 * the new argument cache, if any.
818 * Check if system-wide sampling is in effect or if the
819 * current process is using PMCs. If so, do exec() time
820 * processing. This processing needs to happen AFTER the
821 * P_INEXEC flag is cleared.
823 * The proc lock needs to be released before taking the PMC
826 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
828 VOP_UNLOCK(imgp->vp, 0);
829 pe.pm_credentialschanged = credential_changing;
830 pe.pm_entryaddr = imgp->entry_addr;
832 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
833 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
836 #else /* !HWPMC_HOOKS */
840 /* Set values passed into the program in registers. */
841 if (p->p_sysent->sv_setregs)
842 (*p->p_sysent->sv_setregs)(td, imgp,
843 (u_long)(uintptr_t)stack_base);
845 exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
847 vfs_mark_atime(imgp->vp, td->td_ucred);
849 SDT_PROBE(proc, kernel, , exec__success, args->fname, 0, 0, 0, 0);
851 VOP_UNLOCK(imgp->vp, 0);
854 * Free any resources malloc'd earlier that we didn't use.
862 * Handle deferred decrement of ref counts.
864 if (oldtextvp != NULL)
869 if (tracecred != NULL)
872 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
875 if (oldsigacts != NULL)
876 sigacts_free(oldsigacts);
881 * free various allocated resources
883 if (imgp->firstpage != NULL)
884 exec_unmap_first_page(imgp);
886 if (imgp->vp != NULL) {
888 NDFREE(&nd, NDF_ONLY_PNBUF);
890 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
894 VOP_UNLOCK(imgp->vp, 0);
897 if (imgp->object != NULL)
898 vm_object_deallocate(imgp->object);
900 free(imgp->freepath, M_TEMP);
904 td->td_dbgflags |= TDB_EXEC;
908 * Stop the process here if its stop event mask has
909 * the S_EXEC bit set.
911 STOPEVENT(p, S_EXEC, 0);
916 /* we're done here, clear P_INEXEC */
918 p->p_flag &= ~P_INEXEC;
921 SDT_PROBE(proc, kernel, , exec__failure, error, 0, 0, 0, 0);
925 mac_execve_exit(imgp);
926 mac_execve_interpreter_exit(interpvplabel);
928 exec_free_args(args);
930 if (error && imgp->vmspace_destroyed) {
931 /* sorry, no more process anymore. exit gracefully */
932 exit1(td, 0, SIGABRT);
945 exec_map_first_page(imgp)
946 struct image_params *imgp;
950 vm_page_t ma[VM_INITIAL_PAGEIN];
953 if (imgp->firstpage != NULL)
954 exec_unmap_first_page(imgp);
956 object = imgp->vp->v_object;
959 VM_OBJECT_WLOCK(object);
960 #if VM_NRESERVLEVEL > 0
961 vm_object_color(object, 0);
963 ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
964 if (ma[0]->valid != VM_PAGE_BITS_ALL) {
965 initial_pagein = VM_INITIAL_PAGEIN;
966 if (initial_pagein > object->size)
967 initial_pagein = object->size;
968 for (i = 1; i < initial_pagein; i++) {
969 if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
972 if (vm_page_tryxbusy(ma[i]))
975 ma[i] = vm_page_alloc(object, i,
976 VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
982 rv = vm_pager_get_pages(object, ma, initial_pagein, 0);
983 if (rv != VM_PAGER_OK) {
986 vm_page_unlock(ma[0]);
987 VM_OBJECT_WUNLOCK(object);
991 vm_page_xunbusy(ma[0]);
994 vm_page_activate(ma[0]);
995 vm_page_unlock(ma[0]);
996 VM_OBJECT_WUNLOCK(object);
998 imgp->firstpage = sf_buf_alloc(ma[0], 0);
999 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1005 exec_unmap_first_page(imgp)
1006 struct image_params *imgp;
1010 if (imgp->firstpage != NULL) {
1011 m = sf_buf_page(imgp->firstpage);
1012 sf_buf_free(imgp->firstpage);
1013 imgp->firstpage = NULL;
1021 * Destroy old address space, and allocate a new stack
1022 * The new stack is only SGROWSIZ large because it is grown
1023 * automatically in trap.c.
1026 exec_new_vmspace(imgp, sv)
1027 struct image_params *imgp;
1028 struct sysentvec *sv;
1031 struct proc *p = imgp->proc;
1032 struct vmspace *vmspace = p->p_vmspace;
1034 struct rlimit rlim_stack;
1035 vm_offset_t sv_minuser, stack_addr;
1039 imgp->vmspace_destroyed = 1;
1042 /* May be called with Giant held */
1043 EVENTHANDLER_INVOKE(process_exec, p, imgp);
1046 * Blow away entire process VM, if address space not shared,
1047 * otherwise, create a new VM space so that other threads are
1050 map = &vmspace->vm_map;
1052 sv_minuser = sv->sv_minuser;
1054 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1055 if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1056 vm_map_max(map) == sv->sv_maxuser) {
1058 pmap_remove_pages(vmspace_pmap(vmspace));
1059 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1061 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1064 vmspace = p->p_vmspace;
1065 map = &vmspace->vm_map;
1068 /* Map a shared page */
1069 obj = sv->sv_shared_page_obj;
1071 vm_object_reference(obj);
1072 error = vm_map_fixed(map, obj, 0,
1073 sv->sv_shared_page_base, sv->sv_shared_page_len,
1074 VM_PROT_READ | VM_PROT_EXECUTE,
1075 VM_PROT_READ | VM_PROT_EXECUTE,
1076 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1078 vm_object_deallocate(obj);
1083 /* Allocate a new stack */
1084 if (imgp->stack_sz != 0) {
1085 ssiz = trunc_page(imgp->stack_sz);
1087 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1089 if (ssiz > rlim_stack.rlim_max)
1090 ssiz = rlim_stack.rlim_max;
1091 if (ssiz > rlim_stack.rlim_cur) {
1092 rlim_stack.rlim_cur = ssiz;
1093 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1095 } else if (sv->sv_maxssiz != NULL) {
1096 ssiz = *sv->sv_maxssiz;
1100 stack_addr = sv->sv_usrstack - ssiz;
1101 error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1102 obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1104 VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1109 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1110 * are still used to enforce the stack rlimit on the process stack.
1112 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1113 vmspace->vm_maxsaddr = (char *)stack_addr;
1119 * Copy out argument and environment strings from the old process address
1120 * space into the temporary string buffer.
1123 exec_copyin_args(struct image_args *args, char *fname,
1124 enum uio_seg segflg, char **argv, char **envv)
1130 bzero(args, sizeof(*args));
1135 * Allocate demand-paged memory for the file name, argument, and
1136 * environment strings.
1138 error = exec_alloc_args(args);
1143 * Copy the file name.
1145 if (fname != NULL) {
1146 args->fname = args->buf;
1147 error = (segflg == UIO_SYSSPACE) ?
1148 copystr(fname, args->fname, PATH_MAX, &length) :
1149 copyinstr(fname, args->fname, PATH_MAX, &length);
1155 args->begin_argv = args->buf + length;
1156 args->endp = args->begin_argv;
1157 args->stringspace = ARG_MAX;
1160 * extract arguments first
1163 error = fueword(argv++, &argp);
1170 error = copyinstr((void *)(uintptr_t)argp, args->endp,
1171 args->stringspace, &length);
1173 if (error == ENAMETOOLONG)
1177 args->stringspace -= length;
1178 args->endp += length;
1182 args->begin_envv = args->endp;
1185 * extract environment strings
1189 error = fueword(envv++, &envp);
1196 error = copyinstr((void *)(uintptr_t)envp,
1197 args->endp, args->stringspace, &length);
1199 if (error == ENAMETOOLONG)
1203 args->stringspace -= length;
1204 args->endp += length;
1212 exec_free_args(args);
1217 exec_copyin_data_fds(struct thread *td, struct image_args *args,
1218 const void *data, size_t datalen, const int *fds, size_t fdslen)
1220 struct filedesc *ofdp;
1225 memset(args, '\0', sizeof(*args));
1226 ofdp = td->td_proc->p_fd;
1227 if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
1229 error = exec_alloc_args(args);
1233 args->begin_argv = args->buf;
1234 args->stringspace = ARG_MAX;
1238 * Argument buffer has been provided. Copy it into the
1239 * kernel as a single string and add a terminating null
1242 error = copyin(data, args->begin_argv, datalen);
1245 args->begin_argv[datalen] = '\0';
1246 args->endp = args->begin_argv + datalen + 1;
1247 args->stringspace -= datalen + 1;
1250 * Traditional argument counting. Count the number of
1253 for (p = args->begin_argv; p < args->endp; ++p)
1257 /* No argument buffer provided. */
1258 args->endp = args->begin_argv;
1260 /* There are no environment variables. */
1261 args->begin_envv = args->endp;
1263 /* Create new file descriptor table. */
1264 kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
1265 error = copyin(fds, kfds, fdslen * sizeof(int));
1270 error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
1277 exec_free_args(args);
1282 * Allocate temporary demand-paged, zero-filled memory for the file name,
1283 * argument, and environment strings. Returns zero if the allocation succeeds
1284 * and ENOMEM otherwise.
1287 exec_alloc_args(struct image_args *args)
1290 args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1291 return (args->buf != NULL ? 0 : ENOMEM);
1295 exec_free_args(struct image_args *args)
1298 if (args->buf != NULL) {
1299 kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
1300 PATH_MAX + ARG_MAX);
1303 if (args->fname_buf != NULL) {
1304 free(args->fname_buf, M_TEMP);
1305 args->fname_buf = NULL;
1307 if (args->fdp != NULL)
1308 fdescfree_remapped(args->fdp);
1312 * Copy strings out to the new process address space, constructing new arg
1313 * and env vector tables. Return a pointer to the base so that it can be used
1314 * as the initial stack pointer.
1317 exec_copyout_strings(imgp)
1318 struct image_params *imgp;
1324 register_t *stack_base;
1325 struct ps_strings *arginfo;
1327 size_t execpath_len;
1328 int szsigcode, szps;
1329 char canary[sizeof(long) * 8];
1331 szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1333 * Calculate string base and vector table pointers.
1334 * Also deal with signal trampoline code for this exec type.
1336 if (imgp->execpath != NULL && imgp->auxargs != NULL)
1337 execpath_len = strlen(imgp->execpath) + 1;
1342 arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1343 if (p->p_sysent->sv_sigcode_base == 0) {
1344 if (p->p_sysent->sv_szsigcode != NULL)
1345 szsigcode = *(p->p_sysent->sv_szsigcode);
1347 destp = (uintptr_t)arginfo;
1352 if (szsigcode != 0) {
1354 destp = rounddown2(destp, sizeof(void *));
1355 copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
1359 * Copy the image path for the rtld.
1361 if (execpath_len != 0) {
1362 destp -= execpath_len;
1363 imgp->execpathp = destp;
1364 copyout(imgp->execpath, (void *)destp, execpath_len);
1368 * Prepare the canary for SSP.
1370 arc4rand(canary, sizeof(canary), 0);
1371 destp -= sizeof(canary);
1372 imgp->canary = destp;
1373 copyout(canary, (void *)destp, sizeof(canary));
1374 imgp->canarylen = sizeof(canary);
1377 * Prepare the pagesizes array.
1380 destp = rounddown2(destp, sizeof(void *));
1381 imgp->pagesizes = destp;
1382 copyout(pagesizes, (void *)destp, szps);
1383 imgp->pagesizeslen = szps;
1385 destp -= ARG_MAX - imgp->args->stringspace;
1386 destp = rounddown2(destp, sizeof(void *));
1389 * If we have a valid auxargs ptr, prepare some room
1392 if (imgp->auxargs) {
1394 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1395 * lower compatibility.
1397 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1400 * The '+ 2' is for the null pointers at the end of each of
1401 * the arg and env vector sets,and imgp->auxarg_size is room
1402 * for argument of Runtime loader.
1404 vectp = (char **)(destp - (imgp->args->argc +
1405 imgp->args->envc + 2 + imgp->auxarg_size)
1409 * The '+ 2' is for the null pointers at the end of each of
1410 * the arg and env vector sets
1412 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
1413 + 2) * sizeof(char *));
1417 * vectp also becomes our initial stack base
1419 stack_base = (register_t *)vectp;
1421 stringp = imgp->args->begin_argv;
1422 argc = imgp->args->argc;
1423 envc = imgp->args->envc;
1426 * Copy out strings - arguments and environment.
1428 copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
1431 * Fill in "ps_strings" struct for ps, w, etc.
1433 suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1434 suword32(&arginfo->ps_nargvstr, argc);
1437 * Fill in argument portion of vector table.
1439 for (; argc > 0; --argc) {
1440 suword(vectp++, (long)(intptr_t)destp);
1441 while (*stringp++ != 0)
1446 /* a null vector table pointer separates the argp's from the envp's */
1449 suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1450 suword32(&arginfo->ps_nenvstr, envc);
1453 * Fill in environment portion of vector table.
1455 for (; envc > 0; --envc) {
1456 suword(vectp++, (long)(intptr_t)destp);
1457 while (*stringp++ != 0)
1462 /* end of vector table is a null pointer */
1465 return (stack_base);
1469 * Check permissions of file to execute.
1470 * Called with imgp->vp locked.
1471 * Return 0 for success or error code on failure.
1474 exec_check_permissions(imgp)
1475 struct image_params *imgp;
1477 struct vnode *vp = imgp->vp;
1478 struct vattr *attr = imgp->attr;
1480 int error, writecount;
1484 /* Get file attributes */
1485 error = VOP_GETATTR(vp, attr, td->td_ucred);
1490 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1496 * 1) Check if file execution is disabled for the filesystem that
1497 * this file resides on.
1498 * 2) Ensure that at least one execute bit is on. Otherwise, a
1499 * privileged user will always succeed, and we don't want this
1500 * to happen unless the file really is executable.
1501 * 3) Ensure that the file is a regular file.
1503 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1504 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1505 (attr->va_type != VREG))
1509 * Zero length files can't be exec'd
1511 if (attr->va_size == 0)
1515 * Check for execute permission to file based on current credentials.
1517 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1522 * Check number of open-for-writes on the file and deny execution
1525 error = VOP_GET_WRITECOUNT(vp, &writecount);
1528 if (writecount != 0)
1532 * Call filesystem specific open routine (which does nothing in the
1535 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1542 * Exec handler registration
1545 exec_register(execsw_arg)
1546 const struct execsw *execsw_arg;
1548 const struct execsw **es, **xs, **newexecsw;
1549 int count = 2; /* New slot and trailing NULL */
1552 for (es = execsw; *es; es++)
1554 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1555 if (newexecsw == NULL)
1559 for (es = execsw; *es; es++)
1564 free(execsw, M_TEMP);
1570 exec_unregister(execsw_arg)
1571 const struct execsw *execsw_arg;
1573 const struct execsw **es, **xs, **newexecsw;
1577 panic("unregister with no handlers left?\n");
1579 for (es = execsw; *es; es++) {
1580 if (*es == execsw_arg)
1585 for (es = execsw; *es; es++)
1586 if (*es != execsw_arg)
1588 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1589 if (newexecsw == NULL)
1592 for (es = execsw; *es; es++)
1593 if (*es != execsw_arg)
1597 free(execsw, M_TEMP);