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 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 oexitstatus = exitstatus;
225 expredir(n->nredir.redirect);
226 redirect(n->nredir.redirect, REDIR_PUSH);
227 evaltree(n->nredir.n, flags);
231 evalsubshell(n, flags);
232 do_etest = !(flags & EV_TESTED);
235 evalsubshell(n, flags);
238 evaltree(n->nif.test, EV_TESTED);
242 evaltree(n->nif.ifpart, flags);
243 else if (n->nif.elsepart)
244 evaltree(n->nif.elsepart, flags);
251 evalloop(n, flags & ~EV_EXIT);
254 evalfor(n, flags & ~EV_EXIT);
260 defun(n->narg.text, n->narg.next);
264 evaltree(n->nnot.com, EV_TESTED);
265 exitstatus = !exitstatus;
270 do_etest = !(flags & EV_TESTED);
273 evalcommand(n, flags, (struct backcmd *)NULL);
274 do_etest = !(flags & EV_TESTED);
277 out1fmt("Node type = %d\n", n->type);
284 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
285 exitshell(exitstatus);
290 evalloop(union node *n, int flags)
297 evaltree(n->nbinary.ch1, EV_TESTED);
299 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
303 if (evalskip == SKIPBREAK && --skipcount <= 0)
307 if (n->type == NWHILE) {
314 evaltree(n->nbinary.ch2, flags);
326 evalfor(union node *n, int flags)
328 struct arglist arglist;
331 struct stackmark smark;
333 setstackmark(&smark);
334 arglist.lastp = &arglist.list;
335 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
336 oexitstatus = exitstatus;
337 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
341 *arglist.lastp = NULL;
345 for (sp = arglist.list ; sp ; sp = sp->next) {
346 setvar(n->nfor.var, sp->text, 0);
347 evaltree(n->nfor.body, flags);
349 if (evalskip == SKIPCONT && --skipcount <= 0) {
353 if (evalskip == SKIPBREAK && --skipcount <= 0)
360 popstackmark(&smark);
366 evalcase(union node *n, int flags)
370 struct arglist arglist;
371 struct stackmark smark;
373 setstackmark(&smark);
374 arglist.lastp = &arglist.list;
375 oexitstatus = exitstatus;
377 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
378 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
379 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
380 if (casematch(patp, arglist.list->text)) {
382 evaltree(cp->nclist.body, flags);
389 popstackmark(&smark);
395 * Kick off a subshell to evaluate a tree.
399 evalsubshell(union node *n, int flags)
402 int backgnd = (n->type == NBACKGND);
404 oexitstatus = exitstatus;
405 expredir(n->nredir.redirect);
406 if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
407 forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
410 redirect(n->nredir.redirect, 0);
411 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
412 } else if (! backgnd) {
414 exitstatus = waitforjob(jp, (int *)NULL);
422 * Compute the names of the files in a redirection list.
426 expredir(union node *n)
430 for (redir = n ; redir ; redir = redir->nfile.next) {
433 switch (redir->type) {
439 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
440 redir->nfile.expfname = fn.list->text;
444 if (redir->ndup.vname) {
445 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
446 fixredir(redir, fn.list->text, 1);
456 * Evaluate a pipeline. All the processes in the pipeline are children
457 * of the process creating the pipeline. (This differs from some versions
458 * of the shell, which make the last process in a pipeline the parent
463 evalpipe(union node *n)
471 TRACE(("evalpipe(%p) called\n", (void *)n));
473 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
476 jp = makejob(n, pipelen);
478 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
484 error("Pipe call failed: %s", strerror(errno));
487 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
494 if (!(prevfd >= 0 && pip[0] == 0))
501 evaltree(lp->n, EV_EXIT);
509 if (n->npipe.backgnd == 0) {
511 exitstatus = waitforjob(jp, (int *)NULL);
512 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
520 * Execute a command inside back quotes. If it's a builtin command, we
521 * want to save its output in a block obtained from malloc. Otherwise
522 * we fork off a subprocess and get the output of the command via a pipe.
523 * Should be called with interrupts off.
527 evalbackcmd(union node *n, struct backcmd *result)
531 struct stackmark smark; /* unnecessary */
533 setstackmark(&smark);
542 if (n->type == NCMD) {
543 exitstatus = oexitstatus;
544 evalcommand(n, EV_BACKCMD, result);
548 error("Pipe call failed: %s", strerror(errno));
550 if (forkshell(jp, n, FORK_NOJOB) == 0) {
557 evaltree(n, EV_EXIT);
564 popstackmark(&smark);
565 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
566 result->fd, result->buf, result->nleft, result->jp));
572 * Execute a simple command.
576 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
578 struct stackmark smark;
580 struct arglist arglist;
581 struct arglist varlist;
589 struct cmdentry cmdentry;
591 struct jmploc jmploc;
592 struct jmploc *savehandler;
594 struct shparam saveparam;
595 struct localvar *savelocalvars;
599 int do_clearcmdentry;
601 /* First expand the arguments. */
602 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
603 setstackmark(&smark);
604 arglist.lastp = &arglist.list;
605 varlist.lastp = &varlist.list;
607 do_clearcmdentry = 0;
608 oexitstatus = exitstatus;
610 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
611 char *p = argp->narg.text;
612 if (varflag && is_name(*p)) {
615 } while (is_in_name(*p));
617 expandarg(argp, &varlist, EXP_VARTILDE);
621 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
624 *arglist.lastp = NULL;
625 *varlist.lastp = NULL;
626 expredir(cmd->ncmd.redirect);
628 for (sp = arglist.list ; sp ; sp = sp->next)
630 argv = stalloc(sizeof (char *) * (argc + 1));
632 for (sp = arglist.list ; sp ; sp = sp->next) {
633 TRACE(("evalcommand arg: %s\n", sp->text));
638 if (iflag && funcnest == 0 && argc > 0)
642 /* Print the command if xflag is set. */
647 for (sp = varlist.list ; sp ; sp = sp->next) {
651 while (*p != '=' && *p != '\0')
659 for (sp = arglist.list ; sp ; sp = sp->next) {
662 /* Disambiguate command looking like assignment. */
663 if (sp == arglist.list &&
664 strchr(sp->text, '=') != NULL &&
665 strchr(sp->text, '\'') == NULL) {
677 /* Now locate the command. */
679 /* Variable assignment(s) without command */
680 cmdentry.cmdtype = CMDBUILTIN;
681 cmdentry.u.index = BLTINCMD;
682 cmdentry.special = 1;
684 static const char PATH[] = "PATH=";
685 char *path = pathval();
688 * Modify the command lookup path, if a PATH= assignment
691 for (sp = varlist.list ; sp ; sp = sp->next)
692 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
693 path = sp->text + sizeof(PATH) - 1;
695 * On `PATH=... command`, we need to make
696 * sure that the command isn't using the
697 * non-updated hash table of the outer PATH
698 * setting and we need to make sure that
699 * the hash table isn't filled with items
700 * from the temporary setting.
702 * It would be better to forbit using and
703 * updating the table while this command
704 * runs, by the command finding mechanism
705 * is heavily integrated with hash handling,
706 * so we just delete the hash before and after
707 * the command runs. Partly deleting like
708 * changepatch() does doesn't seem worth the
709 * bookinging effort, since most such runs add
710 * directories in front of the new PATH.
713 do_clearcmdentry = 1;
716 find_command(argv[0], &cmdentry, 1, path);
717 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
722 /* implement the bltin builtin here */
723 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
728 if ((cmdentry.u.index = find_builtin(*argv,
729 &cmdentry.special)) < 0) {
730 outfmt(&errout, "%s: not found\n", *argv);
735 if (cmdentry.u.index != BLTINCMD)
741 /* Fork off a child process if necessary. */
742 if (cmd->ncmd.backgnd
743 || (cmdentry.cmdtype == CMDNORMAL
744 && ((flags & EV_EXIT) == 0 || have_traps()))
745 || ((flags & EV_BACKCMD) != 0
746 && (cmdentry.cmdtype != CMDBUILTIN
747 || cmdentry.u.index == CDCMD
748 || cmdentry.u.index == DOTCMD
749 || cmdentry.u.index == EVALCMD))
750 || (cmdentry.cmdtype == CMDBUILTIN &&
751 cmdentry.u.index == COMMANDCMD)) {
752 jp = makejob(cmd, 1);
753 mode = cmd->ncmd.backgnd;
754 if (flags & EV_BACKCMD) {
757 error("Pipe call failed: %s", strerror(errno));
759 if (forkshell(jp, cmd, mode) != 0)
760 goto parent; /* at end of routine */
761 if (flags & EV_BACKCMD) {
772 /* This is the child process if a fork occurred. */
773 /* Execute the command. */
774 if (cmdentry.cmdtype == CMDFUNCTION) {
776 trputs("Shell function: "); trargs(argv);
778 redirect(cmd->ncmd.redirect, REDIR_PUSH);
779 saveparam = shellparam;
780 shellparam.malloc = 0;
781 shellparam.reset = 1;
782 shellparam.nparam = argc - 1;
783 shellparam.p = argv + 1;
784 shellparam.optnext = NULL;
786 savelocalvars = localvars;
788 reffunc(cmdentry.u.func);
790 savehandler = handler;
791 if (setjmp(jmploc.loc)) {
792 if (exception == EXSHELLPROC)
793 freeparam(&saveparam);
795 freeparam(&shellparam);
796 shellparam = saveparam;
798 unreffunc(cmdentry.u.func);
800 localvars = savelocalvars;
801 handler = savehandler;
802 longjmp(handler->loc, 1);
805 for (sp = varlist.list ; sp ; sp = sp->next)
808 exitstatus = oexitstatus;
809 if (flags & EV_TESTED)
810 evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
812 evaltree(getfuncnode(cmdentry.u.func), 0);
815 unreffunc(cmdentry.u.func);
817 localvars = savelocalvars;
818 freeparam(&shellparam);
819 shellparam = saveparam;
820 handler = savehandler;
823 if (evalskip == SKIPFUNC) {
828 exitshell(exitstatus);
829 } else if (cmdentry.cmdtype == CMDBUILTIN) {
831 trputs("builtin command: "); trargs(argv);
833 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
834 if (flags == EV_BACKCMD) {
836 memout.nextc = memout.buf;
840 savecmdname = commandname;
841 cmdenviron = varlist.list;
843 savehandler = handler;
844 if (setjmp(jmploc.loc)) {
846 exitstatus = (e == EXINT)? SIGINT+128 : 2;
850 redirect(cmd->ncmd.redirect, mode);
851 if (cmdentry.special)
852 listsetvar(cmdenviron);
853 commandname = argv[0];
855 nextopt_optptr = NULL; /* initialize nextopt */
856 builtin_flags = flags;
857 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
864 if (e != EXSHELLPROC) {
865 commandname = savecmdname;
866 if (flags & EV_EXIT) {
867 exitshell(exitstatus);
870 handler = savehandler;
872 if ((e != EXERROR && e != EXEXEC)
877 if (cmdentry.u.index != EXECCMD)
879 if (flags == EV_BACKCMD) {
880 backcmd->buf = memout.buf;
881 backcmd->nleft = memout.nextc - memout.buf;
886 trputs("normal command: "); trargs(argv);
889 redirect(cmd->ncmd.redirect, 0);
890 for (sp = varlist.list ; sp ; sp = sp->next)
891 setvareq(sp->text, VEXPORT|VSTACK);
892 envp = environment();
893 shellexec(argv, envp, pathval(), cmdentry.u.index);
898 parent: /* parent process gets here (if we forked) */
899 if (mode == FORK_FG) { /* argument to fork */
901 exitstatus = waitforjob(jp, &realstatus);
903 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
904 evalskip = SKIPBREAK;
905 skipcount = loopnest;
907 } else if (mode == FORK_NOJOB) {
908 backcmd->fd = pip[0];
915 setvar("_", lastarg, 0);
916 if (do_clearcmdentry)
918 popstackmark(&smark);
924 * Search for a command. This is called before we fork so that the
925 * location of the command will be available in the parent as well as
926 * the child. The check for "goodname" is an overly conservative
927 * check that the name will not be subject to expansion.
931 prehash(union node *n)
933 struct cmdentry entry;
935 if (n && n->type == NCMD && n->ncmd.args)
936 if (goodname(n->ncmd.args->narg.text))
937 find_command(n->ncmd.args->narg.text, &entry, 0,
944 * Builtin commands. Builtin commands whose functions are closely
945 * tied to evaluation are implemented here.
949 * No command given, or a bltin command with no arguments.
953 bltincmd(int argc __unused, char **argv __unused)
956 * Preserve exitstatus of a previous possible redirection
964 * Handle break and continue commands. Break, continue, and return are
965 * all handled by setting the evalskip flag. The evaluation routines
966 * above all check this flag, and if it is set they start skipping
967 * commands rather than executing them. The variable skipcount is
968 * the number of loops to break/continue, or the number of function
969 * levels to return. (The latter is always 1.) It should probably
970 * be an error to break out of more loops than exist, but it isn't
971 * in the standard shell so we don't make it one here.
975 breakcmd(int argc, char **argv)
977 int n = argc > 1 ? number(argv[1]) : 1;
982 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
989 * The `command' command.
992 commandcmd(int argc, char **argv)
994 static char stdpath[] = _PATH_STDPATH;
995 struct jmploc loc, *old;
1001 for (sp = cmdenviron; sp ; sp = sp->next)
1002 setvareq(sp->text, VEXPORT|VSTACK);
1005 optind = optreset = 1;
1007 while ((ch = getopt(argc, argv, "pvV")) != -1) {
1013 cmd = TYPECMD_SMALLV;
1020 error("unknown option: -%c", optopt);
1028 error("wrong number of arguments");
1029 return typecmd_impl(2, argv - 1, cmd);
1034 if (setjmp(handler->loc) == 0)
1035 shellexec(argv, environment(), path, 0);
1037 if (exception == EXEXEC)
1043 * Do nothing successfully if no command was specified;
1044 * ksh also does this.
1051 * The return command.
1055 returncmd(int argc, char **argv)
1057 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1060 evalskip = SKIPFUNC;
1063 /* skip the rest of the file */
1064 evalskip = SKIPFILE;
1072 falsecmd(int argc __unused, char **argv __unused)
1079 truecmd(int argc __unused, char **argv __unused)
1086 execcmd(int argc, char **argv)
1091 iflag = 0; /* exit on error */
1094 for (sp = cmdenviron; sp ; sp = sp->next)
1095 setvareq(sp->text, VEXPORT|VSTACK);
1096 shellexec(argv + 1, environment(), pathval(), 0);
1104 timescmd(int argc __unused, char **argv __unused)
1107 long shumins, shsmins, chumins, chsmins;
1108 double shusecs, shssecs, chusecs, chssecs;
1110 if (getrusage(RUSAGE_SELF, &ru) < 0)
1112 shumins = ru.ru_utime.tv_sec / 60;
1113 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1114 shsmins = ru.ru_stime.tv_sec / 60;
1115 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1116 if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1118 chumins = ru.ru_utime.tv_sec / 60;
1119 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1120 chsmins = ru.ru_stime.tv_sec / 60;
1121 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1122 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1123 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);