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