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