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