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.7 2006/06/19 12:05:43 corecode 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) {
207 evaltree(n->nbinary.ch2, flags);
210 evaltree(n->nbinary.ch1, EV_TESTED);
211 if (evalskip || exitstatus == 0)
213 evaltree(n->nbinary.ch2, flags);
216 expredir(n->nredir.redirect);
217 redirect(n->nredir.redirect, REDIR_PUSH);
218 evaltree(n->nredir.n, flags);
222 evalsubshell(n, flags);
225 evalsubshell(n, flags);
228 evaltree(n->nif.test, EV_TESTED);
232 evaltree(n->nif.ifpart, flags);
233 else if (n->nif.elsepart)
234 evaltree(n->nif.elsepart, flags);
250 defun(n->narg.text, n->narg.next);
254 evaltree(n->nnot.com, EV_TESTED);
255 exitstatus = !exitstatus;
262 evalcommand(n, flags, (struct backcmd *)NULL);
265 out1fmt("Node type = %d\n", n->type);
272 if ((flags & EV_EXIT) || (eflag && exitstatus
273 && !(flags & EV_TESTED) && (n->type == NCMD ||
274 n->type == NSUBSHELL)))
275 exitshell(exitstatus);
280 evalloop(union node *n)
287 evaltree(n->nbinary.ch1, EV_TESTED);
289 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
293 if (evalskip == SKIPBREAK && --skipcount <= 0)
297 if (n->type == NWHILE) {
304 evaltree(n->nbinary.ch2, 0);
316 evalfor(union node *n)
318 struct arglist arglist;
321 struct stackmark smark;
323 setstackmark(&smark);
324 arglist.lastp = &arglist.list;
325 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
326 oexitstatus = exitstatus;
327 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
331 *arglist.lastp = NULL;
335 for (sp = arglist.list ; sp ; sp = sp->next) {
336 setvar(n->nfor.var, sp->text, 0);
337 evaltree(n->nfor.body, 0);
339 if (evalskip == SKIPCONT && --skipcount <= 0) {
343 if (evalskip == SKIPBREAK && --skipcount <= 0)
350 popstackmark(&smark);
356 evalcase(union node *n, int flags)
360 struct arglist arglist;
361 struct stackmark smark;
363 setstackmark(&smark);
364 arglist.lastp = &arglist.list;
365 oexitstatus = exitstatus;
366 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
367 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
368 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
369 if (casematch(patp, arglist.list->text)) {
371 evaltree(cp->nclist.body, flags);
378 popstackmark(&smark);
384 * Kick off a subshell to evaluate a tree.
388 evalsubshell(union node *n, int flags)
391 int backgnd = (n->type == NBACKGND);
393 expredir(n->nredir.redirect);
395 if (forkshell(jp, n, backgnd) == 0) {
398 redirect(n->nredir.redirect, 0);
399 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
403 exitstatus = waitforjob(jp, (int *)NULL);
411 * Compute the names of the files in a redirection list.
415 expredir(union node *n)
419 for (redir = n ; redir ; redir = redir->nfile.next) {
422 oexitstatus = exitstatus;
423 switch (redir->type) {
429 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
430 redir->nfile.expfname = fn.list->text;
434 if (redir->ndup.vname) {
435 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
436 fixredir(redir, fn.list->text, 1);
446 * Evaluate a pipeline. All the processes in the pipeline are children
447 * of the process creating the pipeline. (This differs from some versions
448 * of the shell, which make the last process in a pipeline the parent
453 evalpipe(union node *n)
461 TRACE(("evalpipe(0x%lx) called\n", (long)n));
463 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
466 jp = makejob(n, pipelen);
468 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
475 error("Pipe call failed: %s", strerror(errno));
478 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
486 if (!(prevfd >= 0 && pip[0] == 0))
494 evaltree(lp->n, EV_EXIT);
502 if (n->npipe.backgnd == 0) {
504 exitstatus = waitforjob(jp, (int *)NULL);
505 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
513 * Execute a command inside back quotes. If it's a builtin command, we
514 * want to save its output in a block obtained from malloc. Otherwise
515 * we fork off a subprocess and get the output of the command via a pipe.
516 * Should be called with interrupts off.
520 evalbackcmd(union node *n, struct backcmd *result)
524 struct stackmark smark; /* unnecessary */
526 setstackmark(&smark);
535 if (n->type == NCMD) {
536 exitstatus = oexitstatus;
537 evalcommand(n, EV_BACKCMD, result);
541 error("Pipe call failed: %s", strerror(errno));
543 if (forkshell(jp, n, FORK_NOJOB) == 0) {
551 evaltree(n, EV_EXIT);
558 popstackmark(&smark);
559 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
560 result->fd, result->buf, result->nleft, result->jp));
566 * Execute a simple command.
570 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
572 struct stackmark smark;
574 struct arglist arglist;
575 struct arglist varlist;
583 struct cmdentry cmdentry;
585 struct jmploc jmploc;
586 struct jmploc *volatile savehandler = NULL;
587 const char *volatile savecmdname;
588 volatile struct shparam saveparam;
589 struct localvar *volatile savelocalvars;
593 int do_clearcmdentry;
595 /* Avoid longjmp clobbering */
600 (void) &do_clearcmdentry;
603 /* First expand the arguments. */
604 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
605 setstackmark(&smark);
606 arglist.lastp = &arglist.list;
607 varlist.lastp = &varlist.list;
609 do_clearcmdentry = 0;
610 oexitstatus = exitstatus;
612 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
613 char *p = argp->narg.text;
614 if (varflag && is_name(*p)) {
617 } while (is_in_name(*p));
619 expandarg(argp, &varlist, EXP_VARTILDE);
623 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
626 *arglist.lastp = NULL;
627 *varlist.lastp = NULL;
628 expredir(cmd->ncmd.redirect);
630 for (sp = arglist.list ; sp ; sp = sp->next)
632 argv = stalloc(sizeof (char *) * (argc + 1));
634 for (sp = arglist.list ; sp ; sp = sp->next) {
635 TRACE(("evalcommand arg: %s\n", sp->text));
640 if (iflag && funcnest == 0 && argc > 0)
644 /* Print the command if xflag is set. */
647 for (sp = varlist.list ; sp ; sp = sp->next) {
651 for (sp = arglist.list ; sp ; sp = sp->next) {
659 /* Now locate the command. */
661 cmdentry.cmdtype = CMDBUILTIN;
662 cmdentry.u.index = BLTINCMD;
664 static const char PATH[] = "PATH=";
665 const char *path = pathval();
668 * Modify the command lookup path, if a PATH= assignment
671 for (sp = varlist.list ; sp ; sp = sp->next)
672 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
673 path = sp->text + sizeof(PATH) - 1;
675 * On `PATH=... command`, we need to make
676 * sure that the command isn't using the
677 * non-updated hash table of the outer PATH
678 * setting and we need to make sure that
679 * the hash table isn't filled with items
680 * from the temporary setting.
682 * It would be better to forbit using and
683 * updating the table while this command
684 * runs, by the command finding mechanism
685 * is heavily integrated with hash handling,
686 * so we just delete the hash before and after
687 * the command runs. Partly deleting like
688 * changepatch() does doesn't seem worth the
689 * bookinging effort, since most such runs add
690 * diretories in front of the new PATH.
693 do_clearcmdentry = 1;
696 find_command(argv[0], &cmdentry, 1, path);
697 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
702 /* implement the bltin builtin here */
703 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
708 if ((cmdentry.u.index = find_builtin(*argv)) < 0) {
709 outfmt(&errout, "%s: not found\n", *argv);
714 if (cmdentry.u.index != BLTINCMD)
720 /* Fork off a child process if necessary. */
721 if (cmd->ncmd.backgnd
722 || (cmdentry.cmdtype == CMDNORMAL
723 && ((flags & EV_EXIT) == 0 || Tflag))
724 || ((flags & EV_BACKCMD) != 0
725 && (cmdentry.cmdtype != CMDBUILTIN
726 || cmdentry.u.index == CDCMD
727 || cmdentry.u.index == DOTCMD
728 || cmdentry.u.index == EVALCMD))
729 || (cmdentry.cmdtype == CMDBUILTIN &&
730 cmdentry.u.index == COMMANDCMD)) {
731 jp = makejob(cmd, 1);
732 mode = cmd->ncmd.backgnd;
733 if (flags & EV_BACKCMD) {
736 error("Pipe call failed: %s", strerror(errno));
738 if (forkshell(jp, cmd, mode) != 0)
739 goto parent; /* at end of routine */
740 if (flags & EV_BACKCMD) {
752 /* This is the child process if a fork occurred. */
753 /* Execute the command. */
754 if (cmdentry.cmdtype == CMDFUNCTION) {
756 trputs("Shell function: "); trargs(argv);
758 redirect(cmd->ncmd.redirect, REDIR_PUSH);
759 saveparam = shellparam;
760 shellparam.malloc = 0;
761 shellparam.reset = 1;
762 shellparam.nparam = argc - 1;
763 shellparam.p = argv + 1;
764 shellparam.optnext = NULL;
766 savelocalvars = localvars;
769 if (setjmp(jmploc.loc)) {
770 if (exception == EXSHELLPROC)
771 freeparam((struct shparam *)&saveparam);
773 freeparam(&shellparam);
774 shellparam = saveparam;
777 localvars = savelocalvars;
778 handler = savehandler;
779 longjmp(handler->loc, 1);
781 savehandler = handler;
783 for (sp = varlist.list ; sp ; sp = sp->next)
786 if (flags & EV_TESTED)
787 evaltree(cmdentry.u.func, EV_TESTED);
789 evaltree(cmdentry.u.func, 0);
793 localvars = savelocalvars;
794 freeparam(&shellparam);
795 shellparam = saveparam;
796 handler = savehandler;
799 if (evalskip == SKIPFUNC) {
804 exitshell(exitstatus);
805 } else if (cmdentry.cmdtype == CMDBUILTIN) {
807 trputs("builtin command: "); trargs(argv);
809 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
810 if (flags == EV_BACKCMD) {
812 memout.nextc = memout.buf;
816 redirect(cmd->ncmd.redirect, mode);
817 savecmdname = commandname;
818 cmdenviron = varlist.list;
820 if (setjmp(jmploc.loc)) {
822 exitstatus = (e == EXINT)? SIGINT+128 : 2;
825 savehandler = handler;
827 commandname = argv[0];
829 optptr = NULL; /* initialize nextopt */
830 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
837 if (e != EXSHELLPROC) {
838 commandname = savecmdname;
839 if (flags & EV_EXIT) {
840 exitshell(exitstatus);
843 handler = savehandler;
845 if ((e != EXERROR && e != EXEXEC)
846 || cmdentry.u.index == BLTINCMD
847 || cmdentry.u.index == DOTCMD
848 || cmdentry.u.index == EVALCMD
850 || cmdentry.u.index == HISTCMD
852 || cmdentry.u.index == EXECCMD
853 || cmdentry.u.index == COMMANDCMD)
857 if (cmdentry.u.index != EXECCMD)
859 if (flags == EV_BACKCMD) {
860 backcmd->buf = memout.buf;
861 backcmd->nleft = memout.nextc - memout.buf;
866 trputs("normal command: "); trargs(argv);
869 redirect(cmd->ncmd.redirect, 0);
870 for (sp = varlist.list ; sp ; sp = sp->next)
871 setvareq(sp->text, VEXPORT|VSTACK);
872 envp = environment();
873 shellexec(argv, envp, pathval(), cmdentry.u.index);
878 parent: /* parent process gets here (if we forked) */
879 if (mode == 0) { /* argument to fork */
881 exitstatus = waitforjob(jp, &realstatus);
883 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
884 evalskip = SKIPBREAK;
885 skipcount = loopnest;
887 } else if (mode == 2) {
888 backcmd->fd = pip[0];
895 setvar("_", lastarg, 0);
896 if (do_clearcmdentry)
898 popstackmark(&smark);
904 * Search for a command. This is called before we fork so that the
905 * location of the command will be available in the parent as well as
906 * the child. The check for "goodname" is an overly conservative
907 * check that the name will not be subject to expansion.
911 prehash(union node *n)
913 struct cmdentry entry;
915 if (n->type == NCMD && n->ncmd.args)
916 if (goodname(n->ncmd.args->narg.text))
917 find_command(n->ncmd.args->narg.text, &entry, 0,
924 * Builtin commands. Builtin commands whose functions are closely
925 * tied to evaluation are implemented here.
929 * No command given, or a bltin command with no arguments. Set the
930 * specified variables.
934 bltincmd(int argc __unused, char **argv __unused)
936 listsetvar(cmdenviron);
938 * Preserve exitstatus of a previous possible redirection
946 * Handle break and continue commands. Break, continue, and return are
947 * all handled by setting the evalskip flag. The evaluation routines
948 * above all check this flag, and if it is set they start skipping
949 * commands rather than executing them. The variable skipcount is
950 * the number of loops to break/continue, or the number of function
951 * levels to return. (The latter is always 1.) It should probably
952 * be an error to break out of more loops than exist, but it isn't
953 * in the standard shell so we don't make it one here.
957 breakcmd(int argc, char **argv)
959 int n = argc > 1 ? number(argv[1]) : 1;
964 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
971 * The `command' command.
974 commandcmd(int argc, char **argv)
976 static char stdpath[] = _PATH_STDPATH;
977 struct jmploc loc, *old;
983 /* Avoid longjmp clobbering */
989 for (sp = cmdenviron; sp ; sp = sp->next)
990 setvareq(sp->text, VEXPORT|VSTACK);
993 optind = optreset = 1;
995 while ((ch = getopt(argc, argv, "p")) != -1) {
1002 error("unknown option: -%c", optopt);
1011 if (setjmp(handler->loc) == 0)
1012 shellexec(argv, environment(), path, 0);
1014 if (exception == EXEXEC)
1020 * Do nothing successfully if no command was specified;
1021 * ksh also does this.
1028 * The return command.
1032 returncmd(int argc, char **argv)
1034 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1037 evalskip = SKIPFUNC;
1040 /* skip the rest of the file */
1041 evalskip = SKIPFILE;
1049 falsecmd(int argc __unused, char **argv __unused)
1056 truecmd(int argc __unused, char **argv __unused)
1063 execcmd(int argc, char **argv)
1068 iflag = 0; /* exit on error */
1071 for (sp = cmdenviron; sp ; sp = sp->next)
1072 setvareq(sp->text, VEXPORT|VSTACK);
1073 shellexec(argv + 1, environment(), pathval(), 0);