Resync patch with contrib.
[dragonfly.git] / bin / sh / eval.c
blobae6a39178901e3d516fce2f7b320d30dc071087c
1 /*-
2 * Copyright (c) 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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
34 * SUCH DAMAGE.
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 $
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <sys/wait.h> /* For WIFSIGNALED(status) */
45 #include <errno.h>
46 #include <paths.h>
47 #include <signal.h>
48 #include <stdlib.h>
49 #include <unistd.h>
52 * Evaluate a command.
55 #include "shell.h"
56 #include "nodes.h"
57 #include "syntax.h"
58 #include "expand.h"
59 #include "parser.h"
60 #include "jobs.h"
61 #include "eval.h"
62 #include "builtins.h"
63 #include "options.h"
64 #include "exec.h"
65 #include "redir.h"
66 #include "input.h"
67 #include "output.h"
68 #include "trap.h"
69 #include "var.h"
70 #include "memalloc.h"
71 #include "error.h"
72 #include "show.h"
73 #include "mystring.h"
74 #ifndef NO_HISTORY
75 #include "myhistedit.h"
76 #endif
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.
110 #ifdef mkinit
111 INCLUDE "eval.h"
113 RESET {
114 evalskip = 0;
115 loopnest = 0;
116 funcnest = 0;
119 SHELLPROC {
120 exitstatus = 0;
122 #endif
127 * The eval command.
131 evalcmd(int argc, char **argv)
133 char *p;
134 char *concat;
135 char **ap;
137 if (argc > 1) {
138 p = argv[1];
139 if (argc > 2) {
140 STARTSTACKSTR(concat);
141 ap = argv + 2;
142 for (;;) {
143 while (*p)
144 STPUTC(*p++, concat);
145 if ((p = *ap++) == NULL)
146 break;
147 STPUTC(' ', concat);
149 STPUTC('\0', concat);
150 p = grabstackstr(concat);
152 evalstring(p);
154 return exitstatus;
159 * Execute a command or commands contained in a string.
162 void
163 evalstring(char *s)
165 union node *n;
166 struct stackmark smark;
168 setstackmark(&smark);
169 setinputstring(s, 1);
170 while ((n = parsecmd(0)) != NEOF) {
171 evaltree(n, 0);
172 popstackmark(&smark);
174 popfile();
175 popstackmark(&smark);
181 * Evaluate a parse tree. The value is left in the global variable
182 * exitstatus.
185 void
186 evaltree(union node *n, int flags)
188 int do_etest;
190 do_etest = 0;
191 if (n == NULL) {
192 TRACE(("evaltree(NULL) called\n"));
193 exitstatus = 0;
194 goto out;
196 #ifndef NO_HISTORY
197 displayhist = 1; /* show history substitutions done with fc */
198 #endif
199 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
200 switch (n->type) {
201 case NSEMI:
202 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
203 if (evalskip)
204 goto out;
205 evaltree(n->nbinary.ch2, flags);
206 break;
207 case NAND:
208 evaltree(n->nbinary.ch1, EV_TESTED);
209 if (evalskip || exitstatus != 0) {
210 goto out;
212 evaltree(n->nbinary.ch2, flags);
213 break;
214 case NOR:
215 evaltree(n->nbinary.ch1, EV_TESTED);
216 if (evalskip || exitstatus == 0)
217 goto out;
218 evaltree(n->nbinary.ch2, flags);
219 break;
220 case NREDIR:
221 expredir(n->nredir.redirect);
222 redirect(n->nredir.redirect, REDIR_PUSH);
223 evaltree(n->nredir.n, flags);
224 popredir();
225 break;
226 case NSUBSHELL:
227 evalsubshell(n, flags);
228 do_etest = !(flags & EV_TESTED);
229 break;
230 case NBACKGND:
231 evalsubshell(n, flags);
232 break;
233 case NIF: {
234 evaltree(n->nif.test, EV_TESTED);
235 if (evalskip)
236 goto out;
237 if (exitstatus == 0)
238 evaltree(n->nif.ifpart, flags);
239 else if (n->nif.elsepart)
240 evaltree(n->nif.elsepart, flags);
241 else
242 exitstatus = 0;
243 break;
245 case NWHILE:
246 case NUNTIL:
247 evalloop(n, flags & ~EV_EXIT);
248 break;
249 case NFOR:
250 evalfor(n, flags & ~EV_EXIT);
251 break;
252 case NCASE:
253 evalcase(n, flags);
254 break;
255 case NDEFUN:
256 defun(n->narg.text, n->narg.next);
257 exitstatus = 0;
258 break;
259 case NNOT:
260 evaltree(n->nnot.com, EV_TESTED);
261 exitstatus = !exitstatus;
262 break;
264 case NPIPE:
265 evalpipe(n);
266 do_etest = !(flags & EV_TESTED);
267 break;
268 case NCMD:
269 evalcommand(n, flags, (struct backcmd *)NULL);
270 do_etest = !(flags & EV_TESTED);
271 break;
272 default:
273 out1fmt("Node type = %d\n", n->type);
274 flushout(&output);
275 break;
277 out:
278 if (pendingsigs)
279 dotrap();
280 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
281 exitshell(exitstatus);
285 STATIC void
286 evalloop(union node *n, int flags)
288 int status;
290 loopnest++;
291 status = 0;
292 for (;;) {
293 evaltree(n->nbinary.ch1, EV_TESTED);
294 if (evalskip) {
295 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
296 evalskip = 0;
297 continue;
299 if (evalskip == SKIPBREAK && --skipcount <= 0)
300 evalskip = 0;
301 break;
303 if (n->type == NWHILE) {
304 if (exitstatus != 0)
305 break;
306 } else {
307 if (exitstatus == 0)
308 break;
310 evaltree(n->nbinary.ch2, flags);
311 status = exitstatus;
312 if (evalskip)
313 goto skipping;
315 loopnest--;
316 exitstatus = status;
321 STATIC void
322 evalfor(union node *n, int flags)
324 struct arglist arglist;
325 union node *argp;
326 struct strlist *sp;
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);
334 if (evalskip)
335 goto out;
337 *arglist.lastp = NULL;
339 exitstatus = 0;
340 loopnest++;
341 for (sp = arglist.list ; sp ; sp = sp->next) {
342 setvar(n->nfor.var, sp->text, 0);
343 evaltree(n->nfor.body, flags);
344 if (evalskip) {
345 if (evalskip == SKIPCONT && --skipcount <= 0) {
346 evalskip = 0;
347 continue;
349 if (evalskip == SKIPBREAK && --skipcount <= 0)
350 evalskip = 0;
351 break;
354 loopnest--;
355 out:
356 popstackmark(&smark);
361 STATIC void
362 evalcase(union node *n, int flags)
364 union node *cp;
365 union node *patp;
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)) {
376 if (evalskip == 0) {
377 evaltree(cp->nclist.body, flags);
379 goto out;
383 out:
384 popstackmark(&smark);
390 * Kick off a subshell to evaluate a tree.
393 STATIC void
394 evalsubshell(union node *n, int flags)
396 struct job *jp;
397 int backgnd = (n->type == NBACKGND);
399 expredir(n->nredir.redirect);
400 jp = makejob(n, 1);
401 if (forkshell(jp, n, backgnd) == 0) {
402 if (backgnd)
403 flags &=~ EV_TESTED;
404 redirect(n->nredir.redirect, 0);
405 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
407 if (! backgnd) {
408 INTOFF;
409 exitstatus = waitforjob(jp, (int *)NULL);
410 INTON;
417 * Compute the names of the files in a redirection list.
420 STATIC void
421 expredir(union node *n)
423 union node *redir;
425 for (redir = n ; redir ; redir = redir->nfile.next) {
426 struct arglist fn;
427 fn.lastp = &fn.list;
428 oexitstatus = exitstatus;
429 switch (redir->type) {
430 case NFROM:
431 case NTO:
432 case NFROMTO:
433 case NAPPEND:
434 case NCLOBBER:
435 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
436 redir->nfile.expfname = fn.list->text;
437 break;
438 case NFROMFD:
439 case NTOFD:
440 if (redir->ndup.vname) {
441 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
442 fixredir(redir, fn.list->text, 1);
444 break;
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
455 * of all the rest.)
458 STATIC void
459 evalpipe(union node *n)
461 struct job *jp;
462 struct nodelist *lp;
463 int pipelen;
464 int prevfd;
465 int pip[2];
467 TRACE(("evalpipe(%p) called\n", (void *)n));
468 pipelen = 0;
469 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
470 pipelen++;
471 INTOFF;
472 jp = makejob(n, pipelen);
473 prevfd = -1;
474 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
475 prehash(lp->n);
476 pip[1] = -1;
477 if (lp->next) {
478 if (pipe(pip) < 0) {
479 if (prevfd >= 0)
480 close(prevfd);
481 error("Pipe call failed: %s", strerror(errno));
484 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
485 INTON;
486 if (prevfd > 0) {
487 dup2(prevfd, 0);
488 close(prevfd);
490 if (pip[1] >= 0) {
491 if (!(prevfd >= 0 && pip[0] == 0))
492 close(pip[0]);
493 if (pip[1] != 1) {
494 dup2(pip[1], 1);
495 close(pip[1]);
498 evaltree(lp->n, EV_EXIT);
500 if (prevfd >= 0)
501 close(prevfd);
502 prevfd = pip[0];
503 close(pip[1]);
505 INTON;
506 if (n->npipe.backgnd == 0) {
507 INTOFF;
508 exitstatus = waitforjob(jp, (int *)NULL);
509 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
510 INTON;
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.
523 void
524 evalbackcmd(union node *n, struct backcmd *result)
526 int pip[2];
527 struct job *jp;
528 struct stackmark smark; /* unnecessary */
530 setstackmark(&smark);
531 result->fd = -1;
532 result->buf = NULL;
533 result->nleft = 0;
534 result->jp = NULL;
535 if (n == NULL) {
536 exitstatus = 0;
537 goto out;
539 if (n->type == NCMD) {
540 exitstatus = oexitstatus;
541 evalcommand(n, EV_BACKCMD, result);
542 } else {
543 exitstatus = 0;
544 if (pipe(pip) < 0)
545 error("Pipe call failed: %s", strerror(errno));
546 jp = makejob(n, 1);
547 if (forkshell(jp, n, FORK_NOJOB) == 0) {
548 FORCEINTON;
549 close(pip[0]);
550 if (pip[1] != 1) {
551 dup2(pip[1], 1);
552 close(pip[1]);
554 evaltree(n, EV_EXIT);
556 close(pip[1]);
557 result->fd = pip[0];
558 result->jp = jp;
560 out:
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.
572 STATIC void
573 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd)
575 struct stackmark smark;
576 union node *argp;
577 struct arglist arglist;
578 struct arglist varlist;
579 volatile int flags = flgs;
580 char **volatile argv;
581 volatile int argc;
582 char **envp;
583 int varflag;
584 struct strlist *sp;
585 int mode;
586 int pip[2];
587 struct cmdentry cmdentry;
588 struct job *jp;
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;
594 volatile int e;
595 char *volatile lastarg;
596 int realstatus;
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;
604 varflag = 1;
605 do_clearcmdentry = 0;
606 oexitstatus = exitstatus;
607 exitstatus = 0;
608 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
609 char *p = argp->narg.text;
610 if (varflag && is_name(*p)) {
611 do {
612 p++;
613 } while (is_in_name(*p));
614 if (*p == '=') {
615 expandarg(argp, &varlist, EXP_VARTILDE);
616 continue;
619 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
620 varflag = 0;
622 *arglist.lastp = NULL;
623 *varlist.lastp = NULL;
624 expredir(cmd->ncmd.redirect);
625 argc = 0;
626 for (sp = arglist.list ; sp ; sp = sp->next)
627 argc++;
628 argv = stalloc(sizeof (char *) * (argc + 1));
630 for (sp = arglist.list ; sp ; sp = sp->next) {
631 TRACE(("evalcommand arg: %s\n", sp->text));
632 *argv++ = sp->text;
634 *argv = NULL;
635 lastarg = NULL;
636 if (iflag && funcnest == 0 && argc > 0)
637 lastarg = argv[-1];
638 argv -= argc;
640 /* Print the command if xflag is set. */
641 if (xflag) {
642 char sep = 0;
643 out2str(ps4val());
644 for (sp = varlist.list ; sp ; sp = sp->next) {
645 if (sep != 0)
646 outc(' ', &errout);
647 out2str(sp->text);
648 sep = ' ';
650 for (sp = arglist.list ; sp ; sp = sp->next) {
651 if (sep != 0)
652 outc(' ', &errout);
653 out2str(sp->text);
654 sep = ' ';
656 outc('\n', &errout);
657 flushout(&errout);
660 /* Now locate the command. */
661 if (argc == 0) {
662 /* Variable assignment(s) without command */
663 cmdentry.cmdtype = CMDBUILTIN;
664 cmdentry.u.index = BLTINCMD;
665 cmdentry.special = 1;
666 } else {
667 static const char PATH[] = "PATH=";
668 const char *path = pathval();
671 * Modify the command lookup path, if a PATH= assignment
672 * is present
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.
695 clearcmdentry(0);
696 do_clearcmdentry = 1;
699 find_command(argv[0], &cmdentry, 1, path);
700 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
701 exitstatus = 127;
702 flushout(&errout);
703 return;
705 /* implement the bltin builtin here */
706 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
707 for (;;) {
708 argv++;
709 if (--argc == 0)
710 break;
711 if ((cmdentry.u.index = find_builtin(*argv,
712 &cmdentry.special)) < 0) {
713 outfmt(&errout, "%s: not found\n", *argv);
714 exitstatus = 127;
715 flushout(&errout);
716 return;
718 if (cmdentry.u.index != BLTINCMD)
719 break;
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) {
738 mode = FORK_NOJOB;
739 if (pipe(pip) < 0)
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) {
745 FORCEINTON;
746 close(pip[0]);
747 if (pip[1] != 1) {
748 dup2(pip[1], 1);
749 close(pip[1]);
752 flags |= EV_EXIT;
755 /* This is the child process if a fork occurred. */
756 /* Execute the command. */
757 if (cmdentry.cmdtype == CMDFUNCTION) {
758 #ifdef DEBUG
759 trputs("Shell function: "); trargs(argv);
760 #endif
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;
768 INTOFF;
769 savelocalvars = localvars;
770 localvars = NULL;
771 INTON;
772 if (setjmp(jmploc.loc)) {
773 if (exception == EXSHELLPROC)
774 freeparam(&saveparam);
775 else {
776 freeparam(&shellparam);
777 shellparam = saveparam;
779 poplocalvars();
780 localvars = savelocalvars;
781 handler = savehandler;
782 longjmp(handler->loc, 1);
784 savehandler = handler;
785 handler = &jmploc;
786 for (sp = varlist.list ; sp ; sp = sp->next)
787 mklocal(sp->text);
788 funcnest++;
789 if (flags & EV_TESTED)
790 evaltree(cmdentry.u.func, EV_TESTED);
791 else
792 evaltree(cmdentry.u.func, 0);
793 funcnest--;
794 INTOFF;
795 poplocalvars();
796 localvars = savelocalvars;
797 freeparam(&shellparam);
798 shellparam = saveparam;
799 handler = savehandler;
800 popredir();
801 INTON;
802 if (evalskip == SKIPFUNC) {
803 evalskip = 0;
804 skipcount = 0;
806 if (flags & EV_EXIT)
807 exitshell(exitstatus);
808 } else if (cmdentry.cmdtype == CMDBUILTIN) {
809 #ifdef DEBUG
810 trputs("builtin command: "); trargs(argv);
811 #endif
812 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
813 if (flags == EV_BACKCMD) {
814 memout.nleft = 0;
815 memout.nextc = memout.buf;
816 memout.bufsize = 64;
817 mode |= REDIR_BACKQ;
819 savecmdname = commandname;
820 cmdenviron = varlist.list;
821 e = -1;
822 if (setjmp(jmploc.loc)) {
823 e = exception;
824 exitstatus = (e == EXINT)? SIGINT+128 : 2;
825 goto cmddone;
827 savehandler = handler;
828 handler = &jmploc;
829 redirect(cmd->ncmd.redirect, mode);
830 if (cmdentry.special)
831 listsetvar(cmdenviron);
832 commandname = argv[0];
833 argptr = argv + 1;
834 optptr = NULL; /* initialize nextopt */
835 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
836 flushall();
837 cmddone:
838 cmdenviron = NULL;
839 out1 = &output;
840 out2 = &errout;
841 freestdout();
842 if (e != EXSHELLPROC) {
843 commandname = savecmdname;
844 if (flags & EV_EXIT) {
845 exitshell(exitstatus);
848 handler = savehandler;
849 if (e != -1) {
850 if ((e != EXERROR && e != EXEXEC)
851 || cmdentry.special)
852 exraise(e);
853 FORCEINTON;
855 if (cmdentry.u.index != EXECCMD)
856 popredir();
857 if (flags == EV_BACKCMD) {
858 backcmd->buf = memout.buf;
859 backcmd->nleft = memout.nextc - memout.buf;
860 memout.buf = NULL;
862 } else {
863 #ifdef DEBUG
864 trputs("normal command: "); trargs(argv);
865 #endif
866 clearredir();
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);
872 /*NOTREACHED*/
874 goto out;
876 parent: /* parent process gets here (if we forked) */
877 if (mode == 0) { /* argument to fork */
878 INTOFF;
879 exitstatus = waitforjob(jp, &realstatus);
880 INTON;
881 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
882 evalskip = SKIPBREAK;
883 skipcount = loopnest;
885 } else if (mode == 2) {
886 backcmd->fd = pip[0];
887 close(pip[1]);
888 backcmd->jp = jp;
891 out:
892 if (lastarg)
893 setvar("_", lastarg, 0);
894 if (do_clearcmdentry)
895 clearcmdentry(0);
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.
908 STATIC void
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,
916 pathval());
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
935 * as POSIX mandates
937 return exitstatus;
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;
957 if (n > loopnest)
958 n = loopnest;
959 if (n > 0) {
960 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
961 skipcount = n;
963 return 0;
967 * The `command' command.
970 commandcmd(int argc, char **argv)
972 static char stdpath[] = _PATH_STDPATH;
973 struct jmploc loc, *old;
974 struct strlist *sp;
975 const char *volatile path;
976 int ch;
977 int cmd = -1;
979 for (sp = cmdenviron; sp ; sp = sp->next)
980 setvareq(sp->text, VEXPORT|VSTACK);
981 path = pathval();
983 optind = optreset = 1;
984 opterr = 0;
985 while ((ch = getopt(argc, argv, "pvV")) != -1) {
986 switch (ch) {
987 case 'p':
988 path = stdpath;
989 break;
990 case 'v':
991 cmd = TYPECMD_SMALLV;
992 break;
993 case 'V':
994 cmd = TYPECMD_BIGV;
995 break;
996 case '?':
997 default:
998 error("unknown option: -%c", optopt);
1001 argc -= optind;
1002 argv += optind;
1004 if (cmd != -1) {
1005 if (argc != 1)
1006 error("wrong number of arguments");
1007 return typecmd_impl(2, argv - 1, cmd);
1009 if (argc != 0) {
1010 old = handler;
1011 handler = &loc;
1012 if (setjmp(handler->loc) == 0)
1013 shellexec(argv, environment(), path, 0);
1014 handler = old;
1015 if (exception == EXEXEC)
1016 exit(exerrno);
1017 exraise(exception);
1021 * Do nothing successfully if no command was specified;
1022 * ksh also does this.
1024 exit(0);
1029 * The return command.
1033 returncmd(int argc, char **argv)
1035 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1037 if (funcnest) {
1038 evalskip = SKIPFUNC;
1039 skipcount = 1;
1040 } else {
1041 /* skip the rest of the file */
1042 evalskip = SKIPFILE;
1043 skipcount = 1;
1045 return ret;
1050 falsecmd(int argc __unused, char **argv __unused)
1052 return 1;
1057 truecmd(int argc __unused, char **argv __unused)
1059 return 0;
1064 execcmd(int argc, char **argv)
1066 if (argc > 1) {
1067 struct strlist *sp;
1069 iflag = 0; /* exit on error */
1070 mflag = 0;
1071 optschanged();
1072 for (sp = cmdenviron; sp ; sp = sp->next)
1073 setvareq(sp->text, VEXPORT|VSTACK);
1074 shellexec(argv + 1, environment(), pathval(), 0);
1077 return 0;
1082 timescmd(int argc __unused, char **argv __unused)
1084 struct rusage ru;
1085 long shumins, shsmins, chumins, chsmins;
1086 double shusecs, shssecs, chusecs, chssecs;
1088 if (getrusage(RUSAGE_SELF, &ru) < 0)
1089 return 1;
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)
1095 return 1;
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);
1102 return 0;