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
39 static char sccsid[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95";
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD: src/bin/sh/eval.c,v 1.27.2.5 2002/08/27 01:36:28 tjr Exp $");
48 #include <sys/wait.h> /* For WIFSIGNALED(status) */
75 #include "myhistedit.h"
79 /* flags in argument to evaltree */
80 #define EV_EXIT 01 /* exit after evaluating tree */
81 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
82 #define EV_BACKCMD 04 /* command executing within back quotes */
84 MKINIT int evalskip; /* set if we are skipping commands */
85 STATIC int skipcount; /* number of levels to skip */
86 MKINIT int loopnest; /* current loop nesting level */
87 int funcnest; /* depth of function calls */
91 struct strlist *cmdenviron;
92 int exitstatus; /* exit status of last command */
93 int oexitstatus; /* saved exit status */
96 STATIC void evalloop(union node *);
97 STATIC void evalfor(union node *);
98 STATIC void evalcase(union node *, int);
99 STATIC void evalsubshell(union node *, int);
100 STATIC void expredir(union node *);
101 STATIC void evalpipe(union node *);
102 STATIC void evalcommand(union node *, int, struct backcmd *);
103 STATIC void prehash(union node *);
107 * Called to reset things after an exception.
131 evalcmd(int argc, char **argv)
140 STARTSTACKSTR(concat);
144 STPUTC(*p++, concat);
145 if ((p = *ap++) == NULL)
149 STPUTC('\0', concat);
150 p = grabstackstr(concat);
159 * Execute a command or commands contained in a string.
166 struct stackmark smark;
168 setstackmark(&smark);
169 setinputstring(s, 1);
170 while ((n = parsecmd(0)) != NEOF) {
172 popstackmark(&smark);
175 popstackmark(&smark);
181 * Evaluate a parse tree. The value is left in the global variable
186 evaltree(union node *n, int flags)
189 TRACE(("evaltree(NULL) called\n"));
194 displayhist = 1; /* show history substitutions done with fc */
196 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
199 evaltree(n->nbinary.ch1, 0);
202 evaltree(n->nbinary.ch2, flags);
205 evaltree(n->nbinary.ch1, EV_TESTED);
206 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);
228 evalsubshell(n, flags);
231 evaltree(n->nif.test, EV_TESTED);
235 evaltree(n->nif.ifpart, flags);
236 else if (n->nif.elsepart)
237 evaltree(n->nif.elsepart, flags);
249 * The 'for' command does not set exitstatus, so the value
250 * now in exitstatus is from the last command executed in
251 * the 'for' loop. That exit value had been tested (wrt
252 * 'sh -e' checking) while processing that command, and
253 * it should not be re-tested here.
260 * The 'case' command does not set exitstatus, so the value
261 * now in exitstatus is from the last command executed in
262 * the 'case' block. That exit value had been tested (wrt
263 * 'sh -e' checking) while processing that command, and
264 * it should not be re-tested here.
269 defun(n->narg.text, n->narg.next);
273 evaltree(n->nnot.com, EV_TESTED);
274 exitstatus = !exitstatus;
281 evalcommand(n, flags, (struct backcmd *)NULL);
284 out1fmt("Node type = %d\n", n->type);
292 * XXX - Like "!(n->type == NSEMI)", more types will probably
293 * need to be excluded from this test. It's probably better
294 * to set or unset EV_TESTED in the loop above than to bloat
295 * the conditional here.
297 if ((flags & EV_EXIT) || (eflag && exitstatus
298 && !(flags & EV_TESTED) && !(n->type == NSEMI)))
299 exitshell(exitstatus);
304 evalloop(union node *n)
311 evaltree(n->nbinary.ch1, EV_TESTED);
313 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
317 if (evalskip == SKIPBREAK && --skipcount <= 0)
321 if (n->type == NWHILE) {
328 evaltree(n->nbinary.ch2, 0);
340 evalfor(union node *n)
342 struct arglist arglist;
345 struct stackmark smark;
347 setstackmark(&smark);
348 arglist.lastp = &arglist.list;
349 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
350 oexitstatus = exitstatus;
351 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
355 *arglist.lastp = NULL;
359 for (sp = arglist.list ; sp ; sp = sp->next) {
360 setvar(n->nfor.var, sp->text, 0);
361 evaltree(n->nfor.body, 0);
363 if (evalskip == SKIPCONT && --skipcount <= 0) {
367 if (evalskip == SKIPBREAK && --skipcount <= 0)
374 popstackmark(&smark);
380 evalcase(union node *n, int flags)
384 struct arglist arglist;
385 struct stackmark smark;
387 setstackmark(&smark);
388 arglist.lastp = &arglist.list;
389 oexitstatus = exitstatus;
390 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
391 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
392 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
393 if (casematch(patp, arglist.list->text)) {
395 evaltree(cp->nclist.body, flags);
402 popstackmark(&smark);
408 * Kick off a subshell to evaluate a tree.
412 evalsubshell(union node *n, int flags)
415 int backgnd = (n->type == NBACKGND);
417 expredir(n->nredir.redirect);
419 if (forkshell(jp, n, backgnd) == 0) {
422 redirect(n->nredir.redirect, 0);
423 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
427 exitstatus = waitforjob(jp, (int *)NULL);
435 * Compute the names of the files in a redirection list.
439 expredir(union node *n)
443 for (redir = n ; redir ; redir = redir->nfile.next) {
446 oexitstatus = exitstatus;
447 switch (redir->type) {
453 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
454 redir->nfile.expfname = fn.list->text;
458 if (redir->ndup.vname) {
459 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
460 fixredir(redir, fn.list->text, 1);
470 * Evaluate a pipeline. All the processes in the pipeline are children
471 * of the process creating the pipeline. (This differs from some versions
472 * of the shell, which make the last process in a pipeline the parent
477 evalpipe(union node *n)
485 TRACE(("evalpipe(0x%lx) called\n", (long)n));
487 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
490 jp = makejob(n, pipelen);
492 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
498 error("Pipe call failed: %s", strerror(errno));
501 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
509 if (!(prevfd >= 0 && pip[0] == 0))
517 evaltree(lp->n, EV_EXIT);
525 if (n->npipe.backgnd == 0) {
527 exitstatus = waitforjob(jp, (int *)NULL);
528 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
536 * Execute a command inside back quotes. If it's a builtin command, we
537 * want to save its output in a block obtained from malloc. Otherwise
538 * we fork off a subprocess and get the output of the command via a pipe.
539 * Should be called with interrupts off.
543 evalbackcmd(union node *n, struct backcmd *result)
547 struct stackmark smark; /* unnecessary */
549 setstackmark(&smark);
558 if (n->type == NCMD) {
559 exitstatus = oexitstatus;
560 evalcommand(n, EV_BACKCMD, result);
564 error("Pipe call failed: %s", strerror(errno));
566 if (forkshell(jp, n, FORK_NOJOB) == 0) {
574 evaltree(n, EV_EXIT);
581 popstackmark(&smark);
582 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
583 result->fd, result->buf, result->nleft, result->jp));
589 * Execute a simple command.
593 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
595 struct stackmark smark;
597 struct arglist arglist;
598 struct arglist varlist;
606 struct cmdentry cmdentry;
608 struct jmploc jmploc;
609 struct jmploc *volatile savehandler;
610 char *volatile savecmdname;
611 volatile struct shparam saveparam;
612 struct localvar *volatile savelocalvars;
616 int do_clearcmdentry;
618 /* Avoid longjmp clobbering */
623 (void) &do_clearcmdentry;
626 /* First expand the arguments. */
627 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
628 setstackmark(&smark);
629 arglist.lastp = &arglist.list;
630 varlist.lastp = &varlist.list;
632 do_clearcmdentry = 0;
633 oexitstatus = exitstatus;
635 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
636 char *p = argp->narg.text;
637 if (varflag && is_name(*p)) {
640 } while (is_in_name(*p));
642 expandarg(argp, &varlist, EXP_VARTILDE);
646 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
649 *arglist.lastp = NULL;
650 *varlist.lastp = NULL;
651 expredir(cmd->ncmd.redirect);
653 for (sp = arglist.list ; sp ; sp = sp->next)
655 argv = stalloc(sizeof (char *) * (argc + 1));
657 for (sp = arglist.list ; sp ; sp = sp->next) {
658 TRACE(("evalcommand arg: %s\n", sp->text));
663 if (iflag && funcnest == 0 && argc > 0)
667 /* Print the command if xflag is set. */
670 for (sp = varlist.list ; sp ; sp = sp->next) {
674 for (sp = arglist.list ; sp ; sp = sp->next) {
682 /* Now locate the command. */
684 cmdentry.cmdtype = CMDBUILTIN;
685 cmdentry.u.index = BLTINCMD;
687 static const char PATH[] = "PATH=";
688 char *path = pathval();
691 * Modify the command lookup path, if a PATH= assignment
694 for (sp = varlist.list ; sp ; sp = sp->next)
695 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
696 path = sp->text + sizeof(PATH) - 1;
698 * On `PATH=... command`, we need to make
699 * sure that the command isn't using the
700 * non-updated hash table of the outer PATH
701 * setting and we need to make sure that
702 * the hash table isn't filled with items
703 * from the temporary setting.
705 * It would be better to forbit using and
706 * updating the table while this command
707 * runs, by the command finding mechanism
708 * is heavily integrated with hash handling,
709 * so we just delete the hash before and after
710 * the command runs. Partly deleting like
711 * changepatch() does doesn't seem worth the
712 * bookinging effort, since most such runs add
713 * diretories in front of the new PATH.
716 do_clearcmdentry = 1;
719 find_command(argv[0], &cmdentry, 1, path);
720 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
725 /* implement the bltin builtin here */
726 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
731 if ((cmdentry.u.index = find_builtin(*argv)) < 0) {
732 outfmt(&errout, "%s: not found\n", *argv);
737 if (cmdentry.u.index != BLTINCMD)
743 /* Fork off a child process if necessary. */
744 if (cmd->ncmd.backgnd
745 || (cmdentry.cmdtype == CMDNORMAL
746 && ((flags & EV_EXIT) == 0 || Tflag))
747 || ((flags & EV_BACKCMD) != 0
748 && (cmdentry.cmdtype != CMDBUILTIN
749 || cmdentry.u.index == CDCMD
750 || cmdentry.u.index == DOTCMD
751 || cmdentry.u.index == EVALCMD))
752 || (cmdentry.cmdtype == CMDBUILTIN &&
753 cmdentry.u.index == COMMANDCMD)) {
754 jp = makejob(cmd, 1);
755 mode = cmd->ncmd.backgnd;
756 if (flags & EV_BACKCMD) {
759 error("Pipe call failed: %s", strerror(errno));
761 if (forkshell(jp, cmd, mode) != 0)
762 goto parent; /* at end of routine */
763 if (flags & EV_BACKCMD) {
775 /* This is the child process if a fork occurred. */
776 /* Execute the command. */
777 if (cmdentry.cmdtype == CMDFUNCTION) {
779 trputs("Shell function: "); trargs(argv);
781 redirect(cmd->ncmd.redirect, REDIR_PUSH);
782 saveparam = shellparam;
783 shellparam.malloc = 0;
784 shellparam.reset = 1;
785 shellparam.nparam = argc - 1;
786 shellparam.p = argv + 1;
787 shellparam.optnext = NULL;
789 savelocalvars = localvars;
792 if (setjmp(jmploc.loc)) {
793 if (exception == EXSHELLPROC)
794 freeparam((struct shparam *)&saveparam);
796 freeparam(&shellparam);
797 shellparam = saveparam;
800 localvars = savelocalvars;
801 handler = savehandler;
802 longjmp(handler->loc, 1);
804 savehandler = handler;
806 for (sp = varlist.list ; sp ; sp = sp->next)
809 if (flags & EV_TESTED)
810 evaltree(cmdentry.u.func, EV_TESTED);
812 evaltree(cmdentry.u.func, 0);
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 redirect(cmd->ncmd.redirect, mode);
840 savecmdname = commandname;
841 cmdenviron = varlist.list;
843 if (setjmp(jmploc.loc)) {
845 exitstatus = (e == EXINT)? SIGINT+128 : 2;
848 savehandler = handler;
850 commandname = argv[0];
852 optptr = NULL; /* initialize nextopt */
853 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
860 if (e != EXSHELLPROC) {
861 commandname = savecmdname;
862 if (flags & EV_EXIT) {
863 exitshell(exitstatus);
866 handler = savehandler;
868 if ((e != EXERROR && e != EXEXEC)
869 || cmdentry.u.index == BLTINCMD
870 || cmdentry.u.index == DOTCMD
871 || cmdentry.u.index == EVALCMD
873 || cmdentry.u.index == HISTCMD
875 || cmdentry.u.index == EXECCMD
876 || cmdentry.u.index == COMMANDCMD)
880 if (cmdentry.u.index != EXECCMD)
882 if (flags == EV_BACKCMD) {
883 backcmd->buf = memout.buf;
884 backcmd->nleft = memout.nextc - memout.buf;
889 trputs("normal command: "); trargs(argv);
892 redirect(cmd->ncmd.redirect, 0);
893 for (sp = varlist.list ; sp ; sp = sp->next)
894 setvareq(sp->text, VEXPORT|VSTACK);
895 envp = environment();
896 shellexec(argv, envp, pathval(), cmdentry.u.index);
901 parent: /* parent process gets here (if we forked) */
902 if (mode == 0) { /* argument to fork */
904 exitstatus = waitforjob(jp, &realstatus);
906 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
907 evalskip = SKIPBREAK;
908 skipcount = loopnest;
910 } else if (mode == 2) {
911 backcmd->fd = pip[0];
918 setvar("_", lastarg, 0);
919 if (do_clearcmdentry)
921 popstackmark(&smark);
927 * Search for a command. This is called before we fork so that the
928 * location of the command will be available in the parent as well as
929 * the child. The check for "goodname" is an overly conservative
930 * check that the name will not be subject to expansion.
934 prehash(union node *n)
936 struct cmdentry entry;
938 if (n->type == NCMD && n->ncmd.args)
939 if (goodname(n->ncmd.args->narg.text))
940 find_command(n->ncmd.args->narg.text, &entry, 0,
947 * Builtin commands. Builtin commands whose functions are closely
948 * tied to evaluation are implemented here.
952 * No command given, or a bltin command with no arguments. Set the
953 * specified variables.
957 bltincmd(int argc __unused, char **argv __unused)
959 listsetvar(cmdenviron);
961 * Preserve exitstatus of a previous possible redirection
969 * Handle break and continue commands. Break, continue, and return are
970 * all handled by setting the evalskip flag. The evaluation routines
971 * above all check this flag, and if it is set they start skipping
972 * commands rather than executing them. The variable skipcount is
973 * the number of loops to break/continue, or the number of function
974 * levels to return. (The latter is always 1.) It should probably
975 * be an error to break out of more loops than exist, but it isn't
976 * in the standard shell so we don't make it one here.
980 breakcmd(int argc, char **argv)
982 int n = argc > 1 ? number(argv[1]) : 1;
987 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
994 * The `command' command.
997 commandcmd(int argc, char **argv)
999 static char stdpath[] = _PATH_STDPATH;
1000 struct jmploc loc, *old;
1005 for (sp = cmdenviron; sp ; sp = sp->next)
1006 setvareq(sp->text, VEXPORT|VSTACK);
1009 optind = optreset = 1;
1011 while ((ch = getopt(argc, argv, "p")) != -1) {
1018 error("unknown option: -%c", optopt);
1027 if (setjmp(handler->loc) == 0)
1028 shellexec(argv, environment(), path, 0);
1030 if (exception == EXEXEC)
1036 * Do nothing successfully if no command was specified;
1037 * ksh also does this.
1044 * The return command.
1048 returncmd(int argc, char **argv)
1050 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1053 evalskip = SKIPFUNC;
1056 /* skip the rest of the file */
1057 evalskip = SKIPFILE;
1065 falsecmd(int argc __unused, char **argv __unused)
1072 truecmd(int argc __unused, char **argv __unused)
1079 execcmd(int argc, char **argv)
1084 iflag = 0; /* exit on error */
1087 for (sp = cmdenviron; sp ; sp = sp->next)
1088 setvareq(sp->text, VEXPORT|VSTACK);
1089 shellexec(argv + 1, environment(), pathval(), 0);