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