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