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.53 2006/06/15 07:57:05 stefanf Exp $
38 * $DragonFly: src/bin/sh/eval.c,v 1.12 2007/02/04 19:45:24 corecode Exp $
42 #include <sys/resource.h>
43 #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 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 */
90 const char *commandname
;
91 struct strlist
*cmdenviron
;
92 int exitstatus
; /* exit status of last command */
93 int oexitstatus
; /* saved exit status */
96 STATIC
void evalloop(union node
*, int);
97 STATIC
void evalfor(union node
*, int);
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
)
192 TRACE(("evaltree(NULL) called\n"));
197 displayhist
= 1; /* show history substitutions done with fc */
199 TRACE(("evaltree(%p: %d) called\n", (void *)n
, n
->type
));
202 evaltree(n
->nbinary
.ch1
, flags
& ~EV_EXIT
);
205 evaltree(n
->nbinary
.ch2
, flags
);
208 evaltree(n
->nbinary
.ch1
, EV_TESTED
);
209 if (evalskip
|| exitstatus
!= 0) {
212 evaltree(n
->nbinary
.ch2
, flags
);
215 evaltree(n
->nbinary
.ch1
, EV_TESTED
);
216 if (evalskip
|| exitstatus
== 0)
218 evaltree(n
->nbinary
.ch2
, flags
);
221 expredir(n
->nredir
.redirect
);
222 redirect(n
->nredir
.redirect
, REDIR_PUSH
);
223 evaltree(n
->nredir
.n
, flags
);
227 evalsubshell(n
, flags
);
228 do_etest
= !(flags
& EV_TESTED
);
231 evalsubshell(n
, flags
);
234 evaltree(n
->nif
.test
, EV_TESTED
);
238 evaltree(n
->nif
.ifpart
, flags
);
239 else if (n
->nif
.elsepart
)
240 evaltree(n
->nif
.elsepart
, flags
);
247 evalloop(n
, flags
& ~EV_EXIT
);
250 evalfor(n
, flags
& ~EV_EXIT
);
256 defun(n
->narg
.text
, n
->narg
.next
);
260 evaltree(n
->nnot
.com
, EV_TESTED
);
261 exitstatus
= !exitstatus
;
266 do_etest
= !(flags
& EV_TESTED
);
269 evalcommand(n
, flags
, (struct backcmd
*)NULL
);
270 do_etest
= !(flags
& EV_TESTED
);
273 out1fmt("Node type = %d\n", n
->type
);
280 if ((flags
& EV_EXIT
) || (eflag
&& exitstatus
!= 0 && do_etest
))
281 exitshell(exitstatus
);
286 evalloop(union node
*n
, int flags
)
293 evaltree(n
->nbinary
.ch1
, EV_TESTED
);
295 skipping
: if (evalskip
== SKIPCONT
&& --skipcount
<= 0) {
299 if (evalskip
== SKIPBREAK
&& --skipcount
<= 0)
303 if (n
->type
== NWHILE
) {
310 evaltree(n
->nbinary
.ch2
, flags
);
322 evalfor(union node
*n
, int flags
)
324 struct arglist arglist
;
327 struct stackmark smark
;
329 setstackmark(&smark
);
330 arglist
.lastp
= &arglist
.list
;
331 for (argp
= n
->nfor
.args
; argp
; argp
= argp
->narg
.next
) {
332 oexitstatus
= exitstatus
;
333 expandarg(argp
, &arglist
, EXP_FULL
| EXP_TILDE
);
337 *arglist
.lastp
= NULL
;
341 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
342 setvar(n
->nfor
.var
, sp
->text
, 0);
343 evaltree(n
->nfor
.body
, flags
);
345 if (evalskip
== SKIPCONT
&& --skipcount
<= 0) {
349 if (evalskip
== SKIPBREAK
&& --skipcount
<= 0)
356 popstackmark(&smark
);
362 evalcase(union node
*n
, int flags
)
366 struct arglist arglist
;
367 struct stackmark smark
;
369 setstackmark(&smark
);
370 arglist
.lastp
= &arglist
.list
;
371 oexitstatus
= exitstatus
;
372 expandarg(n
->ncase
.expr
, &arglist
, EXP_TILDE
);
373 for (cp
= n
->ncase
.cases
; cp
&& evalskip
== 0 ; cp
= cp
->nclist
.next
) {
374 for (patp
= cp
->nclist
.pattern
; patp
; patp
= patp
->narg
.next
) {
375 if (casematch(patp
, arglist
.list
->text
)) {
377 evaltree(cp
->nclist
.body
, flags
);
384 popstackmark(&smark
);
390 * Kick off a subshell to evaluate a tree.
394 evalsubshell(union node
*n
, int flags
)
397 int backgnd
= (n
->type
== NBACKGND
);
399 expredir(n
->nredir
.redirect
);
401 if (forkshell(jp
, n
, backgnd
) == 0) {
404 redirect(n
->nredir
.redirect
, 0);
405 evaltree(n
->nredir
.n
, flags
| EV_EXIT
); /* never returns */
409 exitstatus
= waitforjob(jp
, (int *)NULL
);
417 * Compute the names of the files in a redirection list.
421 expredir(union node
*n
)
425 for (redir
= n
; redir
; redir
= redir
->nfile
.next
) {
428 oexitstatus
= exitstatus
;
429 switch (redir
->type
) {
435 expandarg(redir
->nfile
.fname
, &fn
, EXP_TILDE
| EXP_REDIR
);
436 redir
->nfile
.expfname
= fn
.list
->text
;
440 if (redir
->ndup
.vname
) {
441 expandarg(redir
->ndup
.vname
, &fn
, EXP_FULL
| EXP_TILDE
);
442 fixredir(redir
, fn
.list
->text
, 1);
452 * Evaluate a pipeline. All the processes in the pipeline are children
453 * of the process creating the pipeline. (This differs from some versions
454 * of the shell, which make the last process in a pipeline the parent
459 evalpipe(union node
*n
)
467 TRACE(("evalpipe(%p) called\n", (void *)n
));
469 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
)
472 jp
= makejob(n
, pipelen
);
474 for (lp
= n
->npipe
.cmdlist
; lp
; lp
= lp
->next
) {
481 error("Pipe call failed: %s", strerror(errno
));
484 if (forkshell(jp
, lp
->n
, n
->npipe
.backgnd
) == 0) {
491 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) {
554 evaltree(n
, EV_EXIT
);
561 popstackmark(&smark
);
562 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
563 result
->fd
, result
->buf
, result
->nleft
, result
->jp
));
569 * Execute a simple command.
573 evalcommand(union node
*cmd
, int flgs
, struct backcmd
*backcmd
)
575 struct stackmark smark
;
577 struct arglist arglist
;
578 struct arglist varlist
;
579 volatile int flags
= flgs
;
580 char **volatile argv
;
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
;
595 char *volatile lastarg
;
597 volatile int do_clearcmdentry
;
599 /* First expand the arguments. */
600 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd
, flags
));
601 setstackmark(&smark
);
602 arglist
.lastp
= &arglist
.list
;
603 varlist
.lastp
= &varlist
.list
;
605 do_clearcmdentry
= 0;
606 oexitstatus
= exitstatus
;
608 for (argp
= cmd
->ncmd
.args
; argp
; argp
= argp
->narg
.next
) {
609 char *p
= argp
->narg
.text
;
610 if (varflag
&& is_name(*p
)) {
613 } while (is_in_name(*p
));
615 expandarg(argp
, &varlist
, EXP_VARTILDE
);
619 expandarg(argp
, &arglist
, EXP_FULL
| EXP_TILDE
);
622 *arglist
.lastp
= NULL
;
623 *varlist
.lastp
= NULL
;
624 expredir(cmd
->ncmd
.redirect
);
626 for (sp
= arglist
.list
; sp
; sp
= sp
->next
)
628 argv
= stalloc(sizeof (char *) * (argc
+ 1));
630 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
631 TRACE(("evalcommand arg: %s\n", sp
->text
));
636 if (iflag
&& funcnest
== 0 && argc
> 0)
640 /* Print the command if xflag is set. */
644 for (sp
= varlist
.list
; sp
; sp
= sp
->next
) {
650 for (sp
= arglist
.list
; sp
; sp
= sp
->next
) {
660 /* Now locate the command. */
662 /* Variable assignment(s) without command */
663 cmdentry
.cmdtype
= CMDBUILTIN
;
664 cmdentry
.u
.index
= BLTINCMD
;
665 cmdentry
.special
= 1;
667 static const char PATH
[] = "PATH=";
668 const char *path
= pathval();
671 * Modify the command lookup path, if a PATH= assignment
674 for (sp
= varlist
.list
; sp
; sp
= sp
->next
)
675 if (strncmp(sp
->text
, PATH
, sizeof(PATH
) - 1) == 0) {
676 path
= sp
->text
+ sizeof(PATH
) - 1;
678 * On `PATH=... command`, we need to make
679 * sure that the command isn't using the
680 * non-updated hash table of the outer PATH
681 * setting and we need to make sure that
682 * the hash table isn't filled with items
683 * from the temporary setting.
685 * It would be better to forbit using and
686 * updating the table while this command
687 * runs, by the command finding mechanism
688 * is heavily integrated with hash handling,
689 * so we just delete the hash before and after
690 * the command runs. Partly deleting like
691 * changepatch() does doesn't seem worth the
692 * bookinging effort, since most such runs add
693 * directories in front of the new PATH.
696 do_clearcmdentry
= 1;
699 find_command(argv
[0], &cmdentry
, 1, path
);
700 if (cmdentry
.cmdtype
== CMDUNKNOWN
) { /* command not found */
705 /* implement the bltin builtin here */
706 if (cmdentry
.cmdtype
== CMDBUILTIN
&& cmdentry
.u
.index
== BLTINCMD
) {
711 if ((cmdentry
.u
.index
= find_builtin(*argv
,
712 &cmdentry
.special
)) < 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
) {
755 /* This is the child process if a fork occurred. */
756 /* Execute the command. */
757 if (cmdentry
.cmdtype
== CMDFUNCTION
) {
759 trputs("Shell function: "); trargs(argv
);
761 redirect(cmd
->ncmd
.redirect
, REDIR_PUSH
);
762 saveparam
= shellparam
;
763 shellparam
.malloc
= 0;
764 shellparam
.reset
= 1;
765 shellparam
.nparam
= argc
- 1;
766 shellparam
.p
= argv
+ 1;
767 shellparam
.optnext
= NULL
;
769 savelocalvars
= localvars
;
772 if (setjmp(jmploc
.loc
)) {
773 if (exception
== EXSHELLPROC
)
774 freeparam(&saveparam
);
776 freeparam(&shellparam
);
777 shellparam
= saveparam
;
780 localvars
= savelocalvars
;
781 handler
= savehandler
;
782 longjmp(handler
->loc
, 1);
784 savehandler
= handler
;
786 for (sp
= varlist
.list
; sp
; sp
= sp
->next
)
789 if (flags
& EV_TESTED
)
790 evaltree(cmdentry
.u
.func
, EV_TESTED
);
792 evaltree(cmdentry
.u
.func
, 0);
796 localvars
= savelocalvars
;
797 freeparam(&shellparam
);
798 shellparam
= saveparam
;
799 handler
= savehandler
;
802 if (evalskip
== SKIPFUNC
) {
807 exitshell(exitstatus
);
808 } else if (cmdentry
.cmdtype
== CMDBUILTIN
) {
810 trputs("builtin command: "); trargs(argv
);
812 mode
= (cmdentry
.u
.index
== EXECCMD
)? 0 : REDIR_PUSH
;
813 if (flags
== EV_BACKCMD
) {
815 memout
.nextc
= memout
.buf
;
819 savecmdname
= commandname
;
820 cmdenviron
= varlist
.list
;
822 if (setjmp(jmploc
.loc
)) {
824 exitstatus
= (e
== EXINT
)? SIGINT
+128 : 2;
827 savehandler
= handler
;
829 redirect(cmd
->ncmd
.redirect
, mode
);
830 if (cmdentry
.special
)
831 listsetvar(cmdenviron
);
832 commandname
= argv
[0];
834 optptr
= NULL
; /* initialize nextopt */
835 exitstatus
= (*builtinfunc
[cmdentry
.u
.index
])(argc
, argv
);
842 if (e
!= EXSHELLPROC
) {
843 commandname
= savecmdname
;
844 if (flags
& EV_EXIT
) {
845 exitshell(exitstatus
);
848 handler
= savehandler
;
850 if ((e
!= EXERROR
&& e
!= EXEXEC
)
855 if (cmdentry
.u
.index
!= EXECCMD
)
857 if (flags
== EV_BACKCMD
) {
858 backcmd
->buf
= memout
.buf
;
859 backcmd
->nleft
= memout
.nextc
- memout
.buf
;
864 trputs("normal command: "); trargs(argv
);
867 redirect(cmd
->ncmd
.redirect
, 0);
868 for (sp
= varlist
.list
; sp
; sp
= sp
->next
)
869 setvareq(sp
->text
, VEXPORT
|VSTACK
);
870 envp
= environment();
871 shellexec(argv
, envp
, pathval(), cmdentry
.u
.index
);
876 parent
: /* parent process gets here (if we forked) */
877 if (mode
== 0) { /* argument to fork */
879 exitstatus
= waitforjob(jp
, &realstatus
);
881 if (iflag
&& loopnest
> 0 && WIFSIGNALED(realstatus
)) {
882 evalskip
= SKIPBREAK
;
883 skipcount
= loopnest
;
885 } else if (mode
== 2) {
886 backcmd
->fd
= pip
[0];
893 setvar("_", lastarg
, 0);
894 if (do_clearcmdentry
)
896 popstackmark(&smark
);
902 * Search for a command. This is called before we fork so that the
903 * location of the command will be available in the parent as well as
904 * the child. The check for "goodname" is an overly conservative
905 * check that the name will not be subject to expansion.
909 prehash(union node
*n
)
911 struct cmdentry entry
;
913 if (n
&& n
->type
== NCMD
&& n
->ncmd
.args
)
914 if (goodname(n
->ncmd
.args
->narg
.text
))
915 find_command(n
->ncmd
.args
->narg
.text
, &entry
, 0,
922 * Builtin commands. Builtin commands whose functions are closely
923 * tied to evaluation are implemented here.
927 * No command given, or a bltin command with no arguments.
931 bltincmd(int argc __unused
, char **argv __unused
)
934 * Preserve exitstatus of a previous possible redirection
942 * Handle break and continue commands. Break, continue, and return are
943 * all handled by setting the evalskip flag. The evaluation routines
944 * above all check this flag, and if it is set they start skipping
945 * commands rather than executing them. The variable skipcount is
946 * the number of loops to break/continue, or the number of function
947 * levels to return. (The latter is always 1.) It should probably
948 * be an error to break out of more loops than exist, but it isn't
949 * in the standard shell so we don't make it one here.
953 breakcmd(int argc
, char **argv
)
955 int n
= argc
> 1 ? number(argv
[1]) : 1;
960 evalskip
= (**argv
== 'c')? SKIPCONT
: SKIPBREAK
;
967 * The `command' command.
970 commandcmd(int argc
, char **argv
)
972 static char stdpath
[] = _PATH_STDPATH
;
973 struct jmploc loc
, *old
;
975 const char *volatile path
;
979 for (sp
= cmdenviron
; sp
; sp
= sp
->next
)
980 setvareq(sp
->text
, VEXPORT
|VSTACK
);
983 optind
= optreset
= 1;
985 while ((ch
= getopt(argc
, argv
, "pvV")) != -1) {
991 cmd
= TYPECMD_SMALLV
;
998 error("unknown option: -%c", optopt
);
1006 error("wrong number of arguments");
1007 return typecmd_impl(2, argv
- 1, cmd
);
1012 if (setjmp(handler
->loc
) == 0)
1013 shellexec(argv
, environment(), path
, 0);
1015 if (exception
== EXEXEC
)
1021 * Do nothing successfully if no command was specified;
1022 * ksh also does this.
1029 * The return command.
1033 returncmd(int argc
, char **argv
)
1035 int ret
= argc
> 1 ? number(argv
[1]) : oexitstatus
;
1038 evalskip
= SKIPFUNC
;
1041 /* skip the rest of the file */
1042 evalskip
= SKIPFILE
;
1050 falsecmd(int argc __unused
, char **argv __unused
)
1057 truecmd(int argc __unused
, char **argv __unused
)
1064 execcmd(int argc
, char **argv
)
1069 iflag
= 0; /* exit on error */
1072 for (sp
= cmdenviron
; sp
; sp
= sp
->next
)
1073 setvareq(sp
->text
, VEXPORT
|VSTACK
);
1074 shellexec(argv
+ 1, environment(), pathval(), 0);
1082 timescmd(int argc __unused
, char **argv __unused
)
1085 long shumins
, shsmins
, chumins
, chsmins
;
1086 double shusecs
, shssecs
, chusecs
, chssecs
;
1088 if (getrusage(RUSAGE_SELF
, &ru
) < 0)
1090 shumins
= ru
.ru_utime
.tv_sec
/ 60;
1091 shusecs
= ru
.ru_utime
.tv_sec
% 60 + ru
.ru_utime
.tv_usec
/ 1000000.;
1092 shsmins
= ru
.ru_stime
.tv_sec
/ 60;
1093 shssecs
= ru
.ru_stime
.tv_sec
% 60 + ru
.ru_stime
.tv_usec
/ 1000000.;
1094 if (getrusage(RUSAGE_CHILDREN
, &ru
) < 0)
1096 chumins
= ru
.ru_utime
.tv_sec
/ 60;
1097 chusecs
= ru
.ru_utime
.tv_sec
% 60 + ru
.ru_utime
.tv_usec
/ 1000000.;
1098 chsmins
= ru
.ru_stime
.tv_sec
/ 60;
1099 chssecs
= ru
.ru_stime
.tv_sec
% 60 + ru
.ru_stime
.tv_usec
/ 1000000.;
1100 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins
,
1101 shusecs
, shsmins
, shssecs
, chumins
, chusecs
, chsmins
, chssecs
);