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