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
36 * @(#)eval.c 8.9 (Berkeley) 6/8/95
37 * $FreeBSD: src/bin/sh/eval.c,v 1.27.2.5 2002/08/27 01:36:28 tjr Exp $
38 * $DragonFly: src/bin/sh/eval.c,v 1.2 2003/06/17 04:22:50 dillon Exp $
44 #include <sys/wait.h> /* For WIFSIGNALED(status) */
71 #include "myhistedit.h"
75 /* flags in argument to evaltree */
76 #define EV_EXIT 01 /* exit after evaluating tree */
77 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
78 #define EV_BACKCMD 04 /* command executing within back quotes */
80 MKINIT int evalskip; /* set if we are skipping commands */
81 STATIC int skipcount; /* number of levels to skip */
82 MKINIT int loopnest; /* current loop nesting level */
83 int funcnest; /* depth of function calls */
87 struct strlist *cmdenviron;
88 int exitstatus; /* exit status of last command */
89 int oexitstatus; /* saved exit status */
92 STATIC void evalloop(union node *);
93 STATIC void evalfor(union node *);
94 STATIC void evalcase(union node *, int);
95 STATIC void evalsubshell(union node *, int);
96 STATIC void expredir(union node *);
97 STATIC void evalpipe(union node *);
98 STATIC void evalcommand(union node *, int, struct backcmd *);
99 STATIC void prehash(union node *);
103 * Called to reset things after an exception.
127 evalcmd(int argc, char **argv)
136 STARTSTACKSTR(concat);
140 STPUTC(*p++, concat);
141 if ((p = *ap++) == NULL)
145 STPUTC('\0', concat);
146 p = grabstackstr(concat);
155 * Execute a command or commands contained in a string.
162 struct stackmark smark;
164 setstackmark(&smark);
165 setinputstring(s, 1);
166 while ((n = parsecmd(0)) != NEOF) {
168 popstackmark(&smark);
171 popstackmark(&smark);
177 * Evaluate a parse tree. The value is left in the global variable
182 evaltree(union node *n, int flags)
185 TRACE(("evaltree(NULL) called\n"));
190 displayhist = 1; /* show history substitutions done with fc */
192 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
195 evaltree(n->nbinary.ch1, 0);
198 evaltree(n->nbinary.ch2, flags);
201 evaltree(n->nbinary.ch1, EV_TESTED);
202 if (evalskip || exitstatus != 0) {
206 evaltree(n->nbinary.ch2, flags);
209 evaltree(n->nbinary.ch1, EV_TESTED);
210 if (evalskip || exitstatus == 0)
212 evaltree(n->nbinary.ch2, flags);
215 expredir(n->nredir.redirect);
216 redirect(n->nredir.redirect, REDIR_PUSH);
217 evaltree(n->nredir.n, flags);
221 evalsubshell(n, flags);
224 evalsubshell(n, flags);
227 evaltree(n->nif.test, EV_TESTED);
231 evaltree(n->nif.ifpart, flags);
232 else if (n->nif.elsepart)
233 evaltree(n->nif.elsepart, flags);
245 * The 'for' command does not set exitstatus, so the value
246 * now in exitstatus is from the last command executed in
247 * the 'for' loop. That exit value had been tested (wrt
248 * 'sh -e' checking) while processing that command, and
249 * it should not be re-tested here.
256 * The 'case' command does not set exitstatus, so the value
257 * now in exitstatus is from the last command executed in
258 * the 'case' block. That exit value had been tested (wrt
259 * 'sh -e' checking) while processing that command, and
260 * it should not be re-tested here.
265 defun(n->narg.text, n->narg.next);
269 evaltree(n->nnot.com, EV_TESTED);
270 exitstatus = !exitstatus;
277 evalcommand(n, flags, (struct backcmd *)NULL);
280 out1fmt("Node type = %d\n", n->type);
288 * XXX - Like "!(n->type == NSEMI)", more types will probably
289 * need to be excluded from this test. It's probably better
290 * to set or unset EV_TESTED in the loop above than to bloat
291 * the conditional here.
293 if ((flags & EV_EXIT) || (eflag && exitstatus
294 && !(flags & EV_TESTED) && !(n->type == NSEMI)))
295 exitshell(exitstatus);
300 evalloop(union node *n)
307 evaltree(n->nbinary.ch1, EV_TESTED);
309 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
313 if (evalskip == SKIPBREAK && --skipcount <= 0)
317 if (n->type == NWHILE) {
324 evaltree(n->nbinary.ch2, 0);
336 evalfor(union node *n)
338 struct arglist arglist;
341 struct stackmark smark;
343 setstackmark(&smark);
344 arglist.lastp = &arglist.list;
345 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
346 oexitstatus = exitstatus;
347 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
351 *arglist.lastp = NULL;
355 for (sp = arglist.list ; sp ; sp = sp->next) {
356 setvar(n->nfor.var, sp->text, 0);
357 evaltree(n->nfor.body, 0);
359 if (evalskip == SKIPCONT && --skipcount <= 0) {
363 if (evalskip == SKIPBREAK && --skipcount <= 0)
370 popstackmark(&smark);
376 evalcase(union node *n, int flags)
380 struct arglist arglist;
381 struct stackmark smark;
383 setstackmark(&smark);
384 arglist.lastp = &arglist.list;
385 oexitstatus = exitstatus;
386 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
387 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
388 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
389 if (casematch(patp, arglist.list->text)) {
391 evaltree(cp->nclist.body, flags);
398 popstackmark(&smark);
404 * Kick off a subshell to evaluate a tree.
408 evalsubshell(union node *n, int flags)
411 int backgnd = (n->type == NBACKGND);
413 expredir(n->nredir.redirect);
415 if (forkshell(jp, n, backgnd) == 0) {
418 redirect(n->nredir.redirect, 0);
419 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
423 exitstatus = waitforjob(jp, (int *)NULL);
431 * Compute the names of the files in a redirection list.
435 expredir(union node *n)
439 for (redir = n ; redir ; redir = redir->nfile.next) {
442 oexitstatus = exitstatus;
443 switch (redir->type) {
449 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
450 redir->nfile.expfname = fn.list->text;
454 if (redir->ndup.vname) {
455 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
456 fixredir(redir, fn.list->text, 1);
466 * Evaluate a pipeline. All the processes in the pipeline are children
467 * of the process creating the pipeline. (This differs from some versions
468 * of the shell, which make the last process in a pipeline the parent
473 evalpipe(union node *n)
481 TRACE(("evalpipe(0x%lx) called\n", (long)n));
483 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
486 jp = makejob(n, pipelen);
488 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
494 error("Pipe call failed: %s", strerror(errno));
497 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
505 if (!(prevfd >= 0 && pip[0] == 0))
513 evaltree(lp->n, EV_EXIT);
521 if (n->npipe.backgnd == 0) {
523 exitstatus = waitforjob(jp, (int *)NULL);
524 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
532 * Execute a command inside back quotes. If it's a builtin command, we
533 * want to save its output in a block obtained from malloc. Otherwise
534 * we fork off a subprocess and get the output of the command via a pipe.
535 * Should be called with interrupts off.
539 evalbackcmd(union node *n, struct backcmd *result)
543 struct stackmark smark; /* unnecessary */
545 setstackmark(&smark);
554 if (n->type == NCMD) {
555 exitstatus = oexitstatus;
556 evalcommand(n, EV_BACKCMD, result);
560 error("Pipe call failed: %s", strerror(errno));
562 if (forkshell(jp, n, FORK_NOJOB) == 0) {
570 evaltree(n, EV_EXIT);
577 popstackmark(&smark);
578 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
579 result->fd, result->buf, result->nleft, result->jp));
585 * Execute a simple command.
589 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
591 struct stackmark smark;
593 struct arglist arglist;
594 struct arglist varlist;
602 struct cmdentry cmdentry;
604 struct jmploc jmploc;
605 struct jmploc *volatile savehandler;
606 char *volatile savecmdname;
607 volatile struct shparam saveparam;
608 struct localvar *volatile savelocalvars;
612 int do_clearcmdentry;
614 /* Avoid longjmp clobbering */
619 (void) &do_clearcmdentry;
622 /* First expand the arguments. */
623 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
624 setstackmark(&smark);
625 arglist.lastp = &arglist.list;
626 varlist.lastp = &varlist.list;
628 do_clearcmdentry = 0;
629 oexitstatus = exitstatus;
631 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
632 char *p = argp->narg.text;
633 if (varflag && is_name(*p)) {
636 } while (is_in_name(*p));
638 expandarg(argp, &varlist, EXP_VARTILDE);
642 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
645 *arglist.lastp = NULL;
646 *varlist.lastp = NULL;
647 expredir(cmd->ncmd.redirect);
649 for (sp = arglist.list ; sp ; sp = sp->next)
651 argv = stalloc(sizeof (char *) * (argc + 1));
653 for (sp = arglist.list ; sp ; sp = sp->next) {
654 TRACE(("evalcommand arg: %s\n", sp->text));
659 if (iflag && funcnest == 0 && argc > 0)
663 /* Print the command if xflag is set. */
666 for (sp = varlist.list ; sp ; sp = sp->next) {
670 for (sp = arglist.list ; sp ; sp = sp->next) {
678 /* Now locate the command. */
680 cmdentry.cmdtype = CMDBUILTIN;
681 cmdentry.u.index = BLTINCMD;
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 * diretories 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)) < 0) {
728 outfmt(&errout, "%s: not found\n", *argv);
733 if (cmdentry.u.index != BLTINCMD)
739 /* Fork off a child process if necessary. */
740 if (cmd->ncmd.backgnd
741 || (cmdentry.cmdtype == CMDNORMAL
742 && ((flags & EV_EXIT) == 0 || Tflag))
743 || ((flags & EV_BACKCMD) != 0
744 && (cmdentry.cmdtype != CMDBUILTIN
745 || cmdentry.u.index == CDCMD
746 || cmdentry.u.index == DOTCMD
747 || cmdentry.u.index == EVALCMD))
748 || (cmdentry.cmdtype == CMDBUILTIN &&
749 cmdentry.u.index == COMMANDCMD)) {
750 jp = makejob(cmd, 1);
751 mode = cmd->ncmd.backgnd;
752 if (flags & EV_BACKCMD) {
755 error("Pipe call failed: %s", strerror(errno));
757 if (forkshell(jp, cmd, mode) != 0)
758 goto parent; /* at end of routine */
759 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;
788 if (setjmp(jmploc.loc)) {
789 if (exception == EXSHELLPROC)
790 freeparam((struct shparam *)&saveparam);
792 freeparam(&shellparam);
793 shellparam = saveparam;
796 localvars = savelocalvars;
797 handler = savehandler;
798 longjmp(handler->loc, 1);
800 savehandler = handler;
802 for (sp = varlist.list ; sp ; sp = sp->next)
805 if (flags & EV_TESTED)
806 evaltree(cmdentry.u.func, EV_TESTED);
808 evaltree(cmdentry.u.func, 0);
812 localvars = savelocalvars;
813 freeparam(&shellparam);
814 shellparam = saveparam;
815 handler = savehandler;
818 if (evalskip == SKIPFUNC) {
823 exitshell(exitstatus);
824 } else if (cmdentry.cmdtype == CMDBUILTIN) {
826 trputs("builtin command: "); trargs(argv);
828 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
829 if (flags == EV_BACKCMD) {
831 memout.nextc = memout.buf;
835 redirect(cmd->ncmd.redirect, mode);
836 savecmdname = commandname;
837 cmdenviron = varlist.list;
839 if (setjmp(jmploc.loc)) {
841 exitstatus = (e == EXINT)? SIGINT+128 : 2;
844 savehandler = handler;
846 commandname = argv[0];
848 optptr = NULL; /* initialize nextopt */
849 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
856 if (e != EXSHELLPROC) {
857 commandname = savecmdname;
858 if (flags & EV_EXIT) {
859 exitshell(exitstatus);
862 handler = savehandler;
864 if ((e != EXERROR && e != EXEXEC)
865 || cmdentry.u.index == BLTINCMD
866 || cmdentry.u.index == DOTCMD
867 || cmdentry.u.index == EVALCMD
869 || cmdentry.u.index == HISTCMD
871 || cmdentry.u.index == EXECCMD
872 || cmdentry.u.index == COMMANDCMD)
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 == 0) { /* 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 == 2) {
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->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. Set the
949 * specified variables.
953 bltincmd(int argc __unused, char **argv __unused)
955 listsetvar(cmdenviron);
957 * Preserve exitstatus of a previous possible redirection
965 * Handle break and continue commands. Break, continue, and return are
966 * all handled by setting the evalskip flag. The evaluation routines
967 * above all check this flag, and if it is set they start skipping
968 * commands rather than executing them. The variable skipcount is
969 * the number of loops to break/continue, or the number of function
970 * levels to return. (The latter is always 1.) It should probably
971 * be an error to break out of more loops than exist, but it isn't
972 * in the standard shell so we don't make it one here.
976 breakcmd(int argc, char **argv)
978 int n = argc > 1 ? number(argv[1]) : 1;
983 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
990 * The `command' command.
993 commandcmd(int argc, char **argv)
995 static char stdpath[] = _PATH_STDPATH;
996 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, "p")) != -1) {
1014 error("unknown option: -%c", optopt);
1023 if (setjmp(handler->loc) == 0)
1024 shellexec(argv, environment(), path, 0);
1026 if (exception == EXEXEC)
1032 * Do nothing successfully if no command was specified;
1033 * ksh also does this.
1040 * The return command.
1044 returncmd(int argc, char **argv)
1046 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1049 evalskip = SKIPFUNC;
1052 /* skip the rest of the file */
1053 evalskip = SKIPFILE;
1061 falsecmd(int argc __unused, char **argv __unused)
1068 truecmd(int argc __unused, char **argv __unused)
1075 execcmd(int argc, char **argv)
1080 iflag = 0; /* exit on error */
1083 for (sp = cmdenviron; sp ; sp = sp->next)
1084 setvareq(sp->text, VEXPORT|VSTACK);
1085 shellexec(argv + 1, environment(), pathval(), 0);