2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1993, David Greenman
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include "opt_capsicum.h"
33 #include "opt_hwpmc_hooks.h"
34 #include "opt_ktrace.h"
37 #include <sys/param.h>
38 #include <sys/systm.h>
41 #include <sys/capsicum.h>
42 #include <sys/compressor.h>
43 #include <sys/eventhandler.h>
45 #include <sys/fcntl.h>
46 #include <sys/filedesc.h>
47 #include <sys/imgact.h>
48 #include <sys/imgact_elf.h>
49 #include <sys/kernel.h>
51 #include <sys/malloc.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/namei.h>
58 #include <sys/ptrace.h>
60 #include <sys/resourcevar.h>
61 #include <sys/rwlock.h>
62 #include <sys/sched.h>
64 #include <sys/sf_buf.h>
66 #include <sys/signalvar.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysent.h>
72 #include <sys/sysproto.h>
73 #include <sys/timers.h>
74 #include <sys/umtxvar.h>
75 #include <sys/vnode.h>
78 #include <sys/ktrace.h>
82 #include <vm/vm_param.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_extern.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_pager.h>
92 #include <sys/pmckern.h>
95 #include <security/audit/audit.h>
96 #include <security/mac/mac_framework.h>
99 #include <sys/dtrace_bsd.h>
100 dtrace_execexit_func_t dtrace_fasttrap_exec;
103 SDT_PROVIDER_DECLARE(proc);
104 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
105 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
106 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
108 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
110 int coredump_pack_fileinfo = 1;
111 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
112 &coredump_pack_fileinfo, 0,
113 "Enable file path packing in 'procstat -f' coredump notes");
115 int coredump_pack_vmmapinfo = 1;
116 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
117 &coredump_pack_vmmapinfo, 0,
118 "Enable file path packing in 'procstat -v' coredump notes");
120 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
121 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
122 static int sysctl_kern_stacktop(SYSCTL_HANDLER_ARGS);
123 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
124 static int do_execve(struct thread *td, struct image_args *args,
125 struct mac *mac_p, struct vmspace *oldvmspace);
127 /* XXX This should be vm_size_t. */
128 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD|
129 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_ps_strings, "LU",
130 "Location of process' ps_strings structure");
132 /* XXX This should be vm_size_t. */
133 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
134 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_usrstack, "LU",
135 "Top of process stack");
137 SYSCTL_PROC(_kern, KERN_STACKTOP, stacktop, CTLTYPE_ULONG | CTLFLAG_RD |
138 CTLFLAG_CAPRD | CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_stacktop, "LU",
139 "Top of process stack with stack gap.");
141 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_MPSAFE,
142 NULL, 0, sysctl_kern_stackprot, "I",
143 "Stack memory permissions");
145 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
146 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
147 &ps_arg_cache_limit, 0,
148 "Process' command line characters cache limit");
150 static int disallow_high_osrel;
151 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
152 &disallow_high_osrel, 0,
153 "Disallow execution of binaries built for higher version of the world");
155 static int map_at_zero = 0;
156 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
157 "Permit processes to map an object at virtual address 0.");
159 static int core_dump_can_intr = 1;
160 SYSCTL_INT(_kern, OID_AUTO, core_dump_can_intr, CTLFLAG_RWTUN,
161 &core_dump_can_intr, 0,
162 "Core dumping interruptible with SIGKILL");
165 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
172 if (req->flags & SCTL_MASK32) {
174 val = (unsigned int)p->p_sysent->sv_psstrings;
175 error = SYSCTL_OUT(req, &val, sizeof(val));
178 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
179 sizeof(p->p_sysent->sv_psstrings));
184 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
191 if (req->flags & SCTL_MASK32) {
193 val = (unsigned int)p->p_sysent->sv_usrstack;
194 error = SYSCTL_OUT(req, &val, sizeof(val));
197 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
198 sizeof(p->p_sysent->sv_usrstack));
203 sysctl_kern_stacktop(SYSCTL_HANDLER_ARGS)
205 vm_offset_t stacktop;
211 if (req->flags & SCTL_MASK32) {
214 val = (unsigned int)(p->p_sysent->sv_usrstack -
215 p->p_vmspace->vm_stkgap);
216 error = SYSCTL_OUT(req, &val, sizeof(val));
220 stacktop = p->p_sysent->sv_usrstack - p->p_vmspace->vm_stkgap;
221 error = SYSCTL_OUT(req, &stacktop, sizeof(stacktop));
227 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
232 return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
233 sizeof(p->p_sysent->sv_stackprot)));
237 * Each of the items is a pointer to a `const struct execsw', hence the
238 * double pointer here.
240 static const struct execsw **execsw;
242 #ifndef _SYS_SYSPROTO_H_
251 sys_execve(struct thread *td, struct execve_args *uap)
253 struct image_args args;
254 struct vmspace *oldvmspace;
257 error = pre_execve(td, &oldvmspace);
260 error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
261 uap->argv, uap->envv);
263 error = kern_execve(td, &args, NULL, oldvmspace);
264 post_execve(td, error, oldvmspace);
265 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
269 #ifndef _SYS_SYSPROTO_H_
270 struct fexecve_args {
277 sys_fexecve(struct thread *td, struct fexecve_args *uap)
279 struct image_args args;
280 struct vmspace *oldvmspace;
283 error = pre_execve(td, &oldvmspace);
286 error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
287 uap->argv, uap->envv);
290 error = kern_execve(td, &args, NULL, oldvmspace);
292 post_execve(td, error, oldvmspace);
293 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
297 #ifndef _SYS_SYSPROTO_H_
298 struct __mac_execve_args {
307 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
310 struct image_args args;
311 struct vmspace *oldvmspace;
314 error = pre_execve(td, &oldvmspace);
317 error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
318 uap->argv, uap->envv);
320 error = kern_execve(td, &args, uap->mac_p, oldvmspace);
321 post_execve(td, error, oldvmspace);
322 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
330 pre_execve(struct thread *td, struct vmspace **oldvmspace)
335 KASSERT(td == curthread, ("non-current thread %p", td));
338 if ((p->p_flag & P_HADTHREADS) != 0) {
340 if (thread_single(p, SINGLE_BOUNDARY) != 0)
344 KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
346 *oldvmspace = p->p_vmspace;
351 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
355 KASSERT(td == curthread, ("non-current thread %p", td));
357 if ((p->p_flag & P_HADTHREADS) != 0) {
360 * If success, we upgrade to SINGLE_EXIT state to
361 * force other threads to suicide.
363 if (error == EJUSTRETURN)
364 thread_single(p, SINGLE_EXIT);
366 thread_single_end(p, SINGLE_BOUNDARY);
369 exec_cleanup(td, oldvmspace);
373 * kern_execve() has the astonishing property of not always returning to
374 * the caller. If sufficiently bad things happen during the call to
375 * do_execve(), it can end up calling exit1(); as a result, callers must
376 * avoid doing anything which they might need to undo (e.g., allocating
380 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
381 struct vmspace *oldvmspace)
384 TSEXEC(td->td_proc->p_pid, args->begin_argv);
385 AUDIT_ARG_ARGV(args->begin_argv, args->argc,
386 exec_args_get_begin_envv(args) - args->begin_argv);
387 AUDIT_ARG_ENVV(exec_args_get_begin_envv(args), args->envc,
388 args->endp - exec_args_get_begin_envv(args));
389 return (do_execve(td, args, mac_p, oldvmspace));
393 execve_nosetid(struct image_params *imgp)
395 imgp->credential_setid = false;
396 if (imgp->newcred != NULL) {
397 crfree(imgp->newcred);
398 imgp->newcred = NULL;
403 * In-kernel implementation of execve(). All arguments are assumed to be
404 * userspace pointers from the passed thread.
407 do_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
408 struct vmspace *oldvmspace)
410 struct proc *p = td->td_proc;
412 struct ucred *oldcred;
413 struct uidinfo *euip = NULL;
414 uintptr_t stack_base;
415 struct image_params image_params, *imgp;
417 int (*img_first)(struct image_params *);
418 struct pargs *oldargs = NULL, *newargs = NULL;
419 struct sigacts *oldsigacts = NULL, *newsigacts = NULL;
421 struct ktr_io_params *kiop;
423 struct vnode *oldtextvp = NULL, *newtextvp;
424 int credential_changing;
426 struct label *interpvplabel = NULL;
430 struct pmckern_procexec pe;
432 int error, i, orig_osrel;
434 Elf_Brandinfo *orig_brandinfo;
435 static const char fexecv_proc_title[] = "(fexecv)";
437 imgp = &image_params;
443 * Lock the process and set the P_INEXEC flag to indicate that
444 * it should be left alone until we're done here. This is
445 * necessary to avoid race conditions - e.g. in ptrace() -
446 * that might allow a local user to illicitly obtain elevated
450 KASSERT((p->p_flag & P_INEXEC) == 0,
451 ("%s(): process already has P_INEXEC flag", __func__));
452 p->p_flag |= P_INEXEC;
456 * Initialize part of the common data
458 bzero(imgp, sizeof(*imgp));
462 oldcred = p->p_ucred;
463 orig_osrel = p->p_osrel;
464 orig_fctl0 = p->p_fctl0;
465 orig_brandinfo = p->p_elf_brandinfo;
468 error = mac_execve_enter(imgp, mac_p);
474 * Translate the file name. namei() returns a vnode pointer
475 * in ni_vp among other things.
477 * XXXAUDIT: It would be desirable to also audit the name of the
478 * interpreter if this is an interpreted binary.
480 if (args->fname != NULL) {
481 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
482 SAVENAME | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
485 SDT_PROBE1(proc, , , exec, args->fname);
488 if (args->fname != NULL) {
489 #ifdef CAPABILITY_MODE
491 * While capability mode can't reach this point via direct
492 * path arguments to execve(), we also don't allow
493 * interpreters to be used in capability mode (for now).
494 * Catch indirect lookups and return a permissions error.
496 if (IN_CAPABILITY_MODE(td)) {
505 newtextvp = nd.ni_vp;
506 imgp->vp = newtextvp;
508 AUDIT_ARG_FD(args->fd);
510 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
512 error = fgetvp_exec(td, args->fd, &cap_fexecve_rights, &newtextvp);
515 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
516 AUDIT_ARG_VNODE1(newtextvp);
517 imgp->vp = newtextvp;
521 * Check file permissions. Also 'opens' file and sets its vnode to
524 error = exec_check_permissions(imgp);
526 goto exec_fail_dealloc;
528 imgp->object = imgp->vp->v_object;
529 if (imgp->object != NULL)
530 vm_object_reference(imgp->object);
532 error = exec_map_first_page(imgp);
534 goto exec_fail_dealloc;
536 imgp->proc->p_osrel = 0;
537 imgp->proc->p_fctl0 = 0;
538 imgp->proc->p_elf_brandinfo = NULL;
541 * Implement image setuid/setgid.
543 * Determine new credentials before attempting image activators
544 * so that it can be used by process_exec handlers to determine
545 * credential/setid changes.
547 * Don't honor setuid/setgid if the filesystem prohibits it or if
548 * the process is being traced.
550 * We disable setuid/setgid/etc in capability mode on the basis
551 * that most setugid applications are not written with that
552 * environment in mind, and will therefore almost certainly operate
553 * incorrectly. In principle there's no reason that setugid
554 * applications might not be useful in capability mode, so we may want
555 * to reconsider this conservative design choice in the future.
557 * XXXMAC: For the time being, use NOSUID to also prohibit
558 * transitions on the file system.
560 credential_changing = 0;
561 credential_changing |= (attr.va_mode & S_ISUID) &&
562 oldcred->cr_uid != attr.va_uid;
563 credential_changing |= (attr.va_mode & S_ISGID) &&
564 oldcred->cr_gid != attr.va_gid;
566 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
567 interpvplabel, imgp);
568 credential_changing |= will_transition;
571 /* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */
572 if (credential_changing)
573 imgp->proc->p_pdeathsig = 0;
575 if (credential_changing &&
576 #ifdef CAPABILITY_MODE
577 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
579 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
580 (p->p_flag & P_TRACED) == 0) {
581 imgp->credential_setid = true;
582 VOP_UNLOCK(imgp->vp);
583 imgp->newcred = crdup(oldcred);
584 if (attr.va_mode & S_ISUID) {
585 euip = uifind(attr.va_uid);
586 change_euid(imgp->newcred, euip);
588 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
589 if (attr.va_mode & S_ISGID)
590 change_egid(imgp->newcred, attr.va_gid);
592 * Implement correct POSIX saved-id behavior.
594 * XXXMAC: Note that the current logic will save the
595 * uid and gid if a MAC domain transition occurs, even
596 * though maybe it shouldn't.
598 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
599 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
602 * Implement correct POSIX saved-id behavior.
604 * XXX: It's not clear that the existing behavior is
605 * POSIX-compliant. A number of sources indicate that the
606 * saved uid/gid should only be updated if the new ruid is
607 * not equal to the old ruid, or the new euid is not equal
608 * to the old euid and the new euid is not equal to the old
609 * ruid. The FreeBSD code always updates the saved uid/gid.
610 * Also, this code uses the new (replaced) euid and egid as
611 * the source, which may or may not be the right ones to use.
613 if (oldcred->cr_svuid != oldcred->cr_uid ||
614 oldcred->cr_svgid != oldcred->cr_gid) {
615 VOP_UNLOCK(imgp->vp);
616 imgp->newcred = crdup(oldcred);
617 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
618 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
619 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
622 /* The new credentials are installed into the process later. */
625 * Do the best to calculate the full path to the image file.
627 if (args->fname != NULL && args->fname[0] == '/')
628 imgp->execpath = args->fname;
630 VOP_UNLOCK(imgp->vp);
631 if (vn_fullpath(imgp->vp, &imgp->execpath, &imgp->freepath) != 0)
632 imgp->execpath = args->fname;
633 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
637 * If the current process has a special image activator it
638 * wants to try first, call it. For example, emulating shell
639 * scripts differently.
642 if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
643 error = img_first(imgp);
646 * Loop through the list of image activators, calling each one.
647 * An activator returns -1 if there is no match, 0 on success,
648 * and an error otherwise.
650 for (i = 0; error == -1 && execsw[i]; ++i) {
651 if (execsw[i]->ex_imgact == NULL ||
652 execsw[i]->ex_imgact == img_first) {
655 error = (*execsw[i]->ex_imgact)(imgp);
661 goto exec_fail_dealloc;
665 * Special interpreter operation, cleanup and loop up to try to
666 * activate the interpreter.
668 if (imgp->interpreted) {
669 exec_unmap_first_page(imgp);
671 * The text reference needs to be removed for scripts.
672 * There is a short period before we determine that
673 * something is a script where text reference is active.
674 * The vnode lock is held over this entire period
675 * so nothing should illegitimately be blocked.
677 MPASS(imgp->textset);
678 VOP_UNSET_TEXT_CHECKED(newtextvp);
679 imgp->textset = false;
680 /* free name buffer and old vnode */
681 if (args->fname != NULL)
682 NDFREE(&nd, NDF_ONLY_PNBUF);
684 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
687 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
691 vm_object_deallocate(imgp->object);
693 execve_nosetid(imgp);
694 imgp->execpath = NULL;
695 free(imgp->freepath, M_TEMP);
696 imgp->freepath = NULL;
697 /* set new name to that of the interpreter */
698 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
699 SAVENAME, UIO_SYSSPACE, imgp->interpreter_name, td);
700 args->fname = imgp->interpreter_name;
705 * NB: We unlock the vnode here because it is believed that none
706 * of the sv_copyout_strings/sv_fixup operations require the vnode.
708 VOP_UNLOCK(imgp->vp);
710 if (disallow_high_osrel &&
711 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
713 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
714 imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
715 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
716 goto exec_fail_dealloc;
720 * Copy out strings (args and env) and initialize stack base.
722 error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base);
724 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
725 goto exec_fail_dealloc;
731 error = (*p->p_sysent->sv_fixup)(&stack_base, imgp);
733 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
734 goto exec_fail_dealloc;
738 * For security and other reasons, the file descriptor table cannot be
739 * shared after an exec.
743 /* close files on exec */
747 * Malloc things before we need locks.
749 i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv;
750 /* Cache arguments if they fit inside our allowance */
751 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
752 newargs = pargs_alloc(i);
753 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
757 * For security and other reasons, signal handlers cannot
758 * be shared after an exec. The new process gets a copy of the old
759 * handlers. In execsigs(), the new process will have its signals
762 if (sigacts_shared(p->p_sigacts)) {
763 oldsigacts = p->p_sigacts;
764 newsigacts = sigacts_alloc();
765 sigacts_copy(newsigacts, oldsigacts);
768 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
772 p->p_sigacts = newsigacts;
776 /* reset caught signals */
779 /* name this process - nameiexec(p, ndp) */
780 bzero(p->p_comm, sizeof(p->p_comm));
782 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
783 min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
784 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
785 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
786 bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
788 sched_clear_tdname(td);
792 * mark as execed, wakeup the process that vforked (if any) and tell
793 * it that it now has its own resources back
796 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
797 p->p_flag2 &= ~P2_NOTRACE;
798 if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
799 p->p_flag2 &= ~P2_STKGAP_DISABLE;
800 if (p->p_flag & P_PPWAIT) {
801 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
802 cv_broadcast(&p->p_pwait);
803 /* STOPs are no longer ignored, arrange for AST */
807 if ((imgp->sysent->sv_setid_allowed != NULL &&
808 !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
809 (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
810 execve_nosetid(imgp);
813 * Implement image setuid/setgid installation.
815 if (imgp->credential_setid) {
817 * Turn off syscall tracing for set-id programs, except for
818 * root. Record any set-id flags first to make sure that
819 * we do not regain any tracing during a possible block.
823 kiop = ktrprocexec(p);
826 * Close any file descriptors 0..2 that reference procfs,
827 * then make sure file descriptors 0..2 are in use.
829 * Both fdsetugidsafety() and fdcheckstd() may call functions
830 * taking sleepable locks, so temporarily drop our locks.
833 VOP_UNLOCK(imgp->vp);
835 error = fdcheckstd(td);
836 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
838 goto exec_fail_dealloc;
841 if (will_transition) {
842 mac_vnode_execve_transition(oldcred, imgp->newcred,
843 imgp->vp, interpvplabel, imgp);
847 if (oldcred->cr_uid == oldcred->cr_ruid &&
848 oldcred->cr_gid == oldcred->cr_rgid)
849 p->p_flag &= ~P_SUGID;
852 * Set the new credentials.
854 if (imgp->newcred != NULL) {
855 proc_set_cred(p, imgp->newcred);
861 * Store the vp for use in procfs. This vnode was referenced by namei
864 oldtextvp = p->p_textvp;
865 p->p_textvp = newtextvp;
869 * Tell the DTrace fasttrap provider about the exec if it
870 * has declared an interest.
872 if (dtrace_fasttrap_exec)
873 dtrace_fasttrap_exec(p);
877 * Notify others that we exec'd, and clear the P_INEXEC flag
878 * as we're now a bona fide freshly-execed process.
880 KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
881 p->p_flag &= ~P_INEXEC;
883 /* clear "fork but no exec" flag, as we _are_ execing */
884 p->p_acflag &= ~AFORK;
887 * Free any previous argument cache and replace it with
888 * the new argument cache, if any.
898 * Check if system-wide sampling is in effect or if the
899 * current process is using PMCs. If so, do exec() time
900 * processing. This processing needs to happen AFTER the
901 * P_INEXEC flag is cleared.
903 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
904 VOP_UNLOCK(imgp->vp);
905 pe.pm_credentialschanged = credential_changing;
906 pe.pm_entryaddr = imgp->entry_addr;
908 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
909 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
913 /* Set values passed into the program in registers. */
914 (*p->p_sysent->sv_setregs)(td, imgp, stack_base);
916 VOP_MMAPPED(imgp->vp);
918 SDT_PROBE1(proc, , , exec__success, args->fname);
922 p->p_osrel = orig_osrel;
923 p->p_fctl0 = orig_fctl0;
924 p->p_elf_brandinfo = orig_brandinfo;
927 if (imgp->firstpage != NULL)
928 exec_unmap_first_page(imgp);
930 if (imgp->vp != NULL) {
932 NDFREE(&nd, NDF_ONLY_PNBUF);
934 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
936 VOP_UNSET_TEXT_CHECKED(imgp->vp);
940 VOP_UNLOCK(imgp->vp);
943 if (imgp->object != NULL)
944 vm_object_deallocate(imgp->object);
946 free(imgp->freepath, M_TEMP);
949 if (p->p_ptevents & PTRACE_EXEC) {
951 if (p->p_ptevents & PTRACE_EXEC)
952 td->td_dbgflags |= TDB_EXEC;
957 /* we're done here, clear P_INEXEC */
959 p->p_flag &= ~P_INEXEC;
962 SDT_PROBE1(proc, , , exec__failure, error);
965 if (imgp->newcred != NULL && oldcred != NULL)
966 crfree(imgp->newcred);
969 mac_execve_exit(imgp);
970 mac_execve_interpreter_exit(interpvplabel);
972 exec_free_args(args);
975 * Handle deferred decrement of ref counts.
977 if (oldtextvp != NULL)
980 ktr_io_params_free(kiop);
984 if (oldsigacts != NULL)
985 sigacts_free(oldsigacts);
989 if (error && imgp->vmspace_destroyed) {
990 /* sorry, no more process anymore. exit gracefully */
991 exec_cleanup(td, oldvmspace);
992 exit1(td, 0, SIGABRT);
1002 * We don't want cpu_set_syscall_retval() to overwrite any of
1003 * the register values put in place by exec_setregs().
1004 * Implementations of cpu_set_syscall_retval() will leave
1005 * registers unmodified when returning EJUSTRETURN.
1007 return (error == 0 ? EJUSTRETURN : error);
1011 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1013 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1014 KASSERT(td->td_proc->p_vmspace != oldvmspace,
1015 ("oldvmspace still used"));
1016 vmspace_free(oldvmspace);
1017 td->td_pflags &= ~TDP_EXECVMSPC;
1022 exec_map_first_page(struct image_params *imgp)
1028 if (imgp->firstpage != NULL)
1029 exec_unmap_first_page(imgp);
1031 object = imgp->vp->v_object;
1034 #if VM_NRESERVLEVEL > 0
1035 if ((object->flags & OBJ_COLORED) == 0) {
1036 VM_OBJECT_WLOCK(object);
1037 vm_object_color(object, 0);
1038 VM_OBJECT_WUNLOCK(object);
1041 error = vm_page_grab_valid_unlocked(&m, object, 0,
1042 VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1043 VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1045 if (error != VM_PAGER_OK)
1047 imgp->firstpage = sf_buf_alloc(m, 0);
1048 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1054 exec_unmap_first_page(struct image_params *imgp)
1058 if (imgp->firstpage != NULL) {
1059 m = sf_buf_page(imgp->firstpage);
1060 sf_buf_free(imgp->firstpage);
1061 imgp->firstpage = NULL;
1062 vm_page_unwire(m, PQ_ACTIVE);
1067 exec_onexec_old(struct thread *td)
1069 sigfastblock_clear(td);
1070 umtx_exec(td->td_proc);
1074 * Destroy old address space, and allocate a new stack.
1075 * The new stack is only sgrowsiz large because it is grown
1076 * automatically on a page fault.
1079 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1082 struct proc *p = imgp->proc;
1083 struct vmspace *vmspace = p->p_vmspace;
1084 struct thread *td = curthread;
1086 struct rlimit rlim_stack;
1087 vm_offset_t sv_minuser, stack_addr;
1089 vm_prot_t stack_prot;
1092 imgp->vmspace_destroyed = 1;
1095 if (p->p_sysent->sv_onexec_old != NULL)
1096 p->p_sysent->sv_onexec_old(td);
1099 EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1102 * Blow away entire process VM, if address space not shared,
1103 * otherwise, create a new VM space so that other threads are
1106 map = &vmspace->vm_map;
1108 sv_minuser = sv->sv_minuser;
1110 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1111 if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1112 vm_map_min(map) == sv_minuser &&
1113 vm_map_max(map) == sv->sv_maxuser &&
1114 cpu_exec_vmspace_reuse(p, map)) {
1116 pmap_remove_pages(vmspace_pmap(vmspace));
1117 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1119 * An exec terminates mlockall(MCL_FUTURE).
1120 * ASLR and W^X states must be re-evaluated.
1123 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1124 MAP_ASLR_IGNSTART | MAP_WXORX);
1127 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1130 vmspace = p->p_vmspace;
1131 map = &vmspace->vm_map;
1133 map->flags |= imgp->map_flags;
1135 /* Map a shared page */
1136 obj = sv->sv_shared_page_obj;
1138 vm_object_reference(obj);
1139 error = vm_map_fixed(map, obj, 0,
1140 sv->sv_shared_page_base, sv->sv_shared_page_len,
1141 VM_PROT_READ | VM_PROT_EXECUTE,
1142 VM_PROT_READ | VM_PROT_EXECUTE,
1143 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1144 if (error != KERN_SUCCESS) {
1145 vm_object_deallocate(obj);
1146 return (vm_mmap_to_errno(error));
1150 /* Allocate a new stack */
1151 if (imgp->stack_sz != 0) {
1152 ssiz = trunc_page(imgp->stack_sz);
1154 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1156 if (ssiz > rlim_stack.rlim_max)
1157 ssiz = rlim_stack.rlim_max;
1158 if (ssiz > rlim_stack.rlim_cur) {
1159 rlim_stack.rlim_cur = ssiz;
1160 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1162 } else if (sv->sv_maxssiz != NULL) {
1163 ssiz = *sv->sv_maxssiz;
1167 imgp->eff_stack_sz = lim_cur(curthread, RLIMIT_STACK);
1168 if (ssiz < imgp->eff_stack_sz)
1169 imgp->eff_stack_sz = ssiz;
1170 stack_addr = sv->sv_usrstack - ssiz;
1171 stack_prot = obj != NULL && imgp->stack_prot != 0 ?
1172 imgp->stack_prot : sv->sv_stackprot;
1173 error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz, stack_prot,
1174 VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1175 if (error != KERN_SUCCESS) {
1176 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1177 "failed mach error %d errno %d\n", (uintmax_t)ssiz,
1178 stack_prot, error, vm_mmap_to_errno(error));
1179 return (vm_mmap_to_errno(error));
1181 vmspace->vm_stkgap = 0;
1184 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1185 * are still used to enforce the stack rlimit on the process stack.
1187 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1188 vmspace->vm_maxsaddr = (char *)stack_addr;
1190 return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1194 * Copy out argument and environment strings from the old process address
1195 * space into the temporary string buffer.
1198 exec_copyin_args(struct image_args *args, const char *fname,
1199 enum uio_seg segflg, char **argv, char **envv)
1204 bzero(args, sizeof(*args));
1209 * Allocate demand-paged memory for the file name, argument, and
1210 * environment strings.
1212 error = exec_alloc_args(args);
1217 * Copy the file name.
1219 error = exec_args_add_fname(args, fname, segflg);
1224 * extract arguments first
1227 error = fueword(argv++, &arg);
1234 error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1241 * extract environment strings
1245 error = fueword(envv++, &env);
1252 error = exec_args_add_env(args,
1253 (char *)(uintptr_t)env, UIO_USERSPACE);
1262 exec_free_args(args);
1266 struct exec_args_kva {
1269 SLIST_ENTRY(exec_args_kva) next;
1272 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1274 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1275 static struct mtx exec_args_kva_mtx;
1276 static u_int exec_args_gen;
1279 exec_prealloc_args_kva(void *arg __unused)
1281 struct exec_args_kva *argkva;
1284 SLIST_INIT(&exec_args_kva_freelist);
1285 mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1286 for (i = 0; i < exec_map_entries; i++) {
1287 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1288 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size);
1289 argkva->gen = exec_args_gen;
1290 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1293 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1296 exec_alloc_args_kva(void **cookie)
1298 struct exec_args_kva *argkva;
1300 argkva = (void *)atomic_readandclear_ptr(
1301 (uintptr_t *)DPCPU_PTR(exec_args_kva));
1302 if (argkva == NULL) {
1303 mtx_lock(&exec_args_kva_mtx);
1304 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1305 (void)mtx_sleep(&exec_args_kva_freelist,
1306 &exec_args_kva_mtx, 0, "execkva", 0);
1307 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1308 mtx_unlock(&exec_args_kva_mtx);
1310 kasan_mark((void *)argkva->addr, exec_map_entry_size,
1311 exec_map_entry_size, 0);
1312 *(struct exec_args_kva **)cookie = argkva;
1313 return (argkva->addr);
1317 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1321 base = argkva->addr;
1322 kasan_mark((void *)argkva->addr, 0, exec_map_entry_size,
1323 KASAN_EXEC_ARGS_FREED);
1324 if (argkva->gen != gen) {
1325 (void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1329 if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1330 (uintptr_t)NULL, (uintptr_t)argkva)) {
1331 mtx_lock(&exec_args_kva_mtx);
1332 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1333 wakeup_one(&exec_args_kva_freelist);
1334 mtx_unlock(&exec_args_kva_mtx);
1339 exec_free_args_kva(void *cookie)
1342 exec_release_args_kva(cookie, exec_args_gen);
1346 exec_args_kva_lowmem(void *arg __unused)
1348 SLIST_HEAD(, exec_args_kva) head;
1349 struct exec_args_kva *argkva;
1353 gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1356 * Force an madvise of each KVA range. Any currently allocated ranges
1357 * will have MADV_FREE applied once they are freed.
1360 mtx_lock(&exec_args_kva_mtx);
1361 SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1362 mtx_unlock(&exec_args_kva_mtx);
1363 while ((argkva = SLIST_FIRST(&head)) != NULL) {
1364 SLIST_REMOVE_HEAD(&head, next);
1365 exec_release_args_kva(argkva, gen);
1369 argkva = (void *)atomic_readandclear_ptr(
1370 (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1372 exec_release_args_kva(argkva, gen);
1375 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1376 EVENTHANDLER_PRI_ANY);
1379 * Allocate temporary demand-paged, zero-filled memory for the file name,
1380 * argument, and environment strings.
1383 exec_alloc_args(struct image_args *args)
1386 args->buf = (char *)exec_alloc_args_kva(&args->bufkva);
1391 exec_free_args(struct image_args *args)
1394 if (args->buf != NULL) {
1395 exec_free_args_kva(args->bufkva);
1398 if (args->fname_buf != NULL) {
1399 free(args->fname_buf, M_TEMP);
1400 args->fname_buf = NULL;
1405 * A set to functions to fill struct image args.
1407 * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1408 * fname) before the other functions. All exec_args_add_arg() calls must
1409 * be made before any exec_args_add_env() calls. exec_args_adjust_args()
1410 * may be called any time after exec_args_add_fname().
1412 * exec_args_add_fname() - install path to be executed
1413 * exec_args_add_arg() - append an argument string
1414 * exec_args_add_env() - append an env string
1415 * exec_args_adjust_args() - adjust location of the argument list to
1416 * allow new arguments to be prepended
1419 exec_args_add_fname(struct image_args *args, const char *fname,
1420 enum uio_seg segflg)
1425 KASSERT(args->fname == NULL, ("fname already appended"));
1426 KASSERT(args->endp == NULL, ("already appending to args"));
1428 if (fname != NULL) {
1429 args->fname = args->buf;
1430 error = segflg == UIO_SYSSPACE ?
1431 copystr(fname, args->fname, PATH_MAX, &length) :
1432 copyinstr(fname, args->fname, PATH_MAX, &length);
1434 return (error == ENAMETOOLONG ? E2BIG : error);
1438 /* Set up for _arg_*()/_env_*() */
1439 args->endp = args->buf + length;
1440 /* begin_argv must be set and kept updated */
1441 args->begin_argv = args->endp;
1442 KASSERT(exec_map_entry_size - length >= ARG_MAX,
1443 ("too little space remaining for arguments %zu < %zu",
1444 exec_map_entry_size - length, (size_t)ARG_MAX));
1445 args->stringspace = ARG_MAX;
1451 exec_args_add_str(struct image_args *args, const char *str,
1452 enum uio_seg segflg, int *countp)
1457 KASSERT(args->endp != NULL, ("endp not initialized"));
1458 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1460 error = (segflg == UIO_SYSSPACE) ?
1461 copystr(str, args->endp, args->stringspace, &length) :
1462 copyinstr(str, args->endp, args->stringspace, &length);
1464 return (error == ENAMETOOLONG ? E2BIG : error);
1465 args->stringspace -= length;
1466 args->endp += length;
1473 exec_args_add_arg(struct image_args *args, const char *argp,
1474 enum uio_seg segflg)
1477 KASSERT(args->envc == 0, ("appending args after env"));
1479 return (exec_args_add_str(args, argp, segflg, &args->argc));
1483 exec_args_add_env(struct image_args *args, const char *envp,
1484 enum uio_seg segflg)
1487 if (args->envc == 0)
1488 args->begin_envv = args->endp;
1490 return (exec_args_add_str(args, envp, segflg, &args->envc));
1494 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1498 KASSERT(args->endp != NULL, ("endp not initialized"));
1499 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1501 offset = extend - consume;
1502 if (args->stringspace < offset)
1504 memmove(args->begin_argv + extend, args->begin_argv + consume,
1505 args->endp - args->begin_argv + consume);
1507 args->begin_envv += offset;
1508 args->endp += offset;
1509 args->stringspace -= offset;
1514 exec_args_get_begin_envv(struct image_args *args)
1517 KASSERT(args->endp != NULL, ("endp not initialized"));
1520 return (args->begin_envv);
1521 return (args->endp);
1525 exec_stackgap(struct image_params *imgp, uintptr_t *dp)
1527 struct proc *p = imgp->proc;
1529 if (imgp->sysent->sv_stackgap == NULL ||
1530 (p->p_fctl0 & (NT_FREEBSD_FCTL_ASLR_DISABLE |
1531 NT_FREEBSD_FCTL_ASG_DISABLE)) != 0 ||
1532 (imgp->map_flags & MAP_ASLR) == 0) {
1533 p->p_vmspace->vm_stkgap = 0;
1536 p->p_vmspace->vm_stkgap = imgp->sysent->sv_stackgap(imgp, dp);
1540 * Copy strings out to the new process address space, constructing new arg
1541 * and env vector tables. Return a pointer to the base so that it can be used
1542 * as the initial stack pointer.
1545 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1550 uintptr_t destp, ustringp;
1551 struct ps_strings *arginfo;
1553 size_t execpath_len;
1554 int error, szsigcode, szps;
1555 char canary[sizeof(long) * 8];
1557 szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1559 * Calculate string base and vector table pointers.
1560 * Also deal with signal trampoline code for this exec type.
1562 if (imgp->execpath != NULL && imgp->auxargs != NULL)
1563 execpath_len = strlen(imgp->execpath) + 1;
1568 arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1569 imgp->ps_strings = arginfo;
1570 if (p->p_sysent->sv_sigcode_base == 0) {
1571 if (p->p_sysent->sv_szsigcode != NULL)
1572 szsigcode = *(p->p_sysent->sv_szsigcode);
1574 destp = (uintptr_t)arginfo;
1579 if (szsigcode != 0) {
1581 destp = rounddown2(destp, sizeof(void *));
1582 error = copyout(p->p_sysent->sv_sigcode, (void *)destp,
1589 * Copy the image path for the rtld.
1591 if (execpath_len != 0) {
1592 destp -= execpath_len;
1593 destp = rounddown2(destp, sizeof(void *));
1594 imgp->execpathp = (void *)destp;
1595 error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1601 * Prepare the canary for SSP.
1603 arc4rand(canary, sizeof(canary), 0);
1604 destp -= sizeof(canary);
1605 imgp->canary = (void *)destp;
1606 error = copyout(canary, imgp->canary, sizeof(canary));
1609 imgp->canarylen = sizeof(canary);
1612 * Prepare the pagesizes array.
1615 destp = rounddown2(destp, sizeof(void *));
1616 imgp->pagesizes = (void *)destp;
1617 error = copyout(pagesizes, imgp->pagesizes, szps);
1620 imgp->pagesizeslen = szps;
1623 * Allocate room for the argument and environment strings.
1625 destp -= ARG_MAX - imgp->args->stringspace;
1626 destp = rounddown2(destp, sizeof(void *));
1629 exec_stackgap(imgp, &destp);
1631 if (imgp->auxargs) {
1633 * Allocate room on the stack for the ELF auxargs
1634 * array. It has up to AT_COUNT entries.
1636 destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1637 destp = rounddown2(destp, sizeof(void *));
1640 vectp = (char **)destp;
1643 * Allocate room for the argv[] and env vectors including the
1644 * terminating NULL pointers.
1646 vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1649 * vectp also becomes our initial stack base
1651 *stack_base = (uintptr_t)vectp;
1653 stringp = imgp->args->begin_argv;
1654 argc = imgp->args->argc;
1655 envc = imgp->args->envc;
1658 * Copy out strings - arguments and environment.
1660 error = copyout(stringp, (void *)ustringp,
1661 ARG_MAX - imgp->args->stringspace);
1666 * Fill in "ps_strings" struct for ps, w, etc.
1669 if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1670 suword32(&arginfo->ps_nargvstr, argc) != 0)
1674 * Fill in argument portion of vector table.
1676 for (; argc > 0; --argc) {
1677 if (suword(vectp++, ustringp) != 0)
1679 while (*stringp++ != 0)
1684 /* a null vector table pointer separates the argp's from the envp's */
1685 if (suword(vectp++, 0) != 0)
1689 if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1690 suword32(&arginfo->ps_nenvstr, envc) != 0)
1694 * Fill in environment portion of vector table.
1696 for (; envc > 0; --envc) {
1697 if (suword(vectp++, ustringp) != 0)
1699 while (*stringp++ != 0)
1704 /* end of vector table is a null pointer */
1705 if (suword(vectp, 0) != 0)
1708 if (imgp->auxargs) {
1710 error = imgp->sysent->sv_copyout_auxargs(imgp,
1720 * Check permissions of file to execute.
1721 * Called with imgp->vp locked.
1722 * Return 0 for success or error code on failure.
1725 exec_check_permissions(struct image_params *imgp)
1727 struct vnode *vp = imgp->vp;
1728 struct vattr *attr = imgp->attr;
1734 /* Get file attributes */
1735 error = VOP_GETATTR(vp, attr, td->td_ucred);
1740 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1746 * 1) Check if file execution is disabled for the filesystem that
1747 * this file resides on.
1748 * 2) Ensure that at least one execute bit is on. Otherwise, a
1749 * privileged user will always succeed, and we don't want this
1750 * to happen unless the file really is executable.
1751 * 3) Ensure that the file is a regular file.
1753 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1754 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1755 (attr->va_type != VREG))
1759 * Zero length files can't be exec'd
1761 if (attr->va_size == 0)
1765 * Check for execute permission to file based on current credentials.
1767 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1772 * Check number of open-for-writes on the file and deny execution
1775 * Add a text reference now so no one can write to the
1776 * executable while we're activating it.
1778 * Remember if this was set before and unset it in case this is not
1779 * actually an executable image.
1781 error = VOP_SET_TEXT(vp);
1784 imgp->textset = true;
1787 * Call filesystem specific open routine (which does nothing in the
1790 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1797 * Exec handler registration
1800 exec_register(const struct execsw *execsw_arg)
1802 const struct execsw **es, **xs, **newexecsw;
1803 u_int count = 2; /* New slot and trailing NULL */
1806 for (es = execsw; *es; es++)
1808 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1811 for (es = execsw; *es; es++)
1816 free(execsw, M_TEMP);
1822 exec_unregister(const struct execsw *execsw_arg)
1824 const struct execsw **es, **xs, **newexecsw;
1828 panic("unregister with no handlers left?\n");
1830 for (es = execsw; *es; es++) {
1831 if (*es == execsw_arg)
1836 for (es = execsw; *es; es++)
1837 if (*es != execsw_arg)
1839 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1841 for (es = execsw; *es; es++)
1842 if (*es != execsw_arg)
1846 free(execsw, M_TEMP);
1852 * Write out a core segment to the compression stream.
1855 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
1861 chunk_len = MIN(len, CORE_BUF_SIZE);
1864 * We can get EFAULT error here.
1865 * In that case zero out the current chunk of the segment.
1867 error = copyin(base, buf, chunk_len);
1869 bzero(buf, chunk_len);
1870 error = compressor_write(cp->comp, buf, chunk_len);
1880 core_write(struct coredump_params *cp, const void *base, size_t len,
1881 off_t offset, enum uio_seg seg, size_t *resid)
1884 return (vn_rdwr_inchunks(UIO_WRITE, cp->vp, __DECONST(void *, base),
1885 len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1886 cp->active_cred, cp->file_cred, resid, cp->td));
1890 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
1895 size_t resid, runlen;
1899 KASSERT((uintptr_t)base % PAGE_SIZE == 0,
1900 ("%s: user address %p is not page-aligned", __func__, base));
1902 if (cp->comp != NULL)
1903 return (compress_chunk(cp, base, tmpbuf, len));
1905 map = &cp->td->td_proc->p_vmspace->vm_map;
1906 for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
1908 * Attempt to page in all virtual pages in the range. If a
1909 * virtual page is not backed by the pager, it is represented as
1910 * a hole in the file. This can occur with zero-filled
1911 * anonymous memory or truncated files, for example.
1913 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
1914 if (core_dump_can_intr && curproc_sigkilled())
1916 error = vm_fault(map, (uintptr_t)base + runlen,
1917 VM_PROT_READ, VM_FAULT_NOFILL, NULL);
1919 success = error == KERN_SUCCESS;
1920 else if ((error == KERN_SUCCESS) != success)
1925 error = core_write(cp, base, runlen, offset,
1926 UIO_USERSPACE, &resid);
1928 if (error != EFAULT)
1932 * EFAULT may be returned if the user mapping
1933 * could not be accessed, e.g., because a mapped
1934 * file has been truncated. Skip the page if no
1935 * progress was made, to protect against a
1936 * hypothetical scenario where vm_fault() was
1937 * successful but core_write() returns EFAULT
1948 error = vn_start_write(cp->vp, &mp, V_WAIT);
1951 vn_lock(cp->vp, LK_EXCLUSIVE | LK_RETRY);
1952 error = vn_truncate_locked(cp->vp, offset + runlen,
1953 false, cp->td->td_ucred);
1955 vn_finished_write(mp);
1964 * Drain into a core file.
1967 sbuf_drain_core_output(void *arg, const char *data, int len)
1969 struct coredump_params *cp;
1974 p = cp->td->td_proc;
1977 * Some kern_proc out routines that print to this sbuf may
1978 * call us with the process lock held. Draining with the
1979 * non-sleepable lock held is unsafe. The lock is needed for
1980 * those routines when dumping a live process. In our case we
1981 * can safely release the lock before draining and acquire
1984 locked = PROC_LOCKED(p);
1987 if (cp->comp != NULL)
1988 error = compressor_write(cp->comp, __DECONST(char *, data), len);
1990 error = core_write(cp, __DECONST(void *, data), len, cp->offset,
1991 UIO_SYSSPACE, NULL);