builtin: Process multi-byte characters in read(1)
[dash.git] / src / eval.c
blob140a734419fbe396e54e6f85fe68366746681ea4
1 /*-
2 * Copyright (c) 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1997-2005
5 * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
35 #include <stdlib.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <sys/types.h>
41 * Evaluate a command.
44 #include "init.h"
45 #include "main.h"
46 #include "shell.h"
47 #include "nodes.h"
48 #include "syntax.h"
49 #include "expand.h"
50 #include "parser.h"
51 #include "jobs.h"
52 #include "eval.h"
53 #include "builtins.h"
54 #include "options.h"
55 #include "exec.h"
56 #include "redir.h"
57 #include "input.h"
58 #include "output.h"
59 #include "trap.h"
60 #include "var.h"
61 #include "memalloc.h"
62 #include "error.h"
63 #include "show.h"
64 #include "mystring.h"
65 #ifndef SMALL
66 #include "myhistedit.h"
67 #endif
70 int evalskip; /* set if we are skipping commands */
71 STATIC int skipcount; /* number of levels to skip */
72 MKINIT int loopnest; /* current loop nesting level */
73 static int funcline; /* starting line number of current function, or 0 if not in a function */
76 char *commandname;
77 int exitstatus; /* exit status of last command */
78 int back_exitstatus; /* exit status of backquoted command */
79 int savestatus = -1; /* exit status of last command outside traps */
81 /* Prevent PS4 nesting. */
82 MKINIT int inps4;
84 MKINIT int tpip[2] = { -1 };
86 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
87 STATIC
88 #endif
89 void evaltreenr(union node *, int) __attribute__ ((__noreturn__));
90 STATIC int evalloop(union node *, int);
91 STATIC int evalfor(union node *, int);
92 STATIC int evalcase(union node *, int);
93 STATIC int evalsubshell(union node *, int);
94 STATIC void expredir(union node *);
95 STATIC int evalpipe(union node *, int);
96 #ifdef notyet
97 STATIC int evalcommand(union node *, int, struct backcmd *);
98 #else
99 STATIC int evalcommand(union node *, int);
100 #endif
101 STATIC int evalbltin(const struct builtincmd *, int, char **, int);
102 STATIC int evalfun(struct funcnode *, int, char **, int);
103 STATIC void prehash(union node *);
104 STATIC int eprintlist(struct output *, struct strlist *, int);
105 STATIC int bltincmd(int, char **);
108 STATIC const struct builtincmd bltin = {
109 .name = nullstr,
110 .builtin = bltincmd,
111 .flags = BUILTIN_REGULAR,
116 * Called to reset things after an exception.
119 #ifdef mkinit
120 INCLUDE "eval.h"
122 EXITRESET {
123 if (savestatus >= 0) {
124 if (exception == EXEXIT || evalskip == SKIPFUNCDEF)
125 exitstatus = savestatus;
126 savestatus = -1;
128 evalskip = 0;
129 loopnest = 0;
130 inps4 = 0;
132 if (tpip[0] >= 0) {
133 close(tpip[0]);
134 close(tpip[1]);
137 #endif
142 * The eval commmand.
145 static int evalcmd(int argc, char **argv, int flags)
147 char *p;
148 char *concat;
149 char **ap;
151 if (argc > 1) {
152 p = argv[1];
153 if (argc > 2) {
154 STARTSTACKSTR(concat);
155 ap = argv + 2;
156 for (;;) {
157 concat = stputs(p, concat);
158 if ((p = *ap++) == NULL)
159 break;
160 STPUTC(' ', concat);
162 STPUTC('\0', concat);
163 p = grabstackstr(concat);
165 return evalstring(p, flags & EV_TESTED);
167 return 0;
172 * Execute a command or commands contained in a string.
176 evalstring(char *s, int flags)
178 union node *n;
179 struct stackmark smark;
180 int status;
182 s = sstrdup(s);
183 setinputstring(s);
184 setstackmark(&smark);
186 status = 0;
187 for (; (n = parsecmd(0)) != NEOF; popstackmark(&smark)) {
188 int i;
190 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
191 if (n)
192 status = i;
194 if (evalskip)
195 break;
197 popstackmark(&smark);
198 popfile();
199 stunalloc(s);
201 return status;
207 * Evaluate a parse tree. The value is left in the global variable
208 * exitstatus.
212 evaltree(union node *n, int flags)
214 int checkexit = 0;
215 int (*evalfn)(union node *, int);
216 struct stackmark smark;
217 unsigned isor;
218 int status = 0;
220 setstackmark(&smark);
222 if (nflag)
223 goto out;
225 if (n == NULL) {
226 TRACE(("evaltree(NULL) called\n"));
227 goto out;
230 dotrap();
232 #ifndef SMALL
233 displayhist = 1; /* show history substitutions done with fc */
234 #endif
235 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
236 getpid(), n, n->type, flags));
237 switch (n->type) {
238 default:
239 #ifdef DEBUG
240 out1fmt("Node type = %d\n", n->type);
241 #ifndef USE_GLIBC_STDIO
242 flushout(out1);
243 #endif
244 break;
245 #endif
246 case NNOT:
247 status = evaltree(n->nnot.com, EV_TESTED);
248 if (!evalskip)
249 status = !status;
250 break;
251 case NREDIR:
252 errlinno = lineno = n->nredir.linno;
253 if (funcline)
254 lineno -= funcline - 1;
255 expredir(n->nredir.redirect);
256 pushredir(n->nredir.redirect);
257 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
258 if (status)
259 checkexit = EV_TESTED;
260 else
261 status = evaltree(n->nredir.n, flags & EV_TESTED);
262 if (n->nredir.redirect)
263 popredir(0);
264 break;
265 case NCMD:
266 evalfn = evalcommand;
267 checkexit:
268 checkexit = EV_TESTED;
269 goto calleval;
270 case NFOR:
271 evalfn = evalfor;
272 goto calleval;
273 case NWHILE:
274 case NUNTIL:
275 evalfn = evalloop;
276 goto calleval;
277 case NSUBSHELL:
278 case NBACKGND:
279 evalfn = evalsubshell;
280 goto checkexit;
281 case NPIPE:
282 evalfn = evalpipe;
283 goto checkexit;
284 case NCASE:
285 evalfn = evalcase;
286 goto calleval;
287 case NAND:
288 case NOR:
289 case NSEMI:
290 #if NAND + 1 != NOR
291 #error NAND + 1 != NOR
292 #endif
293 #if NOR + 1 != NSEMI
294 #error NOR + 1 != NSEMI
295 #endif
296 isor = n->type - NAND;
297 status = evaltree(n->nbinary.ch1,
298 (flags | ((isor >> 1) - 1)) & EV_TESTED);
299 if ((!status) == isor || evalskip)
300 break;
301 n = n->nbinary.ch2;
302 evaln:
303 evalfn = evaltree;
304 calleval:
305 status = evalfn(n, flags);
306 break;
307 case NIF:
308 status = evaltree(n->nif.test, EV_TESTED);
309 if (evalskip)
310 break;
311 if (!status) {
312 n = n->nif.ifpart;
313 goto evaln;
314 } else if (n->nif.elsepart) {
315 n = n->nif.elsepart;
316 goto evaln;
318 status = 0;
319 break;
320 case NDEFUN:
321 defun(n);
322 break;
325 exitstatus = status;
327 out:
328 dotrap();
330 if (eflag && (~flags & checkexit) && status)
331 goto exexit;
333 if (flags & EV_EXIT) {
334 exexit:
335 exraise(EXEND);
338 popstackmark(&smark);
340 return exitstatus;
344 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
345 STATIC
346 #endif
347 void evaltreenr(union node *n, int flags)
348 #ifdef HAVE_ATTRIBUTE_ALIAS
349 __attribute__ ((alias("evaltree")));
350 #else
352 evaltree(n, flags);
353 abort();
355 #endif
358 static int skiploop(void)
360 int skip = evalskip;
362 switch (skip) {
363 case 0:
364 break;
366 case SKIPBREAK:
367 case SKIPCONT:
368 if (likely(--skipcount <= 0)) {
369 evalskip = 0;
370 break;
373 skip = SKIPBREAK;
374 break;
377 return skip;
381 STATIC int
382 evalloop(union node *n, int flags)
384 int skip;
385 int status;
387 loopnest++;
388 status = 0;
389 flags &= EV_TESTED;
390 do {
391 int i;
393 i = evaltree(n->nbinary.ch1, EV_TESTED);
394 skip = skiploop();
395 if (skip == SKIPFUNC)
396 status = i;
397 if (skip)
398 continue;
399 if (n->type != NWHILE)
400 i = !i;
401 if (i != 0)
402 break;
403 status = evaltree(n->nbinary.ch2, flags);
404 skip = skiploop();
405 } while (!(skip & ~SKIPCONT));
406 loopnest--;
408 return status;
413 STATIC int
414 evalfor(union node *n, int flags)
416 struct arglist arglist;
417 union node *argp;
418 struct strlist *sp;
419 int status;
421 errlinno = lineno = n->nfor.linno;
422 if (funcline)
423 lineno -= funcline - 1;
425 arglist.lastp = &arglist.list;
426 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
427 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
429 *arglist.lastp = NULL;
431 status = 0;
432 loopnest++;
433 flags &= EV_TESTED;
434 for (sp = arglist.list ; sp ; sp = sp->next) {
435 setvar(n->nfor.var, sp->text, 0);
436 status = evaltree(n->nfor.body, flags);
437 if (skiploop() & ~SKIPCONT)
438 break;
440 loopnest--;
442 return status;
447 STATIC int
448 evalcase(union node *n, int flags)
450 union node *cp;
451 union node *patp;
452 struct arglist arglist;
453 int status = 0;
455 errlinno = lineno = n->ncase.linno;
456 if (funcline)
457 lineno -= funcline - 1;
459 arglist.lastp = &arglist.list;
460 expandarg(n->ncase.expr, &arglist, FNMATCH_IS_ENABLED ? EXP_TILDE :
461 EXP_TILDE | EXP_MBCHAR);
462 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
463 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
464 if (casematch(patp, arglist.list->text)) {
465 /* Ensure body is non-empty as otherwise
466 * EV_EXIT may prevent us from setting the
467 * exit status.
469 if (evalskip == 0 && cp->nclist.body) {
470 status = evaltree(cp->nclist.body,
471 flags);
473 goto out;
477 out:
478 return status;
484 * Kick off a subshell to evaluate a tree.
487 STATIC int
488 evalsubshell(union node *n, int flags)
490 struct job *jp;
491 int backgnd = (n->type == NBACKGND);
492 int status;
494 errlinno = lineno = n->nredir.linno;
495 if (funcline)
496 lineno -= funcline - 1;
498 expredir(n->nredir.redirect);
499 INTOFF;
500 if (!backgnd && flags & EV_EXIT && !have_traps()) {
501 forkreset(NULL);
502 goto nofork;
504 jp = makejob(1);
505 if (forkshell(jp, n->nredir.n, backgnd) == 0) {
506 flags |= EV_EXIT;
507 if (backgnd)
508 flags &=~ EV_TESTED;
509 nofork:
510 INTON;
511 redirect(n->nredir.redirect, 0);
512 evaltreenr(n->nredir.n, flags);
513 /* never returns */
515 status = 0;
516 if (! backgnd)
517 status = waitforjob(jp);
518 INTON;
519 return status;
525 * Compute the names of the files in a redirection list.
528 STATIC void
529 expredir(union node *n)
531 union node *redir;
533 for (redir = n ; redir ; redir = redir->nfile.next) {
534 struct arglist fn;
535 fn.lastp = &fn.list;
536 switch (redir->type) {
537 case NFROMTO:
538 case NFROM:
539 case NTO:
540 case NCLOBBER:
541 case NAPPEND:
542 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
543 redir->nfile.expfname = fn.list->text;
544 break;
545 case NFROMFD:
546 case NTOFD:
547 if (redir->ndup.vname) {
548 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
549 fixredir(redir, fn.list->text, 1);
551 break;
559 * Evaluate a pipeline. All the processes in the pipeline are children
560 * of the process creating the pipeline. (This differs from some versions
561 * of the shell, which make the last process in a pipeline the parent
562 * of all the rest.)
565 STATIC int
566 evalpipe(union node *n, int flags)
568 struct job *jp;
569 struct nodelist *lp;
570 int pipelen;
571 int prevfd;
572 int pip[2];
573 int status = 0;
575 TRACE(("evalpipe(0x%lx) called\n", (long)n));
576 pipelen = 0;
577 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
578 pipelen++;
579 flags |= EV_EXIT;
580 INTOFF;
581 jp = makejob(pipelen);
582 prevfd = -1;
583 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
584 prehash(lp->n);
585 pip[1] = -1;
586 if (lp->next) {
587 if (pipe(pip) < 0) {
588 close(prevfd);
589 sh_error("Pipe call failed");
592 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
593 INTON;
594 if (pip[1] >= 0) {
595 close(pip[0]);
597 if (prevfd > 0) {
598 dup2(prevfd, 0);
599 close(prevfd);
601 if (pip[1] > 1) {
602 dup2(pip[1], 1);
603 close(pip[1]);
605 evaltreenr(lp->n, flags);
606 /* never returns */
608 if (prevfd >= 0)
609 close(prevfd);
610 prevfd = pip[0];
611 close(pip[1]);
613 if (n->npipe.backgnd == 0) {
614 status = waitforjob(jp);
615 TRACE(("evalpipe: job done exit status %d\n", status));
617 INTON;
619 return status;
625 * Execute a command inside back quotes. If it's a builtin command, we
626 * want to save its output in a block obtained from malloc. Otherwise
627 * we fork off a subprocess and get the output of the command via a pipe.
628 * Should be called with interrupts off.
631 void
632 evalbackcmd(union node *n, struct backcmd *result)
634 struct job *jp;
635 int pip[2];
636 int pid;
638 result->fd = -1;
639 result->buf = NULL;
640 result->nleft = 0;
641 result->jp = NULL;
642 if (n == NULL) {
643 goto out;
646 sh_pipe(pip, 0);
647 tpip[0] = pip[0];
648 tpip[1] = pip[1];
649 jp = makejob(1);
650 pid = forkshell(jp, n, FORK_NOJOB);
651 tpip[0] = -1;
652 if (pid == 0) {
653 FORCEINTON;
654 close(pip[0]);
655 if (pip[1] != 1) {
656 dup2(pip[1], 1);
657 close(pip[1]);
659 ifsfree();
660 evaltreenr(n, EV_EXIT);
661 /* NOTREACHED */
663 close(pip[1]);
664 result->fd = pip[0];
665 result->jp = jp;
667 out:
668 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
669 result->fd, result->buf, result->nleft, result->jp));
672 static struct strlist *fill_arglist(struct arglist *arglist,
673 union node **argpp)
675 struct strlist **lastp = arglist->lastp;
676 union node *argp;
678 while ((argp = *argpp)) {
679 expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
680 *argpp = argp->narg.next;
681 if (*lastp)
682 break;
685 return *lastp;
688 static int parse_command_args(struct arglist *arglist, union node **argpp,
689 const char **path)
691 struct strlist *sp = arglist->list;
692 char *cp, c;
694 for (;;) {
695 sp = unlikely(sp->next) ? sp->next :
696 fill_arglist(arglist, argpp);
697 if (!sp)
698 return 0;
699 cp = sp->text;
700 if (*cp++ != '-')
701 break;
702 if (!(c = *cp++))
703 break;
704 if (c == '-' && !*cp) {
705 if (likely(!sp->next) && !fill_arglist(arglist, argpp))
706 return 0;
707 sp = sp->next;
708 break;
710 do {
711 switch (c) {
712 case 'p':
713 *path = defpath;
714 break;
715 default:
716 /* run 'typecmd' for other options */
717 return 0;
719 } while ((c = *cp++));
722 arglist->list = sp;
723 return DO_NOFUNC;
727 * Execute a simple command.
730 STATIC int
731 #ifdef notyet
732 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
733 #else
734 evalcommand(union node *cmd, int flags)
735 #endif
737 struct localvar_list *localvar_stop;
738 struct parsefile *file_stop;
739 struct redirtab *redir_stop;
740 union node *argp;
741 struct arglist arglist;
742 struct arglist varlist;
743 char **argv;
744 int argc;
745 struct strlist *osp;
746 struct strlist *sp;
747 #ifdef notyet
748 int pip[2];
749 #endif
750 struct cmdentry cmdentry;
751 struct job *jp;
752 char *lastarg;
753 const char *path;
754 int spclbltin;
755 int cmd_flag;
756 int execcmd;
757 int status;
758 char **nargv;
759 int vflags;
760 int vlocal;
762 errlinno = lineno = cmd->ncmd.linno;
763 if (funcline)
764 lineno -= funcline - 1;
766 /* First expand the arguments. */
767 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
768 file_stop = parsefile;
769 back_exitstatus = 0;
771 cmdentry.cmdtype = CMDBUILTIN;
772 cmdentry.u.cmd = &bltin;
773 varlist.lastp = &varlist.list;
774 *varlist.lastp = NULL;
775 arglist.lastp = &arglist.list;
776 *arglist.lastp = NULL;
778 cmd_flag = 0;
779 execcmd = 0;
780 spclbltin = -1;
781 vflags = 0;
782 vlocal = 0;
783 path = NULL;
785 argc = 0;
786 argp = cmd->ncmd.args;
787 if ((osp = fill_arglist(&arglist, &argp))) {
788 int pseudovarflag = 0;
790 for (;;) {
791 find_command(arglist.list->text, &cmdentry,
792 cmd_flag | DO_REGBLTIN, pathval());
794 vlocal++;
796 /* implement bltin and command here */
797 if (cmdentry.cmdtype != CMDBUILTIN)
798 break;
800 pseudovarflag = cmdentry.u.cmd->flags & BUILTIN_ASSIGN;
801 if (likely(spclbltin < 0)) {
802 spclbltin =
803 cmdentry.u.cmd->flags &
804 BUILTIN_SPECIAL
806 vlocal = spclbltin ^ BUILTIN_SPECIAL;
808 execcmd = cmdentry.u.cmd == EXECCMD;
809 if (likely(cmdentry.u.cmd != COMMANDCMD))
810 break;
812 cmd_flag = parse_command_args(&arglist, &argp, &path);
813 if (!cmd_flag)
814 break;
817 for (; argp; argp = argp->narg.next)
818 expandarg(argp, &arglist,
819 pseudovarflag &&
820 isassignment(argp->narg.text) ?
821 EXP_VARTILDE : EXP_FULL | EXP_TILDE);
823 for (sp = arglist.list; sp; sp = sp->next)
824 argc++;
826 if (execcmd && argc > 1)
827 vflags = VEXPORT;
830 localvar_stop = pushlocalvars(vlocal);
832 /* Reserve one extra spot at the front for shellexec. */
833 nargv = stalloc(sizeof (char *) * (argc + 2));
834 argv = ++nargv;
835 for (sp = arglist.list ; sp ; sp = sp->next) {
836 TRACE(("evalcommand arg: %s\n", sp->text));
837 *nargv++ = sp->text;
839 *nargv = NULL;
841 lastarg = NULL;
842 if (iflag && funcline == 0 && argc > 0)
843 lastarg = nargv[-1];
845 preverrout.fd = 2;
846 expredir(cmd->ncmd.redirect);
847 redir_stop = pushredir(cmd->ncmd.redirect);
848 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
850 if (unlikely(status)) {
851 bail:
852 exitstatus = status;
854 /* We have a redirection error. */
855 if (spclbltin > 0)
856 exraise(EXERROR);
858 goto out;
861 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
862 struct strlist **spp;
864 spp = varlist.lastp;
865 expandarg(argp, &varlist, EXP_VARTILDE);
867 if (vlocal)
868 mklocal((*spp)->text, VEXPORT);
869 else
870 setvareq((*spp)->text, vflags);
873 /* Print the command if xflag is set. */
874 if (xflag && !inps4) {
875 struct output *out;
876 int sep;
878 out = &preverrout;
879 inps4 = 1;
880 outstr(expandstr(ps4val()), out);
881 inps4 = 0;
882 sep = 0;
883 sep = eprintlist(out, varlist.list, sep);
884 eprintlist(out, osp, sep);
885 outcslow('\n', out);
886 #ifdef FLUSHERR
887 flushout(out);
888 #endif
891 /* Now locate the command. */
892 if (cmdentry.cmdtype != CMDBUILTIN ||
893 !(cmdentry.u.cmd->flags & BUILTIN_REGULAR)) {
894 path = unlikely(path) ? path : pathval();
895 find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
898 jp = NULL;
900 /* Execute the command. */
901 switch (cmdentry.cmdtype) {
902 case CMDUNKNOWN:
903 status = 127;
904 #ifdef FLUSHERR
905 flushout(&errout);
906 #endif
907 goto bail;
909 default:
910 /* Fork off a child process if necessary. */
911 if (!(flags & EV_EXIT) || have_traps()) {
912 INTOFF;
913 jp = vforkexec(cmd, argv, path, cmdentry.u.index);
914 break;
916 shellexec(argv, path, cmdentry.u.index);
917 /* NOTREACHED */
919 case CMDBUILTIN:
920 if (evalbltin(cmdentry.u.cmd, argc, argv, flags) &&
921 !(exception == EXERROR && spclbltin <= 0)) {
922 raise:
923 longjmp(handler->loc, 1);
925 break;
927 case CMDFUNCTION:
928 if (evalfun(cmdentry.u.func, argc, argv, flags))
929 goto raise;
930 break;
933 status = waitforjob(jp);
934 FORCEINTON;
936 out:
937 if (cmd->ncmd.redirect)
938 popredir(execcmd);
939 unwindredir(redir_stop);
940 unwindfiles(file_stop);
941 unwindlocalvars(localvar_stop);
942 if (lastarg)
943 /* dsl: I think this is intended to be used to support
944 * '_' in 'vi' command mode during line editing...
945 * However I implemented that within libedit itself.
947 setvar("_", lastarg, 0);
949 return status;
952 STATIC int
953 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
955 char *volatile savecmdname;
956 struct jmploc *volatile savehandler;
957 struct jmploc jmploc;
958 int status;
959 int i;
961 savecmdname = commandname;
962 savehandler = handler;
963 if ((i = setjmp(jmploc.loc)))
964 goto cmddone;
965 handler = &jmploc;
966 commandname = argv[0];
967 argptr = argv + 1;
968 optptr = NULL; /* initialize nextopt */
969 if (cmd == EVALCMD)
970 status = evalcmd(argc, argv, flags);
971 else
972 status = (*cmd->builtin)(argc, argv);
973 flushall();
974 if (outerr(out1))
975 sh_warnx("%s: I/O error", commandname);
976 status |= outerr(out1);
977 exitstatus = status;
978 cmddone:
979 freestdout();
980 commandname = savecmdname;
981 handler = savehandler;
983 return i;
986 STATIC int
987 evalfun(struct funcnode *func, int argc, char **argv, int flags)
989 volatile struct shparam saveparam;
990 struct jmploc *volatile savehandler;
991 struct jmploc jmploc;
992 int e;
993 int savefuncline;
994 int saveloopnest;
996 saveparam = shellparam;
997 savefuncline = funcline;
998 saveloopnest = loopnest;
999 savehandler = handler;
1000 if ((e = setjmp(jmploc.loc))) {
1001 goto funcdone;
1003 INTOFF;
1004 handler = &jmploc;
1005 shellparam.malloc = 0;
1006 func->count++;
1007 funcline = func->n.ndefun.linno;
1008 loopnest = 0;
1009 INTON;
1010 shellparam.nparam = argc - 1;
1011 shellparam.p = argv + 1;
1012 shellparam.optind = 1;
1013 shellparam.optoff = -1;
1014 evaltree(func->n.ndefun.body, flags & EV_TESTED);
1015 funcdone:
1016 INTOFF;
1017 loopnest = saveloopnest;
1018 funcline = savefuncline;
1019 freefunc(func);
1020 freeparam(&shellparam);
1021 shellparam = saveparam;
1022 handler = savehandler;
1023 INTON;
1024 evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
1025 return e;
1030 * Search for a command. This is called before we fork so that the
1031 * location of the command will be available in the parent as well as
1032 * the child. The check for "goodname" is an overly conservative
1033 * check that the name will not be subject to expansion.
1036 STATIC void
1037 prehash(union node *n)
1039 struct cmdentry entry;
1041 if (n->type == NCMD && n->ncmd.args)
1042 if (goodname(n->ncmd.args->narg.text))
1043 find_command(n->ncmd.args->narg.text, &entry, 0,
1044 pathval());
1050 * Builtin commands. Builtin commands whose functions are closely
1051 * tied to evaluation are implemented here.
1055 * No command given.
1058 STATIC int
1059 bltincmd(int argc, char **argv)
1062 * Preserve exitstatus of a previous possible redirection
1063 * as POSIX mandates
1065 return back_exitstatus;
1070 * Handle break and continue commands. Break, continue, and return are
1071 * all handled by setting the evalskip flag. The evaluation routines
1072 * above all check this flag, and if it is set they start skipping
1073 * commands rather than executing them. The variable skipcount is
1074 * the number of loops to break/continue, or the number of function
1075 * levels to return. (The latter is always 1.) It should probably
1076 * be an error to break out of more loops than exist, but it isn't
1077 * in the standard shell so we don't make it one here.
1081 breakcmd(int argc, char **argv)
1083 int n = argc > 1 ? number(argv[1]) : 1;
1085 if (n <= 0)
1086 badnum(argv[1]);
1087 if (n > loopnest)
1088 n = loopnest;
1089 if (n > 0) {
1090 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1091 skipcount = n;
1093 return 0;
1098 * The return command.
1102 returncmd(int argc, char **argv)
1104 int skip;
1105 int status;
1108 * If called outside a function, do what ksh does;
1109 * skip the rest of the file.
1111 if (argv[1]) {
1112 skip = SKIPFUNC;
1113 status = number(argv[1]);
1114 } else {
1115 skip = SKIPFUNCDEF;
1116 status = exitstatus;
1118 evalskip = skip;
1120 return status;
1125 falsecmd(int argc, char **argv)
1127 return 1;
1132 truecmd(int argc, char **argv)
1134 return 0;
1139 execcmd(int argc, char **argv)
1141 if (argc > 1) {
1142 iflag = 0; /* exit on error */
1143 mflag = 0;
1144 optschanged();
1145 shellexec(argv + 1, pathval(), 0);
1147 return 0;
1151 STATIC int
1152 eprintlist(struct output *out, struct strlist *sp, int sep)
1154 while (sp) {
1155 const char *p;
1157 p = " %s";
1158 p += (1 - sep);
1159 sep |= 1;
1160 outfmt(out, p, sp->text);
1161 sp = sp->next;
1164 return sep;