3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)eval.c 8.9 (Berkeley) 6/8/95
37 * $FreeBSD: src/bin/sh/eval.c,v 1.53 2006/06/15 07:57:05 stefanf Exp $
38 * $DragonFly: src/bin/sh/eval.c,v 1.10 2007/01/07 01:14:53 pavalos Exp $
41 #include <sys/resource.h>
42 #include <sys/wait.h> /* For WIFSIGNALED(status) */
74 #include "myhistedit.h"
78 /* flags in argument to evaltree */
79 #define EV_EXIT 01 /* exit after evaluating tree */
80 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
81 #define EV_BACKCMD 04 /* command executing within back quotes */
83 int evalskip; /* set if we are skipping commands */
84 STATIC int skipcount; /* number of levels to skip */
85 MKINIT int loopnest; /* current loop nesting level */
86 int funcnest; /* depth of function calls */
89 const char *commandname;
90 struct strlist *cmdenviron;
91 int exitstatus; /* exit status of last command */
92 int oexitstatus; /* saved exit status */
95 STATIC void evalloop(union node *, int);
96 STATIC void evalfor(union node *, int);
97 STATIC void evalcase(union node *, int);
98 STATIC void evalsubshell(union node *, int);
99 STATIC void expredir(union node *);
100 STATIC void evalpipe(union node *);
101 STATIC void evalcommand(union node *, int, struct backcmd *);
102 STATIC void prehash(union node *);
106 * Called to reset things after an exception.
130 evalcmd(int argc, char **argv)
139 STARTSTACKSTR(concat);
143 STPUTC(*p++, concat);
144 if ((p = *ap++) == NULL)
148 STPUTC('\0', concat);
149 p = grabstackstr(concat);
158 * Execute a command or commands contained in a string.
165 struct stackmark smark;
167 setstackmark(&smark);
168 setinputstring(s, 1);
169 while ((n = parsecmd(0)) != NEOF) {
171 popstackmark(&smark);
174 popstackmark(&smark);
180 * Evaluate a parse tree. The value is left in the global variable
185 evaltree(union node *n, int flags)
191 TRACE(("evaltree(NULL) called\n"));
196 displayhist = 1; /* show history substitutions done with fc */
198 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
201 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
204 evaltree(n->nbinary.ch2, flags);
207 evaltree(n->nbinary.ch1, EV_TESTED);
208 if (evalskip || exitstatus != 0) {
211 evaltree(n->nbinary.ch2, flags);
214 evaltree(n->nbinary.ch1, EV_TESTED);
215 if (evalskip || exitstatus == 0)
217 evaltree(n->nbinary.ch2, flags);
220 expredir(n->nredir.redirect);
221 redirect(n->nredir.redirect, REDIR_PUSH);
222 evaltree(n->nredir.n, flags);
226 evalsubshell(n, flags);
227 do_etest = !(flags & EV_TESTED);
230 evalsubshell(n, flags);
233 evaltree(n->nif.test, EV_TESTED);
237 evaltree(n->nif.ifpart, flags);
238 else if (n->nif.elsepart)
239 evaltree(n->nif.elsepart, flags);
246 evalloop(n, flags & ~EV_EXIT);
249 evalfor(n, flags & ~EV_EXIT);
255 defun(n->narg.text, n->narg.next);
259 evaltree(n->nnot.com, EV_TESTED);
260 exitstatus = !exitstatus;
265 do_etest = !(flags & EV_TESTED);
268 evalcommand(n, flags, (struct backcmd *)NULL);
269 do_etest = !(flags & EV_TESTED);
272 out1fmt("Node type = %d\n", n->type);
279 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
280 exitshell(exitstatus);
285 evalloop(union node *n, int flags)
292 evaltree(n->nbinary.ch1, EV_TESTED);
294 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
298 if (evalskip == SKIPBREAK && --skipcount <= 0)
302 if (n->type == NWHILE) {
309 evaltree(n->nbinary.ch2, flags);
321 evalfor(union node *n, int flags)
323 struct arglist arglist;
326 struct stackmark smark;
328 setstackmark(&smark);
329 arglist.lastp = &arglist.list;
330 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
331 oexitstatus = exitstatus;
332 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
336 *arglist.lastp = NULL;
340 for (sp = arglist.list ; sp ; sp = sp->next) {
341 setvar(n->nfor.var, sp->text, 0);
342 evaltree(n->nfor.body, flags);
344 if (evalskip == SKIPCONT && --skipcount <= 0) {
348 if (evalskip == SKIPBREAK && --skipcount <= 0)
355 popstackmark(&smark);
361 evalcase(union node *n, int flags)
365 struct arglist arglist;
366 struct stackmark smark;
368 setstackmark(&smark);
369 arglist.lastp = &arglist.list;
370 oexitstatus = exitstatus;
371 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
372 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
373 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
374 if (casematch(patp, arglist.list->text)) {
376 evaltree(cp->nclist.body, flags);
383 popstackmark(&smark);
389 * Kick off a subshell to evaluate a tree.
393 evalsubshell(union node *n, int flags)
396 int backgnd = (n->type == NBACKGND);
398 expredir(n->nredir.redirect);
400 if (forkshell(jp, n, backgnd) == 0) {
403 redirect(n->nredir.redirect, 0);
404 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
408 exitstatus = waitforjob(jp, (int *)NULL);
416 * Compute the names of the files in a redirection list.
420 expredir(union node *n)
424 for (redir = n ; redir ; redir = redir->nfile.next) {
427 oexitstatus = exitstatus;
428 switch (redir->type) {
434 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
435 redir->nfile.expfname = fn.list->text;
439 if (redir->ndup.vname) {
440 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
441 fixredir(redir, fn.list->text, 1);
451 * Evaluate a pipeline. All the processes in the pipeline are children
452 * of the process creating the pipeline. (This differs from some versions
453 * of the shell, which make the last process in a pipeline the parent
458 evalpipe(union node *n)
466 TRACE(("evalpipe(%p) called\n", (void *)n));
468 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
471 jp = makejob(n, pipelen);
473 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
480 error("Pipe call failed: %s", strerror(errno));
483 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
490 if (!(prevfd >= 0 && pip[0] == 0))
497 evaltree(lp->n, EV_EXIT);
505 if (n->npipe.backgnd == 0) {
507 exitstatus = waitforjob(jp, (int *)NULL);
508 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
516 * Execute a command inside back quotes. If it's a builtin command, we
517 * want to save its output in a block obtained from malloc. Otherwise
518 * we fork off a subprocess and get the output of the command via a pipe.
519 * Should be called with interrupts off.
523 evalbackcmd(union node *n, struct backcmd *result)
527 struct stackmark smark; /* unnecessary */
529 setstackmark(&smark);
538 if (n->type == NCMD) {
539 exitstatus = oexitstatus;
540 evalcommand(n, EV_BACKCMD, result);
544 error("Pipe call failed: %s", strerror(errno));
546 if (forkshell(jp, n, FORK_NOJOB) == 0) {
553 evaltree(n, EV_EXIT);
560 popstackmark(&smark);
561 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
562 result->fd, result->buf, result->nleft, result->jp));
568 * Execute a simple command.
572 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
574 struct stackmark smark;
576 struct arglist arglist;
577 struct arglist varlist;
585 struct cmdentry cmdentry;
587 struct jmploc jmploc;
588 struct jmploc *volatile savehandler = NULL;
589 const char *volatile savecmdname;
590 volatile struct shparam saveparam;
591 struct localvar *volatile savelocalvars;
595 int do_clearcmdentry;
597 /* Avoid longjmp clobbering */
602 (void) &do_clearcmdentry;
605 /* First expand the arguments. */
606 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
607 setstackmark(&smark);
608 arglist.lastp = &arglist.list;
609 varlist.lastp = &varlist.list;
611 do_clearcmdentry = 0;
612 oexitstatus = exitstatus;
614 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
615 char *p = argp->narg.text;
616 if (varflag && is_name(*p)) {
619 } while (is_in_name(*p));
621 expandarg(argp, &varlist, EXP_VARTILDE);
625 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
628 *arglist.lastp = NULL;
629 *varlist.lastp = NULL;
630 expredir(cmd->ncmd.redirect);
632 for (sp = arglist.list ; sp ; sp = sp->next)
634 argv = stalloc(sizeof (char *) * (argc + 1));
636 for (sp = arglist.list ; sp ; sp = sp->next) {
637 TRACE(("evalcommand arg: %s\n", sp->text));
642 if (iflag && funcnest == 0 && argc > 0)
646 /* Print the command if xflag is set. */
650 for (sp = varlist.list ; sp ; sp = sp->next) {
656 for (sp = arglist.list ; sp ; sp = sp->next) {
666 /* Now locate the command. */
668 /* Variable assignment(s) without command */
669 cmdentry.cmdtype = CMDBUILTIN;
670 cmdentry.u.index = BLTINCMD;
671 cmdentry.special = 1;
673 static const char PATH[] = "PATH=";
674 const char *path = pathval();
677 * Modify the command lookup path, if a PATH= assignment
680 for (sp = varlist.list ; sp ; sp = sp->next)
681 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
682 path = sp->text + sizeof(PATH) - 1;
684 * On `PATH=... command`, we need to make
685 * sure that the command isn't using the
686 * non-updated hash table of the outer PATH
687 * setting and we need to make sure that
688 * the hash table isn't filled with items
689 * from the temporary setting.
691 * It would be better to forbit using and
692 * updating the table while this command
693 * runs, by the command finding mechanism
694 * is heavily integrated with hash handling,
695 * so we just delete the hash before and after
696 * the command runs. Partly deleting like
697 * changepatch() does doesn't seem worth the
698 * bookinging effort, since most such runs add
699 * directories in front of the new PATH.
702 do_clearcmdentry = 1;
705 find_command(argv[0], &cmdentry, 1, path);
706 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
711 /* implement the bltin builtin here */
712 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
717 if ((cmdentry.u.index = find_builtin(*argv,
718 &cmdentry.special)) < 0) {
719 outfmt(&errout, "%s: not found\n", *argv);
724 if (cmdentry.u.index != BLTINCMD)
730 /* Fork off a child process if necessary. */
731 if (cmd->ncmd.backgnd
732 || (cmdentry.cmdtype == CMDNORMAL
733 && ((flags & EV_EXIT) == 0 || Tflag))
734 || ((flags & EV_BACKCMD) != 0
735 && (cmdentry.cmdtype != CMDBUILTIN
736 || cmdentry.u.index == CDCMD
737 || cmdentry.u.index == DOTCMD
738 || cmdentry.u.index == EVALCMD))
739 || (cmdentry.cmdtype == CMDBUILTIN &&
740 cmdentry.u.index == COMMANDCMD)) {
741 jp = makejob(cmd, 1);
742 mode = cmd->ncmd.backgnd;
743 if (flags & EV_BACKCMD) {
746 error("Pipe call failed: %s", strerror(errno));
748 if (forkshell(jp, cmd, mode) != 0)
749 goto parent; /* at end of routine */
750 if (flags & EV_BACKCMD) {
761 /* This is the child process if a fork occurred. */
762 /* Execute the command. */
763 if (cmdentry.cmdtype == CMDFUNCTION) {
765 trputs("Shell function: "); trargs(argv);
767 redirect(cmd->ncmd.redirect, REDIR_PUSH);
768 saveparam = shellparam;
769 shellparam.malloc = 0;
770 shellparam.reset = 1;
771 shellparam.nparam = argc - 1;
772 shellparam.p = argv + 1;
773 shellparam.optnext = NULL;
775 savelocalvars = localvars;
778 if (setjmp(jmploc.loc)) {
779 if (exception == EXSHELLPROC)
780 freeparam(&saveparam);
782 freeparam(&shellparam);
783 shellparam = saveparam;
786 localvars = savelocalvars;
787 handler = savehandler;
788 longjmp(handler->loc, 1);
790 savehandler = handler;
792 for (sp = varlist.list ; sp ; sp = sp->next)
795 if (flags & EV_TESTED)
796 evaltree(cmdentry.u.func, EV_TESTED);
798 evaltree(cmdentry.u.func, 0);
802 localvars = savelocalvars;
803 freeparam(&shellparam);
804 shellparam = saveparam;
805 handler = savehandler;
808 if (evalskip == SKIPFUNC) {
813 exitshell(exitstatus);
814 } else if (cmdentry.cmdtype == CMDBUILTIN) {
816 trputs("builtin command: "); trargs(argv);
818 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
819 if (flags == EV_BACKCMD) {
821 memout.nextc = memout.buf;
825 savecmdname = commandname;
826 cmdenviron = varlist.list;
828 if (setjmp(jmploc.loc)) {
830 exitstatus = (e == EXINT)? SIGINT+128 : 2;
833 savehandler = handler;
835 redirect(cmd->ncmd.redirect, mode);
836 if (cmdentry.special)
837 listsetvar(cmdenviron);
838 commandname = argv[0];
840 optptr = NULL; /* initialize nextopt */
841 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
848 if (e != EXSHELLPROC) {
849 commandname = savecmdname;
850 if (flags & EV_EXIT) {
851 exitshell(exitstatus);
854 handler = savehandler;
856 if ((e != EXERROR && e != EXEXEC)
861 if (cmdentry.u.index != EXECCMD)
863 if (flags == EV_BACKCMD) {
864 backcmd->buf = memout.buf;
865 backcmd->nleft = memout.nextc - memout.buf;
870 trputs("normal command: "); trargs(argv);
873 redirect(cmd->ncmd.redirect, 0);
874 for (sp = varlist.list ; sp ; sp = sp->next)
875 setvareq(sp->text, VEXPORT|VSTACK);
876 envp = environment();
877 shellexec(argv, envp, pathval(), cmdentry.u.index);
882 parent: /* parent process gets here (if we forked) */
883 if (mode == 0) { /* argument to fork */
885 exitstatus = waitforjob(jp, &realstatus);
887 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
888 evalskip = SKIPBREAK;
889 skipcount = loopnest;
891 } else if (mode == 2) {
892 backcmd->fd = pip[0];
899 setvar("_", lastarg, 0);
900 if (do_clearcmdentry)
902 popstackmark(&smark);
908 * Search for a command. This is called before we fork so that the
909 * location of the command will be available in the parent as well as
910 * the child. The check for "goodname" is an overly conservative
911 * check that the name will not be subject to expansion.
915 prehash(union node *n)
917 struct cmdentry entry;
919 if (n && n->type == NCMD && n->ncmd.args)
920 if (goodname(n->ncmd.args->narg.text))
921 find_command(n->ncmd.args->narg.text, &entry, 0,
928 * Builtin commands. Builtin commands whose functions are closely
929 * tied to evaluation are implemented here.
933 * No command given, or a bltin command with no arguments.
937 bltincmd(int argc __unused, char **argv __unused)
940 * Preserve exitstatus of a previous possible redirection
948 * Handle break and continue commands. Break, continue, and return are
949 * all handled by setting the evalskip flag. The evaluation routines
950 * above all check this flag, and if it is set they start skipping
951 * commands rather than executing them. The variable skipcount is
952 * the number of loops to break/continue, or the number of function
953 * levels to return. (The latter is always 1.) It should probably
954 * be an error to break out of more loops than exist, but it isn't
955 * in the standard shell so we don't make it one here.
959 breakcmd(int argc, char **argv)
961 int n = argc > 1 ? number(argv[1]) : 1;
966 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
973 * The `command' command.
976 commandcmd(int argc, char **argv)
978 static char stdpath[] = _PATH_STDPATH;
979 struct jmploc loc, *old;
986 /* Avoid longjmp clobbering */
992 for (sp = cmdenviron; sp ; sp = sp->next)
993 setvareq(sp->text, VEXPORT|VSTACK);
996 optind = optreset = 1;
998 while ((ch = getopt(argc, argv, "pvV")) != -1) {
1004 cmd = TYPECMD_SMALLV;
1011 error("unknown option: -%c", optopt);
1019 error("wrong number of arguments");
1020 return typecmd_impl(2, argv - 1, cmd);
1025 if (setjmp(handler->loc) == 0)
1026 shellexec(argv, environment(), path, 0);
1028 if (exception == EXEXEC)
1034 * Do nothing successfully if no command was specified;
1035 * ksh also does this.
1042 * The return command.
1046 returncmd(int argc, char **argv)
1048 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1051 evalskip = SKIPFUNC;
1054 /* skip the rest of the file */
1055 evalskip = SKIPFILE;
1063 falsecmd(int argc __unused, char **argv __unused)
1070 truecmd(int argc __unused, char **argv __unused)
1077 execcmd(int argc, char **argv)
1082 iflag = 0; /* exit on error */
1085 for (sp = cmdenviron; sp ; sp = sp->next)
1086 setvareq(sp->text, VEXPORT|VSTACK);
1087 shellexec(argv + 1, environment(), pathval(), 0);
1095 timescmd(int argc __unused, char **argv __unused)
1098 long shumins, shsmins, chumins, chsmins;
1099 double shusecs, shssecs, chusecs, chssecs;
1101 if (getrusage(RUSAGE_SELF, &ru) < 0)
1103 shumins = ru.ru_utime.tv_sec / 60;
1104 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1105 shsmins = ru.ru_stime.tv_sec / 60;
1106 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1107 if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1109 chumins = ru.ru_utime.tv_sec / 60;
1110 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1111 chsmins = ru.ru_stime.tv_sec / 60;
1112 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1113 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1114 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);