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