]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/eval.c
Update BIND to version 9.6.1rc1. This version has better performance and
[FreeBSD/FreeBSD.git] / bin / sh / eval.c
1 /*-
2  * Copyright (c) 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)eval.c      8.9 (Berkeley) 6/8/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include <paths.h>
42 #include <signal.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <sys/resource.h>
46 #include <sys/wait.h> /* For WIFSIGNALED(status) */
47 #include <errno.h>
48
49 /*
50  * Evaluate a command.
51  */
52
53 #include "shell.h"
54 #include "nodes.h"
55 #include "syntax.h"
56 #include "expand.h"
57 #include "parser.h"
58 #include "jobs.h"
59 #include "eval.h"
60 #include "builtins.h"
61 #include "options.h"
62 #include "exec.h"
63 #include "redir.h"
64 #include "input.h"
65 #include "output.h"
66 #include "trap.h"
67 #include "var.h"
68 #include "memalloc.h"
69 #include "error.h"
70 #include "show.h"
71 #include "mystring.h"
72 #ifndef NO_HISTORY
73 #include "myhistedit.h"
74 #endif
75
76
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 */
81
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 */
86
87
88 char *commandname;
89 struct strlist *cmdenviron;
90 int exitstatus;                 /* exit status of last command */
91 int oexitstatus;                /* saved exit status */
92
93
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 *);
102
103
104 /*
105  * Called to reset things after an exception.
106  */
107
108 #ifdef mkinit
109 INCLUDE "eval.h"
110
111 RESET {
112         evalskip = 0;
113         loopnest = 0;
114         funcnest = 0;
115 }
116
117 SHELLPROC {
118         exitstatus = 0;
119 }
120 #endif
121
122
123
124 /*
125  * The eval command.
126  */
127
128 int
129 evalcmd(int argc, char **argv)
130 {
131         char *p;
132         char *concat;
133         char **ap;
134
135         if (argc > 1) {
136                 p = argv[1];
137                 if (argc > 2) {
138                         STARTSTACKSTR(concat);
139                         ap = argv + 2;
140                         for (;;) {
141                                 while (*p)
142                                         STPUTC(*p++, concat);
143                                 if ((p = *ap++) == NULL)
144                                         break;
145                                 STPUTC(' ', concat);
146                         }
147                         STPUTC('\0', concat);
148                         p = grabstackstr(concat);
149                 }
150                 evalstring(p);
151         }
152         return exitstatus;
153 }
154
155
156 /*
157  * Execute a command or commands contained in a string.
158  */
159
160 void
161 evalstring(char *s)
162 {
163         union node *n;
164         struct stackmark smark;
165
166         setstackmark(&smark);
167         setinputstring(s, 1);
168         while ((n = parsecmd(0)) != NEOF) {
169                 if (n != NULL)
170                         evaltree(n, 0);
171                 popstackmark(&smark);
172         }
173         popfile();
174         popstackmark(&smark);
175 }
176
177
178
179 /*
180  * Evaluate a parse tree.  The value is left in the global variable
181  * exitstatus.
182  */
183
184 void
185 evaltree(union node *n, int flags)
186 {
187         int do_etest;
188
189         do_etest = 0;
190         if (n == NULL) {
191                 TRACE(("evaltree(NULL) called\n"));
192                 exitstatus = 0;
193                 goto out;
194         }
195 #ifndef NO_HISTORY
196         displayhist = 1;        /* show history substitutions done with fc */
197 #endif
198         TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
199         switch (n->type) {
200         case NSEMI:
201                 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
202                 if (evalskip)
203                         goto out;
204                 evaltree(n->nbinary.ch2, flags);
205                 break;
206         case NAND:
207                 evaltree(n->nbinary.ch1, EV_TESTED);
208                 if (evalskip || exitstatus != 0) {
209                         goto out;
210                 }
211                 evaltree(n->nbinary.ch2, flags);
212                 break;
213         case NOR:
214                 evaltree(n->nbinary.ch1, EV_TESTED);
215                 if (evalskip || exitstatus == 0)
216                         goto out;
217                 evaltree(n->nbinary.ch2, flags);
218                 break;
219         case NREDIR:
220                 expredir(n->nredir.redirect);
221                 redirect(n->nredir.redirect, REDIR_PUSH);
222                 evaltree(n->nredir.n, flags);
223                 popredir();
224                 break;
225         case NSUBSHELL:
226                 evalsubshell(n, flags);
227                 do_etest = !(flags & EV_TESTED);
228                 break;
229         case NBACKGND:
230                 evalsubshell(n, flags);
231                 break;
232         case NIF: {
233                 evaltree(n->nif.test, EV_TESTED);
234                 if (evalskip)
235                         goto out;
236                 if (exitstatus == 0)
237                         evaltree(n->nif.ifpart, flags);
238                 else if (n->nif.elsepart)
239                         evaltree(n->nif.elsepart, flags);
240                 else
241                         exitstatus = 0;
242                 break;
243         }
244         case NWHILE:
245         case NUNTIL:
246                 evalloop(n, flags & ~EV_EXIT);
247                 break;
248         case NFOR:
249                 evalfor(n, flags & ~EV_EXIT);
250                 break;
251         case NCASE:
252                 evalcase(n, flags);
253                 break;
254         case NDEFUN:
255                 defun(n->narg.text, n->narg.next);
256                 exitstatus = 0;
257                 break;
258         case NNOT:
259                 evaltree(n->nnot.com, EV_TESTED);
260                 exitstatus = !exitstatus;
261                 break;
262
263         case NPIPE:
264                 evalpipe(n);
265                 do_etest = !(flags & EV_TESTED);
266                 break;
267         case NCMD:
268                 evalcommand(n, flags, (struct backcmd *)NULL);
269                 do_etest = !(flags & EV_TESTED);
270                 break;
271         default:
272                 out1fmt("Node type = %d\n", n->type);
273                 flushout(&output);
274                 break;
275         }
276 out:
277         if (pendingsigs)
278                 dotrap();
279         if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
280                 exitshell(exitstatus);
281 }
282
283
284 STATIC void
285 evalloop(union node *n, int flags)
286 {
287         int status;
288
289         loopnest++;
290         status = 0;
291         for (;;) {
292                 evaltree(n->nbinary.ch1, EV_TESTED);
293                 if (evalskip) {
294 skipping:         if (evalskip == SKIPCONT && --skipcount <= 0) {
295                                 evalskip = 0;
296                                 continue;
297                         }
298                         if (evalskip == SKIPBREAK && --skipcount <= 0)
299                                 evalskip = 0;
300                         break;
301                 }
302                 if (n->type == NWHILE) {
303                         if (exitstatus != 0)
304                                 break;
305                 } else {
306                         if (exitstatus == 0)
307                                 break;
308                 }
309                 evaltree(n->nbinary.ch2, flags);
310                 status = exitstatus;
311                 if (evalskip)
312                         goto skipping;
313         }
314         loopnest--;
315         exitstatus = status;
316 }
317
318
319
320 STATIC void
321 evalfor(union node *n, int flags)
322 {
323         struct arglist arglist;
324         union node *argp;
325         struct strlist *sp;
326         struct stackmark smark;
327
328         setstackmark(&smark);
329         arglist.lastp = &arglist.list;
330         for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
331                 oexitstatus = exitstatus;
332                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
333                 if (evalskip)
334                         goto out;
335         }
336         *arglist.lastp = NULL;
337
338         exitstatus = 0;
339         loopnest++;
340         for (sp = arglist.list ; sp ; sp = sp->next) {
341                 setvar(n->nfor.var, sp->text, 0);
342                 evaltree(n->nfor.body, flags);
343                 if (evalskip) {
344                         if (evalskip == SKIPCONT && --skipcount <= 0) {
345                                 evalskip = 0;
346                                 continue;
347                         }
348                         if (evalskip == SKIPBREAK && --skipcount <= 0)
349                                 evalskip = 0;
350                         break;
351                 }
352         }
353         loopnest--;
354 out:
355         popstackmark(&smark);
356 }
357
358
359
360 STATIC void
361 evalcase(union node *n, int flags)
362 {
363         union node *cp;
364         union node *patp;
365         struct arglist arglist;
366         struct stackmark smark;
367
368         setstackmark(&smark);
369         arglist.lastp = &arglist.list;
370         oexitstatus = exitstatus;
371         exitstatus = 0;
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);
378                                 }
379                                 goto out;
380                         }
381                 }
382         }
383 out:
384         popstackmark(&smark);
385 }
386
387
388
389 /*
390  * Kick off a subshell to evaluate a tree.
391  */
392
393 STATIC void
394 evalsubshell(union node *n, int flags)
395 {
396         struct job *jp;
397         int backgnd = (n->type == NBACKGND);
398
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 */
406         }
407         if (! backgnd) {
408                 INTOFF;
409                 exitstatus = waitforjob(jp, (int *)NULL);
410                 INTON;
411         }
412 }
413
414
415
416 /*
417  * Compute the names of the files in a redirection list.
418  */
419
420 STATIC void
421 expredir(union node *n)
422 {
423         union node *redir;
424
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_TILDE | EXP_REDIR);
442                                 fixredir(redir, fn.list->text, 1);
443                         }
444                         break;
445                 }
446         }
447 }
448
449
450
451 /*
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.)
456  */
457
458 STATIC void
459 evalpipe(union node *n)
460 {
461         struct job *jp;
462         struct nodelist *lp;
463         int pipelen;
464         int prevfd;
465         int pip[2];
466
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                                 close(prevfd);
480                                 error("Pipe call failed: %s", strerror(errno));
481                         }
482                 }
483                 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
484                         INTON;
485                         if (prevfd > 0) {
486                                 dup2(prevfd, 0);
487                                 close(prevfd);
488                         }
489                         if (pip[1] >= 0) {
490                                 if (!(prevfd >= 0 && pip[0] == 0))
491                                         close(pip[0]);
492                                 if (pip[1] != 1) {
493                                         dup2(pip[1], 1);
494                                         close(pip[1]);
495                                 }
496                         }
497                         evaltree(lp->n, EV_EXIT);
498                 }
499                 if (prevfd >= 0)
500                         close(prevfd);
501                 prevfd = pip[0];
502                 close(pip[1]);
503         }
504         INTON;
505         if (n->npipe.backgnd == 0) {
506                 INTOFF;
507                 exitstatus = waitforjob(jp, (int *)NULL);
508                 TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
509                 INTON;
510         }
511 }
512
513
514
515 /*
516  * Execute a command inside back quotes.  If it's a builtin command, we
517  * want to save its output in a block obtained from malloc.  Otherwise
518  * we fork off a subprocess and get the output of the command via a pipe.
519  * Should be called with interrupts off.
520  */
521
522 void
523 evalbackcmd(union node *n, struct backcmd *result)
524 {
525         int pip[2];
526         struct job *jp;
527         struct stackmark smark;         /* unnecessary */
528
529         setstackmark(&smark);
530         result->fd = -1;
531         result->buf = NULL;
532         result->nleft = 0;
533         result->jp = NULL;
534         if (n == NULL) {
535                 exitstatus = 0;
536                 goto out;
537         }
538         if (n->type == NCMD) {
539                 exitstatus = oexitstatus;
540                 evalcommand(n, EV_BACKCMD, result);
541         } else {
542                 exitstatus = 0;
543                 if (pipe(pip) < 0)
544                         error("Pipe call failed: %s", strerror(errno));
545                 jp = makejob(n, 1);
546                 if (forkshell(jp, n, FORK_NOJOB) == 0) {
547                         FORCEINTON;
548                         close(pip[0]);
549                         if (pip[1] != 1) {
550                                 dup2(pip[1], 1);
551                                 close(pip[1]);
552                         }
553                         evaltree(n, EV_EXIT);
554                 }
555                 close(pip[1]);
556                 result->fd = pip[0];
557                 result->jp = jp;
558         }
559 out:
560         popstackmark(&smark);
561         TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
562                 result->fd, result->buf, result->nleft, result->jp));
563 }
564
565
566
567 /*
568  * Execute a simple command.
569  */
570
571 STATIC void
572 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
573 {
574         struct stackmark smark;
575         union node *argp;
576         struct arglist arglist;
577         struct arglist varlist;
578         char **argv;
579         int argc;
580         char **envp;
581         int varflag;
582         struct strlist *sp;
583         int mode;
584         int pip[2];
585         struct cmdentry cmdentry;
586         struct job *jp;
587         struct jmploc jmploc;
588         struct jmploc *volatile savehandler;
589         char *volatile savecmdname;
590         volatile struct shparam saveparam;
591         struct localvar *volatile savelocalvars;
592         volatile int e;
593         char *lastarg;
594         int realstatus;
595         int do_clearcmdentry;
596 #if __GNUC__
597         /* Avoid longjmp clobbering */
598         (void) &argv;
599         (void) &argc;
600         (void) &lastarg;
601         (void) &flags;
602         (void) &do_clearcmdentry;
603 #endif
604
605         /* First expand the arguments. */
606         TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
607         setstackmark(&smark);
608         arglist.lastp = &arglist.list;
609         varlist.lastp = &varlist.list;
610         varflag = 1;
611         do_clearcmdentry = 0;
612         oexitstatus = exitstatus;
613         exitstatus = 0;
614         for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
615                 char *p = argp->narg.text;
616                 if (varflag && is_name(*p)) {
617                         do {
618                                 p++;
619                         } while (is_in_name(*p));
620                         if (*p == '=') {
621                                 expandarg(argp, &varlist, EXP_VARTILDE);
622                                 continue;
623                         }
624                 }
625                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
626                 varflag = 0;
627         }
628         *arglist.lastp = NULL;
629         *varlist.lastp = NULL;
630         expredir(cmd->ncmd.redirect);
631         argc = 0;
632         for (sp = arglist.list ; sp ; sp = sp->next)
633                 argc++;
634         argv = stalloc(sizeof (char *) * (argc + 1));
635
636         for (sp = arglist.list ; sp ; sp = sp->next) {
637                 TRACE(("evalcommand arg: %s\n", sp->text));
638                 *argv++ = sp->text;
639         }
640         *argv = NULL;
641         lastarg = NULL;
642         if (iflag && funcnest == 0 && argc > 0)
643                 lastarg = argv[-1];
644         argv -= argc;
645
646         /* Print the command if xflag is set. */
647         if (xflag) {
648                 char sep = 0;
649                 out2str(ps4val());
650                 for (sp = varlist.list ; sp ; sp = sp->next) {
651                         if (sep != 0)
652                                 outc(' ', &errout);
653                         out2str(sp->text);
654                         sep = ' ';
655                 }
656                 for (sp = arglist.list ; sp ; sp = sp->next) {
657                         if (sep != 0)
658                                 outc(' ', &errout);
659                         out2str(sp->text);
660                         sep = ' ';
661                 }
662                 outc('\n', &errout);
663                 flushout(&errout);
664         }
665
666         /* Now locate the command. */
667         if (argc == 0) {
668                 /* Variable assignment(s) without command */
669                 cmdentry.cmdtype = CMDBUILTIN;
670                 cmdentry.u.index = BLTINCMD;
671                 cmdentry.special = 1;
672         } else {
673                 static const char PATH[] = "PATH=";
674                 char *path = pathval();
675
676                 /*
677                  * Modify the command lookup path, if a PATH= assignment
678                  * is present
679                  */
680                 for (sp = varlist.list ; sp ; sp = sp->next)
681                         if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
682                                 path = sp->text + sizeof(PATH) - 1;
683                                 /*
684                                  * On `PATH=... command`, we need to make
685                                  * sure that the command isn't using the
686                                  * non-updated hash table of the outer PATH
687                                  * setting and we need to make sure that
688                                  * the hash table isn't filled with items
689                                  * from the temporary setting.
690                                  *
691                                  * It would be better to forbit using and
692                                  * updating the table while this command
693                                  * runs, by the command finding mechanism
694                                  * is heavily integrated with hash handling,
695                                  * so we just delete the hash before and after
696                                  * the command runs. Partly deleting like
697                                  * changepatch() does doesn't seem worth the
698                                  * bookinging effort, since most such runs add
699                                  * directories in front of the new PATH.
700                                  */
701                                 clearcmdentry(0);
702                                 do_clearcmdentry = 1;
703                         }
704
705                 find_command(argv[0], &cmdentry, 1, path);
706                 if (cmdentry.cmdtype == CMDUNKNOWN) {   /* command not found */
707                         exitstatus = 127;
708                         flushout(&errout);
709                         return;
710                 }
711                 /* implement the bltin builtin here */
712                 if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
713                         for (;;) {
714                                 argv++;
715                                 if (--argc == 0)
716                                         break;
717                                 if ((cmdentry.u.index = find_builtin(*argv,
718                                     &cmdentry.special)) < 0) {
719                                         outfmt(&errout, "%s: not found\n", *argv);
720                                         exitstatus = 127;
721                                         flushout(&errout);
722                                         return;
723                                 }
724                                 if (cmdentry.u.index != BLTINCMD)
725                                         break;
726                         }
727                 }
728         }
729
730         /* Fork off a child process if necessary. */
731         if (cmd->ncmd.backgnd
732          || (cmdentry.cmdtype == CMDNORMAL
733             && ((flags & EV_EXIT) == 0 || Tflag))
734          || ((flags & EV_BACKCMD) != 0
735             && (cmdentry.cmdtype != CMDBUILTIN
736                  || cmdentry.u.index == CDCMD
737                  || cmdentry.u.index == DOTCMD
738                  || cmdentry.u.index == EVALCMD))
739          || (cmdentry.cmdtype == CMDBUILTIN &&
740             cmdentry.u.index == COMMANDCMD)) {
741                 jp = makejob(cmd, 1);
742                 mode = cmd->ncmd.backgnd;
743                 if (flags & EV_BACKCMD) {
744                         mode = FORK_NOJOB;
745                         if (pipe(pip) < 0)
746                                 error("Pipe call failed: %s", strerror(errno));
747                 }
748                 if (forkshell(jp, cmd, mode) != 0)
749                         goto parent;    /* at end of routine */
750                 if (flags & EV_BACKCMD) {
751                         FORCEINTON;
752                         close(pip[0]);
753                         if (pip[1] != 1) {
754                                 dup2(pip[1], 1);
755                                 close(pip[1]);
756                         }
757                 }
758                 flags |= EV_EXIT;
759         }
760
761         /* This is the child process if a fork occurred. */
762         /* Execute the command. */
763         if (cmdentry.cmdtype == CMDFUNCTION) {
764 #ifdef DEBUG
765                 trputs("Shell function:  ");  trargs(argv);
766 #endif
767                 redirect(cmd->ncmd.redirect, REDIR_PUSH);
768                 saveparam = shellparam;
769                 shellparam.malloc = 0;
770                 shellparam.reset = 1;
771                 shellparam.nparam = argc - 1;
772                 shellparam.p = argv + 1;
773                 shellparam.optnext = NULL;
774                 INTOFF;
775                 savelocalvars = localvars;
776                 localvars = NULL;
777                 INTON;
778                 if (setjmp(jmploc.loc)) {
779                         if (exception == EXSHELLPROC)
780                                 freeparam((struct shparam *)&saveparam);
781                         else {
782                                 freeparam(&shellparam);
783                                 shellparam = saveparam;
784                         }
785                         poplocalvars();
786                         localvars = savelocalvars;
787                         handler = savehandler;
788                         longjmp(handler->loc, 1);
789                 }
790                 savehandler = handler;
791                 handler = &jmploc;
792                 for (sp = varlist.list ; sp ; sp = sp->next)
793                         mklocal(sp->text);
794                 funcnest++;
795                 exitstatus = oexitstatus;
796                 if (flags & EV_TESTED)
797                         evaltree(cmdentry.u.func, EV_TESTED);
798                 else
799                         evaltree(cmdentry.u.func, 0);
800                 funcnest--;
801                 INTOFF;
802                 poplocalvars();
803                 localvars = savelocalvars;
804                 freeparam(&shellparam);
805                 shellparam = saveparam;
806                 handler = savehandler;
807                 popredir();
808                 INTON;
809                 if (evalskip == SKIPFUNC) {
810                         evalskip = 0;
811                         skipcount = 0;
812                 }
813                 if (flags & EV_EXIT)
814                         exitshell(exitstatus);
815         } else if (cmdentry.cmdtype == CMDBUILTIN) {
816 #ifdef DEBUG
817                 trputs("builtin command:  ");  trargs(argv);
818 #endif
819                 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
820                 if (flags == EV_BACKCMD) {
821                         memout.nleft = 0;
822                         memout.nextc = memout.buf;
823                         memout.bufsize = 64;
824                         mode |= REDIR_BACKQ;
825                 }
826                 savecmdname = commandname;
827                 cmdenviron = varlist.list;
828                 e = -1;
829                 if (setjmp(jmploc.loc)) {
830                         e = exception;
831                         exitstatus = (e == EXINT)? SIGINT+128 : 2;
832                         goto cmddone;
833                 }
834                 savehandler = handler;
835                 handler = &jmploc;
836                 redirect(cmd->ncmd.redirect, mode);
837                 if (cmdentry.special)
838                         listsetvar(cmdenviron);
839                 commandname = argv[0];
840                 argptr = argv + 1;
841                 optptr = NULL;                  /* initialize nextopt */
842                 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
843                 flushall();
844 cmddone:
845                 cmdenviron = NULL;
846                 out1 = &output;
847                 out2 = &errout;
848                 freestdout();
849                 if (e != EXSHELLPROC) {
850                         commandname = savecmdname;
851                         if (flags & EV_EXIT) {
852                                 exitshell(exitstatus);
853                         }
854                 }
855                 handler = savehandler;
856                 if (e != -1) {
857                         if ((e != EXERROR && e != EXEXEC)
858                             || cmdentry.special)
859                                 exraise(e);
860                         FORCEINTON;
861                 }
862                 if (cmdentry.u.index != EXECCMD)
863                         popredir();
864                 if (flags == EV_BACKCMD) {
865                         backcmd->buf = memout.buf;
866                         backcmd->nleft = memout.nextc - memout.buf;
867                         memout.buf = NULL;
868                 }
869         } else {
870 #ifdef DEBUG
871                 trputs("normal command:  ");  trargs(argv);
872 #endif
873                 clearredir();
874                 redirect(cmd->ncmd.redirect, 0);
875                 for (sp = varlist.list ; sp ; sp = sp->next)
876                         setvareq(sp->text, VEXPORT|VSTACK);
877                 envp = environment();
878                 shellexec(argv, envp, pathval(), cmdentry.u.index);
879                 /*NOTREACHED*/
880         }
881         goto out;
882
883 parent: /* parent process gets here (if we forked) */
884         if (mode == 0) {        /* argument to fork */
885                 INTOFF;
886                 exitstatus = waitforjob(jp, &realstatus);
887                 INTON;
888                 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
889                         evalskip = SKIPBREAK;
890                         skipcount = loopnest;
891                 }
892         } else if (mode == 2) {
893                 backcmd->fd = pip[0];
894                 close(pip[1]);
895                 backcmd->jp = jp;
896         }
897
898 out:
899         if (lastarg)
900                 setvar("_", lastarg, 0);
901         if (do_clearcmdentry)
902                 clearcmdentry(0);
903         popstackmark(&smark);
904 }
905
906
907
908 /*
909  * Search for a command.  This is called before we fork so that the
910  * location of the command will be available in the parent as well as
911  * the child.  The check for "goodname" is an overly conservative
912  * check that the name will not be subject to expansion.
913  */
914
915 STATIC void
916 prehash(union node *n)
917 {
918         struct cmdentry entry;
919
920         if (n && n->type == NCMD && n->ncmd.args)
921                 if (goodname(n->ncmd.args->narg.text))
922                         find_command(n->ncmd.args->narg.text, &entry, 0,
923                                      pathval());
924 }
925
926
927
928 /*
929  * Builtin commands.  Builtin commands whose functions are closely
930  * tied to evaluation are implemented here.
931  */
932
933 /*
934  * No command given, or a bltin command with no arguments.
935  */
936
937 int
938 bltincmd(int argc __unused, char **argv __unused)
939 {
940         /*
941          * Preserve exitstatus of a previous possible redirection
942          * as POSIX mandates
943          */
944         return exitstatus;
945 }
946
947
948 /*
949  * Handle break and continue commands.  Break, continue, and return are
950  * all handled by setting the evalskip flag.  The evaluation routines
951  * above all check this flag, and if it is set they start skipping
952  * commands rather than executing them.  The variable skipcount is
953  * the number of loops to break/continue, or the number of function
954  * levels to return.  (The latter is always 1.)  It should probably
955  * be an error to break out of more loops than exist, but it isn't
956  * in the standard shell so we don't make it one here.
957  */
958
959 int
960 breakcmd(int argc, char **argv)
961 {
962         int n = argc > 1 ? number(argv[1]) : 1;
963
964         if (n > loopnest)
965                 n = loopnest;
966         if (n > 0) {
967                 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
968                 skipcount = n;
969         }
970         return 0;
971 }
972
973 /*
974  * The `command' command.
975  */
976 int
977 commandcmd(int argc, char **argv)
978 {
979         static char stdpath[] = _PATH_STDPATH;
980         struct jmploc loc, *old;
981         struct strlist *sp;
982         char *path;
983         int ch;
984         int cmd = -1;
985
986         for (sp = cmdenviron; sp ; sp = sp->next)
987                 setvareq(sp->text, VEXPORT|VSTACK);
988         path = pathval();
989
990         optind = optreset = 1;
991         opterr = 0;
992         while ((ch = getopt(argc, argv, "pvV")) != -1) {
993                 switch (ch) {
994                 case 'p':
995                         path = stdpath;
996                         break;
997                 case 'v':
998                         cmd = TYPECMD_SMALLV;
999                         break;
1000                 case 'V':
1001                         cmd = TYPECMD_BIGV;
1002                         break;
1003                 case '?':
1004                 default:
1005                         error("unknown option: -%c", optopt);
1006                 }
1007         }
1008         argc -= optind;
1009         argv += optind;
1010
1011         if (cmd != -1) {
1012                 if (argc != 1)
1013                         error("wrong number of arguments");
1014                 return typecmd_impl(2, argv - 1, cmd);
1015         }
1016         if (argc != 0) {
1017                 old = handler;
1018                 handler = &loc;
1019                 if (setjmp(handler->loc) == 0)
1020                         shellexec(argv, environment(), path, 0);
1021                 handler = old;
1022                 if (exception == EXEXEC)
1023                         exit(exerrno);
1024                 exraise(exception);
1025         }
1026
1027         /*
1028          * Do nothing successfully if no command was specified;
1029          * ksh also does this.
1030          */
1031         exit(0);
1032 }
1033
1034
1035 /*
1036  * The return command.
1037  */
1038
1039 int
1040 returncmd(int argc, char **argv)
1041 {
1042         int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1043
1044         if (funcnest) {
1045                 evalskip = SKIPFUNC;
1046                 skipcount = 1;
1047         } else {
1048                 /* skip the rest of the file */
1049                 evalskip = SKIPFILE;
1050                 skipcount = 1;
1051         }
1052         return ret;
1053 }
1054
1055
1056 int
1057 falsecmd(int argc __unused, char **argv __unused)
1058 {
1059         return 1;
1060 }
1061
1062
1063 int
1064 truecmd(int argc __unused, char **argv __unused)
1065 {
1066         return 0;
1067 }
1068
1069
1070 int
1071 execcmd(int argc, char **argv)
1072 {
1073         if (argc > 1) {
1074                 struct strlist *sp;
1075
1076                 iflag = 0;              /* exit on error */
1077                 mflag = 0;
1078                 optschanged();
1079                 for (sp = cmdenviron; sp ; sp = sp->next)
1080                         setvareq(sp->text, VEXPORT|VSTACK);
1081                 shellexec(argv + 1, environment(), pathval(), 0);
1082
1083         }
1084         return 0;
1085 }
1086
1087
1088 int
1089 timescmd(int argc __unused, char **argv __unused)
1090 {
1091         struct rusage ru;
1092         long shumins, shsmins, chumins, chsmins;
1093         double shusecs, shssecs, chusecs, chssecs;
1094
1095         if (getrusage(RUSAGE_SELF, &ru) < 0)
1096                 return 1;
1097         shumins = ru.ru_utime.tv_sec / 60;
1098         shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1099         shsmins = ru.ru_stime.tv_sec / 60;
1100         shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1101         if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1102                 return 1;
1103         chumins = ru.ru_utime.tv_sec / 60;
1104         chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1105         chsmins = ru.ru_stime.tv_sec / 60;
1106         chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1107         out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1108             shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1109         return 0;
1110 }