Deleted Added
full compact
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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/sh/eval.c 222907 2011-06-09 23:12:23Z jilles $");
39__FBSDID("$FreeBSD: head/bin/sh/eval.c 223024 2011-06-12 23:06:04Z jilles $");
40
41#include <paths.h>
42#include <signal.h>
43#include <stdlib.h>
44#include <unistd.h>
45#include <sys/resource.h>
46#include <sys/wait.h> /* For WIFSIGNALED(status) */
47#include <errno.h>
48
49/*
50 * Evaluate a command.
51 */
52
53#include "shell.h"
54#include "nodes.h"
55#include "syntax.h"
56#include "expand.h"
57#include "parser.h"
58#include "jobs.h"
59#include "eval.h"
60#include "builtins.h"
61#include "options.h"
62#include "exec.h"
63#include "redir.h"
64#include "input.h"
65#include "output.h"
66#include "trap.h"
67#include "var.h"
68#include "memalloc.h"
69#include "error.h"
70#include "show.h"
71#include "mystring.h"
72#ifndef NO_HISTORY
73#include "myhistedit.h"
74#endif
75
76
77int evalskip; /* set if we are skipping commands */
78static int skipcount; /* number of levels to skip */
79MKINIT int loopnest; /* current loop nesting level */
80int funcnest; /* depth of function calls */
81static int builtin_flags; /* evalcommand flags for builtins */
82
83
84char *commandname;
85struct strlist *cmdenviron;
86int exitstatus; /* exit status of last command */
87int oexitstatus; /* saved exit status */
88
89
90static void evalloop(union node *, int);
91static void evalfor(union node *, int);
92static void evalcase(union node *, int);
93static void evalsubshell(union node *, int);
94static void evalredir(union node *, int);
95static void expredir(union node *);
96static void evalpipe(union node *);
97static int is_valid_fast_cmdsubst(union node *n);
98static void evalcommand(union node *, int, struct backcmd *);
99static void prehash(union node *);
100
101
102/*
103 * Called to reset things after an exception.
104 */
105
106#ifdef mkinit
107INCLUDE "eval.h"
108
109RESET {
110 evalskip = 0;
111 loopnest = 0;
112 funcnest = 0;
113}
114#endif
115
116
117
118/*
119 * The eval command.
120 */
121
122int
123evalcmd(int argc, char **argv)
124{
125 char *p;
126 char *concat;
127 char **ap;
128
129 if (argc > 1) {
130 p = argv[1];
131 if (argc > 2) {
132 STARTSTACKSTR(concat);
133 ap = argv + 2;
134 for (;;) {
135 STPUTS(p, concat);
136 if ((p = *ap++) == NULL)
137 break;
138 STPUTC(' ', concat);
139 }
140 STPUTC('\0', concat);
141 p = grabstackstr(concat);
142 }
143 evalstring(p, builtin_flags & EV_TESTED);
144 } else
145 exitstatus = 0;
146 return exitstatus;
147}
148
149
150/*
151 * Execute a command or commands contained in a string.
152 */
153
154void
155evalstring(char *s, int flags)
156{
157 union node *n;
158 struct stackmark smark;
159 int flags_exit;
160 int any;
161
162 flags_exit = flags & EV_EXIT;
163 flags &= ~EV_EXIT;
164 any = 0;
165 setstackmark(&smark);
166 setinputstring(s, 1);
167 while ((n = parsecmd(0)) != NEOF) {
168 if (n != NULL && !nflag) {
169 if (flags_exit && preadateof())
170 evaltree(n, flags | EV_EXIT);
171 else
172 evaltree(n, flags);
173 any = 1;
174 }
175 popstackmark(&smark);
176 }
177 popfile();
178 popstackmark(&smark);
179 if (!any)
180 exitstatus = 0;
181 if (flags_exit)
182 exraise(EXEXIT);
183}
184
185
186/*
187 * Evaluate a parse tree. The value is left in the global variable
188 * exitstatus.
189 */
190
191void
192evaltree(union node *n, int flags)
193{
194 int do_etest;
195 union node *next;
196
197 do_etest = 0;
198 if (n == NULL) {
199 TRACE(("evaltree(NULL) called\n"));
200 exitstatus = 0;
201 goto out;
202 }
203 do {
204 next = NULL;
205#ifndef NO_HISTORY
206 displayhist = 1; /* show history substitutions done with fc */
207#endif
208 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
209 switch (n->type) {
210 case NSEMI:
211 evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
212 if (evalskip)
213 goto out;
214 next = n->nbinary.ch2;
215 break;
216 case NAND:
217 evaltree(n->nbinary.ch1, EV_TESTED);
218 if (evalskip || exitstatus != 0) {
219 goto out;
220 }
221 next = n->nbinary.ch2;
222 break;
223 case NOR:
224 evaltree(n->nbinary.ch1, EV_TESTED);
225 if (evalskip || exitstatus == 0)
226 goto out;
227 next = n->nbinary.ch2;
228 break;
229 case NREDIR:
230 evalredir(n, flags);
231 break;
232 case NSUBSHELL:
233 evalsubshell(n, flags);
234 do_etest = !(flags & EV_TESTED);
235 break;
236 case NBACKGND:
237 evalsubshell(n, flags);
238 break;
239 case NIF: {
240 evaltree(n->nif.test, EV_TESTED);
241 if (evalskip)
242 goto out;
243 if (exitstatus == 0)
244 next = n->nif.ifpart;
245 else if (n->nif.elsepart)
246 next = n->nif.elsepart;
247 else
248 exitstatus = 0;
249 break;
250 }
251 case NWHILE:
252 case NUNTIL:
253 evalloop(n, flags & ~EV_EXIT);
254 break;
255 case NFOR:
256 evalfor(n, flags & ~EV_EXIT);
257 break;
258 case NCASE:
259 evalcase(n, flags);
260 break;
261 case NDEFUN:
262 defun(n->narg.text, n->narg.next);
263 exitstatus = 0;
264 break;
265 case NNOT:
266 evaltree(n->nnot.com, EV_TESTED);
267 exitstatus = !exitstatus;
268 break;
269
270 case NPIPE:
271 evalpipe(n);
272 do_etest = !(flags & EV_TESTED);
273 break;
274 case NCMD:
275 evalcommand(n, flags, (struct backcmd *)NULL);
276 do_etest = !(flags & EV_TESTED);
277 break;
278 default:
279 out1fmt("Node type = %d\n", n->type);
280 flushout(&output);
281 break;
282 }
283 n = next;
284 } while (n != NULL);
285out:
286 if (pendingsigs)
287 dotrap();
288 if (eflag && exitstatus != 0 && do_etest)
289 exitshell(exitstatus);
290 if (flags & EV_EXIT)
291 exraise(EXEXIT);
292}
293
294
295static void
296evalloop(union node *n, int flags)
297{
298 int status;
299
300 loopnest++;
301 status = 0;
302 for (;;) {
303 evaltree(n->nbinary.ch1, EV_TESTED);
304 if (evalskip) {
305skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
306 evalskip = 0;
307 continue;
308 }
309 if (evalskip == SKIPBREAK && --skipcount <= 0)
310 evalskip = 0;
311 if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
312 status = exitstatus;
313 break;
314 }
315 if (n->type == NWHILE) {
316 if (exitstatus != 0)
317 break;
318 } else {
319 if (exitstatus == 0)
320 break;
321 }
322 evaltree(n->nbinary.ch2, flags);
323 status = exitstatus;
324 if (evalskip)
325 goto skipping;
326 }
327 loopnest--;
328 exitstatus = status;
329}
330
331
332
333static void
334evalfor(union node *n, int flags)
335{
336 struct arglist arglist;
337 union node *argp;
338 struct strlist *sp;
339 struct stackmark smark;
340
341 setstackmark(&smark);
342 arglist.lastp = &arglist.list;
343 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
344 oexitstatus = exitstatus;
345 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
346 if (evalskip)
347 goto out;
348 }
349 *arglist.lastp = NULL;
350
351 exitstatus = 0;
352 loopnest++;
353 for (sp = arglist.list ; sp ; sp = sp->next) {
354 setvar(n->nfor.var, sp->text, 0);
355 evaltree(n->nfor.body, flags);
356 if (evalskip) {
357 if (evalskip == SKIPCONT && --skipcount <= 0) {
358 evalskip = 0;
359 continue;
360 }
361 if (evalskip == SKIPBREAK && --skipcount <= 0)
362 evalskip = 0;
363 break;
364 }
365 }
366 loopnest--;
367out:
368 popstackmark(&smark);
369}
370
371
372
373static void
374evalcase(union node *n, int flags)
375{
376 union node *cp;
377 union node *patp;
378 struct arglist arglist;
379 struct stackmark smark;
380
381 setstackmark(&smark);
382 arglist.lastp = &arglist.list;
383 oexitstatus = exitstatus;
384 exitstatus = 0;
385 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
386 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
387 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
388 if (casematch(patp, arglist.list->text)) {
389 if (evalskip == 0) {
390 evaltree(cp->nclist.body, flags);
391 }
392 goto out;
393 }
394 }
395 }
396out:
397 popstackmark(&smark);
398}
399
400
401
402/*
403 * Kick off a subshell to evaluate a tree.
404 */
405
406static void
407evalsubshell(union node *n, int flags)
408{
409 struct job *jp;
410 int backgnd = (n->type == NBACKGND);
411
412 oexitstatus = exitstatus;
413 expredir(n->nredir.redirect);
414 if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
415 forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
416 if (backgnd)
417 flags &=~ EV_TESTED;
418 redirect(n->nredir.redirect, 0);
419 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
420 } else if (! backgnd) {
421 INTOFF;
422 exitstatus = waitforjob(jp, (int *)NULL);
423 INTON;
424 } else
425 exitstatus = 0;
426}
427
428
429/*
430 * Evaluate a redirected compound command.
431 */
432
433static void
434evalredir(union node *n, int flags)
435{
436 struct jmploc jmploc;
437 struct jmploc *savehandler;
438 volatile int in_redirect = 1;
439
440 oexitstatus = exitstatus;
441 expredir(n->nredir.redirect);
442 savehandler = handler;
443 if (setjmp(jmploc.loc)) {
444 int e;
445
446 handler = savehandler;
447 e = exception;
448 popredir();
449 if (e == EXERROR || e == EXEXEC) {
450 if (in_redirect) {
451 exitstatus = 2;
452 return;
453 }
454 }
455 longjmp(handler->loc, 1);
456 } else {
457 INTOFF;
458 handler = &jmploc;
459 redirect(n->nredir.redirect, REDIR_PUSH);
460 in_redirect = 0;
461 INTON;
462 evaltree(n->nredir.n, flags);
463 }
464 INTOFF;
465 handler = savehandler;
466 popredir();
467 INTON;
468}
469
470
471/*
472 * Compute the names of the files in a redirection list.
473 */
474
475static void
476expredir(union node *n)
477{
478 union node *redir;
479
480 for (redir = n ; redir ; redir = redir->nfile.next) {
481 struct arglist fn;
482 fn.lastp = &fn.list;
483 switch (redir->type) {
484 case NFROM:
485 case NTO:
486 case NFROMTO:
487 case NAPPEND:
488 case NCLOBBER:
489 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
490 redir->nfile.expfname = fn.list->text;
491 break;
492 case NFROMFD:
493 case NTOFD:
494 if (redir->ndup.vname) {
495 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
496 fixredir(redir, fn.list->text, 1);
497 }
498 break;
499 }
500 }
501}
502
503
504
505/*
506 * Evaluate a pipeline. All the processes in the pipeline are children
507 * of the process creating the pipeline. (This differs from some versions
508 * of the shell, which make the last process in a pipeline the parent
509 * of all the rest.)
510 */
511
512static void
513evalpipe(union node *n)
514{
515 struct job *jp;
516 struct nodelist *lp;
517 int pipelen;
518 int prevfd;
519 int pip[2];
520
521 TRACE(("evalpipe(%p) called\n", (void *)n));
522 pipelen = 0;
523 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
524 pipelen++;
525 INTOFF;
526 jp = makejob(n, pipelen);
527 prevfd = -1;
528 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
529 prehash(lp->n);
530 pip[1] = -1;
531 if (lp->next) {
532 if (pipe(pip) < 0) {
533 close(prevfd);
534 error("Pipe call failed: %s", strerror(errno));
535 }
536 }
537 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
538 INTON;
539 if (prevfd > 0) {
540 dup2(prevfd, 0);
541 close(prevfd);
542 }
543 if (pip[1] >= 0) {
544 if (!(prevfd >= 0 && pip[0] == 0))
545 close(pip[0]);
546 if (pip[1] != 1) {
547 dup2(pip[1], 1);
548 close(pip[1]);
549 }
550 }
551 evaltree(lp->n, EV_EXIT);
552 }
553 if (prevfd >= 0)
554 close(prevfd);
555 prevfd = pip[0];
556 if (pip[1] != -1)
557 close(pip[1]);
558 }
559 INTON;
560 if (n->npipe.backgnd == 0) {
561 INTOFF;
562 exitstatus = waitforjob(jp, (int *)NULL);
563 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
564 INTON;
565 } else
566 exitstatus = 0;
567}
568
569
570
571static int
572is_valid_fast_cmdsubst(union node *n)
573{
574 union node *argp;
574
576 if (n->type != NCMD)
577 return 0;
578 for (argp = n->ncmd.args ; argp ; argp = argp->narg.next)
579 if (expandhassideeffects(argp->narg.text))
580 return 0;
581 return 1;
575 return (n->type == NCMD);
576}
577
578/*
579 * Execute a command inside back quotes. If it's a builtin command, we
580 * want to save its output in a block obtained from malloc. Otherwise
581 * we fork off a subprocess and get the output of the command via a pipe.
582 * Should be called with interrupts off.
583 */
584
585void
586evalbackcmd(union node *n, struct backcmd *result)
587{
588 int pip[2];
589 struct job *jp;
590 struct stackmark smark; /* unnecessary */
591 struct jmploc jmploc;
592 struct jmploc *savehandler;
593 struct localvar *savelocalvars;
594
595 setstackmark(&smark);
596 result->fd = -1;
597 result->buf = NULL;
598 result->nleft = 0;
599 result->jp = NULL;
600 if (n == NULL) {
601 exitstatus = 0;
602 goto out;
603 }
604 if (is_valid_fast_cmdsubst(n)) {
605 exitstatus = oexitstatus;
606 savelocalvars = localvars;
607 localvars = NULL;
608 forcelocal++;
609 savehandler = handler;
610 if (setjmp(jmploc.loc)) {
611 if (exception == EXERROR || exception == EXEXEC)
612 exitstatus = 2;
613 else if (exception != 0) {
614 handler = savehandler;
615 forcelocal--;
616 poplocalvars();
617 localvars = savelocalvars;
618 longjmp(handler->loc, 1);
619 }
620 } else {
621 handler = &jmploc;
622 evalcommand(n, EV_BACKCMD, result);
623 }
624 handler = savehandler;
625 forcelocal--;
626 poplocalvars();
627 localvars = savelocalvars;
628 } else {
629 exitstatus = 0;
630 if (pipe(pip) < 0)
631 error("Pipe call failed: %s", strerror(errno));
632 jp = makejob(n, 1);
633 if (forkshell(jp, n, FORK_NOJOB) == 0) {
634 FORCEINTON;
635 close(pip[0]);
636 if (pip[1] != 1) {
637 dup2(pip[1], 1);
638 close(pip[1]);
639 }
640 evaltree(n, EV_EXIT);
641 }
642 close(pip[1]);
643 result->fd = pip[0];
644 result->jp = jp;
645 }
646out:
647 popstackmark(&smark);
648 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
649 result->fd, result->buf, result->nleft, result->jp));
650}
651
652/*
653 * Check if a builtin can safely be executed in the same process,
654 * even though it should be in a subshell (command substitution).
655 * Note that jobid, jobs, times and trap can show information not
656 * available in a child process; this is deliberate.
657 * The arguments should already have been expanded.
658 */
659static int
660safe_builtin(int idx, int argc, char **argv)
661{
662 if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
663 idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
664 idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
665 idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
666 idx == TYPECMD)
667 return (1);
668 if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
669 idx == UMASKCMD)
670 return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
671 if (idx == SETCMD)
672 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
673 argv[1][0] == '+') && argv[1][1] == 'o' &&
674 argv[1][2] == '\0'));
675 return (0);
676}
677
678/*
679 * Execute a simple command.
680 * Note: This may or may not return if (flags & EV_EXIT).
681 */
682
683static void
684evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
685{
686 struct stackmark smark;
687 union node *argp;
688 struct arglist arglist;
689 struct arglist varlist;
690 char **argv;
691 int argc;
692 char **envp;
693 int varflag;
694 struct strlist *sp;
695 int mode;
696 int pip[2];
697 struct cmdentry cmdentry;
698 struct job *jp;
699 struct jmploc jmploc;
700 struct jmploc *savehandler;
701 char *savecmdname;
702 struct shparam saveparam;
703 struct localvar *savelocalvars;
704 struct parsefile *savetopfile;
705 volatile int e;
706 char *lastarg;
707 int realstatus;
708 int do_clearcmdentry;
709 const char *path = pathval();
710
711 /* First expand the arguments. */
712 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
713 setstackmark(&smark);
714 arglist.lastp = &arglist.list;
715 varlist.lastp = &varlist.list;
716 varflag = 1;
717 jp = NULL;
718 do_clearcmdentry = 0;
719 oexitstatus = exitstatus;
720 exitstatus = 0;
721 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
722 if (varflag && isassignment(argp->narg.text)) {
723 expandarg(argp, &varlist, EXP_VARTILDE);
724 continue;
725 }
726 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
727 varflag = 0;
728 }
729 *arglist.lastp = NULL;
730 *varlist.lastp = NULL;
731 expredir(cmd->ncmd.redirect);
732 argc = 0;
733 for (sp = arglist.list ; sp ; sp = sp->next)
734 argc++;
735 /* Add one slot at the beginning for tryexec(). */
736 argv = stalloc(sizeof (char *) * (argc + 2));
737 argv++;
738
739 for (sp = arglist.list ; sp ; sp = sp->next) {
740 TRACE(("evalcommand arg: %s\n", sp->text));
741 *argv++ = sp->text;
742 }
743 *argv = NULL;
744 lastarg = NULL;
745 if (iflag && funcnest == 0 && argc > 0)
746 lastarg = argv[-1];
747 argv -= argc;
748
749 /* Print the command if xflag is set. */
750 if (xflag) {
751 char sep = 0;
752 const char *p, *ps4;
753 ps4 = expandstr(ps4val());
754 out2str(ps4 != NULL ? ps4 : ps4val());
755 for (sp = varlist.list ; sp ; sp = sp->next) {
756 if (sep != 0)
757 out2c(' ');
758 p = strchr(sp->text, '=');
759 if (p != NULL) {
760 p++;
761 outbin(sp->text, p - sp->text, out2);
762 out2qstr(p);
763 } else
764 out2qstr(sp->text);
765 sep = ' ';
766 }
767 for (sp = arglist.list ; sp ; sp = sp->next) {
768 if (sep != 0)
769 out2c(' ');
770 /* Disambiguate command looking like assignment. */
771 if (sp == arglist.list &&
772 strchr(sp->text, '=') != NULL &&
773 strchr(sp->text, '\'') == NULL) {
774 out2c('\'');
775 out2str(sp->text);
776 out2c('\'');
777 } else
778 out2qstr(sp->text);
779 sep = ' ';
780 }
781 out2c('\n');
782 flushout(&errout);
783 }
784
785 /* Now locate the command. */
786 if (argc == 0) {
787 /* Variable assignment(s) without command */
788 cmdentry.cmdtype = CMDBUILTIN;
789 cmdentry.u.index = BLTINCMD;
790 cmdentry.special = 0;
791 } else {
792 static const char PATH[] = "PATH=";
793 int cmd_flags = 0, bltinonly = 0;
794
795 /*
796 * Modify the command lookup path, if a PATH= assignment
797 * is present
798 */
799 for (sp = varlist.list ; sp ; sp = sp->next)
800 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
801 path = sp->text + sizeof(PATH) - 1;
802 /*
803 * On `PATH=... command`, we need to make
804 * sure that the command isn't using the
805 * non-updated hash table of the outer PATH
806 * setting and we need to make sure that
807 * the hash table isn't filled with items
808 * from the temporary setting.
809 *
810 * It would be better to forbit using and
811 * updating the table while this command
812 * runs, by the command finding mechanism
813 * is heavily integrated with hash handling,
814 * so we just delete the hash before and after
815 * the command runs. Partly deleting like
816 * changepatch() does doesn't seem worth the
817 * bookinging effort, since most such runs add
818 * directories in front of the new PATH.
819 */
820 clearcmdentry();
821 do_clearcmdentry = 1;
822 }
823
824 for (;;) {
825 if (bltinonly) {
826 cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
827 if (cmdentry.u.index < 0) {
828 cmdentry.u.index = BLTINCMD;
829 argv--;
830 argc++;
831 break;
832 }
833 } else
834 find_command(argv[0], &cmdentry, cmd_flags, path);
835 /* implement the bltin and command builtins here */
836 if (cmdentry.cmdtype != CMDBUILTIN)
837 break;
838 if (cmdentry.u.index == BLTINCMD) {
839 if (argc == 1)
840 break;
841 argv++;
842 argc--;
843 bltinonly = 1;
844 } else if (cmdentry.u.index == COMMANDCMD) {
845 if (argc == 1)
846 break;
847 if (!strcmp(argv[1], "-p")) {
848 if (argc == 2)
849 break;
850 if (argv[2][0] == '-') {
851 if (strcmp(argv[2], "--"))
852 break;
853 if (argc == 3)
854 break;
855 argv += 3;
856 argc -= 3;
857 } else {
858 argv += 2;
859 argc -= 2;
860 }
861 path = _PATH_STDPATH;
862 clearcmdentry();
863 do_clearcmdentry = 1;
864 } else if (!strcmp(argv[1], "--")) {
865 if (argc == 2)
866 break;
867 argv += 2;
868 argc -= 2;
869 } else if (argv[1][0] == '-')
870 break;
871 else {
872 argv++;
873 argc--;
874 }
875 cmd_flags |= DO_NOFUNC;
876 bltinonly = 0;
877 } else
878 break;
879 }
880 /*
881 * Special builtins lose their special properties when
882 * called via 'command'.
883 */
884 if (cmd_flags & DO_NOFUNC)
885 cmdentry.special = 0;
886 }
887
888 /* Fork off a child process if necessary. */
889 if (cmd->ncmd.backgnd
890 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
891 && ((flags & EV_EXIT) == 0 || have_traps()))
892 || ((flags & EV_BACKCMD) != 0
893 && (cmdentry.cmdtype != CMDBUILTIN ||
894 !safe_builtin(cmdentry.u.index, argc, argv)))) {
895 jp = makejob(cmd, 1);
896 mode = cmd->ncmd.backgnd;
897 if (flags & EV_BACKCMD) {
898 mode = FORK_NOJOB;
899 if (pipe(pip) < 0)
900 error("Pipe call failed: %s", strerror(errno));
901 }
902 if (forkshell(jp, cmd, mode) != 0)
903 goto parent; /* at end of routine */
904 if (flags & EV_BACKCMD) {
905 FORCEINTON;
906 close(pip[0]);
907 if (pip[1] != 1) {
908 dup2(pip[1], 1);
909 close(pip[1]);
910 }
911 }
912 flags |= EV_EXIT;
913 }
914
915 /* This is the child process if a fork occurred. */
916 /* Execute the command. */
917 if (cmdentry.cmdtype == CMDFUNCTION) {
918#ifdef DEBUG
919 trputs("Shell function: "); trargs(argv);
920#endif
921 saveparam = shellparam;
922 shellparam.malloc = 0;
923 shellparam.reset = 1;
924 shellparam.nparam = argc - 1;
925 shellparam.p = argv + 1;
926 shellparam.optnext = NULL;
927 INTOFF;
928 savelocalvars = localvars;
929 localvars = NULL;
930 reffunc(cmdentry.u.func);
931 savehandler = handler;
932 if (setjmp(jmploc.loc)) {
933 freeparam(&shellparam);
934 shellparam = saveparam;
935 popredir();
936 unreffunc(cmdentry.u.func);
937 poplocalvars();
938 localvars = savelocalvars;
939 funcnest--;
940 handler = savehandler;
941 longjmp(handler->loc, 1);
942 }
943 handler = &jmploc;
944 funcnest++;
945 redirect(cmd->ncmd.redirect, REDIR_PUSH);
946 INTON;
947 for (sp = varlist.list ; sp ; sp = sp->next)
948 mklocal(sp->text);
949 exitstatus = oexitstatus;
950 evaltree(getfuncnode(cmdentry.u.func),
951 flags & (EV_TESTED | EV_EXIT));
952 INTOFF;
953 unreffunc(cmdentry.u.func);
954 poplocalvars();
955 localvars = savelocalvars;
956 freeparam(&shellparam);
957 shellparam = saveparam;
958 handler = savehandler;
959 funcnest--;
960 popredir();
961 INTON;
962 if (evalskip == SKIPFUNC) {
963 evalskip = 0;
964 skipcount = 0;
965 }
966 if (jp)
967 exitshell(exitstatus);
968 } else if (cmdentry.cmdtype == CMDBUILTIN) {
969#ifdef DEBUG
970 trputs("builtin command: "); trargs(argv);
971#endif
972 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
973 if (flags == EV_BACKCMD) {
974 memout.nleft = 0;
975 memout.nextc = memout.buf;
976 memout.bufsize = 64;
977 mode |= REDIR_BACKQ;
978 cmdentry.special = 0;
979 }
980 savecmdname = commandname;
981 savetopfile = getcurrentfile();
982 cmdenviron = varlist.list;
983 e = -1;
984 savehandler = handler;
985 if (setjmp(jmploc.loc)) {
986 e = exception;
987 if (e == EXINT)
988 exitstatus = SIGINT+128;
989 else if (e != EXEXIT)
990 exitstatus = 2;
991 goto cmddone;
992 }
993 handler = &jmploc;
994 redirect(cmd->ncmd.redirect, mode);
995 /*
996 * If there is no command word, redirection errors should
997 * not be fatal but assignment errors should.
998 */
999 if (argc == 0 && !(flags & EV_BACKCMD))
1000 cmdentry.special = 1;
1001 listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1002 if (argc > 0)
1003 bltinsetlocale();
1004 commandname = argv[0];
1005 argptr = argv + 1;
1006 nextopt_optptr = NULL; /* initialize nextopt */
1007 builtin_flags = flags;
1008 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1009 flushall();
1010cmddone:
1011 if (argc > 0)
1012 bltinunsetlocale();
1013 cmdenviron = NULL;
1014 out1 = &output;
1015 out2 = &errout;
1016 freestdout();
1017 handler = savehandler;
1018 commandname = savecmdname;
1019 if (jp)
1020 exitshell(exitstatus);
1021 if (flags == EV_BACKCMD) {
1022 backcmd->buf = memout.buf;
1023 backcmd->nleft = memout.nextc - memout.buf;
1024 memout.buf = NULL;
1025 }
1026 if (cmdentry.u.index != EXECCMD)
1027 popredir();
1028 if (e != -1) {
1029 if ((e != EXERROR && e != EXEXEC)
1030 || cmdentry.special)
1031 exraise(e);
1032 popfilesupto(savetopfile);
1033 if (flags != EV_BACKCMD)
1034 FORCEINTON;
1035 }
1036 } else {
1037#ifdef DEBUG
1038 trputs("normal command: "); trargs(argv);
1039#endif
1040 redirect(cmd->ncmd.redirect, 0);
1041 for (sp = varlist.list ; sp ; sp = sp->next)
1042 setvareq(sp->text, VEXPORT|VSTACK);
1043 envp = environment();
1044 shellexec(argv, envp, path, cmdentry.u.index);
1045 /*NOTREACHED*/
1046 }
1047 goto out;
1048
1049parent: /* parent process gets here (if we forked) */
1050 if (mode == FORK_FG) { /* argument to fork */
1051 INTOFF;
1052 exitstatus = waitforjob(jp, &realstatus);
1053 INTON;
1054 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1055 evalskip = SKIPBREAK;
1056 skipcount = loopnest;
1057 }
1058 } else if (mode == FORK_NOJOB) {
1059 backcmd->fd = pip[0];
1060 close(pip[1]);
1061 backcmd->jp = jp;
1062 } else
1063 exitstatus = 0;
1064
1065out:
1066 if (lastarg)
1067 setvar("_", lastarg, 0);
1068 if (do_clearcmdentry)
1069 clearcmdentry();
1070 popstackmark(&smark);
1071}
1072
1073
1074
1075/*
1076 * Search for a command. This is called before we fork so that the
1077 * location of the command will be available in the parent as well as
1078 * the child. The check for "goodname" is an overly conservative
1079 * check that the name will not be subject to expansion.
1080 */
1081
1082static void
1083prehash(union node *n)
1084{
1085 struct cmdentry entry;
1086
1087 if (n && n->type == NCMD && n->ncmd.args)
1088 if (goodname(n->ncmd.args->narg.text))
1089 find_command(n->ncmd.args->narg.text, &entry, 0,
1090 pathval());
1091}
1092
1093
1094
1095/*
1096 * Builtin commands. Builtin commands whose functions are closely
1097 * tied to evaluation are implemented here.
1098 */
1099
1100/*
1101 * No command given, a bltin command with no arguments, or a bltin command
1102 * with an invalid name.
1103 */
1104
1105int
1106bltincmd(int argc, char **argv)
1107{
1108 if (argc > 1) {
1109 out2fmt_flush("%s: not found\n", argv[1]);
1110 return 127;
1111 }
1112 /*
1113 * Preserve exitstatus of a previous possible redirection
1114 * as POSIX mandates
1115 */
1116 return exitstatus;
1117}
1118
1119
1120/*
1121 * Handle break and continue commands. Break, continue, and return are
1122 * all handled by setting the evalskip flag. The evaluation routines
1123 * above all check this flag, and if it is set they start skipping
1124 * commands rather than executing them. The variable skipcount is
1125 * the number of loops to break/continue, or the number of function
1126 * levels to return. (The latter is always 1.) It should probably
1127 * be an error to break out of more loops than exist, but it isn't
1128 * in the standard shell so we don't make it one here.
1129 */
1130
1131int
1132breakcmd(int argc, char **argv)
1133{
1134 int n = argc > 1 ? number(argv[1]) : 1;
1135
1136 if (n > loopnest)
1137 n = loopnest;
1138 if (n > 0) {
1139 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1140 skipcount = n;
1141 }
1142 return 0;
1143}
1144
1145/*
1146 * The `command' command.
1147 */
1148int
1149commandcmd(int argc, char **argv)
1150{
1151 const char *path;
1152 int ch;
1153 int cmd = -1;
1154
1155 path = bltinlookup("PATH", 1);
1156
1157 optind = optreset = 1;
1158 opterr = 0;
1159 while ((ch = getopt(argc, argv, "pvV")) != -1) {
1160 switch (ch) {
1161 case 'p':
1162 path = _PATH_STDPATH;
1163 break;
1164 case 'v':
1165 cmd = TYPECMD_SMALLV;
1166 break;
1167 case 'V':
1168 cmd = TYPECMD_BIGV;
1169 break;
1170 case '?':
1171 default:
1172 error("unknown option: -%c", optopt);
1173 }
1174 }
1175 argc -= optind;
1176 argv += optind;
1177
1178 if (cmd != -1) {
1179 if (argc != 1)
1180 error("wrong number of arguments");
1181 return typecmd_impl(2, argv - 1, cmd, path);
1182 }
1183 if (argc != 0)
1184 error("commandcmd bad call");
1185
1186 /*
1187 * Do nothing successfully if no command was specified;
1188 * ksh also does this.
1189 */
1190 return 0;
1191}
1192
1193
1194/*
1195 * The return command.
1196 */
1197
1198int
1199returncmd(int argc, char **argv)
1200{
1201 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1202
1203 if (funcnest) {
1204 evalskip = SKIPFUNC;
1205 skipcount = 1;
1206 } else {
1207 /* skip the rest of the file */
1208 evalskip = SKIPFILE;
1209 skipcount = 1;
1210 }
1211 return ret;
1212}
1213
1214
1215int
1216falsecmd(int argc __unused, char **argv __unused)
1217{
1218 return 1;
1219}
1220
1221
1222int
1223truecmd(int argc __unused, char **argv __unused)
1224{
1225 return 0;
1226}
1227
1228
1229int
1230execcmd(int argc, char **argv)
1231{
1232 /*
1233 * Because we have historically not supported any options,
1234 * only treat "--" specially.
1235 */
1236 if (argc > 1 && strcmp(argv[1], "--") == 0)
1237 argc--, argv++;
1238 if (argc > 1) {
1239 struct strlist *sp;
1240
1241 iflag = 0; /* exit on error */
1242 mflag = 0;
1243 optschanged();
1244 for (sp = cmdenviron; sp ; sp = sp->next)
1245 setvareq(sp->text, VEXPORT|VSTACK);
1246 shellexec(argv + 1, environment(), pathval(), 0);
1247
1248 }
1249 return 0;
1250}
1251
1252
1253int
1254timescmd(int argc __unused, char **argv __unused)
1255{
1256 struct rusage ru;
1257 long shumins, shsmins, chumins, chsmins;
1258 double shusecs, shssecs, chusecs, chssecs;
1259
1260 if (getrusage(RUSAGE_SELF, &ru) < 0)
1261 return 1;
1262 shumins = ru.ru_utime.tv_sec / 60;
1263 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1264 shsmins = ru.ru_stime.tv_sec / 60;
1265 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1266 if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1267 return 1;
1268 chumins = ru.ru_utime.tv_sec / 60;
1269 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1270 chsmins = ru.ru_stime.tv_sec / 60;
1271 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1272 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1273 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1274 return 0;
1275}