sh: Remove impossible evalskip check in 'for'.
[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.114 2011/11/27 00:09:59 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                         cmdentry.special = 0;
985                 }
986                 savecmdname = commandname;
987                 savetopfile = getcurrentfile();
988                 cmdenviron = varlist.list;
989                 e = -1;
990                 savehandler = handler;
991                 if (setjmp(jmploc.loc)) {
992                         e = exception;
993                         if (e == EXINT)
994                                 exitstatus = SIGINT+128;
995                         else if (e != EXEXIT)
996                                 exitstatus = 2;
997                         goto cmddone;
998                 }
999                 handler = &jmploc;
1000                 redirect(cmd->ncmd.redirect, mode);
1001                 /*
1002                  * If there is no command word, redirection errors should
1003                  * not be fatal but assignment errors should.
1004                  */
1005                 if (argc == 0 && !(flags & EV_BACKCMD))
1006                         cmdentry.special = 1;
1007                 listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1008                 if (argc > 0)
1009                         bltinsetlocale();
1010                 commandname = argv[0];
1011                 argptr = argv + 1;
1012                 nextopt_optptr = NULL;          /* initialize nextopt */
1013                 builtin_flags = flags;
1014                 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1015                 flushall();
1016 cmddone:
1017                 if (argc > 0)
1018                         bltinunsetlocale();
1019                 cmdenviron = NULL;
1020                 out1 = &output;
1021                 out2 = &errout;
1022                 freestdout();
1023                 handler = savehandler;
1024                 commandname = savecmdname;
1025                 if (jp)
1026                         exitshell(exitstatus);
1027                 if (flags == EV_BACKCMD) {
1028                         backcmd->buf = memout.buf;
1029                         backcmd->nleft = memout.nextc - memout.buf;
1030                         memout.buf = NULL;
1031                 }
1032                 if (cmdentry.u.index != EXECCMD)
1033                         popredir();
1034                 if (e != -1) {
1035                         if ((e != EXERROR && e != EXEXEC)
1036                             || cmdentry.special)
1037                                 exraise(e);
1038                         popfilesupto(savetopfile);
1039                         if (flags != EV_BACKCMD)
1040                                 FORCEINTON;
1041                 }
1042         } else {
1043 #ifdef DEBUG
1044                 trputs("normal command:  ");  trargs(argv);
1045 #endif
1046                 redirect(cmd->ncmd.redirect, 0);
1047                 for (sp = varlist.list ; sp ; sp = sp->next)
1048                         setvareq(sp->text, VEXPORT|VSTACK);
1049                 envp = environment();
1050                 shellexec(argv, envp, path, cmdentry.u.index);
1051                 /*NOTREACHED*/
1052         }
1053         goto out;
1054
1055 parent: /* parent process gets here (if we forked) */
1056         if (mode == FORK_FG) {  /* argument to fork */
1057                 INTOFF;
1058                 exitstatus = waitforjob(jp, &realstatus);
1059                 INTON;
1060                 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1061                         evalskip = SKIPBREAK;
1062                         skipcount = loopnest;
1063                 }
1064         } else if (mode == FORK_NOJOB) {
1065                 backcmd->fd = pip[0];
1066                 close(pip[1]);
1067                 backcmd->jp = jp;
1068         }
1069
1070 out:
1071         if (lastarg)
1072                 setvar("_", lastarg, 0);
1073         if (do_clearcmdentry)
1074                 clearcmdentry();
1075         popstackmark(&smark);
1076 }
1077
1078
1079
1080 /*
1081  * Search for a command.  This is called before we fork so that the
1082  * location of the command will be available in the parent as well as
1083  * the child.  The check for "goodname" is an overly conservative
1084  * check that the name will not be subject to expansion.
1085  */
1086
1087 static void
1088 prehash(union node *n)
1089 {
1090         struct cmdentry entry;
1091
1092         if (n && n->type == NCMD && n->ncmd.args)
1093                 if (goodname(n->ncmd.args->narg.text))
1094                         find_command(n->ncmd.args->narg.text, &entry, 0,
1095                                      pathval());
1096 }
1097
1098
1099
1100 /*
1101  * Builtin commands.  Builtin commands whose functions are closely
1102  * tied to evaluation are implemented here.
1103  */
1104
1105 /*
1106  * No command given, a bltin command with no arguments, or a bltin command
1107  * with an invalid name.
1108  */
1109
1110 int
1111 bltincmd(int argc, char **argv)
1112 {
1113         if (argc > 1) {
1114                 out2fmt_flush("%s: not found\n", argv[1]);
1115                 return 127;
1116         }
1117         /*
1118          * Preserve exitstatus of a previous possible redirection
1119          * as POSIX mandates
1120          */
1121         return exitstatus;
1122 }
1123
1124
1125 /*
1126  * Handle break and continue commands.  Break, continue, and return are
1127  * all handled by setting the evalskip flag.  The evaluation routines
1128  * above all check this flag, and if it is set they start skipping
1129  * commands rather than executing them.  The variable skipcount is
1130  * the number of loops to break/continue, or the number of function
1131  * levels to return.  (The latter is always 1.)  It should probably
1132  * be an error to break out of more loops than exist, but it isn't
1133  * in the standard shell so we don't make it one here.
1134  */
1135
1136 int
1137 breakcmd(int argc, char **argv)
1138 {
1139         int n = argc > 1 ? number(argv[1]) : 1;
1140
1141         if (n > loopnest)
1142                 n = loopnest;
1143         if (n > 0) {
1144                 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1145                 skipcount = n;
1146         }
1147         return 0;
1148 }
1149
1150 /*
1151  * The `command' command.
1152  */
1153 int
1154 commandcmd(int argc, char **argv)
1155 {
1156         const char *path;
1157         int ch;
1158         int cmd = -1;
1159
1160         path = bltinlookup("PATH", 1);
1161
1162         optind = optreset = 1;
1163         opterr = 0;
1164         while ((ch = getopt(argc, argv, "pvV")) != -1) {
1165                 switch (ch) {
1166                 case 'p':
1167                         path = _PATH_STDPATH;
1168                         break;
1169                 case 'v':
1170                         cmd = TYPECMD_SMALLV;
1171                         break;
1172                 case 'V':
1173                         cmd = TYPECMD_BIGV;
1174                         break;
1175                 case '?':
1176                 default:
1177                         error("unknown option: -%c", optopt);
1178                 }
1179         }
1180         argc -= optind;
1181         argv += optind;
1182
1183         if (cmd != -1) {
1184                 if (argc != 1)
1185                         error("wrong number of arguments");
1186                 return typecmd_impl(2, argv - 1, cmd, path);
1187         }
1188         if (argc != 0)
1189                 error("commandcmd bad call");
1190
1191         /*
1192          * Do nothing successfully if no command was specified;
1193          * ksh also does this.
1194          */
1195         return(0);
1196 }
1197
1198
1199 /*
1200  * The return command.
1201  */
1202
1203 int
1204 returncmd(int argc, char **argv)
1205 {
1206         int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1207
1208         if (funcnest) {
1209                 evalskip = SKIPFUNC;
1210                 skipcount = 1;
1211         } else {
1212                 /* skip the rest of the file */
1213                 evalskip = SKIPFILE;
1214                 skipcount = 1;
1215         }
1216         return ret;
1217 }
1218
1219
1220 int
1221 falsecmd(int argc __unused, char **argv __unused)
1222 {
1223         return 1;
1224 }
1225
1226
1227 int
1228 truecmd(int argc __unused, char **argv __unused)
1229 {
1230         return 0;
1231 }
1232
1233
1234 int
1235 execcmd(int argc, char **argv)
1236 {
1237         /*
1238          * Because we have historically not supported any options,
1239          * only treat "--" specially.
1240          */
1241         if (argc > 1 && strcmp(argv[1], "--") == 0)
1242                 argc--, argv++;
1243         if (argc > 1) {
1244                 struct strlist *sp;
1245
1246                 iflag = 0;              /* exit on error */
1247                 mflag = 0;
1248                 optschanged();
1249                 for (sp = cmdenviron; sp ; sp = sp->next)
1250                         setvareq(sp->text, VEXPORT|VSTACK);
1251                 shellexec(argv + 1, environment(), pathval(), 0);
1252
1253         }
1254         return 0;
1255 }
1256
1257
1258 int
1259 timescmd(int argc __unused, char **argv __unused)
1260 {
1261         struct rusage ru;
1262         long shumins, shsmins, chumins, chsmins;
1263         double shusecs, shssecs, chusecs, chssecs;
1264
1265         if (getrusage(RUSAGE_SELF, &ru) < 0)
1266                 return 1;
1267         shumins = ru.ru_utime.tv_sec / 60;
1268         shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1269         shsmins = ru.ru_stime.tv_sec / 60;
1270         shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1271         if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1272                 return 1;
1273         chumins = ru.ru_utime.tv_sec / 60;
1274         chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1275         chsmins = ru.ru_stime.tv_sec / 60;
1276         chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1277         out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1278             shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1279         return 0;
1280 }