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