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 expredir(union node *);
95 static void evalpipe(union node *);
96 static void evalcommand(union node *, int, struct backcmd *);
97 static void prehash(union node *);
101 * Called to reset things after an exception.
125 evalcmd(int argc, char **argv)
134 STARTSTACKSTR(concat);
138 STPUTC(*p++, concat);
139 if ((p = *ap++) == NULL)
143 STPUTC('\0', concat);
144 p = grabstackstr(concat);
146 evalstring(p, builtin_flags & EV_TESTED);
153 * Execute a command or commands contained in a string.
157 evalstring(char *s, int flags)
160 struct stackmark smark;
163 flags_exit = flags & EV_EXIT;
165 setstackmark(&smark);
166 setinputstring(s, 1);
167 while ((n = parsecmd(0)) != NEOF) {
169 if (flags_exit && preadateof())
170 evaltree(n, flags | EV_EXIT);
174 popstackmark(&smark);
177 popstackmark(&smark);
179 exitshell(exitstatus);
184 * Evaluate a parse tree. The value is left in the global variable
189 evaltree(union node *n, int flags)
195 TRACE(("evaltree(NULL) called\n"));
200 displayhist = 1; /* show history substitutions done with fc */
202 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
205 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
208 evaltree(n->nbinary.ch2, flags);
211 evaltree(n->nbinary.ch1, EV_TESTED);
212 if (evalskip || exitstatus != 0) {
215 evaltree(n->nbinary.ch2, flags);
218 evaltree(n->nbinary.ch1, EV_TESTED);
219 if (evalskip || exitstatus == 0)
221 evaltree(n->nbinary.ch2, flags);
224 expredir(n->nredir.redirect);
225 redirect(n->nredir.redirect, REDIR_PUSH);
226 evaltree(n->nredir.n, flags);
230 evalsubshell(n, flags);
231 do_etest = !(flags & EV_TESTED);
234 evalsubshell(n, flags);
237 evaltree(n->nif.test, EV_TESTED);
241 evaltree(n->nif.ifpart, flags);
242 else if (n->nif.elsepart)
243 evaltree(n->nif.elsepart, flags);
250 evalloop(n, flags & ~EV_EXIT);
253 evalfor(n, flags & ~EV_EXIT);
259 defun(n->narg.text, n->narg.next);
263 evaltree(n->nnot.com, EV_TESTED);
264 exitstatus = !exitstatus;
269 do_etest = !(flags & EV_TESTED);
272 evalcommand(n, flags, (struct backcmd *)NULL);
273 do_etest = !(flags & EV_TESTED);
276 out1fmt("Node type = %d\n", n->type);
283 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
284 exitshell(exitstatus);
289 evalloop(union node *n, int flags)
296 evaltree(n->nbinary.ch1, EV_TESTED);
298 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
302 if (evalskip == SKIPBREAK && --skipcount <= 0)
306 if (n->type == NWHILE) {
313 evaltree(n->nbinary.ch2, flags);
325 evalfor(union node *n, int flags)
327 struct arglist arglist;
330 struct stackmark smark;
332 setstackmark(&smark);
333 arglist.lastp = &arglist.list;
334 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
335 oexitstatus = exitstatus;
336 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
340 *arglist.lastp = NULL;
344 for (sp = arglist.list ; sp ; sp = sp->next) {
345 setvar(n->nfor.var, sp->text, 0);
346 evaltree(n->nfor.body, flags);
348 if (evalskip == SKIPCONT && --skipcount <= 0) {
352 if (evalskip == SKIPBREAK && --skipcount <= 0)
359 popstackmark(&smark);
365 evalcase(union node *n, int flags)
369 struct arglist arglist;
370 struct stackmark smark;
372 setstackmark(&smark);
373 arglist.lastp = &arglist.list;
374 oexitstatus = exitstatus;
376 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
377 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
378 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
379 if (casematch(patp, arglist.list->text)) {
381 evaltree(cp->nclist.body, flags);
388 popstackmark(&smark);
394 * Kick off a subshell to evaluate a tree.
398 evalsubshell(union node *n, int flags)
401 int backgnd = (n->type == NBACKGND);
403 expredir(n->nredir.redirect);
404 if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
405 forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
408 redirect(n->nredir.redirect, 0);
409 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
410 } else if (! backgnd) {
412 exitstatus = waitforjob(jp, (int *)NULL);
420 * Compute the names of the files in a redirection list.
424 expredir(union node *n)
428 for (redir = n ; redir ; redir = redir->nfile.next) {
431 oexitstatus = exitstatus;
432 switch (redir->type) {
438 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
439 redir->nfile.expfname = fn.list->text;
443 if (redir->ndup.vname) {
444 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
445 fixredir(redir, fn.list->text, 1);
455 * Evaluate a pipeline. All the processes in the pipeline are children
456 * of the process creating the pipeline. (This differs from some versions
457 * of the shell, which make the last process in a pipeline the parent
462 evalpipe(union node *n)
470 TRACE(("evalpipe(%p) called\n", (void *)n));
472 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
475 jp = makejob(n, pipelen);
477 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
483 error("Pipe call failed: %s", strerror(errno));
486 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
493 if (!(prevfd >= 0 && pip[0] == 0))
500 evaltree(lp->n, EV_EXIT);
508 if (n->npipe.backgnd == 0) {
510 exitstatus = waitforjob(jp, (int *)NULL);
511 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
519 * Execute a command inside back quotes. If it's a builtin command, we
520 * want to save its output in a block obtained from malloc. Otherwise
521 * we fork off a subprocess and get the output of the command via a pipe.
522 * Should be called with interrupts off.
526 evalbackcmd(union node *n, struct backcmd *result)
530 struct stackmark smark; /* unnecessary */
532 setstackmark(&smark);
541 if (n->type == NCMD) {
542 exitstatus = oexitstatus;
543 evalcommand(n, EV_BACKCMD, result);
547 error("Pipe call failed: %s", strerror(errno));
549 if (forkshell(jp, n, FORK_NOJOB) == 0) {
556 evaltree(n, EV_EXIT);
563 popstackmark(&smark);
564 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
565 result->fd, result->buf, result->nleft, result->jp));
571 * Execute a simple command.
575 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
577 struct stackmark smark;
579 struct arglist arglist;
580 struct arglist varlist;
588 struct cmdentry cmdentry;
590 struct jmploc jmploc;
591 struct jmploc *savehandler;
593 struct shparam saveparam;
594 struct localvar *savelocalvars;
598 int do_clearcmdentry;
600 /* First expand the arguments. */
601 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
602 setstackmark(&smark);
603 arglist.lastp = &arglist.list;
604 varlist.lastp = &varlist.list;
606 do_clearcmdentry = 0;
607 oexitstatus = exitstatus;
609 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
610 char *p = argp->narg.text;
611 if (varflag && is_name(*p)) {
614 } while (is_in_name(*p));
616 expandarg(argp, &varlist, EXP_VARTILDE);
620 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
623 *arglist.lastp = NULL;
624 *varlist.lastp = NULL;
625 expredir(cmd->ncmd.redirect);
627 for (sp = arglist.list ; sp ; sp = sp->next)
629 argv = stalloc(sizeof (char *) * (argc + 1));
631 for (sp = arglist.list ; sp ; sp = sp->next) {
632 TRACE(("evalcommand arg: %s\n", sp->text));
637 if (iflag && funcnest == 0 && argc > 0)
641 /* Print the command if xflag is set. */
646 for (sp = varlist.list ; sp ; sp = sp->next) {
650 while (*p != '=' && *p != '\0')
658 for (sp = arglist.list ; sp ; sp = sp->next) {
661 /* Disambiguate command looking like assignment. */
662 if (sp == arglist.list &&
663 strchr(sp->text, '=') != NULL &&
664 strchr(sp->text, '\'') == NULL) {
676 /* Now locate the command. */
678 /* Variable assignment(s) without command */
679 cmdentry.cmdtype = CMDBUILTIN;
680 cmdentry.u.index = BLTINCMD;
681 cmdentry.special = 1;
683 static const char PATH[] = "PATH=";
684 char *path = pathval();
687 * Modify the command lookup path, if a PATH= assignment
690 for (sp = varlist.list ; sp ; sp = sp->next)
691 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
692 path = sp->text + sizeof(PATH) - 1;
694 * On `PATH=... command`, we need to make
695 * sure that the command isn't using the
696 * non-updated hash table of the outer PATH
697 * setting and we need to make sure that
698 * the hash table isn't filled with items
699 * from the temporary setting.
701 * It would be better to forbit using and
702 * updating the table while this command
703 * runs, by the command finding mechanism
704 * is heavily integrated with hash handling,
705 * so we just delete the hash before and after
706 * the command runs. Partly deleting like
707 * changepatch() does doesn't seem worth the
708 * bookinging effort, since most such runs add
709 * directories in front of the new PATH.
712 do_clearcmdentry = 1;
715 find_command(argv[0], &cmdentry, 1, path);
716 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
721 /* implement the bltin builtin here */
722 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
727 if ((cmdentry.u.index = find_builtin(*argv,
728 &cmdentry.special)) < 0) {
729 outfmt(&errout, "%s: not found\n", *argv);
734 if (cmdentry.u.index != BLTINCMD)
740 /* Fork off a child process if necessary. */
741 if (cmd->ncmd.backgnd
742 || (cmdentry.cmdtype == CMDNORMAL
743 && ((flags & EV_EXIT) == 0 || have_traps()))
744 || ((flags & EV_BACKCMD) != 0
745 && (cmdentry.cmdtype != CMDBUILTIN
746 || cmdentry.u.index == CDCMD
747 || cmdentry.u.index == DOTCMD
748 || cmdentry.u.index == EVALCMD))
749 || (cmdentry.cmdtype == CMDBUILTIN &&
750 cmdentry.u.index == COMMANDCMD)) {
751 jp = makejob(cmd, 1);
752 mode = cmd->ncmd.backgnd;
753 if (flags & EV_BACKCMD) {
756 error("Pipe call failed: %s", strerror(errno));
758 if (forkshell(jp, cmd, mode) != 0)
759 goto parent; /* at end of routine */
760 if (flags & EV_BACKCMD) {
771 /* This is the child process if a fork occurred. */
772 /* Execute the command. */
773 if (cmdentry.cmdtype == CMDFUNCTION) {
775 trputs("Shell function: "); trargs(argv);
777 redirect(cmd->ncmd.redirect, REDIR_PUSH);
778 saveparam = shellparam;
779 shellparam.malloc = 0;
780 shellparam.reset = 1;
781 shellparam.nparam = argc - 1;
782 shellparam.p = argv + 1;
783 shellparam.optnext = NULL;
785 savelocalvars = localvars;
787 reffunc(cmdentry.u.func);
789 savehandler = handler;
790 if (setjmp(jmploc.loc)) {
791 if (exception == EXSHELLPROC)
792 freeparam(&saveparam);
794 freeparam(&shellparam);
795 shellparam = saveparam;
797 unreffunc(cmdentry.u.func);
799 localvars = savelocalvars;
800 handler = savehandler;
801 longjmp(handler->loc, 1);
804 for (sp = varlist.list ; sp ; sp = sp->next)
807 exitstatus = oexitstatus;
808 if (flags & EV_TESTED)
809 evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
811 evaltree(getfuncnode(cmdentry.u.func), 0);
814 unreffunc(cmdentry.u.func);
816 localvars = savelocalvars;
817 freeparam(&shellparam);
818 shellparam = saveparam;
819 handler = savehandler;
822 if (evalskip == SKIPFUNC) {
827 exitshell(exitstatus);
828 } else if (cmdentry.cmdtype == CMDBUILTIN) {
830 trputs("builtin command: "); trargs(argv);
832 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
833 if (flags == EV_BACKCMD) {
835 memout.nextc = memout.buf;
839 savecmdname = commandname;
840 cmdenviron = varlist.list;
842 savehandler = handler;
843 if (setjmp(jmploc.loc)) {
845 exitstatus = (e == EXINT)? SIGINT+128 : 2;
849 redirect(cmd->ncmd.redirect, mode);
850 if (cmdentry.special)
851 listsetvar(cmdenviron);
852 commandname = argv[0];
854 nextopt_optptr = NULL; /* initialize nextopt */
855 builtin_flags = flags;
856 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
863 if (e != EXSHELLPROC) {
864 commandname = savecmdname;
865 if (flags & EV_EXIT) {
866 exitshell(exitstatus);
869 handler = savehandler;
871 if ((e != EXERROR && e != EXEXEC)
876 if (cmdentry.u.index != EXECCMD)
878 if (flags == EV_BACKCMD) {
879 backcmd->buf = memout.buf;
880 backcmd->nleft = memout.nextc - memout.buf;
885 trputs("normal command: "); trargs(argv);
888 redirect(cmd->ncmd.redirect, 0);
889 for (sp = varlist.list ; sp ; sp = sp->next)
890 setvareq(sp->text, VEXPORT|VSTACK);
891 envp = environment();
892 shellexec(argv, envp, pathval(), cmdentry.u.index);
897 parent: /* parent process gets here (if we forked) */
898 if (mode == FORK_FG) { /* argument to fork */
900 exitstatus = waitforjob(jp, &realstatus);
902 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
903 evalskip = SKIPBREAK;
904 skipcount = loopnest;
906 } else if (mode == FORK_NOJOB) {
907 backcmd->fd = pip[0];
914 setvar("_", lastarg, 0);
915 if (do_clearcmdentry)
917 popstackmark(&smark);
923 * Search for a command. This is called before we fork so that the
924 * location of the command will be available in the parent as well as
925 * the child. The check for "goodname" is an overly conservative
926 * check that the name will not be subject to expansion.
930 prehash(union node *n)
932 struct cmdentry entry;
934 if (n && n->type == NCMD && n->ncmd.args)
935 if (goodname(n->ncmd.args->narg.text))
936 find_command(n->ncmd.args->narg.text, &entry, 0,
943 * Builtin commands. Builtin commands whose functions are closely
944 * tied to evaluation are implemented here.
948 * No command given, or a bltin command with no arguments.
952 bltincmd(int argc __unused, char **argv __unused)
955 * Preserve exitstatus of a previous possible redirection
963 * Handle break and continue commands. Break, continue, and return are
964 * all handled by setting the evalskip flag. The evaluation routines
965 * above all check this flag, and if it is set they start skipping
966 * commands rather than executing them. The variable skipcount is
967 * the number of loops to break/continue, or the number of function
968 * levels to return. (The latter is always 1.) It should probably
969 * be an error to break out of more loops than exist, but it isn't
970 * in the standard shell so we don't make it one here.
974 breakcmd(int argc, char **argv)
976 int n = argc > 1 ? number(argv[1]) : 1;
981 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
988 * The `command' command.
991 commandcmd(int argc, char **argv)
993 static char stdpath[] = _PATH_STDPATH;
994 struct jmploc loc, *old;
1000 for (sp = cmdenviron; sp ; sp = sp->next)
1001 setvareq(sp->text, VEXPORT|VSTACK);
1004 optind = optreset = 1;
1006 while ((ch = getopt(argc, argv, "pvV")) != -1) {
1012 cmd = TYPECMD_SMALLV;
1019 error("unknown option: -%c", optopt);
1027 error("wrong number of arguments");
1028 return typecmd_impl(2, argv - 1, cmd);
1033 if (setjmp(handler->loc) == 0)
1034 shellexec(argv, environment(), path, 0);
1036 if (exception == EXEXEC)
1042 * Do nothing successfully if no command was specified;
1043 * ksh also does this.
1050 * The return command.
1054 returncmd(int argc, char **argv)
1056 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1059 evalskip = SKIPFUNC;
1062 /* skip the rest of the file */
1063 evalskip = SKIPFILE;
1071 falsecmd(int argc __unused, char **argv __unused)
1078 truecmd(int argc __unused, char **argv __unused)
1085 execcmd(int argc, char **argv)
1090 iflag = 0; /* exit on error */
1093 for (sp = cmdenviron; sp ; sp = sp->next)
1094 setvareq(sp->text, VEXPORT|VSTACK);
1095 shellexec(argv + 1, environment(), pathval(), 0);
1103 timescmd(int argc __unused, char **argv __unused)
1106 long shumins, shsmins, chumins, chsmins;
1107 double shusecs, shssecs, chusecs, chssecs;
1109 if (getrusage(RUSAGE_SELF, &ru) < 0)
1111 shumins = ru.ru_utime.tv_sec / 60;
1112 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1113 shsmins = ru.ru_stime.tv_sec / 60;
1114 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1115 if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1117 chumins = ru.ru_utime.tv_sec / 60;
1118 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1119 chsmins = ru.ru_stime.tv_sec / 60;
1120 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1121 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1122 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);