The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_exec.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1993, David Greenman
    3  * All rights reserved.
    4  *
    5  * Redistribution and use in source and binary forms, with or without
    6  * modification, are permitted provided that the following conditions
    7  * are met:
    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.
   13  *
   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
   24  * SUCH DAMAGE.
   25  */
   26 
   27 #include <sys/cdefs.h>
   28 __FBSDID("$FreeBSD: releng/11.0/sys/kern/kern_exec.c 303606 2016-08-01 06:34:55Z kib $");
   29 
   30 #include "opt_capsicum.h"
   31 #include "opt_hwpmc_hooks.h"
   32 #include "opt_ktrace.h"
   33 #include "opt_vm.h"
   34 
   35 #include <sys/param.h>
   36 #include <sys/capsicum.h>
   37 #include <sys/systm.h>
   38 #include <sys/eventhandler.h>
   39 #include <sys/lock.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>
   47 #include <sys/acct.h>
   48 #include <sys/exec.h>
   49 #include <sys/imgact.h>
   50 #include <sys/imgact_elf.h>
   51 #include <sys/wait.h>
   52 #include <sys/malloc.h>
   53 #include <sys/priv.h>
   54 #include <sys/proc.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>
   60 #include <sys/sdt.h>
   61 #include <sys/sf_buf.h>
   62 #include <sys/syscallsubr.h>
   63 #include <sys/sysent.h>
   64 #include <sys/shm.h>
   65 #include <sys/sysctl.h>
   66 #include <sys/vnode.h>
   67 #include <sys/stat.h>
   68 #ifdef KTRACE
   69 #include <sys/ktrace.h>
   70 #endif
   71 
   72 #include <vm/vm.h>
   73 #include <vm/vm_param.h>
   74 #include <vm/pmap.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>
   81 
   82 #ifdef  HWPMC_HOOKS
   83 #include <sys/pmckern.h>
   84 #endif
   85 
   86 #include <machine/reg.h>
   87 
   88 #include <security/audit/audit.h>
   89 #include <security/mac/mac_framework.h>
   90 
   91 #ifdef KDTRACE_HOOKS
   92 #include <sys/dtrace_bsd.h>
   93 dtrace_execexit_func_t  dtrace_fasttrap_exec;
   94 #endif
   95 
   96 SDT_PROVIDER_DECLARE(proc);
   97 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
   98 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
   99 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
  100 
  101 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
  102 
  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");
  107 
  108 int coredump_pack_vmmapinfo = 1;
  109 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
  110     &coredump_pack_vmmapinfo, 0,
  111     "Enable file path packing in 'procstat -v' coredump notes");
  112 
  113 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
  114 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
  115 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
  116 static int do_execve(struct thread *td, struct image_args *args,
  117     struct mac *mac_p);
  118 
  119 /* XXX This should be vm_size_t. */
  120 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
  121     NULL, 0, sysctl_kern_ps_strings, "LU", "");
  122 
  123 /* XXX This should be vm_size_t. */
  124 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
  125     CTLFLAG_CAPRD, NULL, 0, sysctl_kern_usrstack, "LU", "");
  126 
  127 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
  128     NULL, 0, sysctl_kern_stackprot, "I", "");
  129 
  130 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
  131 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW, 
  132     &ps_arg_cache_limit, 0, "");
  133 
  134 static int disallow_high_osrel;
  135 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
  136     &disallow_high_osrel, 0,
  137     "Disallow execution of binaries built for higher version of the world");
  138 
  139 static int map_at_zero = 0;
  140 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
  141     "Permit processes to map an object at virtual address 0.");
  142 
  143 static int
  144 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
  145 {
  146         struct proc *p;
  147         int error;
  148 
  149         p = curproc;
  150 #ifdef SCTL_MASK32
  151         if (req->flags & SCTL_MASK32) {
  152                 unsigned int val;
  153                 val = (unsigned int)p->p_sysent->sv_psstrings;
  154                 error = SYSCTL_OUT(req, &val, sizeof(val));
  155         } else
  156 #endif
  157                 error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
  158                    sizeof(p->p_sysent->sv_psstrings));
  159         return error;
  160 }
  161 
  162 static int
  163 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
  164 {
  165         struct proc *p;
  166         int error;
  167 
  168         p = curproc;
  169 #ifdef SCTL_MASK32
  170         if (req->flags & SCTL_MASK32) {
  171                 unsigned int val;
  172                 val = (unsigned int)p->p_sysent->sv_usrstack;
  173                 error = SYSCTL_OUT(req, &val, sizeof(val));
  174         } else
  175 #endif
  176                 error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
  177                     sizeof(p->p_sysent->sv_usrstack));
  178         return error;
  179 }
  180 
  181 static int
  182 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
  183 {
  184         struct proc *p;
  185 
  186         p = curproc;
  187         return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
  188             sizeof(p->p_sysent->sv_stackprot)));
  189 }
  190 
  191 /*
  192  * Each of the items is a pointer to a `const struct execsw', hence the
  193  * double pointer here.
  194  */
  195 static const struct execsw **execsw;
  196 
  197 #ifndef _SYS_SYSPROTO_H_
  198 struct execve_args {
  199         char    *fname; 
  200         char    **argv;
  201         char    **envv; 
  202 };
  203 #endif
  204 
  205 int
  206 sys_execve(struct thread *td, struct execve_args *uap)
  207 {
  208         struct image_args args;
  209         struct vmspace *oldvmspace;
  210         int error;
  211 
  212         error = pre_execve(td, &oldvmspace);
  213         if (error != 0)
  214                 return (error);
  215         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
  216             uap->argv, uap->envv);
  217         if (error == 0)
  218                 error = kern_execve(td, &args, NULL);
  219         post_execve(td, error, oldvmspace);
  220         return (error);
  221 }
  222 
  223 #ifndef _SYS_SYSPROTO_H_
  224 struct fexecve_args {
  225         int     fd;
  226         char    **argv;
  227         char    **envv;
  228 }
  229 #endif
  230 int
  231 sys_fexecve(struct thread *td, struct fexecve_args *uap)
  232 {
  233         struct image_args args;
  234         struct vmspace *oldvmspace;
  235         int error;
  236 
  237         error = pre_execve(td, &oldvmspace);
  238         if (error != 0)
  239                 return (error);
  240         error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
  241             uap->argv, uap->envv);
  242         if (error == 0) {
  243                 args.fd = uap->fd;
  244                 error = kern_execve(td, &args, NULL);
  245         }
  246         post_execve(td, error, oldvmspace);
  247         return (error);
  248 }
  249 
  250 #ifndef _SYS_SYSPROTO_H_
  251 struct __mac_execve_args {
  252         char    *fname;
  253         char    **argv;
  254         char    **envv;
  255         struct mac      *mac_p;
  256 };
  257 #endif
  258 
  259 int
  260 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
  261 {
  262 #ifdef MAC
  263         struct image_args args;
  264         struct vmspace *oldvmspace;
  265         int error;
  266 
  267         error = pre_execve(td, &oldvmspace);
  268         if (error != 0)
  269                 return (error);
  270         error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
  271             uap->argv, uap->envv);
  272         if (error == 0)
  273                 error = kern_execve(td, &args, uap->mac_p);
  274         post_execve(td, error, oldvmspace);
  275         return (error);
  276 #else
  277         return (ENOSYS);
  278 #endif
  279 }
  280 
  281 int
  282 pre_execve(struct thread *td, struct vmspace **oldvmspace)
  283 {
  284         struct proc *p;
  285         int error;
  286 
  287         KASSERT(td == curthread, ("non-current thread %p", td));
  288         error = 0;
  289         p = td->td_proc;
  290         if ((p->p_flag & P_HADTHREADS) != 0) {
  291                 PROC_LOCK(p);
  292                 if (thread_single(p, SINGLE_BOUNDARY) != 0)
  293                         error = ERESTART;
  294                 PROC_UNLOCK(p);
  295         }
  296         KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
  297             ("nested execve"));
  298         *oldvmspace = p->p_vmspace;
  299         return (error);
  300 }
  301 
  302 void
  303 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
  304 {
  305         struct proc *p;
  306 
  307         KASSERT(td == curthread, ("non-current thread %p", td));
  308         p = td->td_proc;
  309         if ((p->p_flag & P_HADTHREADS) != 0) {
  310                 PROC_LOCK(p);
  311                 /*
  312                  * If success, we upgrade to SINGLE_EXIT state to
  313                  * force other threads to suicide.
  314                  */
  315                 if (error == 0)
  316                         thread_single(p, SINGLE_EXIT);
  317                 else
  318                         thread_single_end(p, SINGLE_BOUNDARY);
  319                 PROC_UNLOCK(p);
  320         }
  321         if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
  322                 KASSERT(p->p_vmspace != oldvmspace,
  323                     ("oldvmspace still used"));
  324                 vmspace_free(oldvmspace);
  325                 td->td_pflags &= ~TDP_EXECVMSPC;
  326         }
  327 }
  328 
  329 /*
  330  * XXX: kern_execve has the astonishing property of not always returning to
  331  * the caller.  If sufficiently bad things happen during the call to
  332  * do_execve(), it can end up calling exit1(); as a result, callers must
  333  * avoid doing anything which they might need to undo (e.g., allocating
  334  * memory).
  335  */
  336 int
  337 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p)
  338 {
  339 
  340         AUDIT_ARG_ARGV(args->begin_argv, args->argc,
  341             args->begin_envv - args->begin_argv);
  342         AUDIT_ARG_ENVV(args->begin_envv, args->envc,
  343             args->endp - args->begin_envv);
  344         return (do_execve(td, args, mac_p));
  345 }
  346 
  347 /*
  348  * In-kernel implementation of execve().  All arguments are assumed to be
  349  * userspace pointers from the passed thread.
  350  */
  351 static int
  352 do_execve(td, args, mac_p)
  353         struct thread *td;
  354         struct image_args *args;
  355         struct mac *mac_p;
  356 {
  357         struct proc *p = td->td_proc;
  358         struct nameidata nd;
  359         struct ucred *oldcred;
  360         struct uidinfo *euip = NULL;
  361         register_t *stack_base;
  362         int error, i;
  363         struct image_params image_params, *imgp;
  364         struct vattr attr;
  365         int (*img_first)(struct image_params *);
  366         struct pargs *oldargs = NULL, *newargs = NULL;
  367         struct sigacts *oldsigacts = NULL, *newsigacts = NULL;
  368 #ifdef KTRACE
  369         struct vnode *tracevp = NULL;
  370         struct ucred *tracecred = NULL;
  371 #endif
  372         struct vnode *oldtextvp = NULL, *newtextvp;
  373         cap_rights_t rights;
  374         int credential_changing;
  375         int textset;
  376 #ifdef MAC
  377         struct label *interpvplabel = NULL;
  378         int will_transition;
  379 #endif
  380 #ifdef HWPMC_HOOKS
  381         struct pmckern_procexec pe;
  382 #endif
  383         static const char fexecv_proc_title[] = "(fexecv)";
  384 
  385         imgp = &image_params;
  386 
  387         /*
  388          * Lock the process and set the P_INEXEC flag to indicate that
  389          * it should be left alone until we're done here.  This is
  390          * necessary to avoid race conditions - e.g. in ptrace() -
  391          * that might allow a local user to illicitly obtain elevated
  392          * privileges.
  393          */
  394         PROC_LOCK(p);
  395         KASSERT((p->p_flag & P_INEXEC) == 0,
  396             ("%s(): process already has P_INEXEC flag", __func__));
  397         p->p_flag |= P_INEXEC;
  398         PROC_UNLOCK(p);
  399 
  400         /*
  401          * Initialize part of the common data
  402          */
  403         bzero(imgp, sizeof(*imgp));
  404         imgp->proc = p;
  405         imgp->attr = &attr;
  406         imgp->args = args;
  407         oldcred = p->p_ucred;
  408 
  409 #ifdef MAC
  410         error = mac_execve_enter(imgp, mac_p);
  411         if (error)
  412                 goto exec_fail;
  413 #endif
  414 
  415         /*
  416          * Translate the file name. namei() returns a vnode pointer
  417          *      in ni_vp among other things.
  418          *
  419          * XXXAUDIT: It would be desirable to also audit the name of the
  420          * interpreter if this is an interpreted binary.
  421          */
  422         if (args->fname != NULL) {
  423                 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
  424                     | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
  425         }
  426 
  427         SDT_PROBE1(proc, , , exec, args->fname);
  428 
  429 interpret:
  430         if (args->fname != NULL) {
  431 #ifdef CAPABILITY_MODE
  432                 /*
  433                  * While capability mode can't reach this point via direct
  434                  * path arguments to execve(), we also don't allow
  435                  * interpreters to be used in capability mode (for now).
  436                  * Catch indirect lookups and return a permissions error.
  437                  */
  438                 if (IN_CAPABILITY_MODE(td)) {
  439                         error = ECAPMODE;
  440                         goto exec_fail;
  441                 }
  442 #endif
  443                 error = namei(&nd);
  444                 if (error)
  445                         goto exec_fail;
  446 
  447                 newtextvp = nd.ni_vp;
  448                 imgp->vp = newtextvp;
  449         } else {
  450                 AUDIT_ARG_FD(args->fd);
  451                 /*
  452                  * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
  453                  */
  454                 error = fgetvp_exec(td, args->fd,
  455                     cap_rights_init(&rights, CAP_FEXECVE), &newtextvp);
  456                 if (error)
  457                         goto exec_fail;
  458                 vn_lock(newtextvp, LK_EXCLUSIVE | LK_RETRY);
  459                 AUDIT_ARG_VNODE1(newtextvp);
  460                 imgp->vp = newtextvp;
  461         }
  462 
  463         /*
  464          * Check file permissions (also 'opens' file)
  465          */
  466         error = exec_check_permissions(imgp);
  467         if (error)
  468                 goto exec_fail_dealloc;
  469 
  470         imgp->object = imgp->vp->v_object;
  471         if (imgp->object != NULL)
  472                 vm_object_reference(imgp->object);
  473 
  474         /*
  475          * Set VV_TEXT now so no one can write to the executable while we're
  476          * activating it.
  477          *
  478          * Remember if this was set before and unset it in case this is not
  479          * actually an executable image.
  480          */
  481         textset = VOP_IS_TEXT(imgp->vp);
  482         VOP_SET_TEXT(imgp->vp);
  483 
  484         error = exec_map_first_page(imgp);
  485         if (error)
  486                 goto exec_fail_dealloc;
  487 
  488         imgp->proc->p_osrel = 0;
  489 
  490         /*
  491          * Implement image setuid/setgid.
  492          *
  493          * Determine new credentials before attempting image activators
  494          * so that it can be used by process_exec handlers to determine
  495          * credential/setid changes.
  496          *
  497          * Don't honor setuid/setgid if the filesystem prohibits it or if
  498          * the process is being traced.
  499          *
  500          * We disable setuid/setgid/etc in capability mode on the basis
  501          * that most setugid applications are not written with that
  502          * environment in mind, and will therefore almost certainly operate
  503          * incorrectly. In principle there's no reason that setugid
  504          * applications might not be useful in capability mode, so we may want
  505          * to reconsider this conservative design choice in the future.
  506          *
  507          * XXXMAC: For the time being, use NOSUID to also prohibit
  508          * transitions on the file system.
  509          */
  510         credential_changing = 0;
  511         credential_changing |= (attr.va_mode & S_ISUID) &&
  512             oldcred->cr_uid != attr.va_uid;
  513         credential_changing |= (attr.va_mode & S_ISGID) &&
  514             oldcred->cr_gid != attr.va_gid;
  515 #ifdef MAC
  516         will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
  517             interpvplabel, imgp);
  518         credential_changing |= will_transition;
  519 #endif
  520 
  521         if (credential_changing &&
  522 #ifdef CAPABILITY_MODE
  523             ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
  524 #endif
  525             (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
  526             (p->p_flag & P_TRACED) == 0) {
  527                 imgp->credential_setid = true;
  528                 VOP_UNLOCK(imgp->vp, 0);
  529                 imgp->newcred = crdup(oldcred);
  530                 if (attr.va_mode & S_ISUID) {
  531                         euip = uifind(attr.va_uid);
  532                         change_euid(imgp->newcred, euip);
  533                 }
  534                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
  535                 if (attr.va_mode & S_ISGID)
  536                         change_egid(imgp->newcred, attr.va_gid);
  537                 /*
  538                  * Implement correct POSIX saved-id behavior.
  539                  *
  540                  * XXXMAC: Note that the current logic will save the
  541                  * uid and gid if a MAC domain transition occurs, even
  542                  * though maybe it shouldn't.
  543                  */
  544                 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
  545                 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
  546         } else {
  547                 /*
  548                  * Implement correct POSIX saved-id behavior.
  549                  *
  550                  * XXX: It's not clear that the existing behavior is
  551                  * POSIX-compliant.  A number of sources indicate that the
  552                  * saved uid/gid should only be updated if the new ruid is
  553                  * not equal to the old ruid, or the new euid is not equal
  554                  * to the old euid and the new euid is not equal to the old
  555                  * ruid.  The FreeBSD code always updates the saved uid/gid.
  556                  * Also, this code uses the new (replaced) euid and egid as
  557                  * the source, which may or may not be the right ones to use.
  558                  */
  559                 if (oldcred->cr_svuid != oldcred->cr_uid ||
  560                     oldcred->cr_svgid != oldcred->cr_gid) {
  561                         VOP_UNLOCK(imgp->vp, 0);
  562                         imgp->newcred = crdup(oldcred);
  563                         vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
  564                         change_svuid(imgp->newcred, imgp->newcred->cr_uid);
  565                         change_svgid(imgp->newcred, imgp->newcred->cr_gid);
  566                 }
  567         }
  568         /* The new credentials are installed into the process later. */
  569 
  570         /*
  571          * Do the best to calculate the full path to the image file.
  572          */
  573         if (args->fname != NULL && args->fname[0] == '/')
  574                 imgp->execpath = args->fname;
  575         else {
  576                 VOP_UNLOCK(imgp->vp, 0);
  577                 if (vn_fullpath(td, imgp->vp, &imgp->execpath,
  578                     &imgp->freepath) != 0)
  579                         imgp->execpath = args->fname;
  580                 vn_lock(imgp->vp, LK_EXCLUSIVE | LK_RETRY);
  581         }
  582 
  583         /*
  584          *      If the current process has a special image activator it
  585          *      wants to try first, call it.   For example, emulating shell
  586          *      scripts differently.
  587          */
  588         error = -1;
  589         if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
  590                 error = img_first(imgp);
  591 
  592         /*
  593          *      Loop through the list of image activators, calling each one.
  594          *      An activator returns -1 if there is no match, 0 on success,
  595          *      and an error otherwise.
  596          */
  597         for (i = 0; error == -1 && execsw[i]; ++i) {
  598                 if (execsw[i]->ex_imgact == NULL ||
  599                     execsw[i]->ex_imgact == img_first) {
  600                         continue;
  601                 }
  602                 error = (*execsw[i]->ex_imgact)(imgp);
  603         }
  604 
  605         if (error) {
  606                 if (error == -1) {
  607                         if (textset == 0)
  608                                 VOP_UNSET_TEXT(imgp->vp);
  609                         error = ENOEXEC;
  610                 }
  611                 goto exec_fail_dealloc;
  612         }
  613 
  614         /*
  615          * Special interpreter operation, cleanup and loop up to try to
  616          * activate the interpreter.
  617          */
  618         if (imgp->interpreted) {
  619                 exec_unmap_first_page(imgp);
  620                 /*
  621                  * VV_TEXT needs to be unset for scripts.  There is a short
  622                  * period before we determine that something is a script where
  623                  * VV_TEXT will be set. The vnode lock is held over this
  624                  * entire period so nothing should illegitimately be blocked.
  625                  */
  626                 VOP_UNSET_TEXT(imgp->vp);
  627                 /* free name buffer and old vnode */
  628                 if (args->fname != NULL)
  629                         NDFREE(&nd, NDF_ONLY_PNBUF);
  630 #ifdef MAC
  631                 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
  632 #endif
  633                 if (imgp->opened) {
  634                         VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
  635                         imgp->opened = 0;
  636                 }
  637                 vput(newtextvp);
  638                 vm_object_deallocate(imgp->object);
  639                 imgp->object = NULL;
  640                 imgp->credential_setid = false;
  641                 if (imgp->newcred != NULL) {
  642                         crfree(imgp->newcred);
  643                         imgp->newcred = NULL;
  644                 }
  645                 imgp->execpath = NULL;
  646                 free(imgp->freepath, M_TEMP);
  647                 imgp->freepath = NULL;
  648                 /* set new name to that of the interpreter */
  649                 NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
  650                     UIO_SYSSPACE, imgp->interpreter_name, td);
  651                 args->fname = imgp->interpreter_name;
  652                 goto interpret;
  653         }
  654 
  655         /*
  656          * NB: We unlock the vnode here because it is believed that none
  657          * of the sv_copyout_strings/sv_fixup operations require the vnode.
  658          */
  659         VOP_UNLOCK(imgp->vp, 0);
  660 
  661         if (disallow_high_osrel &&
  662             P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
  663                 error = ENOEXEC;
  664                 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
  665                     imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
  666                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
  667                 goto exec_fail_dealloc;
  668         }
  669 
  670         /* ABI enforces the use of Capsicum. Switch into capabilities mode. */
  671         if (SV_PROC_FLAG(p, SV_CAPSICUM))
  672                 sys_cap_enter(td, NULL);
  673 
  674         /*
  675          * Copy out strings (args and env) and initialize stack base
  676          */
  677         if (p->p_sysent->sv_copyout_strings)
  678                 stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
  679         else
  680                 stack_base = exec_copyout_strings(imgp);
  681 
  682         /*
  683          * If custom stack fixup routine present for this process
  684          * let it do the stack setup.
  685          * Else stuff argument count as first item on stack
  686          */
  687         if (p->p_sysent->sv_fixup != NULL)
  688                 (*p->p_sysent->sv_fixup)(&stack_base, imgp);
  689         else
  690                 suword(--stack_base, imgp->args->argc);
  691 
  692         if (args->fdp != NULL) {
  693                 /* Install a brand new file descriptor table. */
  694                 fdinstall_remapped(td, args->fdp);
  695                 args->fdp = NULL;
  696         } else {
  697                 /*
  698                  * Keep on using the existing file descriptor table. For
  699                  * security and other reasons, the file descriptor table
  700                  * cannot be shared after an exec.
  701                  */
  702                 fdunshare(td);
  703                 /* close files on exec */
  704                 fdcloseexec(td);
  705         }
  706 
  707         /*
  708          * Malloc things before we need locks.
  709          */
  710         i = imgp->args->begin_envv - imgp->args->begin_argv;
  711         /* Cache arguments if they fit inside our allowance */
  712         if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
  713                 newargs = pargs_alloc(i);
  714                 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
  715         }
  716 
  717         /*
  718          * For security and other reasons, signal handlers cannot
  719          * be shared after an exec. The new process gets a copy of the old
  720          * handlers. In execsigs(), the new process will have its signals
  721          * reset.
  722          */
  723         if (sigacts_shared(p->p_sigacts)) {
  724                 oldsigacts = p->p_sigacts;
  725                 newsigacts = sigacts_alloc();
  726                 sigacts_copy(newsigacts, oldsigacts);
  727         }
  728 
  729         vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
  730 
  731         PROC_LOCK(p);
  732         if (oldsigacts)
  733                 p->p_sigacts = newsigacts;
  734         /* Stop profiling */
  735         stopprofclock(p);
  736 
  737         /* reset caught signals */
  738         execsigs(p);
  739 
  740         /* name this process - nameiexec(p, ndp) */
  741         bzero(p->p_comm, sizeof(p->p_comm));
  742         if (args->fname)
  743                 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
  744                     min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
  745         else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
  746                 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
  747         bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
  748 #ifdef KTR
  749         sched_clear_tdname(td);
  750 #endif
  751 
  752         /*
  753          * mark as execed, wakeup the process that vforked (if any) and tell
  754          * it that it now has its own resources back
  755          */
  756         p->p_flag |= P_EXEC;
  757         if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
  758                 p->p_flag2 &= ~P2_NOTRACE;
  759         if (p->p_flag & P_PPWAIT) {
  760                 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
  761                 cv_broadcast(&p->p_pwait);
  762                 /* STOPs are no longer ignored, arrange for AST */
  763                 signotify(td);
  764         }
  765 
  766         /*
  767          * Implement image setuid/setgid installation.
  768          */
  769         if (imgp->credential_setid) {
  770                 /*
  771                  * Turn off syscall tracing for set-id programs, except for
  772                  * root.  Record any set-id flags first to make sure that
  773                  * we do not regain any tracing during a possible block.
  774                  */
  775                 setsugid(p);
  776 
  777 #ifdef KTRACE
  778                 if (p->p_tracecred != NULL &&
  779                     priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
  780                         ktrprocexec(p, &tracecred, &tracevp);
  781 #endif
  782                 /*
  783                  * Close any file descriptors 0..2 that reference procfs,
  784                  * then make sure file descriptors 0..2 are in use.
  785                  *
  786                  * Both fdsetugidsafety() and fdcheckstd() may call functions
  787                  * taking sleepable locks, so temporarily drop our locks.
  788                  */
  789                 PROC_UNLOCK(p);
  790                 VOP_UNLOCK(imgp->vp, 0);
  791                 fdsetugidsafety(td);
  792                 error = fdcheckstd(td);
  793                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
  794                 if (error != 0)
  795                         goto exec_fail_dealloc;
  796                 PROC_LOCK(p);
  797 #ifdef MAC
  798                 if (will_transition) {
  799                         mac_vnode_execve_transition(oldcred, imgp->newcred,
  800                             imgp->vp, interpvplabel, imgp);
  801                 }
  802 #endif
  803         } else {
  804                 if (oldcred->cr_uid == oldcred->cr_ruid &&
  805                     oldcred->cr_gid == oldcred->cr_rgid)
  806                         p->p_flag &= ~P_SUGID;
  807         }
  808         /*
  809          * Set the new credentials.
  810          */
  811         if (imgp->newcred != NULL) {
  812                 proc_set_cred(p, imgp->newcred);
  813                 crfree(oldcred);
  814                 oldcred = NULL;
  815         }
  816 
  817         /*
  818          * Store the vp for use in procfs.  This vnode was referenced by namei
  819          * or fgetvp_exec.
  820          */
  821         oldtextvp = p->p_textvp;
  822         p->p_textvp = newtextvp;
  823 
  824 #ifdef KDTRACE_HOOKS
  825         /*
  826          * Tell the DTrace fasttrap provider about the exec if it
  827          * has declared an interest.
  828          */
  829         if (dtrace_fasttrap_exec)
  830                 dtrace_fasttrap_exec(p);
  831 #endif
  832 
  833         /*
  834          * Notify others that we exec'd, and clear the P_INEXEC flag
  835          * as we're now a bona fide freshly-execed process.
  836          */
  837         KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
  838         p->p_flag &= ~P_INEXEC;
  839 
  840         /* clear "fork but no exec" flag, as we _are_ execing */
  841         p->p_acflag &= ~AFORK;
  842 
  843         /*
  844          * Free any previous argument cache and replace it with
  845          * the new argument cache, if any.
  846          */
  847         oldargs = p->p_args;
  848         p->p_args = newargs;
  849         newargs = NULL;
  850 
  851 #ifdef  HWPMC_HOOKS
  852         /*
  853          * Check if system-wide sampling is in effect or if the
  854          * current process is using PMCs.  If so, do exec() time
  855          * processing.  This processing needs to happen AFTER the
  856          * P_INEXEC flag is cleared.
  857          *
  858          * The proc lock needs to be released before taking the PMC
  859          * SX.
  860          */
  861         if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
  862                 PROC_UNLOCK(p);
  863                 VOP_UNLOCK(imgp->vp, 0);
  864                 pe.pm_credentialschanged = credential_changing;
  865                 pe.pm_entryaddr = imgp->entry_addr;
  866 
  867                 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
  868                 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
  869         } else
  870                 PROC_UNLOCK(p);
  871 #else  /* !HWPMC_HOOKS */
  872         PROC_UNLOCK(p);
  873 #endif
  874 
  875         /* Set values passed into the program in registers. */
  876         if (p->p_sysent->sv_setregs)
  877                 (*p->p_sysent->sv_setregs)(td, imgp, 
  878                     (u_long)(uintptr_t)stack_base);
  879         else
  880                 exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
  881 
  882         vfs_mark_atime(imgp->vp, td->td_ucred);
  883 
  884         SDT_PROBE1(proc, , , exec__success, args->fname);
  885 
  886 exec_fail_dealloc:
  887         if (imgp->firstpage != NULL)
  888                 exec_unmap_first_page(imgp);
  889 
  890         if (imgp->vp != NULL) {
  891                 if (args->fname)
  892                         NDFREE(&nd, NDF_ONLY_PNBUF);
  893                 if (imgp->opened)
  894                         VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
  895                 if (error != 0)
  896                         vput(imgp->vp);
  897                 else
  898                         VOP_UNLOCK(imgp->vp, 0);
  899         }
  900 
  901         if (imgp->object != NULL)
  902                 vm_object_deallocate(imgp->object);
  903 
  904         free(imgp->freepath, M_TEMP);
  905 
  906         if (error == 0) {
  907                 PROC_LOCK(p);
  908                 td->td_dbgflags |= TDB_EXEC;
  909                 PROC_UNLOCK(p);
  910 
  911                 /*
  912                  * Stop the process here if its stop event mask has
  913                  * the S_EXEC bit set.
  914                  */
  915                 STOPEVENT(p, S_EXEC, 0);
  916         } else {
  917 exec_fail:
  918                 /* we're done here, clear P_INEXEC */
  919                 PROC_LOCK(p);
  920                 p->p_flag &= ~P_INEXEC;
  921                 PROC_UNLOCK(p);
  922 
  923                 SDT_PROBE1(proc, , , exec__failure, error);
  924         }
  925 
  926         if (imgp->newcred != NULL && oldcred != NULL)
  927                 crfree(imgp->newcred);
  928 
  929 #ifdef MAC
  930         mac_execve_exit(imgp);
  931         mac_execve_interpreter_exit(interpvplabel);
  932 #endif
  933         exec_free_args(args);
  934 
  935         /*
  936          * Handle deferred decrement of ref counts.
  937          */
  938         if (oldtextvp != NULL)
  939                 vrele(oldtextvp);
  940 #ifdef KTRACE
  941         if (tracevp != NULL)
  942                 vrele(tracevp);
  943         if (tracecred != NULL)
  944                 crfree(tracecred);
  945 #endif
  946         pargs_drop(oldargs);
  947         pargs_drop(newargs);
  948         if (oldsigacts != NULL)
  949                 sigacts_free(oldsigacts);
  950         if (euip != NULL)
  951                 uifree(euip);
  952 
  953         if (error && imgp->vmspace_destroyed) {
  954                 /* sorry, no more process anymore. exit gracefully */
  955                 exit1(td, 0, SIGABRT);
  956                 /* NOT REACHED */
  957         }
  958 
  959 #ifdef KTRACE
  960         if (error == 0)
  961                 ktrprocctor(p);
  962 #endif
  963 
  964         return (error);
  965 }
  966 
  967 int
  968 exec_map_first_page(imgp)
  969         struct image_params *imgp;
  970 {
  971         int rv, i, after, initial_pagein;
  972         vm_page_t ma[VM_INITIAL_PAGEIN];
  973         vm_object_t object;
  974 
  975         if (imgp->firstpage != NULL)
  976                 exec_unmap_first_page(imgp);
  977 
  978         object = imgp->vp->v_object;
  979         if (object == NULL)
  980                 return (EACCES);
  981         VM_OBJECT_WLOCK(object);
  982 #if VM_NRESERVLEVEL > 0
  983         vm_object_color(object, 0);
  984 #endif
  985         ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
  986         if (ma[0]->valid != VM_PAGE_BITS_ALL) {
  987                 if (!vm_pager_has_page(object, 0, NULL, &after)) {
  988                         vm_page_lock(ma[0]);
  989                         vm_page_free(ma[0]);
  990                         vm_page_unlock(ma[0]);
  991                         vm_page_xunbusy(ma[0]);
  992                         VM_OBJECT_WUNLOCK(object);
  993                         return (EIO);
  994                 }
  995                 initial_pagein = min(after, VM_INITIAL_PAGEIN);
  996                 KASSERT(initial_pagein <= object->size,
  997                     ("%s: initial_pagein %d object->size %ju",
  998                     __func__, initial_pagein, (uintmax_t )object->size));
  999                 for (i = 1; i < initial_pagein; i++) {
 1000                         if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
 1001                                 if (ma[i]->valid)
 1002                                         break;
 1003                                 if (vm_page_tryxbusy(ma[i]))
 1004                                         break;
 1005                         } else {
 1006                                 ma[i] = vm_page_alloc(object, i,
 1007                                     VM_ALLOC_NORMAL | VM_ALLOC_IFNOTCACHED);
 1008                                 if (ma[i] == NULL)
 1009                                         break;
 1010                         }
 1011                 }
 1012                 initial_pagein = i;
 1013                 rv = vm_pager_get_pages(object, ma, initial_pagein, NULL, NULL);
 1014                 if (rv != VM_PAGER_OK) {
 1015                         for (i = 0; i < initial_pagein; i++) {
 1016                                 vm_page_lock(ma[i]);
 1017                                 vm_page_free(ma[i]);
 1018                                 vm_page_unlock(ma[i]);
 1019                                 vm_page_xunbusy(ma[i]);
 1020                         }
 1021                         VM_OBJECT_WUNLOCK(object);
 1022                         return (EIO);
 1023                 }
 1024                 for (i = 1; i < initial_pagein; i++)
 1025                         vm_page_readahead_finish(ma[i]);
 1026         }
 1027         vm_page_xunbusy(ma[0]);
 1028         vm_page_lock(ma[0]);
 1029         vm_page_hold(ma[0]);
 1030         vm_page_activate(ma[0]);
 1031         vm_page_unlock(ma[0]);
 1032         VM_OBJECT_WUNLOCK(object);
 1033 
 1034         imgp->firstpage = sf_buf_alloc(ma[0], 0);
 1035         imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
 1036 
 1037         return (0);
 1038 }
 1039 
 1040 void
 1041 exec_unmap_first_page(imgp)
 1042         struct image_params *imgp;
 1043 {
 1044         vm_page_t m;
 1045 
 1046         if (imgp->firstpage != NULL) {
 1047                 m = sf_buf_page(imgp->firstpage);
 1048                 sf_buf_free(imgp->firstpage);
 1049                 imgp->firstpage = NULL;
 1050                 vm_page_lock(m);
 1051                 vm_page_unhold(m);
 1052                 vm_page_unlock(m);
 1053         }
 1054 }
 1055 
 1056 /*
 1057  * Destroy old address space, and allocate a new stack
 1058  *      The new stack is only SGROWSIZ large because it is grown
 1059  *      automatically in trap.c.
 1060  */
 1061 int
 1062 exec_new_vmspace(imgp, sv)
 1063         struct image_params *imgp;
 1064         struct sysentvec *sv;
 1065 {
 1066         int error;
 1067         struct proc *p = imgp->proc;
 1068         struct vmspace *vmspace = p->p_vmspace;
 1069         vm_object_t obj;
 1070         struct rlimit rlim_stack;
 1071         vm_offset_t sv_minuser, stack_addr;
 1072         vm_map_t map;
 1073         u_long ssiz;
 1074 
 1075         imgp->vmspace_destroyed = 1;
 1076         imgp->sysent = sv;
 1077 
 1078         /* May be called with Giant held */
 1079         EVENTHANDLER_INVOKE(process_exec, p, imgp);
 1080 
 1081         /*
 1082          * Blow away entire process VM, if address space not shared,
 1083          * otherwise, create a new VM space so that other threads are
 1084          * not disrupted
 1085          */
 1086         map = &vmspace->vm_map;
 1087         if (map_at_zero)
 1088                 sv_minuser = sv->sv_minuser;
 1089         else
 1090                 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
 1091         if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
 1092             vm_map_max(map) == sv->sv_maxuser) {
 1093                 shmexit(vmspace);
 1094                 pmap_remove_pages(vmspace_pmap(vmspace));
 1095                 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
 1096         } else {
 1097                 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
 1098                 if (error)
 1099                         return (error);
 1100                 vmspace = p->p_vmspace;
 1101                 map = &vmspace->vm_map;
 1102         }
 1103 
 1104         /* Map a shared page */
 1105         obj = sv->sv_shared_page_obj;
 1106         if (obj != NULL) {
 1107                 vm_object_reference(obj);
 1108                 error = vm_map_fixed(map, obj, 0,
 1109                     sv->sv_shared_page_base, sv->sv_shared_page_len,
 1110                     VM_PROT_READ | VM_PROT_EXECUTE,
 1111                     VM_PROT_READ | VM_PROT_EXECUTE,
 1112                     MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
 1113                 if (error) {
 1114                         vm_object_deallocate(obj);
 1115                         return (error);
 1116                 }
 1117         }
 1118 
 1119         /* Allocate a new stack */
 1120         if (imgp->stack_sz != 0) {
 1121                 ssiz = trunc_page(imgp->stack_sz);
 1122                 PROC_LOCK(p);
 1123                 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
 1124                 PROC_UNLOCK(p);
 1125                 if (ssiz > rlim_stack.rlim_max)
 1126                         ssiz = rlim_stack.rlim_max;
 1127                 if (ssiz > rlim_stack.rlim_cur) {
 1128                         rlim_stack.rlim_cur = ssiz;
 1129                         kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
 1130                 }
 1131         } else if (sv->sv_maxssiz != NULL) {
 1132                 ssiz = *sv->sv_maxssiz;
 1133         } else {
 1134                 ssiz = maxssiz;
 1135         }
 1136         stack_addr = sv->sv_usrstack - ssiz;
 1137         error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
 1138             obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
 1139                 sv->sv_stackprot,
 1140             VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
 1141         if (error)
 1142                 return (error);
 1143 
 1144         /*
 1145          * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
 1146          * are still used to enforce the stack rlimit on the process stack.
 1147          */
 1148         vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
 1149         vmspace->vm_maxsaddr = (char *)stack_addr;
 1150 
 1151         return (0);
 1152 }
 1153 
 1154 /*
 1155  * Copy out argument and environment strings from the old process address
 1156  * space into the temporary string buffer.
 1157  */
 1158 int
 1159 exec_copyin_args(struct image_args *args, char *fname,
 1160     enum uio_seg segflg, char **argv, char **envv)
 1161 {
 1162         u_long argp, envp;
 1163         int error;
 1164         size_t length;
 1165 
 1166         bzero(args, sizeof(*args));
 1167         if (argv == NULL)
 1168                 return (EFAULT);
 1169 
 1170         /*
 1171          * Allocate demand-paged memory for the file name, argument, and
 1172          * environment strings.
 1173          */
 1174         error = exec_alloc_args(args);
 1175         if (error != 0)
 1176                 return (error);
 1177 
 1178         /*
 1179          * Copy the file name.
 1180          */
 1181         if (fname != NULL) {
 1182                 args->fname = args->buf;
 1183                 error = (segflg == UIO_SYSSPACE) ?
 1184                     copystr(fname, args->fname, PATH_MAX, &length) :
 1185                     copyinstr(fname, args->fname, PATH_MAX, &length);
 1186                 if (error != 0)
 1187                         goto err_exit;
 1188         } else
 1189                 length = 0;
 1190 
 1191         args->begin_argv = args->buf + length;
 1192         args->endp = args->begin_argv;
 1193         args->stringspace = ARG_MAX;
 1194 
 1195         /*
 1196          * extract arguments first
 1197          */
 1198         for (;;) {
 1199                 error = fueword(argv++, &argp);
 1200                 if (error == -1) {
 1201                         error = EFAULT;
 1202                         goto err_exit;
 1203                 }
 1204                 if (argp == 0)
 1205                         break;
 1206                 error = copyinstr((void *)(uintptr_t)argp, args->endp,
 1207                     args->stringspace, &length);
 1208                 if (error != 0) {
 1209                         if (error == ENAMETOOLONG) 
 1210                                 error = E2BIG;
 1211                         goto err_exit;
 1212                 }
 1213                 args->stringspace -= length;
 1214                 args->endp += length;
 1215                 args->argc++;
 1216         }
 1217 
 1218         args->begin_envv = args->endp;
 1219 
 1220         /*
 1221          * extract environment strings
 1222          */
 1223         if (envv) {
 1224                 for (;;) {
 1225                         error = fueword(envv++, &envp);
 1226                         if (error == -1) {
 1227                                 error = EFAULT;
 1228                                 goto err_exit;
 1229                         }
 1230                         if (envp == 0)
 1231                                 break;
 1232                         error = copyinstr((void *)(uintptr_t)envp,
 1233                             args->endp, args->stringspace, &length);
 1234                         if (error != 0) {
 1235                                 if (error == ENAMETOOLONG)
 1236                                         error = E2BIG;
 1237                                 goto err_exit;
 1238                         }
 1239                         args->stringspace -= length;
 1240                         args->endp += length;
 1241                         args->envc++;
 1242                 }
 1243         }
 1244 
 1245         return (0);
 1246 
 1247 err_exit:
 1248         exec_free_args(args);
 1249         return (error);
 1250 }
 1251 
 1252 int
 1253 exec_copyin_data_fds(struct thread *td, struct image_args *args,
 1254     const void *data, size_t datalen, const int *fds, size_t fdslen)
 1255 {
 1256         struct filedesc *ofdp;
 1257         const char *p;
 1258         int *kfds;
 1259         int error;
 1260 
 1261         memset(args, '\0', sizeof(*args));
 1262         ofdp = td->td_proc->p_fd;
 1263         if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
 1264                 return (E2BIG);
 1265         error = exec_alloc_args(args);
 1266         if (error != 0)
 1267                 return (error);
 1268 
 1269         args->begin_argv = args->buf;
 1270         args->stringspace = ARG_MAX;
 1271 
 1272         if (datalen > 0) {
 1273                 /*
 1274                  * Argument buffer has been provided. Copy it into the
 1275                  * kernel as a single string and add a terminating null
 1276                  * byte.
 1277                  */
 1278                 error = copyin(data, args->begin_argv, datalen);
 1279                 if (error != 0)
 1280                         goto err_exit;
 1281                 args->begin_argv[datalen] = '\0';
 1282                 args->endp = args->begin_argv + datalen + 1;
 1283                 args->stringspace -= datalen + 1;
 1284 
 1285                 /*
 1286                  * Traditional argument counting. Count the number of
 1287                  * null bytes.
 1288                  */
 1289                 for (p = args->begin_argv; p < args->endp; ++p)
 1290                         if (*p == '\0')
 1291                                 ++args->argc;
 1292         } else {
 1293                 /* No argument buffer provided. */
 1294                 args->endp = args->begin_argv;
 1295         }
 1296         /* There are no environment variables. */
 1297         args->begin_envv = args->endp;
 1298 
 1299         /* Create new file descriptor table. */
 1300         kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
 1301         error = copyin(fds, kfds, fdslen * sizeof(int));
 1302         if (error != 0) {
 1303                 free(kfds, M_TEMP);
 1304                 goto err_exit;
 1305         }
 1306         error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
 1307         free(kfds, M_TEMP);
 1308         if (error != 0)
 1309                 goto err_exit;
 1310 
 1311         return (0);
 1312 err_exit:
 1313         exec_free_args(args);
 1314         return (error);
 1315 }
 1316 
 1317 /*
 1318  * Allocate temporary demand-paged, zero-filled memory for the file name,
 1319  * argument, and environment strings.  Returns zero if the allocation succeeds
 1320  * and ENOMEM otherwise.
 1321  */
 1322 int
 1323 exec_alloc_args(struct image_args *args)
 1324 {
 1325 
 1326         args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
 1327         return (args->buf != NULL ? 0 : ENOMEM);
 1328 }
 1329 
 1330 void
 1331 exec_free_args(struct image_args *args)
 1332 {
 1333 
 1334         if (args->buf != NULL) {
 1335                 kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
 1336                     PATH_MAX + ARG_MAX);
 1337                 args->buf = NULL;
 1338         }
 1339         if (args->fname_buf != NULL) {
 1340                 free(args->fname_buf, M_TEMP);
 1341                 args->fname_buf = NULL;
 1342         }
 1343         if (args->fdp != NULL)
 1344                 fdescfree_remapped(args->fdp);
 1345 }
 1346 
 1347 /*
 1348  * Copy strings out to the new process address space, constructing new arg
 1349  * and env vector tables. Return a pointer to the base so that it can be used
 1350  * as the initial stack pointer.
 1351  */
 1352 register_t *
 1353 exec_copyout_strings(imgp)
 1354         struct image_params *imgp;
 1355 {
 1356         int argc, envc;
 1357         char **vectp;
 1358         char *stringp;
 1359         uintptr_t destp;
 1360         register_t *stack_base;
 1361         struct ps_strings *arginfo;
 1362         struct proc *p;
 1363         size_t execpath_len;
 1364         int szsigcode, szps;
 1365         char canary[sizeof(long) * 8];
 1366 
 1367         szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
 1368         /*
 1369          * Calculate string base and vector table pointers.
 1370          * Also deal with signal trampoline code for this exec type.
 1371          */
 1372         if (imgp->execpath != NULL && imgp->auxargs != NULL)
 1373                 execpath_len = strlen(imgp->execpath) + 1;
 1374         else
 1375                 execpath_len = 0;
 1376         p = imgp->proc;
 1377         szsigcode = 0;
 1378         arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
 1379         if (p->p_sysent->sv_sigcode_base == 0) {
 1380                 if (p->p_sysent->sv_szsigcode != NULL)
 1381                         szsigcode = *(p->p_sysent->sv_szsigcode);
 1382         }
 1383         destp = (uintptr_t)arginfo;
 1384 
 1385         /*
 1386          * install sigcode
 1387          */
 1388         if (szsigcode != 0) {
 1389                 destp -= szsigcode;
 1390                 destp = rounddown2(destp, sizeof(void *));
 1391                 copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
 1392         }
 1393 
 1394         /*
 1395          * Copy the image path for the rtld.
 1396          */
 1397         if (execpath_len != 0) {
 1398                 destp -= execpath_len;
 1399                 imgp->execpathp = destp;
 1400                 copyout(imgp->execpath, (void *)destp, execpath_len);
 1401         }
 1402 
 1403         /*
 1404          * Prepare the canary for SSP.
 1405          */
 1406         arc4rand(canary, sizeof(canary), 0);
 1407         destp -= sizeof(canary);
 1408         imgp->canary = destp;
 1409         copyout(canary, (void *)destp, sizeof(canary));
 1410         imgp->canarylen = sizeof(canary);
 1411 
 1412         /*
 1413          * Prepare the pagesizes array.
 1414          */
 1415         destp -= szps;
 1416         destp = rounddown2(destp, sizeof(void *));
 1417         imgp->pagesizes = destp;
 1418         copyout(pagesizes, (void *)destp, szps);
 1419         imgp->pagesizeslen = szps;
 1420 
 1421         destp -= ARG_MAX - imgp->args->stringspace;
 1422         destp = rounddown2(destp, sizeof(void *));
 1423 
 1424         /*
 1425          * If we have a valid auxargs ptr, prepare some room
 1426          * on the stack.
 1427          */
 1428         if (imgp->auxargs) {
 1429                 /*
 1430                  * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
 1431                  * lower compatibility.
 1432                  */
 1433                 imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
 1434                     (AT_COUNT * 2);
 1435                 /*
 1436                  * The '+ 2' is for the null pointers at the end of each of
 1437                  * the arg and env vector sets,and imgp->auxarg_size is room
 1438                  * for argument of Runtime loader.
 1439                  */
 1440                 vectp = (char **)(destp - (imgp->args->argc +
 1441                     imgp->args->envc + 2 + imgp->auxarg_size)
 1442                     * sizeof(char *));
 1443         } else {
 1444                 /*
 1445                  * The '+ 2' is for the null pointers at the end of each of
 1446                  * the arg and env vector sets
 1447                  */
 1448                 vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
 1449                     + 2) * sizeof(char *));
 1450         }
 1451 
 1452         /*
 1453          * vectp also becomes our initial stack base
 1454          */
 1455         stack_base = (register_t *)vectp;
 1456 
 1457         stringp = imgp->args->begin_argv;
 1458         argc = imgp->args->argc;
 1459         envc = imgp->args->envc;
 1460 
 1461         /*
 1462          * Copy out strings - arguments and environment.
 1463          */
 1464         copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
 1465 
 1466         /*
 1467          * Fill in "ps_strings" struct for ps, w, etc.
 1468          */
 1469         suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
 1470         suword32(&arginfo->ps_nargvstr, argc);
 1471 
 1472         /*
 1473          * Fill in argument portion of vector table.
 1474          */
 1475         for (; argc > 0; --argc) {
 1476                 suword(vectp++, (long)(intptr_t)destp);
 1477                 while (*stringp++ != 0)
 1478                         destp++;
 1479                 destp++;
 1480         }
 1481 
 1482         /* a null vector table pointer separates the argp's from the envp's */
 1483         suword(vectp++, 0);
 1484 
 1485         suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
 1486         suword32(&arginfo->ps_nenvstr, envc);
 1487 
 1488         /*
 1489          * Fill in environment portion of vector table.
 1490          */
 1491         for (; envc > 0; --envc) {
 1492                 suword(vectp++, (long)(intptr_t)destp);
 1493                 while (*stringp++ != 0)
 1494                         destp++;
 1495                 destp++;
 1496         }
 1497 
 1498         /* end of vector table is a null pointer */
 1499         suword(vectp, 0);
 1500 
 1501         return (stack_base);
 1502 }
 1503 
 1504 /*
 1505  * Check permissions of file to execute.
 1506  *      Called with imgp->vp locked.
 1507  *      Return 0 for success or error code on failure.
 1508  */
 1509 int
 1510 exec_check_permissions(imgp)
 1511         struct image_params *imgp;
 1512 {
 1513         struct vnode *vp = imgp->vp;
 1514         struct vattr *attr = imgp->attr;
 1515         struct thread *td;
 1516         int error, writecount;
 1517 
 1518         td = curthread;
 1519 
 1520         /* Get file attributes */
 1521         error = VOP_GETATTR(vp, attr, td->td_ucred);
 1522         if (error)
 1523                 return (error);
 1524 
 1525 #ifdef MAC
 1526         error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
 1527         if (error)
 1528                 return (error);
 1529 #endif
 1530 
 1531         /*
 1532          * 1) Check if file execution is disabled for the filesystem that
 1533          *    this file resides on.
 1534          * 2) Ensure that at least one execute bit is on. Otherwise, a
 1535          *    privileged user will always succeed, and we don't want this
 1536          *    to happen unless the file really is executable.
 1537          * 3) Ensure that the file is a regular file.
 1538          */
 1539         if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
 1540             (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
 1541             (attr->va_type != VREG))
 1542                 return (EACCES);
 1543 
 1544         /*
 1545          * Zero length files can't be exec'd
 1546          */
 1547         if (attr->va_size == 0)
 1548                 return (ENOEXEC);
 1549 
 1550         /*
 1551          *  Check for execute permission to file based on current credentials.
 1552          */
 1553         error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
 1554         if (error)
 1555                 return (error);
 1556 
 1557         /*
 1558          * Check number of open-for-writes on the file and deny execution
 1559          * if there are any.
 1560          */
 1561         error = VOP_GET_WRITECOUNT(vp, &writecount);
 1562         if (error != 0)
 1563                 return (error);
 1564         if (writecount != 0)
 1565                 return (ETXTBSY);
 1566 
 1567         /*
 1568          * Call filesystem specific open routine (which does nothing in the
 1569          * general case).
 1570          */
 1571         error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
 1572         if (error == 0)
 1573                 imgp->opened = 1;
 1574         return (error);
 1575 }
 1576 
 1577 /*
 1578  * Exec handler registration
 1579  */
 1580 int
 1581 exec_register(execsw_arg)
 1582         const struct execsw *execsw_arg;
 1583 {
 1584         const struct execsw **es, **xs, **newexecsw;
 1585         int count = 2;  /* New slot and trailing NULL */
 1586 
 1587         if (execsw)
 1588                 for (es = execsw; *es; es++)
 1589                         count++;
 1590         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
 1591         xs = newexecsw;
 1592         if (execsw)
 1593                 for (es = execsw; *es; es++)
 1594                         *xs++ = *es;
 1595         *xs++ = execsw_arg;
 1596         *xs = NULL;
 1597         if (execsw)
 1598                 free(execsw, M_TEMP);
 1599         execsw = newexecsw;
 1600         return (0);
 1601 }
 1602 
 1603 int
 1604 exec_unregister(execsw_arg)
 1605         const struct execsw *execsw_arg;
 1606 {
 1607         const struct execsw **es, **xs, **newexecsw;
 1608         int count = 1;
 1609 
 1610         if (execsw == NULL)
 1611                 panic("unregister with no handlers left?\n");
 1612 
 1613         for (es = execsw; *es; es++) {
 1614                 if (*es == execsw_arg)
 1615                         break;
 1616         }
 1617         if (*es == NULL)
 1618                 return (ENOENT);
 1619         for (es = execsw; *es; es++)
 1620                 if (*es != execsw_arg)
 1621                         count++;
 1622         newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
 1623         xs = newexecsw;
 1624         for (es = execsw; *es; es++)
 1625                 if (*es != execsw_arg)
 1626                         *xs++ = *es;
 1627         *xs = NULL;
 1628         if (execsw)
 1629                 free(execsw, M_TEMP);
 1630         execsw = newexecsw;
 1631         return (0);
 1632 }

Cache object: b79fb12239fd7398aaf68866edcd1c65


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.