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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 static char sccsid[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95";
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
45 #include <sys/resource.h>
46 #include <sys/wait.h> /* For WIFSIGNALED(status) */
73 #include "myhistedit.h"
77 /* flags in argument to evaltree */
78 #define EV_EXIT 01 /* exit after evaluating tree */
79 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
80 #define EV_BACKCMD 04 /* command executing within back quotes */
82 MKINIT int evalskip; /* set if we are skipping commands */
83 STATIC int skipcount; /* number of levels to skip */
84 MKINIT int loopnest; /* current loop nesting level */
85 int funcnest; /* depth of function calls */
89 struct strlist *cmdenviron;
90 int exitstatus; /* exit status of last command */
91 int oexitstatus; /* saved exit status */
94 STATIC void evalloop(union node *, int);
95 STATIC void evalfor(union node *, int);
96 STATIC void evalcase(union node *, int);
97 STATIC void evalsubshell(union node *, int);
98 STATIC void expredir(union node *);
99 STATIC void evalpipe(union node *);
100 STATIC void evalcommand(union node *, int, struct backcmd *);
101 STATIC void prehash(union node *);
105 * Called to reset things after an exception.
129 evalcmd(int argc, char **argv)
138 STARTSTACKSTR(concat);
142 STPUTC(*p++, concat);
143 if ((p = *ap++) == NULL)
147 STPUTC('\0', concat);
148 p = grabstackstr(concat);
157 * Execute a command or commands contained in a string.
164 struct stackmark smark;
166 setstackmark(&smark);
167 setinputstring(s, 1);
168 while ((n = parsecmd(0)) != NEOF) {
170 popstackmark(&smark);
173 popstackmark(&smark);
179 * Evaluate a parse tree. The value is left in the global variable
184 evaltree(union node *n, int flags)
190 TRACE(("evaltree(NULL) called\n"));
195 displayhist = 1; /* show history substitutions done with fc */
197 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
200 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
203 evaltree(n->nbinary.ch2, flags);
206 evaltree(n->nbinary.ch1, EV_TESTED);
207 if (evalskip || exitstatus != 0) {
210 evaltree(n->nbinary.ch2, flags);
213 evaltree(n->nbinary.ch1, EV_TESTED);
214 if (evalskip || exitstatus == 0)
216 evaltree(n->nbinary.ch2, flags);
219 expredir(n->nredir.redirect);
220 redirect(n->nredir.redirect, REDIR_PUSH);
221 evaltree(n->nredir.n, flags);
225 evalsubshell(n, flags);
226 do_etest = !(flags & EV_TESTED);
229 evalsubshell(n, flags);
232 evaltree(n->nif.test, EV_TESTED);
236 evaltree(n->nif.ifpart, flags);
237 else if (n->nif.elsepart)
238 evaltree(n->nif.elsepart, flags);
245 evalloop(n, flags & ~EV_EXIT);
248 evalfor(n, flags & ~EV_EXIT);
254 defun(n->narg.text, n->narg.next);
258 evaltree(n->nnot.com, EV_TESTED);
259 exitstatus = !exitstatus;
264 do_etest = !(flags & EV_TESTED);
267 evalcommand(n, flags, (struct backcmd *)NULL);
268 do_etest = !(flags & EV_TESTED);
271 out1fmt("Node type = %d\n", n->type);
278 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
279 exitshell(exitstatus);
284 evalloop(union node *n, int flags)
291 evaltree(n->nbinary.ch1, EV_TESTED);
293 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
297 if (evalskip == SKIPBREAK && --skipcount <= 0)
301 if (n->type == NWHILE) {
308 evaltree(n->nbinary.ch2, flags);
320 evalfor(union node *n, int flags)
322 struct arglist arglist;
325 struct stackmark smark;
327 setstackmark(&smark);
328 arglist.lastp = &arglist.list;
329 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
330 oexitstatus = exitstatus;
331 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
335 *arglist.lastp = NULL;
339 for (sp = arglist.list ; sp ; sp = sp->next) {
340 setvar(n->nfor.var, sp->text, 0);
341 evaltree(n->nfor.body, flags);
343 if (evalskip == SKIPCONT && --skipcount <= 0) {
347 if (evalskip == SKIPBREAK && --skipcount <= 0)
354 popstackmark(&smark);
360 evalcase(union node *n, int flags)
364 struct arglist arglist;
365 struct stackmark smark;
367 setstackmark(&smark);
368 arglist.lastp = &arglist.list;
369 oexitstatus = exitstatus;
370 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
371 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
372 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
373 if (casematch(patp, arglist.list->text)) {
375 evaltree(cp->nclist.body, flags);
382 popstackmark(&smark);
388 * Kick off a subshell to evaluate a tree.
392 evalsubshell(union node *n, int flags)
395 int backgnd = (n->type == NBACKGND);
397 expredir(n->nredir.redirect);
399 if (forkshell(jp, n, backgnd) == 0) {
402 redirect(n->nredir.redirect, 0);
403 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
407 exitstatus = waitforjob(jp, (int *)NULL);
415 * Compute the names of the files in a redirection list.
419 expredir(union node *n)
423 for (redir = n ; redir ; redir = redir->nfile.next) {
426 oexitstatus = exitstatus;
427 switch (redir->type) {
433 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
434 redir->nfile.expfname = fn.list->text;
438 if (redir->ndup.vname) {
439 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
440 fixredir(redir, fn.list->text, 1);
450 * Evaluate a pipeline. All the processes in the pipeline are children
451 * of the process creating the pipeline. (This differs from some versions
452 * of the shell, which make the last process in a pipeline the parent
457 evalpipe(union node *n)
465 TRACE(("evalpipe(%p) called\n", (void *)n));
467 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
470 jp = makejob(n, pipelen);
472 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
478 error("Pipe call failed: %s", strerror(errno));
481 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
488 if (!(prevfd >= 0 && pip[0] == 0))
495 evaltree(lp->n, EV_EXIT);
503 if (n->npipe.backgnd == 0) {
505 exitstatus = waitforjob(jp, (int *)NULL);
506 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
514 * Execute a command inside back quotes. If it's a builtin command, we
515 * want to save its output in a block obtained from malloc. Otherwise
516 * we fork off a subprocess and get the output of the command via a pipe.
517 * Should be called with interrupts off.
521 evalbackcmd(union node *n, struct backcmd *result)
525 struct stackmark smark; /* unnecessary */
527 setstackmark(&smark);
536 if (n->type == NCMD) {
537 exitstatus = oexitstatus;
538 evalcommand(n, EV_BACKCMD, result);
542 error("Pipe call failed: %s", strerror(errno));
544 if (forkshell(jp, n, FORK_NOJOB) == 0) {
551 evaltree(n, EV_EXIT);
558 popstackmark(&smark);
559 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
560 result->fd, result->buf, result->nleft, result->jp));
566 * Execute a simple command.
570 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
572 struct stackmark smark;
574 struct arglist arglist;
575 struct arglist varlist;
583 struct cmdentry cmdentry;
585 struct jmploc jmploc;
586 struct jmploc *volatile savehandler;
587 char *volatile savecmdname;
588 volatile struct shparam saveparam;
589 struct localvar *volatile savelocalvars;
593 int do_clearcmdentry;
595 /* Avoid longjmp clobbering */
600 (void) &do_clearcmdentry;
603 /* First expand the arguments. */
604 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
605 setstackmark(&smark);
606 arglist.lastp = &arglist.list;
607 varlist.lastp = &varlist.list;
609 do_clearcmdentry = 0;
610 oexitstatus = exitstatus;
612 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
613 char *p = argp->narg.text;
614 if (varflag && is_name(*p)) {
617 } while (is_in_name(*p));
619 expandarg(argp, &varlist, EXP_VARTILDE);
623 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
626 *arglist.lastp = NULL;
627 *varlist.lastp = NULL;
628 expredir(cmd->ncmd.redirect);
630 for (sp = arglist.list ; sp ; sp = sp->next)
632 argv = stalloc(sizeof (char *) * (argc + 1));
634 for (sp = arglist.list ; sp ; sp = sp->next) {
635 TRACE(("evalcommand arg: %s\n", sp->text));
640 if (iflag && funcnest == 0 && argc > 0)
644 /* Print the command if xflag is set. */
648 for (sp = varlist.list ; sp ; sp = sp->next) {
654 for (sp = arglist.list ; sp ; sp = sp->next) {
664 /* Now locate the command. */
666 /* Variable assignment(s) without command */
667 cmdentry.cmdtype = CMDBUILTIN;
668 cmdentry.u.index = BLTINCMD;
669 cmdentry.special = 1;
671 static const char PATH[] = "PATH=";
672 char *path = pathval();
675 * Modify the command lookup path, if a PATH= assignment
678 for (sp = varlist.list ; sp ; sp = sp->next)
679 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
680 path = sp->text + sizeof(PATH) - 1;
682 * On `PATH=... command`, we need to make
683 * sure that the command isn't using the
684 * non-updated hash table of the outer PATH
685 * setting and we need to make sure that
686 * the hash table isn't filled with items
687 * from the temporary setting.
689 * It would be better to forbit using and
690 * updating the table while this command
691 * runs, by the command finding mechanism
692 * is heavily integrated with hash handling,
693 * so we just delete the hash before and after
694 * the command runs. Partly deleting like
695 * changepatch() does doesn't seem worth the
696 * bookinging effort, since most such runs add
697 * directories in front of the new PATH.
700 do_clearcmdentry = 1;
703 find_command(argv[0], &cmdentry, 1, path);
704 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
709 /* implement the bltin builtin here */
710 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
715 if ((cmdentry.u.index = find_builtin(*argv,
716 &cmdentry.special)) < 0) {
717 outfmt(&errout, "%s: not found\n", *argv);
722 if (cmdentry.u.index != BLTINCMD)
728 /* Fork off a child process if necessary. */
729 if (cmd->ncmd.backgnd
730 || (cmdentry.cmdtype == CMDNORMAL
731 && ((flags & EV_EXIT) == 0 || Tflag))
732 || ((flags & EV_BACKCMD) != 0
733 && (cmdentry.cmdtype != CMDBUILTIN
734 || cmdentry.u.index == CDCMD
735 || cmdentry.u.index == DOTCMD
736 || cmdentry.u.index == EVALCMD))
737 || (cmdentry.cmdtype == CMDBUILTIN &&
738 cmdentry.u.index == COMMANDCMD)) {
739 jp = makejob(cmd, 1);
740 mode = cmd->ncmd.backgnd;
741 if (flags & EV_BACKCMD) {
744 error("Pipe call failed: %s", strerror(errno));
746 if (forkshell(jp, cmd, mode) != 0)
747 goto parent; /* at end of routine */
748 if (flags & EV_BACKCMD) {
759 /* This is the child process if a fork occurred. */
760 /* Execute the command. */
761 if (cmdentry.cmdtype == CMDFUNCTION) {
763 trputs("Shell function: "); trargs(argv);
765 redirect(cmd->ncmd.redirect, REDIR_PUSH);
766 saveparam = shellparam;
767 shellparam.malloc = 0;
768 shellparam.reset = 1;
769 shellparam.nparam = argc - 1;
770 shellparam.p = argv + 1;
771 shellparam.optnext = NULL;
773 savelocalvars = localvars;
776 if (setjmp(jmploc.loc)) {
777 if (exception == EXSHELLPROC)
778 freeparam((struct shparam *)&saveparam);
780 freeparam(&shellparam);
781 shellparam = saveparam;
784 localvars = savelocalvars;
785 handler = savehandler;
786 longjmp(handler->loc, 1);
788 savehandler = handler;
790 for (sp = varlist.list ; sp ; sp = sp->next)
793 if (flags & EV_TESTED)
794 evaltree(cmdentry.u.func, EV_TESTED);
796 evaltree(cmdentry.u.func, 0);
800 localvars = savelocalvars;
801 freeparam(&shellparam);
802 shellparam = saveparam;
803 handler = savehandler;
806 if (evalskip == SKIPFUNC) {
811 exitshell(exitstatus);
812 } else if (cmdentry.cmdtype == CMDBUILTIN) {
814 trputs("builtin command: "); trargs(argv);
816 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
817 if (flags == EV_BACKCMD) {
819 memout.nextc = memout.buf;
823 savecmdname = commandname;
824 cmdenviron = varlist.list;
826 if (setjmp(jmploc.loc)) {
828 exitstatus = (e == EXINT)? SIGINT+128 : 2;
831 savehandler = handler;
833 redirect(cmd->ncmd.redirect, mode);
834 if (cmdentry.special)
835 listsetvar(cmdenviron);
836 commandname = argv[0];
838 optptr = NULL; /* initialize nextopt */
839 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
846 if (e != EXSHELLPROC) {
847 commandname = savecmdname;
848 if (flags & EV_EXIT) {
849 exitshell(exitstatus);
852 handler = savehandler;
854 if ((e != EXERROR && e != EXEXEC)
859 if (cmdentry.u.index != EXECCMD)
861 if (flags == EV_BACKCMD) {
862 backcmd->buf = memout.buf;
863 backcmd->nleft = memout.nextc - memout.buf;
868 trputs("normal command: "); trargs(argv);
871 redirect(cmd->ncmd.redirect, 0);
872 for (sp = varlist.list ; sp ; sp = sp->next)
873 setvareq(sp->text, VEXPORT|VSTACK);
874 envp = environment();
875 shellexec(argv, envp, pathval(), cmdentry.u.index);
880 parent: /* parent process gets here (if we forked) */
881 if (mode == 0) { /* argument to fork */
883 exitstatus = waitforjob(jp, &realstatus);
885 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
886 evalskip = SKIPBREAK;
887 skipcount = loopnest;
889 } else if (mode == 2) {
890 backcmd->fd = pip[0];
897 setvar("_", lastarg, 0);
898 if (do_clearcmdentry)
900 popstackmark(&smark);
906 * Search for a command. This is called before we fork so that the
907 * location of the command will be available in the parent as well as
908 * the child. The check for "goodname" is an overly conservative
909 * check that the name will not be subject to expansion.
913 prehash(union node *n)
915 struct cmdentry entry;
917 if (n && n->type == NCMD && n->ncmd.args)
918 if (goodname(n->ncmd.args->narg.text))
919 find_command(n->ncmd.args->narg.text, &entry, 0,
926 * Builtin commands. Builtin commands whose functions are closely
927 * tied to evaluation are implemented here.
931 * No command given, or a bltin command with no arguments.
935 bltincmd(int argc __unused, char **argv __unused)
938 * Preserve exitstatus of a previous possible redirection
946 * Handle break and continue commands. Break, continue, and return are
947 * all handled by setting the evalskip flag. The evaluation routines
948 * above all check this flag, and if it is set they start skipping
949 * commands rather than executing them. The variable skipcount is
950 * the number of loops to break/continue, or the number of function
951 * levels to return. (The latter is always 1.) It should probably
952 * be an error to break out of more loops than exist, but it isn't
953 * in the standard shell so we don't make it one here.
957 breakcmd(int argc, char **argv)
959 int n = argc > 1 ? number(argv[1]) : 1;
964 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
971 * The `command' command.
974 commandcmd(int argc, char **argv)
976 static char stdpath[] = _PATH_STDPATH;
977 struct jmploc loc, *old;
983 for (sp = cmdenviron; sp ; sp = sp->next)
984 setvareq(sp->text, VEXPORT|VSTACK);
987 optind = optreset = 1;
989 while ((ch = getopt(argc, argv, "pvV")) != -1) {
995 cmd = TYPECMD_SMALLV;
1002 error("unknown option: -%c", optopt);
1010 error("wrong number of arguments");
1011 return typecmd_impl(2, argv - 1, cmd);
1016 if (setjmp(handler->loc) == 0)
1017 shellexec(argv, environment(), path, 0);
1019 if (exception == EXEXEC)
1025 * Do nothing successfully if no command was specified;
1026 * ksh also does this.
1033 * The return command.
1037 returncmd(int argc, char **argv)
1039 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1042 evalskip = SKIPFUNC;
1045 /* skip the rest of the file */
1046 evalskip = SKIPFILE;
1054 falsecmd(int argc __unused, char **argv __unused)
1061 truecmd(int argc __unused, char **argv __unused)
1068 execcmd(int argc, char **argv)
1073 iflag = 0; /* exit on error */
1076 for (sp = cmdenviron; sp ; sp = sp->next)
1077 setvareq(sp->text, VEXPORT|VSTACK);
1078 shellexec(argv + 1, environment(), pathval(), 0);
1086 timescmd(int argc __unused, char **argv __unused)
1089 long shumins, shsmins, chumins, chsmins;
1090 double shusecs, shssecs, chusecs, chssecs;
1092 if (getrusage(RUSAGE_SELF, &ru) < 0)
1094 shumins = ru.ru_utime.tv_sec / 60;
1095 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1096 shsmins = ru.ru_stime.tv_sec / 60;
1097 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1098 if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1100 chumins = ru.ru_utime.tv_sec / 60;
1101 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1102 chsmins = ru.ru_stime.tv_sec / 60;
1103 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1104 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1105 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);