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