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