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, *newtextvp;
424 struct vnode *oldtextdvp, *newtextdvp;
425 char *oldbinname, *newbinname;
426 bool credential_changing;
428 struct label *interpvplabel = NULL;
429 bool will_transition;
432 struct pmckern_procexec pe;
434 int error, i, orig_osrel;
436 Elf_Brandinfo *orig_brandinfo;
437 size_t freepath_size;
438 static const char fexecv_proc_title[] = "(fexecv)";
440 imgp = &image_params;
441 oldtextvp = oldtextdvp = NULL;
442 newtextvp = newtextdvp = NULL;
443 newbinname = oldbinname = NULL;
449 * Lock the process and set the P_INEXEC flag to indicate that
450 * it should be left alone until we're done here. This is
451 * necessary to avoid race conditions - e.g. in ptrace() -
452 * that might allow a local user to illicitly obtain elevated
456 KASSERT((p->p_flag & P_INEXEC) == 0,
457 ("%s(): process already has P_INEXEC flag", __func__));
458 p->p_flag |= P_INEXEC;
462 * Initialize part of the common data
464 bzero(imgp, sizeof(*imgp));
468 oldcred = p->p_ucred;
469 orig_osrel = p->p_osrel;
470 orig_fctl0 = p->p_fctl0;
471 orig_brandinfo = p->p_elf_brandinfo;
474 error = mac_execve_enter(imgp, mac_p);
479 SDT_PROBE1(proc, , , exec, args->fname);
482 if (args->fname != NULL) {
483 #ifdef CAPABILITY_MODE
485 * While capability mode can't reach this point via direct
486 * path arguments to execve(), we also don't allow
487 * interpreters to be used in capability mode (for now).
488 * Catch indirect lookups and return a permissions error.
490 if (IN_CAPABILITY_MODE(td)) {
497 * Translate the file name. namei() returns a vnode
498 * pointer in ni_vp among other things.
500 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
501 SAVENAME | AUDITVNODE1 | WANTPARENT, UIO_SYSSPACE,
508 newtextvp = nd.ni_vp;
509 newtextdvp = nd.ni_dvp;
511 newbinname = malloc(nd.ni_cnd.cn_namelen + 1, M_PARGS,
513 memcpy(newbinname, nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen);
514 newbinname[nd.ni_cnd.cn_namelen] = '\0';
515 imgp->vp = newtextvp;
518 * Do the best to calculate the full path to the image file.
520 if (args->fname[0] == '/') {
521 imgp->execpath = args->fname;
523 VOP_UNLOCK(imgp->vp);
524 freepath_size = MAXPATHLEN;
525 if (vn_fullpath_hardlink(newtextvp, newtextdvp,
526 newbinname, nd.ni_cnd.cn_namelen, &imgp->execpath,
527 &imgp->freepath, &freepath_size) != 0)
528 imgp->execpath = args->fname;
529 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
532 AUDIT_ARG_FD(args->fd);
534 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
536 error = fgetvp_exec(td, args->fd, &cap_fexecve_rights,
540 if (vn_fullpath(newtextvp, &imgp->execpath,
541 &imgp->freepath) != 0)
542 imgp->execpath = args->fname;
543 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
544 AUDIT_ARG_VNODE1(newtextvp);
545 imgp->vp = newtextvp;
549 * Check file permissions. Also 'opens' file and sets its vnode to
552 error = exec_check_permissions(imgp);
554 goto exec_fail_dealloc;
556 imgp->object = imgp->vp->v_object;
557 if (imgp->object != NULL)
558 vm_object_reference(imgp->object);
560 error = exec_map_first_page(imgp);
562 goto exec_fail_dealloc;
564 imgp->proc->p_osrel = 0;
565 imgp->proc->p_fctl0 = 0;
566 imgp->proc->p_elf_brandinfo = NULL;
569 * Implement image setuid/setgid.
571 * Determine new credentials before attempting image activators
572 * so that it can be used by process_exec handlers to determine
573 * credential/setid changes.
575 * Don't honor setuid/setgid if the filesystem prohibits it or if
576 * the process is being traced.
578 * We disable setuid/setgid/etc in capability mode on the basis
579 * that most setugid applications are not written with that
580 * environment in mind, and will therefore almost certainly operate
581 * incorrectly. In principle there's no reason that setugid
582 * applications might not be useful in capability mode, so we may want
583 * to reconsider this conservative design choice in the future.
585 * XXXMAC: For the time being, use NOSUID to also prohibit
586 * transitions on the file system.
588 credential_changing = false;
589 credential_changing |= (attr.va_mode & S_ISUID) &&
590 oldcred->cr_uid != attr.va_uid;
591 credential_changing |= (attr.va_mode & S_ISGID) &&
592 oldcred->cr_gid != attr.va_gid;
594 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
595 interpvplabel, imgp) != 0;
596 credential_changing |= will_transition;
599 /* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */
600 if (credential_changing)
601 imgp->proc->p_pdeathsig = 0;
603 if (credential_changing &&
604 #ifdef CAPABILITY_MODE
605 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
607 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
608 (p->p_flag & P_TRACED) == 0) {
609 imgp->credential_setid = true;
610 VOP_UNLOCK(imgp->vp);
611 imgp->newcred = crdup(oldcred);
612 if (attr.va_mode & S_ISUID) {
613 euip = uifind(attr.va_uid);
614 change_euid(imgp->newcred, euip);
616 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
617 if (attr.va_mode & S_ISGID)
618 change_egid(imgp->newcred, attr.va_gid);
620 * Implement correct POSIX saved-id behavior.
622 * XXXMAC: Note that the current logic will save the
623 * uid and gid if a MAC domain transition occurs, even
624 * though maybe it shouldn't.
626 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
627 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
630 * Implement correct POSIX saved-id behavior.
632 * XXX: It's not clear that the existing behavior is
633 * POSIX-compliant. A number of sources indicate that the
634 * saved uid/gid should only be updated if the new ruid is
635 * not equal to the old ruid, or the new euid is not equal
636 * to the old euid and the new euid is not equal to the old
637 * ruid. The FreeBSD code always updates the saved uid/gid.
638 * Also, this code uses the new (replaced) euid and egid as
639 * the source, which may or may not be the right ones to use.
641 if (oldcred->cr_svuid != oldcred->cr_uid ||
642 oldcred->cr_svgid != oldcred->cr_gid) {
643 VOP_UNLOCK(imgp->vp);
644 imgp->newcred = crdup(oldcred);
645 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
646 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
647 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
650 /* The new credentials are installed into the process later. */
653 * If the current process has a special image activator it
654 * wants to try first, call it. For example, emulating shell
655 * scripts differently.
658 if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
659 error = img_first(imgp);
662 * Loop through the list of image activators, calling each one.
663 * An activator returns -1 if there is no match, 0 on success,
664 * and an error otherwise.
666 for (i = 0; error == -1 && execsw[i]; ++i) {
667 if (execsw[i]->ex_imgact == NULL ||
668 execsw[i]->ex_imgact == img_first) {
671 error = (*execsw[i]->ex_imgact)(imgp);
677 goto exec_fail_dealloc;
681 * Special interpreter operation, cleanup and loop up to try to
682 * activate the interpreter.
684 if (imgp->interpreted) {
685 exec_unmap_first_page(imgp);
687 * The text reference needs to be removed for scripts.
688 * There is a short period before we determine that
689 * something is a script where text reference is active.
690 * The vnode lock is held over this entire period
691 * so nothing should illegitimately be blocked.
693 MPASS(imgp->textset);
694 VOP_UNSET_TEXT_CHECKED(newtextvp);
695 imgp->textset = false;
696 /* free name buffer and old vnode */
698 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
701 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
702 imgp->opened = false;
705 imgp->vp = newtextvp = NULL;
706 if (args->fname != NULL) {
707 if (newtextdvp != NULL) {
711 NDFREE(&nd, NDF_ONLY_PNBUF);
712 free(newbinname, M_PARGS);
715 vm_object_deallocate(imgp->object);
717 execve_nosetid(imgp);
718 imgp->execpath = NULL;
719 free(imgp->freepath, M_TEMP);
720 imgp->freepath = NULL;
721 /* set new name to that of the interpreter */
722 args->fname = imgp->interpreter_name;
727 * NB: We unlock the vnode here because it is believed that none
728 * of the sv_copyout_strings/sv_fixup operations require the vnode.
730 VOP_UNLOCK(imgp->vp);
732 if (disallow_high_osrel &&
733 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
735 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
736 imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
737 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
738 goto exec_fail_dealloc;
742 * Copy out strings (args and env) and initialize stack base.
744 error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base);
746 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
747 goto exec_fail_dealloc;
753 error = (*p->p_sysent->sv_fixup)(&stack_base, imgp);
755 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
756 goto exec_fail_dealloc;
760 * For security and other reasons, the file descriptor table cannot be
761 * shared after an exec.
765 /* close files on exec */
769 * Malloc things before we need locks.
771 i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv;
772 /* Cache arguments if they fit inside our allowance */
773 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
774 newargs = pargs_alloc(i);
775 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
779 * For security and other reasons, signal handlers cannot
780 * be shared after an exec. The new process gets a copy of the old
781 * handlers. In execsigs(), the new process will have its signals
784 if (sigacts_shared(p->p_sigacts)) {
785 oldsigacts = p->p_sigacts;
786 newsigacts = sigacts_alloc();
787 sigacts_copy(newsigacts, oldsigacts);
790 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
794 p->p_sigacts = newsigacts;
798 /* reset caught signals */
801 /* name this process - nameiexec(p, ndp) */
802 bzero(p->p_comm, sizeof(p->p_comm));
804 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
805 min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
806 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
807 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
808 bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
810 sched_clear_tdname(td);
814 * mark as execed, wakeup the process that vforked (if any) and tell
815 * it that it now has its own resources back
818 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
819 p->p_flag2 &= ~P2_NOTRACE;
820 if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
821 p->p_flag2 &= ~P2_STKGAP_DISABLE;
822 if (p->p_flag & P_PPWAIT) {
823 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
824 cv_broadcast(&p->p_pwait);
825 /* STOPs are no longer ignored, arrange for AST */
829 if ((imgp->sysent->sv_setid_allowed != NULL &&
830 !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
831 (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
832 execve_nosetid(imgp);
835 * Implement image setuid/setgid installation.
837 if (imgp->credential_setid) {
839 * Turn off syscall tracing for set-id programs, except for
840 * root. Record any set-id flags first to make sure that
841 * we do not regain any tracing during a possible block.
845 kiop = ktrprocexec(p);
848 * Close any file descriptors 0..2 that reference procfs,
849 * then make sure file descriptors 0..2 are in use.
851 * Both fdsetugidsafety() and fdcheckstd() may call functions
852 * taking sleepable locks, so temporarily drop our locks.
855 VOP_UNLOCK(imgp->vp);
857 error = fdcheckstd(td);
858 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
860 goto exec_fail_dealloc;
863 if (will_transition) {
864 mac_vnode_execve_transition(oldcred, imgp->newcred,
865 imgp->vp, interpvplabel, imgp);
869 if (oldcred->cr_uid == oldcred->cr_ruid &&
870 oldcred->cr_gid == oldcred->cr_rgid)
871 p->p_flag &= ~P_SUGID;
874 * Set the new credentials.
876 if (imgp->newcred != NULL) {
877 proc_set_cred(p, imgp->newcred);
883 * Store the vp for use in kern.proc.pathname. This vnode was
884 * referenced by namei() or fgetvp_exec().
886 oldtextvp = p->p_textvp;
887 p->p_textvp = newtextvp;
888 oldtextdvp = p->p_textdvp;
889 p->p_textdvp = newtextdvp;
891 oldbinname = p->p_binname;
892 p->p_binname = newbinname;
897 * Tell the DTrace fasttrap provider about the exec if it
898 * has declared an interest.
900 if (dtrace_fasttrap_exec)
901 dtrace_fasttrap_exec(p);
905 * Notify others that we exec'd, and clear the P_INEXEC flag
906 * as we're now a bona fide freshly-execed process.
908 KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
909 p->p_flag &= ~P_INEXEC;
911 /* clear "fork but no exec" flag, as we _are_ execing */
912 p->p_acflag &= ~AFORK;
915 * Free any previous argument cache and replace it with
916 * the new argument cache, if any.
926 * Check if system-wide sampling is in effect or if the
927 * current process is using PMCs. If so, do exec() time
928 * processing. This processing needs to happen AFTER the
929 * P_INEXEC flag is cleared.
931 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
932 VOP_UNLOCK(imgp->vp);
933 pe.pm_credentialschanged = credential_changing;
934 pe.pm_entryaddr = imgp->entry_addr;
936 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
937 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
941 /* Set values passed into the program in registers. */
942 (*p->p_sysent->sv_setregs)(td, imgp, stack_base);
944 VOP_MMAPPED(imgp->vp);
946 SDT_PROBE1(proc, , , exec__success, args->fname);
950 p->p_osrel = orig_osrel;
951 p->p_fctl0 = orig_fctl0;
952 p->p_elf_brandinfo = orig_brandinfo;
955 if (imgp->firstpage != NULL)
956 exec_unmap_first_page(imgp);
958 if (imgp->vp != NULL) {
960 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
962 VOP_UNSET_TEXT_CHECKED(imgp->vp);
966 VOP_UNLOCK(imgp->vp);
967 if (args->fname != NULL)
968 NDFREE(&nd, NDF_ONLY_PNBUF);
969 if (newtextdvp != NULL)
971 free(newbinname, M_PARGS);
974 if (imgp->object != NULL)
975 vm_object_deallocate(imgp->object);
977 free(imgp->freepath, M_TEMP);
980 if (p->p_ptevents & PTRACE_EXEC) {
982 if (p->p_ptevents & PTRACE_EXEC)
983 td->td_dbgflags |= TDB_EXEC;
988 /* we're done here, clear P_INEXEC */
990 p->p_flag &= ~P_INEXEC;
993 SDT_PROBE1(proc, , , exec__failure, error);
996 if (imgp->newcred != NULL && oldcred != NULL)
997 crfree(imgp->newcred);
1000 mac_execve_exit(imgp);
1001 mac_execve_interpreter_exit(interpvplabel);
1003 exec_free_args(args);
1006 * Handle deferred decrement of ref counts.
1008 if (oldtextvp != NULL)
1010 if (oldtextdvp != NULL)
1012 free(oldbinname, M_PARGS);
1014 ktr_io_params_free(kiop);
1016 pargs_drop(oldargs);
1017 pargs_drop(newargs);
1018 if (oldsigacts != NULL)
1019 sigacts_free(oldsigacts);
1023 if (error && imgp->vmspace_destroyed) {
1024 /* sorry, no more process anymore. exit gracefully */
1025 exec_cleanup(td, oldvmspace);
1026 exit1(td, 0, SIGABRT);
1036 * We don't want cpu_set_syscall_retval() to overwrite any of
1037 * the register values put in place by exec_setregs().
1038 * Implementations of cpu_set_syscall_retval() will leave
1039 * registers unmodified when returning EJUSTRETURN.
1041 return (error == 0 ? EJUSTRETURN : error);
1045 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1047 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1048 KASSERT(td->td_proc->p_vmspace != oldvmspace,
1049 ("oldvmspace still used"));
1050 vmspace_free(oldvmspace);
1051 td->td_pflags &= ~TDP_EXECVMSPC;
1056 exec_map_first_page(struct image_params *imgp)
1062 if (imgp->firstpage != NULL)
1063 exec_unmap_first_page(imgp);
1065 object = imgp->vp->v_object;
1068 #if VM_NRESERVLEVEL > 0
1069 if ((object->flags & OBJ_COLORED) == 0) {
1070 VM_OBJECT_WLOCK(object);
1071 vm_object_color(object, 0);
1072 VM_OBJECT_WUNLOCK(object);
1075 error = vm_page_grab_valid_unlocked(&m, object, 0,
1076 VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1077 VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1079 if (error != VM_PAGER_OK)
1081 imgp->firstpage = sf_buf_alloc(m, 0);
1082 imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1088 exec_unmap_first_page(struct image_params *imgp)
1092 if (imgp->firstpage != NULL) {
1093 m = sf_buf_page(imgp->firstpage);
1094 sf_buf_free(imgp->firstpage);
1095 imgp->firstpage = NULL;
1096 vm_page_unwire(m, PQ_ACTIVE);
1101 exec_onexec_old(struct thread *td)
1103 sigfastblock_clear(td);
1104 umtx_exec(td->td_proc);
1108 * This is an optimization which removes the unmanaged shared page
1109 * mapping. In combination with pmap_remove_pages(), which cleans all
1110 * managed mappings in the process' vmspace pmap, no work will be left
1111 * for pmap_remove(min, max).
1114 exec_free_abi_mappings(struct proc *p)
1116 struct vmspace *vmspace;
1117 struct sysentvec *sv;
1119 vmspace = p->p_vmspace;
1120 if (refcount_load(&vmspace->vm_refcnt) != 1)
1124 if (sv->sv_shared_page_obj == NULL)
1127 pmap_remove(vmspace_pmap(vmspace), sv->sv_shared_page_base,
1128 sv->sv_shared_page_base + sv->sv_shared_page_len);
1132 * Destroy old address space, and allocate a new stack.
1133 * The new stack is only sgrowsiz large because it is grown
1134 * automatically on a page fault.
1137 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1140 struct proc *p = imgp->proc;
1141 struct vmspace *vmspace = p->p_vmspace;
1142 struct thread *td = curthread;
1144 struct rlimit rlim_stack;
1145 vm_offset_t sv_minuser, stack_addr;
1147 vm_prot_t stack_prot;
1150 imgp->vmspace_destroyed = true;
1153 if (p->p_sysent->sv_onexec_old != NULL)
1154 p->p_sysent->sv_onexec_old(td);
1157 EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1160 * Blow away entire process VM, if address space not shared,
1161 * otherwise, create a new VM space so that other threads are
1164 map = &vmspace->vm_map;
1166 sv_minuser = sv->sv_minuser;
1168 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1169 if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1170 vm_map_min(map) == sv_minuser &&
1171 vm_map_max(map) == sv->sv_maxuser &&
1172 cpu_exec_vmspace_reuse(p, map)) {
1173 exec_free_abi_mappings(p);
1175 pmap_remove_pages(vmspace_pmap(vmspace));
1176 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1178 * An exec terminates mlockall(MCL_FUTURE).
1179 * ASLR and W^X states must be re-evaluated.
1182 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1183 MAP_ASLR_IGNSTART | MAP_WXORX);
1186 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1189 vmspace = p->p_vmspace;
1190 map = &vmspace->vm_map;
1192 map->flags |= imgp->map_flags;
1194 /* Map a shared page */
1195 obj = sv->sv_shared_page_obj;
1197 vm_object_reference(obj);
1198 error = vm_map_fixed(map, obj, 0,
1199 sv->sv_shared_page_base, sv->sv_shared_page_len,
1200 VM_PROT_READ | VM_PROT_EXECUTE,
1201 VM_PROT_READ | VM_PROT_EXECUTE,
1202 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1203 if (error != KERN_SUCCESS) {
1204 vm_object_deallocate(obj);
1205 return (vm_mmap_to_errno(error));
1209 /* Allocate a new stack */
1210 if (imgp->stack_sz != 0) {
1211 ssiz = trunc_page(imgp->stack_sz);
1213 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1215 if (ssiz > rlim_stack.rlim_max)
1216 ssiz = rlim_stack.rlim_max;
1217 if (ssiz > rlim_stack.rlim_cur) {
1218 rlim_stack.rlim_cur = ssiz;
1219 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1221 } else if (sv->sv_maxssiz != NULL) {
1222 ssiz = *sv->sv_maxssiz;
1226 imgp->eff_stack_sz = lim_cur(curthread, RLIMIT_STACK);
1227 if (ssiz < imgp->eff_stack_sz)
1228 imgp->eff_stack_sz = ssiz;
1229 stack_addr = sv->sv_usrstack - ssiz;
1230 stack_prot = obj != NULL && imgp->stack_prot != 0 ?
1231 imgp->stack_prot : sv->sv_stackprot;
1232 error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz, stack_prot,
1233 VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1234 if (error != KERN_SUCCESS) {
1235 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1236 "failed mach error %d errno %d\n", (uintmax_t)ssiz,
1237 stack_prot, error, vm_mmap_to_errno(error));
1238 return (vm_mmap_to_errno(error));
1240 vmspace->vm_stkgap = 0;
1243 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1244 * are still used to enforce the stack rlimit on the process stack.
1246 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1247 vmspace->vm_maxsaddr = (char *)stack_addr;
1249 return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1253 * Copy out argument and environment strings from the old process address
1254 * space into the temporary string buffer.
1257 exec_copyin_args(struct image_args *args, const char *fname,
1258 enum uio_seg segflg, char **argv, char **envv)
1263 bzero(args, sizeof(*args));
1268 * Allocate demand-paged memory for the file name, argument, and
1269 * environment strings.
1271 error = exec_alloc_args(args);
1276 * Copy the file name.
1278 error = exec_args_add_fname(args, fname, segflg);
1283 * extract arguments first
1286 error = fueword(argv++, &arg);
1293 error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1300 * extract environment strings
1304 error = fueword(envv++, &env);
1311 error = exec_args_add_env(args,
1312 (char *)(uintptr_t)env, UIO_USERSPACE);
1321 exec_free_args(args);
1325 struct exec_args_kva {
1328 SLIST_ENTRY(exec_args_kva) next;
1331 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1333 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1334 static struct mtx exec_args_kva_mtx;
1335 static u_int exec_args_gen;
1338 exec_prealloc_args_kva(void *arg __unused)
1340 struct exec_args_kva *argkva;
1343 SLIST_INIT(&exec_args_kva_freelist);
1344 mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1345 for (i = 0; i < exec_map_entries; i++) {
1346 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1347 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size);
1348 argkva->gen = exec_args_gen;
1349 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1352 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1355 exec_alloc_args_kva(void **cookie)
1357 struct exec_args_kva *argkva;
1359 argkva = (void *)atomic_readandclear_ptr(
1360 (uintptr_t *)DPCPU_PTR(exec_args_kva));
1361 if (argkva == NULL) {
1362 mtx_lock(&exec_args_kva_mtx);
1363 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1364 (void)mtx_sleep(&exec_args_kva_freelist,
1365 &exec_args_kva_mtx, 0, "execkva", 0);
1366 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1367 mtx_unlock(&exec_args_kva_mtx);
1369 kasan_mark((void *)argkva->addr, exec_map_entry_size,
1370 exec_map_entry_size, 0);
1371 *(struct exec_args_kva **)cookie = argkva;
1372 return (argkva->addr);
1376 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1380 base = argkva->addr;
1381 kasan_mark((void *)argkva->addr, 0, exec_map_entry_size,
1382 KASAN_EXEC_ARGS_FREED);
1383 if (argkva->gen != gen) {
1384 (void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1388 if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1389 (uintptr_t)NULL, (uintptr_t)argkva)) {
1390 mtx_lock(&exec_args_kva_mtx);
1391 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1392 wakeup_one(&exec_args_kva_freelist);
1393 mtx_unlock(&exec_args_kva_mtx);
1398 exec_free_args_kva(void *cookie)
1401 exec_release_args_kva(cookie, exec_args_gen);
1405 exec_args_kva_lowmem(void *arg __unused)
1407 SLIST_HEAD(, exec_args_kva) head;
1408 struct exec_args_kva *argkva;
1412 gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1415 * Force an madvise of each KVA range. Any currently allocated ranges
1416 * will have MADV_FREE applied once they are freed.
1419 mtx_lock(&exec_args_kva_mtx);
1420 SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1421 mtx_unlock(&exec_args_kva_mtx);
1422 while ((argkva = SLIST_FIRST(&head)) != NULL) {
1423 SLIST_REMOVE_HEAD(&head, next);
1424 exec_release_args_kva(argkva, gen);
1428 argkva = (void *)atomic_readandclear_ptr(
1429 (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1431 exec_release_args_kva(argkva, gen);
1434 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1435 EVENTHANDLER_PRI_ANY);
1438 * Allocate temporary demand-paged, zero-filled memory for the file name,
1439 * argument, and environment strings.
1442 exec_alloc_args(struct image_args *args)
1445 args->buf = (char *)exec_alloc_args_kva(&args->bufkva);
1450 exec_free_args(struct image_args *args)
1453 if (args->buf != NULL) {
1454 exec_free_args_kva(args->bufkva);
1457 if (args->fname_buf != NULL) {
1458 free(args->fname_buf, M_TEMP);
1459 args->fname_buf = NULL;
1464 * A set to functions to fill struct image args.
1466 * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1467 * fname) before the other functions. All exec_args_add_arg() calls must
1468 * be made before any exec_args_add_env() calls. exec_args_adjust_args()
1469 * may be called any time after exec_args_add_fname().
1471 * exec_args_add_fname() - install path to be executed
1472 * exec_args_add_arg() - append an argument string
1473 * exec_args_add_env() - append an env string
1474 * exec_args_adjust_args() - adjust location of the argument list to
1475 * allow new arguments to be prepended
1478 exec_args_add_fname(struct image_args *args, const char *fname,
1479 enum uio_seg segflg)
1484 KASSERT(args->fname == NULL, ("fname already appended"));
1485 KASSERT(args->endp == NULL, ("already appending to args"));
1487 if (fname != NULL) {
1488 args->fname = args->buf;
1489 error = segflg == UIO_SYSSPACE ?
1490 copystr(fname, args->fname, PATH_MAX, &length) :
1491 copyinstr(fname, args->fname, PATH_MAX, &length);
1493 return (error == ENAMETOOLONG ? E2BIG : error);
1497 /* Set up for _arg_*()/_env_*() */
1498 args->endp = args->buf + length;
1499 /* begin_argv must be set and kept updated */
1500 args->begin_argv = args->endp;
1501 KASSERT(exec_map_entry_size - length >= ARG_MAX,
1502 ("too little space remaining for arguments %zu < %zu",
1503 exec_map_entry_size - length, (size_t)ARG_MAX));
1504 args->stringspace = ARG_MAX;
1510 exec_args_add_str(struct image_args *args, const char *str,
1511 enum uio_seg segflg, int *countp)
1516 KASSERT(args->endp != NULL, ("endp not initialized"));
1517 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1519 error = (segflg == UIO_SYSSPACE) ?
1520 copystr(str, args->endp, args->stringspace, &length) :
1521 copyinstr(str, args->endp, args->stringspace, &length);
1523 return (error == ENAMETOOLONG ? E2BIG : error);
1524 args->stringspace -= length;
1525 args->endp += length;
1532 exec_args_add_arg(struct image_args *args, const char *argp,
1533 enum uio_seg segflg)
1536 KASSERT(args->envc == 0, ("appending args after env"));
1538 return (exec_args_add_str(args, argp, segflg, &args->argc));
1542 exec_args_add_env(struct image_args *args, const char *envp,
1543 enum uio_seg segflg)
1546 if (args->envc == 0)
1547 args->begin_envv = args->endp;
1549 return (exec_args_add_str(args, envp, segflg, &args->envc));
1553 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1557 KASSERT(args->endp != NULL, ("endp not initialized"));
1558 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1560 offset = extend - consume;
1561 if (args->stringspace < offset)
1563 memmove(args->begin_argv + extend, args->begin_argv + consume,
1564 args->endp - args->begin_argv + consume);
1566 args->begin_envv += offset;
1567 args->endp += offset;
1568 args->stringspace -= offset;
1573 exec_args_get_begin_envv(struct image_args *args)
1576 KASSERT(args->endp != NULL, ("endp not initialized"));
1579 return (args->begin_envv);
1580 return (args->endp);
1584 exec_stackgap(struct image_params *imgp, uintptr_t *dp)
1586 struct proc *p = imgp->proc;
1588 if (imgp->sysent->sv_stackgap == NULL ||
1589 (p->p_fctl0 & (NT_FREEBSD_FCTL_ASLR_DISABLE |
1590 NT_FREEBSD_FCTL_ASG_DISABLE)) != 0 ||
1591 (imgp->map_flags & MAP_ASLR) == 0) {
1592 p->p_vmspace->vm_stkgap = 0;
1595 p->p_vmspace->vm_stkgap = imgp->sysent->sv_stackgap(imgp, dp);
1599 * Copy strings out to the new process address space, constructing new arg
1600 * and env vector tables. Return a pointer to the base so that it can be used
1601 * as the initial stack pointer.
1604 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1609 uintptr_t destp, ustringp;
1610 struct ps_strings *arginfo;
1612 size_t execpath_len;
1613 int error, szsigcode, szps;
1614 char canary[sizeof(long) * 8];
1616 szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1618 * Calculate string base and vector table pointers.
1619 * Also deal with signal trampoline code for this exec type.
1621 if (imgp->execpath != NULL && imgp->auxargs != NULL)
1622 execpath_len = strlen(imgp->execpath) + 1;
1627 arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1628 imgp->ps_strings = arginfo;
1629 if (p->p_sysent->sv_sigcode_base == 0) {
1630 if (p->p_sysent->sv_szsigcode != NULL)
1631 szsigcode = *(p->p_sysent->sv_szsigcode);
1633 destp = (uintptr_t)arginfo;
1638 if (szsigcode != 0) {
1640 destp = rounddown2(destp, sizeof(void *));
1641 error = copyout(p->p_sysent->sv_sigcode, (void *)destp,
1648 * Copy the image path for the rtld.
1650 if (execpath_len != 0) {
1651 destp -= execpath_len;
1652 destp = rounddown2(destp, sizeof(void *));
1653 imgp->execpathp = (void *)destp;
1654 error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1660 * Prepare the canary for SSP.
1662 arc4rand(canary, sizeof(canary), 0);
1663 destp -= sizeof(canary);
1664 imgp->canary = (void *)destp;
1665 error = copyout(canary, imgp->canary, sizeof(canary));
1668 imgp->canarylen = sizeof(canary);
1671 * Prepare the pagesizes array.
1674 destp = rounddown2(destp, sizeof(void *));
1675 imgp->pagesizes = (void *)destp;
1676 error = copyout(pagesizes, imgp->pagesizes, szps);
1679 imgp->pagesizeslen = szps;
1682 * Allocate room for the argument and environment strings.
1684 destp -= ARG_MAX - imgp->args->stringspace;
1685 destp = rounddown2(destp, sizeof(void *));
1688 exec_stackgap(imgp, &destp);
1690 if (imgp->auxargs) {
1692 * Allocate room on the stack for the ELF auxargs
1693 * array. It has up to AT_COUNT entries.
1695 destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1696 destp = rounddown2(destp, sizeof(void *));
1699 vectp = (char **)destp;
1702 * Allocate room for the argv[] and env vectors including the
1703 * terminating NULL pointers.
1705 vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1708 * vectp also becomes our initial stack base
1710 *stack_base = (uintptr_t)vectp;
1712 stringp = imgp->args->begin_argv;
1713 argc = imgp->args->argc;
1714 envc = imgp->args->envc;
1717 * Copy out strings - arguments and environment.
1719 error = copyout(stringp, (void *)ustringp,
1720 ARG_MAX - imgp->args->stringspace);
1725 * Fill in "ps_strings" struct for ps, w, etc.
1728 if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1729 suword32(&arginfo->ps_nargvstr, argc) != 0)
1733 * Fill in argument portion of vector table.
1735 for (; argc > 0; --argc) {
1736 if (suword(vectp++, ustringp) != 0)
1738 while (*stringp++ != 0)
1743 /* a null vector table pointer separates the argp's from the envp's */
1744 if (suword(vectp++, 0) != 0)
1748 if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1749 suword32(&arginfo->ps_nenvstr, envc) != 0)
1753 * Fill in environment portion of vector table.
1755 for (; envc > 0; --envc) {
1756 if (suword(vectp++, ustringp) != 0)
1758 while (*stringp++ != 0)
1763 /* end of vector table is a null pointer */
1764 if (suword(vectp, 0) != 0)
1767 if (imgp->auxargs) {
1769 error = imgp->sysent->sv_copyout_auxargs(imgp,
1779 * Check permissions of file to execute.
1780 * Called with imgp->vp locked.
1781 * Return 0 for success or error code on failure.
1784 exec_check_permissions(struct image_params *imgp)
1786 struct vnode *vp = imgp->vp;
1787 struct vattr *attr = imgp->attr;
1793 /* Get file attributes */
1794 error = VOP_GETATTR(vp, attr, td->td_ucred);
1799 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1805 * 1) Check if file execution is disabled for the filesystem that
1806 * this file resides on.
1807 * 2) Ensure that at least one execute bit is on. Otherwise, a
1808 * privileged user will always succeed, and we don't want this
1809 * to happen unless the file really is executable.
1810 * 3) Ensure that the file is a regular file.
1812 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1813 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1814 (attr->va_type != VREG))
1818 * Zero length files can't be exec'd
1820 if (attr->va_size == 0)
1824 * Check for execute permission to file based on current credentials.
1826 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1831 * Check number of open-for-writes on the file and deny execution
1834 * Add a text reference now so no one can write to the
1835 * executable while we're activating it.
1837 * Remember if this was set before and unset it in case this is not
1838 * actually an executable image.
1840 error = VOP_SET_TEXT(vp);
1843 imgp->textset = true;
1846 * Call filesystem specific open routine (which does nothing in the
1849 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1851 imgp->opened = true;
1856 * Exec handler registration
1859 exec_register(const struct execsw *execsw_arg)
1861 const struct execsw **es, **xs, **newexecsw;
1862 u_int count = 2; /* New slot and trailing NULL */
1865 for (es = execsw; *es; es++)
1867 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1870 for (es = execsw; *es; es++)
1875 free(execsw, M_TEMP);
1881 exec_unregister(const struct execsw *execsw_arg)
1883 const struct execsw **es, **xs, **newexecsw;
1887 panic("unregister with no handlers left?\n");
1889 for (es = execsw; *es; es++) {
1890 if (*es == execsw_arg)
1895 for (es = execsw; *es; es++)
1896 if (*es != execsw_arg)
1898 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1900 for (es = execsw; *es; es++)
1901 if (*es != execsw_arg)
1905 free(execsw, M_TEMP);
1911 * Write out a core segment to the compression stream.
1914 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
1920 chunk_len = MIN(len, CORE_BUF_SIZE);
1923 * We can get EFAULT error here.
1924 * In that case zero out the current chunk of the segment.
1926 error = copyin(base, buf, chunk_len);
1928 bzero(buf, chunk_len);
1929 error = compressor_write(cp->comp, buf, chunk_len);
1939 core_write(struct coredump_params *cp, const void *base, size_t len,
1940 off_t offset, enum uio_seg seg, size_t *resid)
1943 return (vn_rdwr_inchunks(UIO_WRITE, cp->vp, __DECONST(void *, base),
1944 len, offset, seg, IO_UNIT | IO_DIRECT | IO_RANGELOCKED,
1945 cp->active_cred, cp->file_cred, resid, cp->td));
1949 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
1954 size_t resid, runlen;
1958 KASSERT((uintptr_t)base % PAGE_SIZE == 0,
1959 ("%s: user address %p is not page-aligned", __func__, base));
1961 if (cp->comp != NULL)
1962 return (compress_chunk(cp, base, tmpbuf, len));
1964 map = &cp->td->td_proc->p_vmspace->vm_map;
1965 for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
1967 * Attempt to page in all virtual pages in the range. If a
1968 * virtual page is not backed by the pager, it is represented as
1969 * a hole in the file. This can occur with zero-filled
1970 * anonymous memory or truncated files, for example.
1972 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
1973 if (core_dump_can_intr && curproc_sigkilled())
1975 error = vm_fault(map, (uintptr_t)base + runlen,
1976 VM_PROT_READ, VM_FAULT_NOFILL, NULL);
1978 success = error == KERN_SUCCESS;
1979 else if ((error == KERN_SUCCESS) != success)
1984 error = core_write(cp, base, runlen, offset,
1985 UIO_USERSPACE, &resid);
1987 if (error != EFAULT)
1991 * EFAULT may be returned if the user mapping
1992 * could not be accessed, e.g., because a mapped
1993 * file has been truncated. Skip the page if no
1994 * progress was made, to protect against a
1995 * hypothetical scenario where vm_fault() was
1996 * successful but core_write() returns EFAULT
2007 error = vn_start_write(cp->vp, &mp, V_WAIT);
2010 vn_lock(cp->vp, LK_EXCLUSIVE | LK_RETRY);
2011 error = vn_truncate_locked(cp->vp, offset + runlen,
2012 false, cp->td->td_ucred);
2014 vn_finished_write(mp);
2023 * Drain into a core file.
2026 sbuf_drain_core_output(void *arg, const char *data, int len)
2028 struct coredump_params *cp;
2033 p = cp->td->td_proc;
2036 * Some kern_proc out routines that print to this sbuf may
2037 * call us with the process lock held. Draining with the
2038 * non-sleepable lock held is unsafe. The lock is needed for
2039 * those routines when dumping a live process. In our case we
2040 * can safely release the lock before draining and acquire
2043 locked = PROC_LOCKED(p);
2046 if (cp->comp != NULL)
2047 error = compressor_write(cp->comp, __DECONST(char *, data),
2050 error = core_write(cp, __DECONST(void *, data), len, cp->offset,
2051 UIO_SYSSPACE, NULL);