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