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