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 int evalskip; /* set if we are skipping commands */
78 STATIC int skipcount; /* number of levels to skip */
79 MKINIT int loopnest; /* current loop nesting level */
80 int funcnest; /* depth of function calls */
81 STATIC int builtin_flags; /* evalcommand flags for builtins */
85 struct strlist *cmdenviron;
86 int exitstatus; /* exit status of last command */
87 int oexitstatus; /* saved exit status */
90 STATIC void evalloop(union node *, int);
91 STATIC void evalfor(union node *, int);
92 STATIC void evalcase(union node *, int);
93 STATIC void evalsubshell(union node *, int);
94 STATIC void evalredir(union node *, int);
95 STATIC void expredir(union node *);
96 STATIC void evalpipe(union node *);
97 STATIC void evalcommand(union node *, int, struct backcmd *);
98 STATIC void prehash(union node *);
102 * Called to reset things after an exception.
126 evalcmd(int argc, char **argv)
135 STARTSTACKSTR(concat);
139 STPUTC(*p++, concat);
140 if ((p = *ap++) == NULL)
144 STPUTC('\0', concat);
145 p = grabstackstr(concat);
147 evalstring(p, builtin_flags & EV_TESTED);
155 * Execute a command or commands contained in a string.
159 evalstring(char *s, int flags)
162 struct stackmark smark;
166 flags_exit = flags & EV_EXIT;
169 setstackmark(&smark);
170 setinputstring(s, 1);
171 while ((n = parsecmd(0)) != NEOF) {
173 if (flags_exit && preadateof())
174 evaltree(n, flags | EV_EXIT);
179 popstackmark(&smark);
182 popstackmark(&smark);
186 exitshell(exitstatus);
191 * Evaluate a parse tree. The value is left in the global variable
196 evaltree(union node *n, int flags)
202 TRACE(("evaltree(NULL) called\n"));
207 displayhist = 1; /* show history substitutions done with fc */
209 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
212 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
215 evaltree(n->nbinary.ch2, flags);
218 evaltree(n->nbinary.ch1, EV_TESTED);
219 if (evalskip || exitstatus != 0) {
222 evaltree(n->nbinary.ch2, flags);
225 evaltree(n->nbinary.ch1, EV_TESTED);
226 if (evalskip || exitstatus == 0)
228 evaltree(n->nbinary.ch2, flags);
234 evalsubshell(n, flags);
235 do_etest = !(flags & EV_TESTED);
238 evalsubshell(n, flags);
241 evaltree(n->nif.test, EV_TESTED);
245 evaltree(n->nif.ifpart, flags);
246 else if (n->nif.elsepart)
247 evaltree(n->nif.elsepart, flags);
254 evalloop(n, flags & ~EV_EXIT);
257 evalfor(n, flags & ~EV_EXIT);
263 defun(n->narg.text, n->narg.next);
267 evaltree(n->nnot.com, EV_TESTED);
268 exitstatus = !exitstatus;
273 do_etest = !(flags & EV_TESTED);
276 evalcommand(n, flags, (struct backcmd *)NULL);
277 do_etest = !(flags & EV_TESTED);
280 out1fmt("Node type = %d\n", n->type);
287 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
288 exitshell(exitstatus);
293 evalloop(union node *n, int flags)
300 evaltree(n->nbinary.ch1, EV_TESTED);
302 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
306 if (evalskip == SKIPBREAK && --skipcount <= 0)
310 if (n->type == NWHILE) {
317 evaltree(n->nbinary.ch2, flags);
329 evalfor(union node *n, int flags)
331 struct arglist arglist;
334 struct stackmark smark;
336 setstackmark(&smark);
337 arglist.lastp = &arglist.list;
338 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
339 oexitstatus = exitstatus;
340 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
344 *arglist.lastp = NULL;
348 for (sp = arglist.list ; sp ; sp = sp->next) {
349 setvar(n->nfor.var, sp->text, 0);
350 evaltree(n->nfor.body, flags);
352 if (evalskip == SKIPCONT && --skipcount <= 0) {
356 if (evalskip == SKIPBREAK && --skipcount <= 0)
363 popstackmark(&smark);
369 evalcase(union node *n, int flags)
373 struct arglist arglist;
374 struct stackmark smark;
376 setstackmark(&smark);
377 arglist.lastp = &arglist.list;
378 oexitstatus = exitstatus;
380 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
381 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
382 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
383 if (casematch(patp, arglist.list->text)) {
385 evaltree(cp->nclist.body, flags);
392 popstackmark(&smark);
398 * Kick off a subshell to evaluate a tree.
402 evalsubshell(union node *n, int flags)
405 int backgnd = (n->type == NBACKGND);
407 expredir(n->nredir.redirect);
408 if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
409 forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
412 redirect(n->nredir.redirect, 0);
413 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
414 } else if (! backgnd) {
416 exitstatus = waitforjob(jp, (int *)NULL);
423 * Evaluate a redirected compound command.
427 evalredir(union node *n, int flags)
429 struct jmploc jmploc;
430 struct jmploc *savehandler;
431 volatile int in_redirect = 1;
433 expredir(n->nredir.redirect);
434 savehandler = handler;
435 if (setjmp(jmploc.loc)) {
438 handler = savehandler;
440 if (e == EXERROR || e == EXEXEC) {
447 longjmp(handler->loc, 1);
451 redirect(n->nredir.redirect, REDIR_PUSH);
454 evaltree(n->nredir.n, flags);
457 handler = savehandler;
464 * Compute the names of the files in a redirection list.
468 expredir(union node *n)
472 for (redir = n ; redir ; redir = redir->nfile.next) {
475 oexitstatus = exitstatus;
476 switch (redir->type) {
482 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
483 redir->nfile.expfname = fn.list->text;
487 if (redir->ndup.vname) {
488 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
489 fixredir(redir, fn.list->text, 1);
499 * Evaluate a pipeline. All the processes in the pipeline are children
500 * of the process creating the pipeline. (This differs from some versions
501 * of the shell, which make the last process in a pipeline the parent
506 evalpipe(union node *n)
514 TRACE(("evalpipe(%p) called\n", (void *)n));
516 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
519 jp = makejob(n, pipelen);
521 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
527 error("Pipe call failed: %s", strerror(errno));
530 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
537 if (!(prevfd >= 0 && pip[0] == 0))
544 evaltree(lp->n, EV_EXIT);
552 if (n->npipe.backgnd == 0) {
554 exitstatus = waitforjob(jp, (int *)NULL);
555 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
563 * Execute a command inside back quotes. If it's a builtin command, we
564 * want to save its output in a block obtained from malloc. Otherwise
565 * we fork off a subprocess and get the output of the command via a pipe.
566 * Should be called with interrupts off.
570 evalbackcmd(union node *n, struct backcmd *result)
574 struct stackmark smark; /* unnecessary */
576 setstackmark(&smark);
585 if (n->type == NCMD) {
586 exitstatus = oexitstatus;
587 evalcommand(n, EV_BACKCMD, result);
591 error("Pipe call failed: %s", strerror(errno));
593 if (forkshell(jp, n, FORK_NOJOB) == 0) {
600 evaltree(n, EV_EXIT);
607 popstackmark(&smark);
608 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
609 result->fd, result->buf, result->nleft, result->jp));
615 * Execute a simple command.
619 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
621 struct stackmark smark;
623 struct arglist arglist;
624 struct arglist varlist;
632 struct cmdentry cmdentry;
634 struct jmploc jmploc;
635 struct jmploc *savehandler;
637 struct shparam saveparam;
638 struct localvar *savelocalvars;
639 struct parsefile *savetopfile;
643 int do_clearcmdentry;
644 char *path = pathval();
646 /* First expand the arguments. */
647 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
648 setstackmark(&smark);
649 arglist.lastp = &arglist.list;
650 varlist.lastp = &varlist.list;
652 do_clearcmdentry = 0;
653 oexitstatus = exitstatus;
655 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
656 char *p = argp->narg.text;
657 if (varflag && is_name(*p)) {
660 } while (is_in_name(*p));
662 expandarg(argp, &varlist, EXP_VARTILDE);
666 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
669 *arglist.lastp = NULL;
670 *varlist.lastp = NULL;
671 expredir(cmd->ncmd.redirect);
673 for (sp = arglist.list ; sp ; sp = sp->next)
675 argv = stalloc(sizeof (char *) * (argc + 1));
677 for (sp = arglist.list ; sp ; sp = sp->next) {
678 TRACE(("evalcommand arg: %s\n", sp->text));
683 if (iflag && funcnest == 0 && argc > 0)
687 /* Print the command if xflag is set. */
692 for (sp = varlist.list ; sp ; sp = sp->next) {
696 while (*p != '=' && *p != '\0')
704 for (sp = arglist.list ; sp ; sp = sp->next) {
707 /* Disambiguate command looking like assignment. */
708 if (sp == arglist.list &&
709 strchr(sp->text, '=') != NULL &&
710 strchr(sp->text, '\'') == NULL) {
722 /* Now locate the command. */
724 /* Variable assignment(s) without command */
725 cmdentry.cmdtype = CMDBUILTIN;
726 cmdentry.u.index = BLTINCMD;
727 cmdentry.special = 0;
729 static const char PATH[] = "PATH=";
730 int cmd_flags = 0, bltinonly = 0;
733 * Modify the command lookup path, if a PATH= assignment
736 for (sp = varlist.list ; sp ; sp = sp->next)
737 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
738 path = sp->text + sizeof(PATH) - 1;
740 * On `PATH=... command`, we need to make
741 * sure that the command isn't using the
742 * non-updated hash table of the outer PATH
743 * setting and we need to make sure that
744 * the hash table isn't filled with items
745 * from the temporary setting.
747 * It would be better to forbit using and
748 * updating the table while this command
749 * runs, by the command finding mechanism
750 * is heavily integrated with hash handling,
751 * so we just delete the hash before and after
752 * the command runs. Partly deleting like
753 * changepatch() does doesn't seem worth the
754 * bookinging effort, since most such runs add
755 * directories in front of the new PATH.
758 do_clearcmdentry = 1;
763 cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
764 if (cmdentry.u.index < 0) {
765 cmdentry.u.index = BLTINCMD;
771 find_command(argv[0], &cmdentry, cmd_flags, path);
772 /* implement the bltin and command builtins here */
773 if (cmdentry.cmdtype != CMDBUILTIN)
775 if (cmdentry.u.index == BLTINCMD) {
781 } else if (cmdentry.u.index == COMMANDCMD) {
784 if (!strcmp(argv[1], "-p")) {
787 if (argv[2][0] == '-') {
788 if (strcmp(argv[2], "--"))
798 path = _PATH_STDPATH;
800 do_clearcmdentry = 1;
801 } else if (!strcmp(argv[1], "--")) {
806 } else if (argv[1][0] == '-')
812 cmd_flags |= DO_NOFUNC;
818 * Special builtins lose their special properties when
819 * called via 'command'.
821 if (cmd_flags & DO_NOFUNC)
822 cmdentry.special = 0;
825 /* Fork off a child process if necessary. */
826 if (cmd->ncmd.backgnd
827 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
828 && ((flags & EV_EXIT) == 0 || have_traps()))
829 || ((flags & EV_BACKCMD) != 0
830 && (cmdentry.cmdtype != CMDBUILTIN
831 || cmdentry.u.index == CDCMD
832 || cmdentry.u.index == DOTCMD
833 || cmdentry.u.index == EVALCMD))) {
834 jp = makejob(cmd, 1);
835 mode = cmd->ncmd.backgnd;
836 if (flags & EV_BACKCMD) {
839 error("Pipe call failed: %s", strerror(errno));
841 if (forkshell(jp, cmd, mode) != 0)
842 goto parent; /* at end of routine */
843 if (flags & EV_BACKCMD) {
854 /* This is the child process if a fork occurred. */
855 /* Execute the command. */
856 if (cmdentry.cmdtype == CMDFUNCTION) {
858 trputs("Shell function: "); trargs(argv);
860 saveparam = shellparam;
861 shellparam.malloc = 0;
862 shellparam.reset = 1;
863 shellparam.nparam = argc - 1;
864 shellparam.p = argv + 1;
865 shellparam.optnext = NULL;
867 savelocalvars = localvars;
869 reffunc(cmdentry.u.func);
870 savehandler = handler;
871 if (setjmp(jmploc.loc)) {
872 if (exception == EXSHELLPROC)
873 freeparam(&saveparam);
875 freeparam(&shellparam);
876 shellparam = saveparam;
877 if (exception == EXERROR || exception == EXEXEC)
880 unreffunc(cmdentry.u.func);
882 localvars = savelocalvars;
884 handler = savehandler;
885 longjmp(handler->loc, 1);
889 redirect(cmd->ncmd.redirect, REDIR_PUSH);
891 for (sp = varlist.list ; sp ; sp = sp->next)
893 exitstatus = oexitstatus;
894 if (flags & EV_TESTED)
895 evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
897 evaltree(getfuncnode(cmdentry.u.func), 0);
899 unreffunc(cmdentry.u.func);
901 localvars = savelocalvars;
902 freeparam(&shellparam);
903 shellparam = saveparam;
904 handler = savehandler;
908 if (evalskip == SKIPFUNC) {
913 exitshell(exitstatus);
914 } else if (cmdentry.cmdtype == CMDBUILTIN) {
916 trputs("builtin command: "); trargs(argv);
918 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
919 if (flags == EV_BACKCMD) {
921 memout.nextc = memout.buf;
924 cmdentry.special = 0;
926 savecmdname = commandname;
927 savetopfile = getcurrentfile();
928 cmdenviron = varlist.list;
930 savehandler = handler;
931 if (setjmp(jmploc.loc)) {
933 exitstatus = (e == EXINT)? SIGINT+128 : 2;
937 redirect(cmd->ncmd.redirect, mode);
939 * If there is no command word, redirection errors should
940 * not be fatal but assignment errors should.
942 if (argc == 0 && !(flags & EV_BACKCMD))
943 cmdentry.special = 1;
944 if (cmdentry.special)
945 listsetvar(cmdenviron);
948 commandname = argv[0];
950 nextopt_optptr = NULL; /* initialize nextopt */
951 builtin_flags = flags;
952 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
961 if (e != EXSHELLPROC) {
962 commandname = savecmdname;
963 if (flags & EV_EXIT) {
964 exitshell(exitstatus);
967 handler = savehandler;
968 if (flags == EV_BACKCMD) {
969 backcmd->buf = memout.buf;
970 backcmd->nleft = memout.nextc - memout.buf;
973 if (cmdentry.u.index != EXECCMD &&
974 (e == -1 || e == EXERROR || e == EXEXEC))
977 if ((e != EXERROR && e != EXEXEC)
980 popfilesupto(savetopfile);
981 if (flags != EV_BACKCMD)
986 trputs("normal command: "); trargs(argv);
988 redirect(cmd->ncmd.redirect, 0);
989 for (sp = varlist.list ; sp ; sp = sp->next)
990 setvareq(sp->text, VEXPORT|VSTACK);
991 envp = environment();
992 shellexec(argv, envp, path, cmdentry.u.index);
997 parent: /* parent process gets here (if we forked) */
998 if (mode == 0) { /* argument to fork */
1000 exitstatus = waitforjob(jp, &realstatus);
1002 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1003 evalskip = SKIPBREAK;
1004 skipcount = loopnest;
1006 } else if (mode == 2) {
1007 backcmd->fd = pip[0];
1014 setvar("_", lastarg, 0);
1015 if (do_clearcmdentry)
1017 popstackmark(&smark);
1023 * Search for a command. This is called before we fork so that the
1024 * location of the command will be available in the parent as well as
1025 * the child. The check for "goodname" is an overly conservative
1026 * check that the name will not be subject to expansion.
1030 prehash(union node *n)
1032 struct cmdentry entry;
1034 if (n && n->type == NCMD && n->ncmd.args)
1035 if (goodname(n->ncmd.args->narg.text))
1036 find_command(n->ncmd.args->narg.text, &entry, 0,
1043 * Builtin commands. Builtin commands whose functions are closely
1044 * tied to evaluation are implemented here.
1048 * No command given, a bltin command with no arguments, or a bltin command
1049 * with an invalid name.
1053 bltincmd(int argc, char **argv)
1056 out2fmt_flush("%s: not found\n", argv[1]);
1060 * Preserve exitstatus of a previous possible redirection
1068 * Handle break and continue commands. Break, continue, and return are
1069 * all handled by setting the evalskip flag. The evaluation routines
1070 * above all check this flag, and if it is set they start skipping
1071 * commands rather than executing them. The variable skipcount is
1072 * the number of loops to break/continue, or the number of function
1073 * levels to return. (The latter is always 1.) It should probably
1074 * be an error to break out of more loops than exist, but it isn't
1075 * in the standard shell so we don't make it one here.
1079 breakcmd(int argc, char **argv)
1081 int n = argc > 1 ? number(argv[1]) : 1;
1086 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1093 * The `command' command.
1096 commandcmd(int argc, char **argv)
1102 path = bltinlookup("PATH", 1);
1104 optind = optreset = 1;
1106 while ((ch = getopt(argc, argv, "pvV")) != -1) {
1109 path = _PATH_STDPATH;
1112 cmd = TYPECMD_SMALLV;
1119 error("unknown option: -%c", optopt);
1127 error("wrong number of arguments");
1128 return typecmd_impl(2, argv - 1, cmd, path);
1131 error("commandcmd() called while it should not be");
1134 * Do nothing successfully if no command was specified;
1135 * ksh also does this.
1142 * The return command.
1146 returncmd(int argc, char **argv)
1148 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1151 evalskip = SKIPFUNC;
1154 /* skip the rest of the file */
1155 evalskip = SKIPFILE;
1163 falsecmd(int argc __unused, char **argv __unused)
1170 truecmd(int argc __unused, char **argv __unused)
1177 execcmd(int argc, char **argv)
1180 * Because we have historically not supported any options,
1181 * only treat "--" specially.
1183 if (argc > 1 && strcmp(argv[1], "--") == 0)
1188 iflag = 0; /* exit on error */
1191 for (sp = cmdenviron; sp ; sp = sp->next)
1192 setvareq(sp->text, VEXPORT|VSTACK);
1193 shellexec(argv + 1, environment(), pathval(), 0);
1201 timescmd(int argc __unused, char **argv __unused)
1204 long shumins, shsmins, chumins, chsmins;
1205 double shusecs, shssecs, chusecs, chssecs;
1207 if (getrusage(RUSAGE_SELF, &ru) < 0)
1209 shumins = ru.ru_utime.tv_sec / 60;
1210 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1211 shsmins = ru.ru_stime.tv_sec / 60;
1212 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1213 if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1215 chumins = ru.ru_utime.tv_sec / 60;
1216 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1217 chsmins = ru.ru_stime.tv_sec / 60;
1218 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1219 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1220 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);