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.9 2006/09/28 22:29:44 pavalos 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 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 *, int);
95 STATIC void evalfor(union node *, int);
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)
190 TRACE(("evaltree(NULL) called\n"));
195 displayhist = 1; /* show history substitutions done with fc */
197 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
200 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
203 evaltree(n->nbinary.ch2, flags);
206 evaltree(n->nbinary.ch1, EV_TESTED);
207 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);
226 do_etest = !(flags & EV_TESTED);
229 evalsubshell(n, flags);
232 evaltree(n->nif.test, EV_TESTED);
236 evaltree(n->nif.ifpart, flags);
237 else if (n->nif.elsepart)
238 evaltree(n->nif.elsepart, flags);
245 evalloop(n, flags & ~EV_EXIT);
248 evalfor(n, flags & ~EV_EXIT);
254 defun(n->narg.text, n->narg.next);
258 evaltree(n->nnot.com, EV_TESTED);
259 exitstatus = !exitstatus;
264 do_etest = !(flags & EV_TESTED);
267 evalcommand(n, flags, (struct backcmd *)NULL);
268 do_etest = !(flags & EV_TESTED);
271 out1fmt("Node type = %d\n", n->type);
278 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
279 exitshell(exitstatus);
284 evalloop(union node *n, int flags)
291 evaltree(n->nbinary.ch1, EV_TESTED);
293 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
297 if (evalskip == SKIPBREAK && --skipcount <= 0)
301 if (n->type == NWHILE) {
308 evaltree(n->nbinary.ch2, flags);
320 evalfor(union node *n, int flags)
322 struct arglist arglist;
325 struct stackmark smark;
327 setstackmark(&smark);
328 arglist.lastp = &arglist.list;
329 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
330 oexitstatus = exitstatus;
331 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
335 *arglist.lastp = NULL;
339 for (sp = arglist.list ; sp ; sp = sp->next) {
340 setvar(n->nfor.var, sp->text, 0);
341 evaltree(n->nfor.body, flags);
343 if (evalskip == SKIPCONT && --skipcount <= 0) {
347 if (evalskip == SKIPBREAK && --skipcount <= 0)
354 popstackmark(&smark);
360 evalcase(union node *n, int flags)
364 struct arglist arglist;
365 struct stackmark smark;
367 setstackmark(&smark);
368 arglist.lastp = &arglist.list;
369 oexitstatus = exitstatus;
370 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
371 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
372 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
373 if (casematch(patp, arglist.list->text)) {
375 evaltree(cp->nclist.body, flags);
382 popstackmark(&smark);
388 * Kick off a subshell to evaluate a tree.
392 evalsubshell(union node *n, int flags)
395 int backgnd = (n->type == NBACKGND);
397 expredir(n->nredir.redirect);
399 if (forkshell(jp, n, backgnd) == 0) {
402 redirect(n->nredir.redirect, 0);
403 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
407 exitstatus = waitforjob(jp, (int *)NULL);
415 * Compute the names of the files in a redirection list.
419 expredir(union node *n)
423 for (redir = n ; redir ; redir = redir->nfile.next) {
426 oexitstatus = exitstatus;
427 switch (redir->type) {
433 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
434 redir->nfile.expfname = fn.list->text;
438 if (redir->ndup.vname) {
439 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
440 fixredir(redir, fn.list->text, 1);
450 * Evaluate a pipeline. All the processes in the pipeline are children
451 * of the process creating the pipeline. (This differs from some versions
452 * of the shell, which make the last process in a pipeline the parent
457 evalpipe(union node *n)
465 TRACE(("evalpipe(0x%lx) called\n", (long)n));
467 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
470 jp = makejob(n, pipelen);
472 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
479 error("Pipe call failed: %s", strerror(errno));
482 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
490 if (!(prevfd >= 0 && pip[0] == 0))
498 evaltree(lp->n, EV_EXIT);
506 if (n->npipe.backgnd == 0) {
508 exitstatus = waitforjob(jp, (int *)NULL);
509 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
517 * Execute a command inside back quotes. If it's a builtin command, we
518 * want to save its output in a block obtained from malloc. Otherwise
519 * we fork off a subprocess and get the output of the command via a pipe.
520 * Should be called with interrupts off.
524 evalbackcmd(union node *n, struct backcmd *result)
528 struct stackmark smark; /* unnecessary */
530 setstackmark(&smark);
539 if (n->type == NCMD) {
540 exitstatus = oexitstatus;
541 evalcommand(n, EV_BACKCMD, result);
545 error("Pipe call failed: %s", strerror(errno));
547 if (forkshell(jp, n, FORK_NOJOB) == 0) {
555 evaltree(n, EV_EXIT);
562 popstackmark(&smark);
563 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
564 result->fd, result->buf, result->nleft, result->jp));
570 * Execute a simple command.
574 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
576 struct stackmark smark;
578 struct arglist arglist;
579 struct arglist varlist;
587 struct cmdentry cmdentry;
589 struct jmploc jmploc;
590 struct jmploc *volatile savehandler = NULL;
591 const char *volatile savecmdname;
592 volatile struct shparam saveparam;
593 struct localvar *volatile savelocalvars;
597 int do_clearcmdentry;
599 /* Avoid longjmp clobbering */
604 (void) &do_clearcmdentry;
607 /* First expand the arguments. */
608 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
609 setstackmark(&smark);
610 arglist.lastp = &arglist.list;
611 varlist.lastp = &varlist.list;
613 do_clearcmdentry = 0;
614 oexitstatus = exitstatus;
616 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
617 char *p = argp->narg.text;
618 if (varflag && is_name(*p)) {
621 } while (is_in_name(*p));
623 expandarg(argp, &varlist, EXP_VARTILDE);
627 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
630 *arglist.lastp = NULL;
631 *varlist.lastp = NULL;
632 expredir(cmd->ncmd.redirect);
634 for (sp = arglist.list ; sp ; sp = sp->next)
636 argv = stalloc(sizeof (char *) * (argc + 1));
638 for (sp = arglist.list ; sp ; sp = sp->next) {
639 TRACE(("evalcommand arg: %s\n", sp->text));
644 if (iflag && funcnest == 0 && argc > 0)
648 /* Print the command if xflag is set. */
651 for (sp = varlist.list ; sp ; sp = sp->next) {
655 for (sp = arglist.list ; sp ; sp = sp->next) {
663 /* Now locate the command. */
665 cmdentry.cmdtype = CMDBUILTIN;
666 cmdentry.u.index = BLTINCMD;
668 static const char PATH[] = "PATH=";
669 const char *path = pathval();
672 * Modify the command lookup path, if a PATH= assignment
675 for (sp = varlist.list ; sp ; sp = sp->next)
676 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
677 path = sp->text + sizeof(PATH) - 1;
679 * On `PATH=... command`, we need to make
680 * sure that the command isn't using the
681 * non-updated hash table of the outer PATH
682 * setting and we need to make sure that
683 * the hash table isn't filled with items
684 * from the temporary setting.
686 * It would be better to forbit using and
687 * updating the table while this command
688 * runs, by the command finding mechanism
689 * is heavily integrated with hash handling,
690 * so we just delete the hash before and after
691 * the command runs. Partly deleting like
692 * changepatch() does doesn't seem worth the
693 * bookinging effort, since most such runs add
694 * diretories in front of the new PATH.
697 do_clearcmdentry = 1;
700 find_command(argv[0], &cmdentry, 1, path);
701 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
706 /* implement the bltin builtin here */
707 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
712 if ((cmdentry.u.index = find_builtin(*argv)) < 0) {
713 outfmt(&errout, "%s: not found\n", *argv);
718 if (cmdentry.u.index != BLTINCMD)
724 /* Fork off a child process if necessary. */
725 if (cmd->ncmd.backgnd
726 || (cmdentry.cmdtype == CMDNORMAL
727 && ((flags & EV_EXIT) == 0 || Tflag))
728 || ((flags & EV_BACKCMD) != 0
729 && (cmdentry.cmdtype != CMDBUILTIN
730 || cmdentry.u.index == CDCMD
731 || cmdentry.u.index == DOTCMD
732 || cmdentry.u.index == EVALCMD))
733 || (cmdentry.cmdtype == CMDBUILTIN &&
734 cmdentry.u.index == COMMANDCMD)) {
735 jp = makejob(cmd, 1);
736 mode = cmd->ncmd.backgnd;
737 if (flags & EV_BACKCMD) {
740 error("Pipe call failed: %s", strerror(errno));
742 if (forkshell(jp, cmd, mode) != 0)
743 goto parent; /* at end of routine */
744 if (flags & EV_BACKCMD) {
756 /* This is the child process if a fork occurred. */
757 /* Execute the command. */
758 if (cmdentry.cmdtype == CMDFUNCTION) {
760 trputs("Shell function: "); trargs(argv);
762 redirect(cmd->ncmd.redirect, REDIR_PUSH);
763 saveparam = shellparam;
764 shellparam.malloc = 0;
765 shellparam.reset = 1;
766 shellparam.nparam = argc - 1;
767 shellparam.p = argv + 1;
768 shellparam.optnext = NULL;
770 savelocalvars = localvars;
773 if (setjmp(jmploc.loc)) {
774 if (exception == EXSHELLPROC)
775 freeparam(&saveparam);
777 freeparam(&shellparam);
778 shellparam = saveparam;
781 localvars = savelocalvars;
782 handler = savehandler;
783 longjmp(handler->loc, 1);
785 savehandler = handler;
787 for (sp = varlist.list ; sp ; sp = sp->next)
790 if (flags & EV_TESTED)
791 evaltree(cmdentry.u.func, EV_TESTED);
793 evaltree(cmdentry.u.func, 0);
797 localvars = savelocalvars;
798 freeparam(&shellparam);
799 shellparam = saveparam;
800 handler = savehandler;
803 if (evalskip == SKIPFUNC) {
808 exitshell(exitstatus);
809 } else if (cmdentry.cmdtype == CMDBUILTIN) {
811 trputs("builtin command: "); trargs(argv);
813 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
814 if (flags == EV_BACKCMD) {
816 memout.nextc = memout.buf;
820 redirect(cmd->ncmd.redirect, mode);
821 savecmdname = commandname;
822 cmdenviron = varlist.list;
824 if (setjmp(jmploc.loc)) {
826 exitstatus = (e == EXINT)? SIGINT+128 : 2;
829 savehandler = handler;
831 commandname = argv[0];
833 optptr = NULL; /* initialize nextopt */
834 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
841 if (e != EXSHELLPROC) {
842 commandname = savecmdname;
843 if (flags & EV_EXIT) {
844 exitshell(exitstatus);
847 handler = savehandler;
849 if ((e != EXERROR && e != EXEXEC)
850 || cmdentry.u.index == BLTINCMD
851 || cmdentry.u.index == DOTCMD
852 || cmdentry.u.index == EVALCMD
854 || cmdentry.u.index == HISTCMD
856 || cmdentry.u.index == EXECCMD
857 || cmdentry.u.index == COMMANDCMD)
861 if (cmdentry.u.index != EXECCMD)
863 if (flags == EV_BACKCMD) {
864 backcmd->buf = memout.buf;
865 backcmd->nleft = memout.nextc - memout.buf;
870 trputs("normal command: "); trargs(argv);
873 redirect(cmd->ncmd.redirect, 0);
874 for (sp = varlist.list ; sp ; sp = sp->next)
875 setvareq(sp->text, VEXPORT|VSTACK);
876 envp = environment();
877 shellexec(argv, envp, pathval(), cmdentry.u.index);
882 parent: /* parent process gets here (if we forked) */
883 if (mode == 0) { /* argument to fork */
885 exitstatus = waitforjob(jp, &realstatus);
887 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
888 evalskip = SKIPBREAK;
889 skipcount = loopnest;
891 } else if (mode == 2) {
892 backcmd->fd = pip[0];
899 setvar("_", lastarg, 0);
900 if (do_clearcmdentry)
902 popstackmark(&smark);
908 * Search for a command. This is called before we fork so that the
909 * location of the command will be available in the parent as well as
910 * the child. The check for "goodname" is an overly conservative
911 * check that the name will not be subject to expansion.
915 prehash(union node *n)
917 struct cmdentry entry;
919 if (n->type == NCMD && n->ncmd.args)
920 if (goodname(n->ncmd.args->narg.text))
921 find_command(n->ncmd.args->narg.text, &entry, 0,
928 * Builtin commands. Builtin commands whose functions are closely
929 * tied to evaluation are implemented here.
933 * No command given, or a bltin command with no arguments. Set the
934 * specified variables.
938 bltincmd(int argc __unused, char **argv __unused)
940 listsetvar(cmdenviron);
942 * Preserve exitstatus of a previous possible redirection
950 * Handle break and continue commands. Break, continue, and return are
951 * all handled by setting the evalskip flag. The evaluation routines
952 * above all check this flag, and if it is set they start skipping
953 * commands rather than executing them. The variable skipcount is
954 * the number of loops to break/continue, or the number of function
955 * levels to return. (The latter is always 1.) It should probably
956 * be an error to break out of more loops than exist, but it isn't
957 * in the standard shell so we don't make it one here.
961 breakcmd(int argc, char **argv)
963 int n = argc > 1 ? number(argv[1]) : 1;
968 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
975 * The `command' command.
978 commandcmd(int argc, char **argv)
980 static char stdpath[] = _PATH_STDPATH;
981 struct jmploc loc, *old;
987 /* Avoid longjmp clobbering */
993 for (sp = cmdenviron; sp ; sp = sp->next)
994 setvareq(sp->text, VEXPORT|VSTACK);
997 optind = optreset = 1;
999 while ((ch = getopt(argc, argv, "p")) != -1) {
1006 error("unknown option: -%c", optopt);
1015 if (setjmp(handler->loc) == 0)
1016 shellexec(argv, environment(), path, 0);
1018 if (exception == EXEXEC)
1024 * Do nothing successfully if no command was specified;
1025 * ksh also does this.
1032 * The return command.
1036 returncmd(int argc, char **argv)
1038 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1041 evalskip = SKIPFUNC;
1044 /* skip the rest of the file */
1045 evalskip = SKIPFILE;
1053 falsecmd(int argc __unused, char **argv __unused)
1060 truecmd(int argc __unused, char **argv __unused)
1067 execcmd(int argc, char **argv)
1072 iflag = 0; /* exit on error */
1075 for (sp = cmdenviron; sp ; sp = sp->next)
1076 setvareq(sp->text, VEXPORT|VSTACK);
1077 shellexec(argv + 1, environment(), pathval(), 0);