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.4 2004/03/19 18:39:41 cpressey Exp $
41 #include <sys/wait.h> /* For WIFSIGNALED(status) */
73 #include "myhistedit.h"
77 /* flags in argument to evaltree */
78 #define EV_EXIT 01 /* exit after evaluating tree */
79 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
80 #define EV_BACKCMD 04 /* command executing within back quotes */
82 MKINIT int evalskip; /* set if we are skipping commands */
83 STATIC int skipcount; /* number of levels to skip */
84 MKINIT int loopnest; /* current loop nesting level */
85 int funcnest; /* depth of function calls */
88 const char *commandname;
89 struct strlist *cmdenviron;
90 int exitstatus; /* exit status of last command */
91 int oexitstatus; /* saved exit status */
94 STATIC void evalloop(union node *);
95 STATIC void evalfor(union node *);
96 STATIC void evalcase(union node *, int);
97 STATIC void evalsubshell(union node *, int);
98 STATIC void expredir(union node *);
99 STATIC void evalpipe(union node *);
100 STATIC void evalcommand(union node *, int, struct backcmd *);
101 STATIC void prehash(union node *);
105 * Called to reset things after an exception.
129 evalcmd(int argc, char **argv)
138 STARTSTACKSTR(concat);
142 STPUTC(*p++, concat);
143 if ((p = *ap++) == NULL)
147 STPUTC('\0', concat);
148 p = grabstackstr(concat);
157 * Execute a command or commands contained in a string.
164 struct stackmark smark;
166 setstackmark(&smark);
167 setinputstring(s, 1);
168 while ((n = parsecmd(0)) != NEOF) {
170 popstackmark(&smark);
173 popstackmark(&smark);
179 * Evaluate a parse tree. The value is left in the global variable
184 evaltree(union node *n, int flags)
187 TRACE(("evaltree(NULL) called\n"));
192 displayhist = 1; /* show history substitutions done with fc */
194 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
197 evaltree(n->nbinary.ch1, 0);
200 evaltree(n->nbinary.ch2, flags);
203 evaltree(n->nbinary.ch1, EV_TESTED);
204 if (evalskip || exitstatus != 0) {
208 evaltree(n->nbinary.ch2, flags);
211 evaltree(n->nbinary.ch1, EV_TESTED);
212 if (evalskip || exitstatus == 0)
214 evaltree(n->nbinary.ch2, flags);
217 expredir(n->nredir.redirect);
218 redirect(n->nredir.redirect, REDIR_PUSH);
219 evaltree(n->nredir.n, flags);
223 evalsubshell(n, flags);
226 evalsubshell(n, flags);
229 evaltree(n->nif.test, EV_TESTED);
233 evaltree(n->nif.ifpart, flags);
234 else if (n->nif.elsepart)
235 evaltree(n->nif.elsepart, flags);
247 * The 'for' command does not set exitstatus, so the value
248 * now in exitstatus is from the last command executed in
249 * the 'for' loop. That exit value had been tested (wrt
250 * 'sh -e' checking) while processing that command, and
251 * it should not be re-tested here.
258 * The 'case' command does not set exitstatus, so the value
259 * now in exitstatus is from the last command executed in
260 * the 'case' block. That exit value had been tested (wrt
261 * 'sh -e' checking) while processing that command, and
262 * it should not be re-tested here.
267 defun(n->narg.text, n->narg.next);
271 evaltree(n->nnot.com, EV_TESTED);
272 exitstatus = !exitstatus;
279 evalcommand(n, flags, (struct backcmd *)NULL);
282 out1fmt("Node type = %d\n", n->type);
290 * XXX - Like "!(n->type == NSEMI)", more types will probably
291 * need to be excluded from this test. It's probably better
292 * to set or unset EV_TESTED in the loop above than to bloat
293 * the conditional here.
295 if ((flags & EV_EXIT) || (eflag && exitstatus
296 && !(flags & EV_TESTED) && !(n->type == NSEMI)))
297 exitshell(exitstatus);
302 evalloop(union node *n)
309 evaltree(n->nbinary.ch1, EV_TESTED);
311 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
315 if (evalskip == SKIPBREAK && --skipcount <= 0)
319 if (n->type == NWHILE) {
326 evaltree(n->nbinary.ch2, 0);
338 evalfor(union node *n)
340 struct arglist arglist;
343 struct stackmark smark;
345 setstackmark(&smark);
346 arglist.lastp = &arglist.list;
347 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
348 oexitstatus = exitstatus;
349 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
353 *arglist.lastp = NULL;
357 for (sp = arglist.list ; sp ; sp = sp->next) {
358 setvar(n->nfor.var, sp->text, 0);
359 evaltree(n->nfor.body, 0);
361 if (evalskip == SKIPCONT && --skipcount <= 0) {
365 if (evalskip == SKIPBREAK && --skipcount <= 0)
372 popstackmark(&smark);
378 evalcase(union node *n, int flags)
382 struct arglist arglist;
383 struct stackmark smark;
385 setstackmark(&smark);
386 arglist.lastp = &arglist.list;
387 oexitstatus = exitstatus;
388 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
389 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
390 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
391 if (casematch(patp, arglist.list->text)) {
393 evaltree(cp->nclist.body, flags);
400 popstackmark(&smark);
406 * Kick off a subshell to evaluate a tree.
410 evalsubshell(union node *n, int flags)
413 int backgnd = (n->type == NBACKGND);
415 expredir(n->nredir.redirect);
417 if (forkshell(jp, n, backgnd) == 0) {
420 redirect(n->nredir.redirect, 0);
421 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
425 exitstatus = waitforjob(jp, (int *)NULL);
433 * Compute the names of the files in a redirection list.
437 expredir(union node *n)
441 for (redir = n ; redir ; redir = redir->nfile.next) {
444 oexitstatus = exitstatus;
445 switch (redir->type) {
451 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
452 redir->nfile.expfname = fn.list->text;
456 if (redir->ndup.vname) {
457 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
458 fixredir(redir, fn.list->text, 1);
468 * Evaluate a pipeline. All the processes in the pipeline are children
469 * of the process creating the pipeline. (This differs from some versions
470 * of the shell, which make the last process in a pipeline the parent
475 evalpipe(union node *n)
483 TRACE(("evalpipe(0x%lx) called\n", (long)n));
485 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
488 jp = makejob(n, pipelen);
490 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
496 error("Pipe call failed: %s", strerror(errno));
499 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
507 if (!(prevfd >= 0 && pip[0] == 0))
515 evaltree(lp->n, EV_EXIT);
523 if (n->npipe.backgnd == 0) {
525 exitstatus = waitforjob(jp, (int *)NULL);
526 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
534 * Execute a command inside back quotes. If it's a builtin command, we
535 * want to save its output in a block obtained from malloc. Otherwise
536 * we fork off a subprocess and get the output of the command via a pipe.
537 * Should be called with interrupts off.
541 evalbackcmd(union node *n, struct backcmd *result)
545 struct stackmark smark; /* unnecessary */
547 setstackmark(&smark);
556 if (n->type == NCMD) {
557 exitstatus = oexitstatus;
558 evalcommand(n, EV_BACKCMD, result);
562 error("Pipe call failed: %s", strerror(errno));
564 if (forkshell(jp, n, FORK_NOJOB) == 0) {
572 evaltree(n, EV_EXIT);
579 popstackmark(&smark);
580 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
581 result->fd, result->buf, result->nleft, result->jp));
587 * Execute a simple command.
591 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
593 struct stackmark smark;
595 struct arglist arglist;
596 struct arglist varlist;
604 struct cmdentry cmdentry;
606 struct jmploc jmploc;
607 struct jmploc *volatile savehandler;
608 const char *volatile savecmdname;
609 volatile struct shparam saveparam;
610 struct localvar *volatile savelocalvars;
614 int do_clearcmdentry;
616 /* Avoid longjmp clobbering */
621 (void) &do_clearcmdentry;
624 /* First expand the arguments. */
625 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
626 setstackmark(&smark);
627 arglist.lastp = &arglist.list;
628 varlist.lastp = &varlist.list;
630 do_clearcmdentry = 0;
631 oexitstatus = exitstatus;
633 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
634 char *p = argp->narg.text;
635 if (varflag && is_name(*p)) {
638 } while (is_in_name(*p));
640 expandarg(argp, &varlist, EXP_VARTILDE);
644 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
647 *arglist.lastp = NULL;
648 *varlist.lastp = NULL;
649 expredir(cmd->ncmd.redirect);
651 for (sp = arglist.list ; sp ; sp = sp->next)
653 argv = stalloc(sizeof (char *) * (argc + 1));
655 for (sp = arglist.list ; sp ; sp = sp->next) {
656 TRACE(("evalcommand arg: %s\n", sp->text));
661 if (iflag && funcnest == 0 && argc > 0)
665 /* Print the command if xflag is set. */
668 for (sp = varlist.list ; sp ; sp = sp->next) {
672 for (sp = arglist.list ; sp ; sp = sp->next) {
680 /* Now locate the command. */
682 cmdentry.cmdtype = CMDBUILTIN;
683 cmdentry.u.index = BLTINCMD;
685 static const char PATH[] = "PATH=";
686 const char *path = pathval();
689 * Modify the command lookup path, if a PATH= assignment
692 for (sp = varlist.list ; sp ; sp = sp->next)
693 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
694 path = sp->text + sizeof(PATH) - 1;
696 * On `PATH=... command`, we need to make
697 * sure that the command isn't using the
698 * non-updated hash table of the outer PATH
699 * setting and we need to make sure that
700 * the hash table isn't filled with items
701 * from the temporary setting.
703 * It would be better to forbit using and
704 * updating the table while this command
705 * runs, by the command finding mechanism
706 * is heavily integrated with hash handling,
707 * so we just delete the hash before and after
708 * the command runs. Partly deleting like
709 * changepatch() does doesn't seem worth the
710 * bookinging effort, since most such runs add
711 * diretories in front of the new PATH.
714 do_clearcmdentry = 1;
717 find_command(argv[0], &cmdentry, 1, path);
718 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
723 /* implement the bltin builtin here */
724 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
729 if ((cmdentry.u.index = find_builtin(*argv)) < 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 || Tflag))
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) {
773 /* This is the child process if a fork occurred. */
774 /* Execute the command. */
775 if (cmdentry.cmdtype == CMDFUNCTION) {
777 trputs("Shell function: "); trargs(argv);
779 redirect(cmd->ncmd.redirect, REDIR_PUSH);
780 saveparam = shellparam;
781 shellparam.malloc = 0;
782 shellparam.reset = 1;
783 shellparam.nparam = argc - 1;
784 shellparam.p = argv + 1;
785 shellparam.optnext = NULL;
787 savelocalvars = localvars;
790 if (setjmp(jmploc.loc)) {
791 if (exception == EXSHELLPROC)
792 freeparam((struct shparam *)&saveparam);
794 freeparam(&shellparam);
795 shellparam = saveparam;
798 localvars = savelocalvars;
799 handler = savehandler;
800 longjmp(handler->loc, 1);
802 savehandler = handler;
804 for (sp = varlist.list ; sp ; sp = sp->next)
807 if (flags & EV_TESTED)
808 evaltree(cmdentry.u.func, EV_TESTED);
810 evaltree(cmdentry.u.func, 0);
814 localvars = savelocalvars;
815 freeparam(&shellparam);
816 shellparam = saveparam;
817 handler = savehandler;
820 if (evalskip == SKIPFUNC) {
825 exitshell(exitstatus);
826 } else if (cmdentry.cmdtype == CMDBUILTIN) {
828 trputs("builtin command: "); trargs(argv);
830 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
831 if (flags == EV_BACKCMD) {
833 memout.nextc = memout.buf;
837 redirect(cmd->ncmd.redirect, mode);
838 savecmdname = commandname;
839 cmdenviron = varlist.list;
841 if (setjmp(jmploc.loc)) {
843 exitstatus = (e == EXINT)? SIGINT+128 : 2;
846 savehandler = handler;
848 commandname = argv[0];
850 optptr = NULL; /* initialize nextopt */
851 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
858 if (e != EXSHELLPROC) {
859 commandname = savecmdname;
860 if (flags & EV_EXIT) {
861 exitshell(exitstatus);
864 handler = savehandler;
866 if ((e != EXERROR && e != EXEXEC)
867 || cmdentry.u.index == BLTINCMD
868 || cmdentry.u.index == DOTCMD
869 || cmdentry.u.index == EVALCMD
871 || cmdentry.u.index == HISTCMD
873 || cmdentry.u.index == EXECCMD
874 || cmdentry.u.index == COMMANDCMD)
878 if (cmdentry.u.index != EXECCMD)
880 if (flags == EV_BACKCMD) {
881 backcmd->buf = memout.buf;
882 backcmd->nleft = memout.nextc - memout.buf;
887 trputs("normal command: "); trargs(argv);
890 redirect(cmd->ncmd.redirect, 0);
891 for (sp = varlist.list ; sp ; sp = sp->next)
892 setvareq(sp->text, VEXPORT|VSTACK);
893 envp = environment();
894 shellexec(argv, envp, pathval(), cmdentry.u.index);
899 parent: /* parent process gets here (if we forked) */
900 if (mode == 0) { /* argument to fork */
902 exitstatus = waitforjob(jp, &realstatus);
904 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
905 evalskip = SKIPBREAK;
906 skipcount = loopnest;
908 } else if (mode == 2) {
909 backcmd->fd = pip[0];
916 setvar("_", lastarg, 0);
917 if (do_clearcmdentry)
919 popstackmark(&smark);
925 * Search for a command. This is called before we fork so that the
926 * location of the command will be available in the parent as well as
927 * the child. The check for "goodname" is an overly conservative
928 * check that the name will not be subject to expansion.
932 prehash(union node *n)
934 struct cmdentry entry;
936 if (n->type == NCMD && n->ncmd.args)
937 if (goodname(n->ncmd.args->narg.text))
938 find_command(n->ncmd.args->narg.text, &entry, 0,
945 * Builtin commands. Builtin commands whose functions are closely
946 * tied to evaluation are implemented here.
950 * No command given, or a bltin command with no arguments. Set the
951 * specified variables.
955 bltincmd(int argc __unused, char **argv __unused)
957 listsetvar(cmdenviron);
959 * Preserve exitstatus of a previous possible redirection
967 * Handle break and continue commands. Break, continue, and return are
968 * all handled by setting the evalskip flag. The evaluation routines
969 * above all check this flag, and if it is set they start skipping
970 * commands rather than executing them. The variable skipcount is
971 * the number of loops to break/continue, or the number of function
972 * levels to return. (The latter is always 1.) It should probably
973 * be an error to break out of more loops than exist, but it isn't
974 * in the standard shell so we don't make it one here.
978 breakcmd(int argc, char **argv)
980 int n = argc > 1 ? number(argv[1]) : 1;
985 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
992 * The `command' command.
995 commandcmd(int argc, char **argv)
997 static char stdpath[] = _PATH_STDPATH;
998 struct jmploc loc, *old;
1003 for (sp = cmdenviron; sp ; sp = sp->next)
1004 setvareq(sp->text, VEXPORT|VSTACK);
1007 optind = optreset = 1;
1009 while ((ch = getopt(argc, argv, "p")) != -1) {
1016 error("unknown option: -%c", optopt);
1025 if (setjmp(handler->loc) == 0)
1026 shellexec(argv, environment(), path, 0);
1028 if (exception == EXEXEC)
1034 * Do nothing successfully if no command was specified;
1035 * ksh also does this.
1042 * The return command.
1046 returncmd(int argc, char **argv)
1048 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1051 evalskip = SKIPFUNC;
1054 /* skip the rest of the file */
1055 evalskip = SKIPFILE;
1063 falsecmd(int argc __unused, char **argv __unused)
1070 truecmd(int argc __unused, char **argv __unused)
1077 execcmd(int argc, char **argv)
1082 iflag = 0; /* exit on error */
1085 for (sp = cmdenviron; sp ; sp = sp->next)
1086 setvareq(sp->text, VEXPORT|VSTACK);
1087 shellexec(argv + 1, environment(), pathval(), 0);