]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/eval.c
MFC @r254374.
[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 int evalskip;                   /* set if we are skipping commands */
78 int skipcount;                  /* number of levels to skip */
79 static int loopnest;            /* current loop nesting level */
80 int funcnest;                   /* depth of function calls */
81 static int builtin_flags;       /* evalcommand flags for builtins */
82
83
84 char *commandname;
85 struct strlist *cmdenviron;
86 int exitstatus;                 /* exit status of last command */
87 int oexitstatus;                /* saved exit status */
88
89
90 static void evalloop(union node *, int);
91 static void evalfor(union node *, int);
92 static union node *evalcase(union node *);
93 static void evalsubshell(union node *, int);
94 static void evalredir(union node *, int);
95 static void exphere(union node *, struct arglist *);
96 static void expredir(union node *);
97 static void evalpipe(union node *);
98 static int is_valid_fast_cmdsubst(union node *n);
99 static void evalcommand(union node *, int, struct backcmd *);
100 static void prehash(union node *);
101
102
103 /*
104  * Called to reset things after an exception.
105  */
106
107 void
108 reseteval(void)
109 {
110         evalskip = 0;
111         loopnest = 0;
112         funcnest = 0;
113 }
114
115
116 /*
117  * The eval command.
118  */
119
120 int
121 evalcmd(int argc, char **argv)
122 {
123         char *p;
124         char *concat;
125         char **ap;
126
127         if (argc > 1) {
128                 p = argv[1];
129                 if (argc > 2) {
130                         STARTSTACKSTR(concat);
131                         ap = argv + 2;
132                         for (;;) {
133                                 STPUTS(p, concat);
134                                 if ((p = *ap++) == NULL)
135                                         break;
136                                 STPUTC(' ', concat);
137                         }
138                         STPUTC('\0', concat);
139                         p = grabstackstr(concat);
140                 }
141                 evalstring(p, builtin_flags);
142         } else
143                 exitstatus = 0;
144         return exitstatus;
145 }
146
147
148 /*
149  * Execute a command or commands contained in a string.
150  */
151
152 void
153 evalstring(char *s, int flags)
154 {
155         union node *n;
156         struct stackmark smark;
157         int flags_exit;
158         int any;
159
160         flags_exit = flags & EV_EXIT;
161         flags &= ~EV_EXIT;
162         any = 0;
163         setstackmark(&smark);
164         setinputstring(s, 1);
165         while ((n = parsecmd(0)) != NEOF) {
166                 if (n != NULL && !nflag) {
167                         if (flags_exit && preadateof())
168                                 evaltree(n, flags | EV_EXIT);
169                         else
170                                 evaltree(n, flags);
171                         any = 1;
172                 }
173                 popstackmark(&smark);
174                 setstackmark(&smark);
175         }
176         popfile();
177         popstackmark(&smark);
178         if (!any)
179                 exitstatus = 0;
180         if (flags_exit)
181                 exraise(EXEXIT);
182 }
183
184
185 /*
186  * Evaluate a parse tree.  The value is left in the global variable
187  * exitstatus.
188  */
189
190 void
191 evaltree(union node *n, int flags)
192 {
193         int do_etest;
194         union node *next;
195         struct stackmark smark;
196
197         setstackmark(&smark);
198         do_etest = 0;
199         if (n == NULL) {
200                 TRACE(("evaltree(NULL) called\n"));
201                 exitstatus = 0;
202                 goto out;
203         }
204         do {
205                 next = NULL;
206 #ifndef NO_HISTORY
207                 displayhist = 1;        /* show history substitutions done with fc */
208 #endif
209                 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
210                 switch (n->type) {
211                 case NSEMI:
212                         evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
213                         if (evalskip)
214                                 goto out;
215                         next = n->nbinary.ch2;
216                         break;
217                 case NAND:
218                         evaltree(n->nbinary.ch1, EV_TESTED);
219                         if (evalskip || exitstatus != 0) {
220                                 goto out;
221                         }
222                         next = n->nbinary.ch2;
223                         break;
224                 case NOR:
225                         evaltree(n->nbinary.ch1, EV_TESTED);
226                         if (evalskip || exitstatus == 0)
227                                 goto out;
228                         next = n->nbinary.ch2;
229                         break;
230                 case NREDIR:
231                         evalredir(n, flags);
232                         break;
233                 case NSUBSHELL:
234                         evalsubshell(n, flags);
235                         do_etest = !(flags & EV_TESTED);
236                         break;
237                 case NBACKGND:
238                         evalsubshell(n, flags);
239                         break;
240                 case NIF: {
241                         evaltree(n->nif.test, EV_TESTED);
242                         if (evalskip)
243                                 goto out;
244                         if (exitstatus == 0)
245                                 next = n->nif.ifpart;
246                         else if (n->nif.elsepart)
247                                 next = n->nif.elsepart;
248                         else
249                                 exitstatus = 0;
250                         break;
251                 }
252                 case NWHILE:
253                 case NUNTIL:
254                         evalloop(n, flags & ~EV_EXIT);
255                         break;
256                 case NFOR:
257                         evalfor(n, flags & ~EV_EXIT);
258                         break;
259                 case NCASE:
260                         next = evalcase(n);
261                         break;
262                 case NCLIST:
263                         next = n->nclist.body;
264                         break;
265                 case NCLISTFALLTHRU:
266                         if (n->nclist.body) {
267                                 evaltree(n->nclist.body, flags & ~EV_EXIT);
268                                 if (evalskip)
269                                         goto out;
270                         }
271                         next = n->nclist.next;
272                         break;
273                 case NDEFUN:
274                         defun(n->narg.text, n->narg.next);
275                         exitstatus = 0;
276                         break;
277                 case NNOT:
278                         evaltree(n->nnot.com, EV_TESTED);
279                         if (evalskip)
280                                 goto out;
281                         exitstatus = !exitstatus;
282                         break;
283
284                 case NPIPE:
285                         evalpipe(n);
286                         do_etest = !(flags & EV_TESTED);
287                         break;
288                 case NCMD:
289                         evalcommand(n, flags, (struct backcmd *)NULL);
290                         do_etest = !(flags & EV_TESTED);
291                         break;
292                 default:
293                         out1fmt("Node type = %d\n", n->type);
294                         flushout(&output);
295                         break;
296                 }
297                 n = next;
298                 popstackmark(&smark);
299                 setstackmark(&smark);
300         } while (n != NULL);
301 out:
302         popstackmark(&smark);
303         if (pendingsig)
304                 dotrap();
305         if (eflag && exitstatus != 0 && do_etest)
306                 exitshell(exitstatus);
307         if (flags & EV_EXIT)
308                 exraise(EXEXIT);
309 }
310
311
312 static void
313 evalloop(union node *n, int flags)
314 {
315         int status;
316
317         loopnest++;
318         status = 0;
319         for (;;) {
320                 evaltree(n->nbinary.ch1, EV_TESTED);
321                 if (evalskip) {
322 skipping:         if (evalskip == SKIPCONT && --skipcount <= 0) {
323                                 evalskip = 0;
324                                 continue;
325                         }
326                         if (evalskip == SKIPBREAK && --skipcount <= 0)
327                                 evalskip = 0;
328                         if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
329                                 status = exitstatus;
330                         break;
331                 }
332                 if (n->type == NWHILE) {
333                         if (exitstatus != 0)
334                                 break;
335                 } else {
336                         if (exitstatus == 0)
337                                 break;
338                 }
339                 evaltree(n->nbinary.ch2, flags);
340                 status = exitstatus;
341                 if (evalskip)
342                         goto skipping;
343         }
344         loopnest--;
345         exitstatus = status;
346 }
347
348
349
350 static void
351 evalfor(union node *n, int flags)
352 {
353         struct arglist arglist;
354         union node *argp;
355         struct strlist *sp;
356         int status;
357
358         arglist.lastp = &arglist.list;
359         for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
360                 oexitstatus = exitstatus;
361                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
362         }
363         *arglist.lastp = NULL;
364
365         loopnest++;
366         status = 0;
367         for (sp = arglist.list ; sp ; sp = sp->next) {
368                 setvar(n->nfor.var, sp->text, 0);
369                 evaltree(n->nfor.body, flags);
370                 status = exitstatus;
371                 if (evalskip) {
372                         if (evalskip == SKIPCONT && --skipcount <= 0) {
373                                 evalskip = 0;
374                                 continue;
375                         }
376                         if (evalskip == SKIPBREAK && --skipcount <= 0)
377                                 evalskip = 0;
378                         break;
379                 }
380         }
381         loopnest--;
382         exitstatus = status;
383 }
384
385
386 /*
387  * Evaluate a case statement, returning the selected tree.
388  *
389  * The exit status needs care to get right.
390  */
391
392 static union node *
393 evalcase(union node *n)
394 {
395         union node *cp;
396         union node *patp;
397         struct arglist arglist;
398
399         arglist.lastp = &arglist.list;
400         oexitstatus = exitstatus;
401         expandarg(n->ncase.expr, &arglist, EXP_TILDE);
402         for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) {
403                 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
404                         if (casematch(patp, arglist.list->text)) {
405                                 while (cp->nclist.next &&
406                                     cp->type == NCLISTFALLTHRU &&
407                                     cp->nclist.body == NULL)
408                                         cp = cp->nclist.next;
409                                 if (cp->nclist.next &&
410                                     cp->type == NCLISTFALLTHRU)
411                                         return (cp);
412                                 if (cp->nclist.body == NULL)
413                                         exitstatus = 0;
414                                 return (cp->nclist.body);
415                         }
416                 }
417         }
418         exitstatus = 0;
419         return (NULL);
420 }
421
422
423
424 /*
425  * Kick off a subshell to evaluate a tree.
426  */
427
428 static void
429 evalsubshell(union node *n, int flags)
430 {
431         struct job *jp;
432         int backgnd = (n->type == NBACKGND);
433
434         oexitstatus = exitstatus;
435         expredir(n->nredir.redirect);
436         if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
437                         forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
438                 if (backgnd)
439                         flags &=~ EV_TESTED;
440                 redirect(n->nredir.redirect, 0);
441                 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
442         } else if (! backgnd) {
443                 INTOFF;
444                 exitstatus = waitforjob(jp, (int *)NULL);
445                 INTON;
446         } else
447                 exitstatus = 0;
448 }
449
450
451 /*
452  * Evaluate a redirected compound command.
453  */
454
455 static void
456 evalredir(union node *n, int flags)
457 {
458         struct jmploc jmploc;
459         struct jmploc *savehandler;
460         volatile int in_redirect = 1;
461
462         oexitstatus = exitstatus;
463         expredir(n->nredir.redirect);
464         savehandler = handler;
465         if (setjmp(jmploc.loc)) {
466                 int e;
467
468                 handler = savehandler;
469                 e = exception;
470                 popredir();
471                 if (e == EXERROR || e == EXEXEC) {
472                         if (in_redirect) {
473                                 exitstatus = 2;
474                                 return;
475                         }
476                 }
477                 longjmp(handler->loc, 1);
478         } else {
479                 INTOFF;
480                 handler = &jmploc;
481                 redirect(n->nredir.redirect, REDIR_PUSH);
482                 in_redirect = 0;
483                 INTON;
484                 evaltree(n->nredir.n, flags);
485         }
486         INTOFF;
487         handler = savehandler;
488         popredir();
489         INTON;
490 }
491
492
493 static void
494 exphere(union node *redir, struct arglist *fn)
495 {
496         struct jmploc jmploc;
497         struct jmploc *savehandler;
498         struct localvar *savelocalvars;
499         int need_longjmp = 0;
500
501         redir->nhere.expdoc = nullstr;
502         savelocalvars = localvars;
503         localvars = NULL;
504         forcelocal++;
505         savehandler = handler;
506         if (setjmp(jmploc.loc))
507                 need_longjmp = exception != EXERROR && exception != EXEXEC;
508         else {
509                 handler = &jmploc;
510                 expandarg(redir->nhere.doc, fn, 0);
511                 redir->nhere.expdoc = fn->list->text;
512                 INTOFF;
513         }
514         handler = savehandler;
515         forcelocal--;
516         poplocalvars();
517         localvars = savelocalvars;
518         if (need_longjmp)
519                 longjmp(handler->loc, 1);
520         INTON;
521 }
522
523
524 /*
525  * Compute the names of the files in a redirection list.
526  */
527
528 static void
529 expredir(union node *n)
530 {
531         union node *redir;
532
533         for (redir = n ; redir ; redir = redir->nfile.next) {
534                 struct arglist fn;
535                 fn.lastp = &fn.list;
536                 switch (redir->type) {
537                 case NFROM:
538                 case NTO:
539                 case NFROMTO:
540                 case NAPPEND:
541                 case NCLOBBER:
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);
550                         }
551                         break;
552                 case NXHERE:
553                         exphere(redir, &fn);
554                         break;
555                 }
556         }
557 }
558
559
560
561 /*
562  * Evaluate a pipeline.  All the processes in the pipeline are children
563  * of the process creating the pipeline.  (This differs from some versions
564  * of the shell, which make the last process in a pipeline the parent
565  * of all the rest.)
566  */
567
568 static void
569 evalpipe(union node *n)
570 {
571         struct job *jp;
572         struct nodelist *lp;
573         int pipelen;
574         int prevfd;
575         int pip[2];
576
577         TRACE(("evalpipe(%p) called\n", (void *)n));
578         pipelen = 0;
579         for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
580                 pipelen++;
581         INTOFF;
582         jp = makejob(n, pipelen);
583         prevfd = -1;
584         for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
585                 prehash(lp->n);
586                 pip[1] = -1;
587                 if (lp->next) {
588                         if (pipe(pip) < 0) {
589                                 if (prevfd >= 0)
590                                         close(prevfd);
591                                 error("Pipe call failed: %s", strerror(errno));
592                         }
593                 }
594                 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
595                         INTON;
596                         if (prevfd > 0) {
597                                 dup2(prevfd, 0);
598                                 close(prevfd);
599                         }
600                         if (pip[1] >= 0) {
601                                 if (!(prevfd >= 0 && pip[0] == 0))
602                                         close(pip[0]);
603                                 if (pip[1] != 1) {
604                                         dup2(pip[1], 1);
605                                         close(pip[1]);
606                                 }
607                         }
608                         evaltree(lp->n, EV_EXIT);
609                 }
610                 if (prevfd >= 0)
611                         close(prevfd);
612                 prevfd = pip[0];
613                 if (pip[1] != -1)
614                         close(pip[1]);
615         }
616         INTON;
617         if (n->npipe.backgnd == 0) {
618                 INTOFF;
619                 exitstatus = waitforjob(jp, (int *)NULL);
620                 TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
621                 INTON;
622         } else
623                 exitstatus = 0;
624 }
625
626
627
628 static int
629 is_valid_fast_cmdsubst(union node *n)
630 {
631
632         return (n->type == NCMD);
633 }
634
635 /*
636  * Execute a command inside back quotes.  If it's a builtin command, we
637  * want to save its output in a block obtained from malloc.  Otherwise
638  * we fork off a subprocess and get the output of the command via a pipe.
639  * Should be called with interrupts off.
640  */
641
642 void
643 evalbackcmd(union node *n, struct backcmd *result)
644 {
645         int pip[2];
646         struct job *jp;
647         struct stackmark smark;
648         struct jmploc jmploc;
649         struct jmploc *savehandler;
650         struct localvar *savelocalvars;
651
652         setstackmark(&smark);
653         result->fd = -1;
654         result->buf = NULL;
655         result->nleft = 0;
656         result->jp = NULL;
657         if (n == NULL) {
658                 exitstatus = 0;
659                 goto out;
660         }
661         exitstatus = oexitstatus;
662         if (is_valid_fast_cmdsubst(n)) {
663                 savelocalvars = localvars;
664                 localvars = NULL;
665                 forcelocal++;
666                 savehandler = handler;
667                 if (setjmp(jmploc.loc)) {
668                         if (exception == EXERROR || exception == EXEXEC)
669                                 exitstatus = 2;
670                         else if (exception != 0) {
671                                 handler = savehandler;
672                                 forcelocal--;
673                                 poplocalvars();
674                                 localvars = savelocalvars;
675                                 longjmp(handler->loc, 1);
676                         }
677                 } else {
678                         handler = &jmploc;
679                         evalcommand(n, EV_BACKCMD, result);
680                 }
681                 handler = savehandler;
682                 forcelocal--;
683                 poplocalvars();
684                 localvars = savelocalvars;
685         } else {
686                 if (pipe(pip) < 0)
687                         error("Pipe call failed: %s", strerror(errno));
688                 jp = makejob(n, 1);
689                 if (forkshell(jp, n, FORK_NOJOB) == 0) {
690                         FORCEINTON;
691                         close(pip[0]);
692                         if (pip[1] != 1) {
693                                 dup2(pip[1], 1);
694                                 close(pip[1]);
695                         }
696                         evaltree(n, EV_EXIT);
697                 }
698                 close(pip[1]);
699                 result->fd = pip[0];
700                 result->jp = jp;
701         }
702 out:
703         popstackmark(&smark);
704         TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
705                 result->fd, result->buf, result->nleft, result->jp));
706 }
707
708 static int
709 mustexpandto(const char *argtext, const char *mask)
710 {
711         for (;;) {
712                 if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) {
713                         argtext++;
714                         continue;
715                 }
716                 if (*argtext == CTLESC)
717                         argtext++;
718                 else if (BASESYNTAX[(int)*argtext] == CCTL)
719                         return (0);
720                 if (*argtext != *mask)
721                         return (0);
722                 if (*argtext == '\0')
723                         return (1);
724                 argtext++;
725                 mask++;
726         }
727 }
728
729 static int
730 isdeclarationcmd(struct narg *arg)
731 {
732         int have_command = 0;
733
734         if (arg == NULL)
735                 return (0);
736         while (mustexpandto(arg->text, "command")) {
737                 have_command = 1;
738                 arg = &arg->next->narg;
739                 if (arg == NULL)
740                         return (0);
741                 /*
742                  * To also allow "command -p" and "command --" as part of
743                  * a declaration command, add code here.
744                  * We do not do this, as ksh does not do it either and it
745                  * is not required by POSIX.
746                  */
747         }
748         return (mustexpandto(arg->text, "export") ||
749             mustexpandto(arg->text, "readonly") ||
750             (mustexpandto(arg->text, "local") &&
751                 (have_command || !isfunc("local"))));
752 }
753
754 /*
755  * Check if a builtin can safely be executed in the same process,
756  * even though it should be in a subshell (command substitution).
757  * Note that jobid, jobs, times and trap can show information not
758  * available in a child process; this is deliberate.
759  * The arguments should already have been expanded.
760  */
761 static int
762 safe_builtin(int idx, int argc, char **argv)
763 {
764         if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
765             idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
766             idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
767             idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
768             idx == TYPECMD)
769                 return (1);
770         if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
771             idx == UMASKCMD)
772                 return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
773         if (idx == SETCMD)
774                 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
775                     argv[1][0] == '+') && argv[1][1] == 'o' &&
776                     argv[1][2] == '\0'));
777         return (0);
778 }
779
780 /*
781  * Execute a simple command.
782  * Note: This may or may not return if (flags & EV_EXIT).
783  */
784
785 static void
786 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
787 {
788         union node *argp;
789         struct arglist arglist;
790         struct arglist varlist;
791         char **argv;
792         int argc;
793         char **envp;
794         int varflag;
795         struct strlist *sp;
796         int mode;
797         int pip[2];
798         struct cmdentry cmdentry;
799         struct job *jp;
800         struct jmploc jmploc;
801         struct jmploc *savehandler;
802         char *savecmdname;
803         struct shparam saveparam;
804         struct localvar *savelocalvars;
805         struct parsefile *savetopfile;
806         volatile int e;
807         char *lastarg;
808         int realstatus;
809         int do_clearcmdentry;
810         const char *path = pathval();
811
812         /* First expand the arguments. */
813         TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
814         arglist.lastp = &arglist.list;
815         varlist.lastp = &varlist.list;
816         varflag = 1;
817         jp = NULL;
818         do_clearcmdentry = 0;
819         oexitstatus = exitstatus;
820         exitstatus = 0;
821         for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
822                 if (varflag && isassignment(argp->narg.text)) {
823                         expandarg(argp, varflag == 1 ? &varlist : &arglist,
824                             EXP_VARTILDE);
825                         continue;
826                 } else if (varflag == 1)
827                         varflag = isdeclarationcmd(&argp->narg) ? 2 : 0;
828                 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
829         }
830         *arglist.lastp = NULL;
831         *varlist.lastp = NULL;
832         expredir(cmd->ncmd.redirect);
833         argc = 0;
834         for (sp = arglist.list ; sp ; sp = sp->next)
835                 argc++;
836         /* Add one slot at the beginning for tryexec(). */
837         argv = stalloc(sizeof (char *) * (argc + 2));
838         argv++;
839
840         for (sp = arglist.list ; sp ; sp = sp->next) {
841                 TRACE(("evalcommand arg: %s\n", sp->text));
842                 *argv++ = sp->text;
843         }
844         *argv = NULL;
845         lastarg = NULL;
846         if (iflag && funcnest == 0 && argc > 0)
847                 lastarg = argv[-1];
848         argv -= argc;
849
850         /* Print the command if xflag is set. */
851         if (xflag) {
852                 char sep = 0;
853                 const char *p, *ps4;
854                 ps4 = expandstr(ps4val());
855                 out2str(ps4 != NULL ? ps4 : ps4val());
856                 for (sp = varlist.list ; sp ; sp = sp->next) {
857                         if (sep != 0)
858                                 out2c(' ');
859                         p = strchr(sp->text, '=');
860                         if (p != NULL) {
861                                 p++;
862                                 outbin(sp->text, p - sp->text, out2);
863                                 out2qstr(p);
864                         } else
865                                 out2qstr(sp->text);
866                         sep = ' ';
867                 }
868                 for (sp = arglist.list ; sp ; sp = sp->next) {
869                         if (sep != 0)
870                                 out2c(' ');
871                         /* Disambiguate command looking like assignment. */
872                         if (sp == arglist.list &&
873                                         strchr(sp->text, '=') != NULL &&
874                                         strchr(sp->text, '\'') == NULL) {
875                                 out2c('\'');
876                                 out2str(sp->text);
877                                 out2c('\'');
878                         } else
879                                 out2qstr(sp->text);
880                         sep = ' ';
881                 }
882                 out2c('\n');
883                 flushout(&errout);
884         }
885
886         /* Now locate the command. */
887         if (argc == 0) {
888                 /* Variable assignment(s) without command */
889                 cmdentry.cmdtype = CMDBUILTIN;
890                 cmdentry.u.index = BLTINCMD;
891                 cmdentry.special = 0;
892         } else {
893                 static const char PATH[] = "PATH=";
894                 int cmd_flags = 0, bltinonly = 0;
895
896                 /*
897                  * Modify the command lookup path, if a PATH= assignment
898                  * is present
899                  */
900                 for (sp = varlist.list ; sp ; sp = sp->next)
901                         if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
902                                 path = sp->text + sizeof(PATH) - 1;
903                                 /*
904                                  * On `PATH=... command`, we need to make
905                                  * sure that the command isn't using the
906                                  * non-updated hash table of the outer PATH
907                                  * setting and we need to make sure that
908                                  * the hash table isn't filled with items
909                                  * from the temporary setting.
910                                  *
911                                  * It would be better to forbit using and
912                                  * updating the table while this command
913                                  * runs, by the command finding mechanism
914                                  * is heavily integrated with hash handling,
915                                  * so we just delete the hash before and after
916                                  * the command runs. Partly deleting like
917                                  * changepatch() does doesn't seem worth the
918                                  * bookinging effort, since most such runs add
919                                  * directories in front of the new PATH.
920                                  */
921                                 clearcmdentry();
922                                 do_clearcmdentry = 1;
923                         }
924
925                 for (;;) {
926                         if (bltinonly) {
927                                 cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
928                                 if (cmdentry.u.index < 0) {
929                                         cmdentry.u.index = BLTINCMD;
930                                         argv--;
931                                         argc++;
932                                         break;
933                                 }
934                         } else
935                                 find_command(argv[0], &cmdentry, cmd_flags, path);
936                         /* implement the bltin and command builtins here */
937                         if (cmdentry.cmdtype != CMDBUILTIN)
938                                 break;
939                         if (cmdentry.u.index == BLTINCMD) {
940                                 if (argc == 1)
941                                         break;
942                                 argv++;
943                                 argc--;
944                                 bltinonly = 1;
945                         } else if (cmdentry.u.index == COMMANDCMD) {
946                                 if (argc == 1)
947                                         break;
948                                 if (!strcmp(argv[1], "-p")) {
949                                         if (argc == 2)
950                                                 break;
951                                         if (argv[2][0] == '-') {
952                                                 if (strcmp(argv[2], "--"))
953                                                         break;
954                                                 if (argc == 3)
955                                                         break;
956                                                 argv += 3;
957                                                 argc -= 3;
958                                         } else {
959                                                 argv += 2;
960                                                 argc -= 2;
961                                         }
962                                         path = _PATH_STDPATH;
963                                         clearcmdentry();
964                                         do_clearcmdentry = 1;
965                                 } else if (!strcmp(argv[1], "--")) {
966                                         if (argc == 2)
967                                                 break;
968                                         argv += 2;
969                                         argc -= 2;
970                                 } else if (argv[1][0] == '-')
971                                         break;
972                                 else {
973                                         argv++;
974                                         argc--;
975                                 }
976                                 cmd_flags |= DO_NOFUNC;
977                                 bltinonly = 0;
978                         } else
979                                 break;
980                 }
981                 /*
982                  * Special builtins lose their special properties when
983                  * called via 'command'.
984                  */
985                 if (cmd_flags & DO_NOFUNC)
986                         cmdentry.special = 0;
987         }
988
989         /* Fork off a child process if necessary. */
990         if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
991             && ((flags & EV_EXIT) == 0 || have_traps()))
992          || ((flags & EV_BACKCMD) != 0
993             && (cmdentry.cmdtype != CMDBUILTIN ||
994                  !safe_builtin(cmdentry.u.index, argc, argv)))) {
995                 jp = makejob(cmd, 1);
996                 mode = FORK_FG;
997                 if (flags & EV_BACKCMD) {
998                         mode = FORK_NOJOB;
999                         if (pipe(pip) < 0)
1000                                 error("Pipe call failed: %s", strerror(errno));
1001                 }
1002                 if (cmdentry.cmdtype == CMDNORMAL &&
1003                     cmd->ncmd.redirect == NULL &&
1004                     varlist.list == NULL &&
1005                     (mode == FORK_FG || mode == FORK_NOJOB) &&
1006                     !disvforkset() && !iflag && !mflag) {
1007                         vforkexecshell(jp, argv, environment(), path,
1008                             cmdentry.u.index, flags & EV_BACKCMD ? pip : NULL);
1009                         goto parent;
1010                 }
1011                 if (forkshell(jp, cmd, mode) != 0)
1012                         goto parent;    /* at end of routine */
1013                 if (flags & EV_BACKCMD) {
1014                         FORCEINTON;
1015                         close(pip[0]);
1016                         if (pip[1] != 1) {
1017                                 dup2(pip[1], 1);
1018                                 close(pip[1]);
1019                         }
1020                         flags &= ~EV_BACKCMD;
1021                 }
1022                 flags |= EV_EXIT;
1023         }
1024
1025         /* This is the child process if a fork occurred. */
1026         /* Execute the command. */
1027         if (cmdentry.cmdtype == CMDFUNCTION) {
1028 #ifdef DEBUG
1029                 trputs("Shell function:  ");  trargs(argv);
1030 #endif
1031                 saveparam = shellparam;
1032                 shellparam.malloc = 0;
1033                 shellparam.reset = 1;
1034                 shellparam.nparam = argc - 1;
1035                 shellparam.p = argv + 1;
1036                 shellparam.optnext = NULL;
1037                 INTOFF;
1038                 savelocalvars = localvars;
1039                 localvars = NULL;
1040                 reffunc(cmdentry.u.func);
1041                 savehandler = handler;
1042                 if (setjmp(jmploc.loc)) {
1043                         freeparam(&shellparam);
1044                         shellparam = saveparam;
1045                         popredir();
1046                         unreffunc(cmdentry.u.func);
1047                         poplocalvars();
1048                         localvars = savelocalvars;
1049                         funcnest--;
1050                         handler = savehandler;
1051                         longjmp(handler->loc, 1);
1052                 }
1053                 handler = &jmploc;
1054                 funcnest++;
1055                 redirect(cmd->ncmd.redirect, REDIR_PUSH);
1056                 INTON;
1057                 for (sp = varlist.list ; sp ; sp = sp->next)
1058                         mklocal(sp->text);
1059                 exitstatus = oexitstatus;
1060                 evaltree(getfuncnode(cmdentry.u.func),
1061                     flags & (EV_TESTED | EV_EXIT));
1062                 INTOFF;
1063                 unreffunc(cmdentry.u.func);
1064                 poplocalvars();
1065                 localvars = savelocalvars;
1066                 freeparam(&shellparam);
1067                 shellparam = saveparam;
1068                 handler = savehandler;
1069                 funcnest--;
1070                 popredir();
1071                 INTON;
1072                 if (evalskip == SKIPFUNC) {
1073                         evalskip = 0;
1074                         skipcount = 0;
1075                 }
1076                 if (jp)
1077                         exitshell(exitstatus);
1078         } else if (cmdentry.cmdtype == CMDBUILTIN) {
1079 #ifdef DEBUG
1080                 trputs("builtin command:  ");  trargs(argv);
1081 #endif
1082                 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
1083                 if (flags == EV_BACKCMD) {
1084                         memout.nleft = 0;
1085                         memout.nextc = memout.buf;
1086                         memout.bufsize = 64;
1087                         mode |= REDIR_BACKQ;
1088                 }
1089                 savecmdname = commandname;
1090                 savetopfile = getcurrentfile();
1091                 cmdenviron = varlist.list;
1092                 e = -1;
1093                 savehandler = handler;
1094                 if (setjmp(jmploc.loc)) {
1095                         e = exception;
1096                         if (e == EXINT)
1097                                 exitstatus = SIGINT+128;
1098                         else if (e != EXEXIT)
1099                                 exitstatus = 2;
1100                         goto cmddone;
1101                 }
1102                 handler = &jmploc;
1103                 redirect(cmd->ncmd.redirect, mode);
1104                 outclearerror(out1);
1105                 /*
1106                  * If there is no command word, redirection errors should
1107                  * not be fatal but assignment errors should.
1108                  */
1109                 if (argc == 0)
1110                         cmdentry.special = 1;
1111                 listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1112                 if (argc > 0)
1113                         bltinsetlocale();
1114                 commandname = argv[0];
1115                 argptr = argv + 1;
1116                 nextopt_optptr = NULL;          /* initialize nextopt */
1117                 builtin_flags = flags;
1118                 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1119                 flushall();
1120                 if (outiserror(out1)) {
1121                         warning("write error on stdout");
1122                         if (exitstatus == 0 || exitstatus == 1)
1123                                 exitstatus = 2;
1124                 }
1125 cmddone:
1126                 if (argc > 0)
1127                         bltinunsetlocale();
1128                 cmdenviron = NULL;
1129                 out1 = &output;
1130                 out2 = &errout;
1131                 freestdout();
1132                 handler = savehandler;
1133                 commandname = savecmdname;
1134                 if (jp)
1135                         exitshell(exitstatus);
1136                 if (flags == EV_BACKCMD) {
1137                         backcmd->buf = memout.buf;
1138                         backcmd->nleft = memout.nextc - memout.buf;
1139                         memout.buf = NULL;
1140                 }
1141                 if (cmdentry.u.index != EXECCMD)
1142                         popredir();
1143                 if (e != -1) {
1144                         if ((e != EXERROR && e != EXEXEC)
1145                             || cmdentry.special)
1146                                 exraise(e);
1147                         popfilesupto(savetopfile);
1148                         if (flags != EV_BACKCMD)
1149                                 FORCEINTON;
1150                 }
1151         } else {
1152 #ifdef DEBUG
1153                 trputs("normal command:  ");  trargs(argv);
1154 #endif
1155                 redirect(cmd->ncmd.redirect, 0);
1156                 for (sp = varlist.list ; sp ; sp = sp->next)
1157                         setvareq(sp->text, VEXPORT|VSTACK);
1158                 envp = environment();
1159                 shellexec(argv, envp, path, cmdentry.u.index);
1160                 /*NOTREACHED*/
1161         }
1162         goto out;
1163
1164 parent: /* parent process gets here (if we forked) */
1165         if (mode == FORK_FG) {  /* argument to fork */
1166                 INTOFF;
1167                 exitstatus = waitforjob(jp, &realstatus);
1168                 INTON;
1169                 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1170                         evalskip = SKIPBREAK;
1171                         skipcount = loopnest;
1172                 }
1173         } else if (mode == FORK_NOJOB) {
1174                 backcmd->fd = pip[0];
1175                 close(pip[1]);
1176                 backcmd->jp = jp;
1177         }
1178
1179 out:
1180         if (lastarg)
1181                 setvar("_", lastarg, 0);
1182         if (do_clearcmdentry)
1183                 clearcmdentry();
1184 }
1185
1186
1187
1188 /*
1189  * Search for a command.  This is called before we fork so that the
1190  * location of the command will be available in the parent as well as
1191  * the child.  The check for "goodname" is an overly conservative
1192  * check that the name will not be subject to expansion.
1193  */
1194
1195 static void
1196 prehash(union node *n)
1197 {
1198         struct cmdentry entry;
1199
1200         if (n && n->type == NCMD && n->ncmd.args)
1201                 if (goodname(n->ncmd.args->narg.text))
1202                         find_command(n->ncmd.args->narg.text, &entry, 0,
1203                                      pathval());
1204 }
1205
1206
1207
1208 /*
1209  * Builtin commands.  Builtin commands whose functions are closely
1210  * tied to evaluation are implemented here.
1211  */
1212
1213 /*
1214  * No command given, a bltin command with no arguments, or a bltin command
1215  * with an invalid name.
1216  */
1217
1218 int
1219 bltincmd(int argc, char **argv)
1220 {
1221         if (argc > 1) {
1222                 out2fmt_flush("%s: not found\n", argv[1]);
1223                 return 127;
1224         }
1225         /*
1226          * Preserve exitstatus of a previous possible redirection
1227          * as POSIX mandates
1228          */
1229         return exitstatus;
1230 }
1231
1232
1233 /*
1234  * Handle break and continue commands.  Break, continue, and return are
1235  * all handled by setting the evalskip flag.  The evaluation routines
1236  * above all check this flag, and if it is set they start skipping
1237  * commands rather than executing them.  The variable skipcount is
1238  * the number of loops to break/continue, or the number of function
1239  * levels to return.  (The latter is always 1.)  It should probably
1240  * be an error to break out of more loops than exist, but it isn't
1241  * in the standard shell so we don't make it one here.
1242  */
1243
1244 int
1245 breakcmd(int argc, char **argv)
1246 {
1247         int n = argc > 1 ? number(argv[1]) : 1;
1248
1249         if (n > loopnest)
1250                 n = loopnest;
1251         if (n > 0) {
1252                 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1253                 skipcount = n;
1254         }
1255         return 0;
1256 }
1257
1258 /*
1259  * The `command' command.
1260  */
1261 int
1262 commandcmd(int argc __unused, char **argv __unused)
1263 {
1264         const char *path;
1265         int ch;
1266         int cmd = -1;
1267
1268         path = bltinlookup("PATH", 1);
1269
1270         while ((ch = nextopt("pvV")) != '\0') {
1271                 switch (ch) {
1272                 case 'p':
1273                         path = _PATH_STDPATH;
1274                         break;
1275                 case 'v':
1276                         cmd = TYPECMD_SMALLV;
1277                         break;
1278                 case 'V':
1279                         cmd = TYPECMD_BIGV;
1280                         break;
1281                 }
1282         }
1283
1284         if (cmd != -1) {
1285                 if (*argptr == NULL || argptr[1] != NULL)
1286                         error("wrong number of arguments");
1287                 return typecmd_impl(2, argptr - 1, cmd, path);
1288         }
1289         if (*argptr != NULL)
1290                 error("commandcmd bad call");
1291
1292         /*
1293          * Do nothing successfully if no command was specified;
1294          * ksh also does this.
1295          */
1296         return 0;
1297 }
1298
1299
1300 /*
1301  * The return command.
1302  */
1303
1304 int
1305 returncmd(int argc, char **argv)
1306 {
1307         int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1308
1309         if (funcnest) {
1310                 evalskip = SKIPFUNC;
1311                 skipcount = 1;
1312         } else {
1313                 /* skip the rest of the file */
1314                 evalskip = SKIPFILE;
1315                 skipcount = 1;
1316         }
1317         return ret;
1318 }
1319
1320
1321 int
1322 falsecmd(int argc __unused, char **argv __unused)
1323 {
1324         return 1;
1325 }
1326
1327
1328 int
1329 truecmd(int argc __unused, char **argv __unused)
1330 {
1331         return 0;
1332 }
1333
1334
1335 int
1336 execcmd(int argc, char **argv)
1337 {
1338         /*
1339          * Because we have historically not supported any options,
1340          * only treat "--" specially.
1341          */
1342         if (argc > 1 && strcmp(argv[1], "--") == 0)
1343                 argc--, argv++;
1344         if (argc > 1) {
1345                 struct strlist *sp;
1346
1347                 iflag = 0;              /* exit on error */
1348                 mflag = 0;
1349                 optschanged();
1350                 for (sp = cmdenviron; sp ; sp = sp->next)
1351                         setvareq(sp->text, VEXPORT|VSTACK);
1352                 shellexec(argv + 1, environment(), pathval(), 0);
1353
1354         }
1355         return 0;
1356 }
1357
1358
1359 int
1360 timescmd(int argc __unused, char **argv __unused)
1361 {
1362         struct rusage ru;
1363         long shumins, shsmins, chumins, chsmins;
1364         double shusecs, shssecs, chusecs, chssecs;
1365
1366         if (getrusage(RUSAGE_SELF, &ru) < 0)
1367                 return 1;
1368         shumins = ru.ru_utime.tv_sec / 60;
1369         shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1370         shsmins = ru.ru_stime.tv_sec / 60;
1371         shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1372         if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1373                 return 1;
1374         chumins = ru.ru_utime.tv_sec / 60;
1375         chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1376         chsmins = ru.ru_stime.tv_sec / 60;
1377         chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1378         out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1379             shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1380         return 0;
1381 }