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