xref: /freebsd/bin/sh/eval.c (revision ff0ba87247820afbdfdc1b307c803f7923d0e4d3)
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 			if (evalskip)
172 				break;
173 		}
174 		popstackmark(&smark);
175 		setstackmark(&smark);
176 	}
177 	popfile();
178 	popstackmark(&smark);
179 	if (!any)
180 		exitstatus = 0;
181 	if (flags_exit)
182 		exraise(EXEXIT);
183 }
184 
185 
186 /*
187  * Evaluate a parse tree.  The value is left in the global variable
188  * exitstatus.
189  */
190 
191 void
192 evaltree(union node *n, int flags)
193 {
194 	int do_etest;
195 	union node *next;
196 	struct stackmark smark;
197 
198 	setstackmark(&smark);
199 	do_etest = 0;
200 	if (n == NULL) {
201 		TRACE(("evaltree(NULL) called\n"));
202 		exitstatus = 0;
203 		goto out;
204 	}
205 	do {
206 		next = NULL;
207 #ifndef NO_HISTORY
208 		displayhist = 1;	/* show history substitutions done with fc */
209 #endif
210 		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
211 		switch (n->type) {
212 		case NSEMI:
213 			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
214 			if (evalskip)
215 				goto out;
216 			next = n->nbinary.ch2;
217 			break;
218 		case NAND:
219 			evaltree(n->nbinary.ch1, EV_TESTED);
220 			if (evalskip || exitstatus != 0) {
221 				goto out;
222 			}
223 			next = n->nbinary.ch2;
224 			break;
225 		case NOR:
226 			evaltree(n->nbinary.ch1, EV_TESTED);
227 			if (evalskip || exitstatus == 0)
228 				goto out;
229 			next = n->nbinary.ch2;
230 			break;
231 		case NREDIR:
232 			evalredir(n, flags);
233 			break;
234 		case NSUBSHELL:
235 			evalsubshell(n, flags);
236 			do_etest = !(flags & EV_TESTED);
237 			break;
238 		case NBACKGND:
239 			evalsubshell(n, flags);
240 			break;
241 		case NIF: {
242 			evaltree(n->nif.test, EV_TESTED);
243 			if (evalskip)
244 				goto out;
245 			if (exitstatus == 0)
246 				next = n->nif.ifpart;
247 			else if (n->nif.elsepart)
248 				next = n->nif.elsepart;
249 			else
250 				exitstatus = 0;
251 			break;
252 		}
253 		case NWHILE:
254 		case NUNTIL:
255 			evalloop(n, flags & ~EV_EXIT);
256 			break;
257 		case NFOR:
258 			evalfor(n, flags & ~EV_EXIT);
259 			break;
260 		case NCASE:
261 			next = evalcase(n);
262 			break;
263 		case NCLIST:
264 			next = n->nclist.body;
265 			break;
266 		case NCLISTFALLTHRU:
267 			if (n->nclist.body) {
268 				evaltree(n->nclist.body, flags & ~EV_EXIT);
269 				if (evalskip)
270 					goto out;
271 			}
272 			next = n->nclist.next;
273 			break;
274 		case NDEFUN:
275 			defun(n->narg.text, n->narg.next);
276 			exitstatus = 0;
277 			break;
278 		case NNOT:
279 			evaltree(n->nnot.com, EV_TESTED);
280 			if (evalskip)
281 				goto out;
282 			exitstatus = !exitstatus;
283 			break;
284 
285 		case NPIPE:
286 			evalpipe(n);
287 			do_etest = !(flags & EV_TESTED);
288 			break;
289 		case NCMD:
290 			evalcommand(n, flags, (struct backcmd *)NULL);
291 			do_etest = !(flags & EV_TESTED);
292 			break;
293 		default:
294 			out1fmt("Node type = %d\n", n->type);
295 			flushout(&output);
296 			break;
297 		}
298 		n = next;
299 		popstackmark(&smark);
300 		setstackmark(&smark);
301 	} while (n != NULL);
302 out:
303 	popstackmark(&smark);
304 	if (pendingsig)
305 		dotrap();
306 	if (eflag && exitstatus != 0 && do_etest)
307 		exitshell(exitstatus);
308 	if (flags & EV_EXIT)
309 		exraise(EXEXIT);
310 }
311 
312 
313 static void
314 evalloop(union node *n, int flags)
315 {
316 	int status;
317 
318 	loopnest++;
319 	status = 0;
320 	for (;;) {
321 		if (!evalskip)
322 			evaltree(n->nbinary.ch1, EV_TESTED);
323 		if (evalskip) {
324 			if (evalskip == SKIPCONT && --skipcount <= 0) {
325 				evalskip = 0;
326 				continue;
327 			}
328 			if (evalskip == SKIPBREAK && --skipcount <= 0)
329 				evalskip = 0;
330 			if (evalskip == SKIPRETURN)
331 				status = exitstatus;
332 			break;
333 		}
334 		if (n->type == NWHILE) {
335 			if (exitstatus != 0)
336 				break;
337 		} else {
338 			if (exitstatus == 0)
339 				break;
340 		}
341 		evaltree(n->nbinary.ch2, flags);
342 		status = exitstatus;
343 	}
344 	loopnest--;
345 	exitstatus = status;
346 }
347 
348 
349 
350 static void
351 evalfor(union node *n, int flags)
352 {
353 	struct arglist arglist;
354 	union node *argp;
355 	struct strlist *sp;
356 	int status;
357 
358 	arglist.lastp = &arglist.list;
359 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
360 		oexitstatus = exitstatus;
361 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
362 	}
363 	*arglist.lastp = NULL;
364 
365 	loopnest++;
366 	status = 0;
367 	for (sp = arglist.list ; sp ; sp = sp->next) {
368 		setvar(n->nfor.var, sp->text, 0);
369 		evaltree(n->nfor.body, flags);
370 		status = exitstatus;
371 		if (evalskip) {
372 			if (evalskip == SKIPCONT && --skipcount <= 0) {
373 				evalskip = 0;
374 				continue;
375 			}
376 			if (evalskip == SKIPBREAK && --skipcount <= 0)
377 				evalskip = 0;
378 			break;
379 		}
380 	}
381 	loopnest--;
382 	exitstatus = status;
383 }
384 
385 
386 /*
387  * Evaluate a case statement, returning the selected tree.
388  *
389  * The exit status needs care to get right.
390  */
391 
392 static union node *
393 evalcase(union node *n)
394 {
395 	union node *cp;
396 	union node *patp;
397 	struct arglist arglist;
398 
399 	arglist.lastp = &arglist.list;
400 	oexitstatus = exitstatus;
401 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
402 	for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) {
403 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
404 			if (casematch(patp, arglist.list->text)) {
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 	exitstatus = 0;
419 	return (NULL);
420 }
421 
422 
423 
424 /*
425  * Kick off a subshell to evaluate a tree.
426  */
427 
428 static void
429 evalsubshell(union node *n, int flags)
430 {
431 	struct job *jp;
432 	int backgnd = (n->type == NBACKGND);
433 
434 	oexitstatus = exitstatus;
435 	expredir(n->nredir.redirect);
436 	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
437 			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
438 		if (backgnd)
439 			flags &=~ EV_TESTED;
440 		redirect(n->nredir.redirect, 0);
441 		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
442 	} else if (! backgnd) {
443 		INTOFF;
444 		exitstatus = waitforjob(jp, (int *)NULL);
445 		INTON;
446 	} else
447 		exitstatus = 0;
448 }
449 
450 
451 /*
452  * Evaluate a redirected compound command.
453  */
454 
455 static void
456 evalredir(union node *n, int flags)
457 {
458 	struct jmploc jmploc;
459 	struct jmploc *savehandler;
460 	volatile int in_redirect = 1;
461 
462 	oexitstatus = exitstatus;
463 	expredir(n->nredir.redirect);
464 	savehandler = handler;
465 	if (setjmp(jmploc.loc)) {
466 		int e;
467 
468 		handler = savehandler;
469 		e = exception;
470 		popredir();
471 		if (e == EXERROR || e == EXEXEC) {
472 			if (in_redirect) {
473 				exitstatus = 2;
474 				return;
475 			}
476 		}
477 		longjmp(handler->loc, 1);
478 	} else {
479 		INTOFF;
480 		handler = &jmploc;
481 		redirect(n->nredir.redirect, REDIR_PUSH);
482 		in_redirect = 0;
483 		INTON;
484 		evaltree(n->nredir.n, flags);
485 	}
486 	INTOFF;
487 	handler = savehandler;
488 	popredir();
489 	INTON;
490 }
491 
492 
493 static void
494 exphere(union node *redir, struct arglist *fn)
495 {
496 	struct jmploc jmploc;
497 	struct jmploc *savehandler;
498 	struct localvar *savelocalvars;
499 	int need_longjmp = 0;
500 
501 	redir->nhere.expdoc = nullstr;
502 	savelocalvars = localvars;
503 	localvars = NULL;
504 	forcelocal++;
505 	savehandler = handler;
506 	if (setjmp(jmploc.loc))
507 		need_longjmp = exception != EXERROR && exception != EXEXEC;
508 	else {
509 		handler = &jmploc;
510 		expandarg(redir->nhere.doc, fn, 0);
511 		redir->nhere.expdoc = fn->list->text;
512 		INTOFF;
513 	}
514 	handler = savehandler;
515 	forcelocal--;
516 	poplocalvars();
517 	localvars = savelocalvars;
518 	if (need_longjmp)
519 		longjmp(handler->loc, 1);
520 	INTON;
521 }
522 
523 
524 /*
525  * Compute the names of the files in a redirection list.
526  */
527 
528 static void
529 expredir(union node *n)
530 {
531 	union node *redir;
532 
533 	for (redir = n ; redir ; redir = redir->nfile.next) {
534 		struct arglist fn;
535 		fn.lastp = &fn.list;
536 		switch (redir->type) {
537 		case NFROM:
538 		case NTO:
539 		case NFROMTO:
540 		case NAPPEND:
541 		case NCLOBBER:
542 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
543 			redir->nfile.expfname = fn.list->text;
544 			break;
545 		case NFROMFD:
546 		case NTOFD:
547 			if (redir->ndup.vname) {
548 				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
549 				fixredir(redir, fn.list->text, 1);
550 			}
551 			break;
552 		case NXHERE:
553 			exphere(redir, &fn);
554 			break;
555 		}
556 	}
557 }
558 
559 
560 
561 /*
562  * Evaluate a pipeline.  All the processes in the pipeline are children
563  * of the process creating the pipeline.  (This differs from some versions
564  * of the shell, which make the last process in a pipeline the parent
565  * of all the rest.)
566  */
567 
568 static void
569 evalpipe(union node *n)
570 {
571 	struct job *jp;
572 	struct nodelist *lp;
573 	int pipelen;
574 	int prevfd;
575 	int pip[2];
576 
577 	TRACE(("evalpipe(%p) called\n", (void *)n));
578 	pipelen = 0;
579 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
580 		pipelen++;
581 	INTOFF;
582 	jp = makejob(n, pipelen);
583 	prevfd = -1;
584 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
585 		prehash(lp->n);
586 		pip[1] = -1;
587 		if (lp->next) {
588 			if (pipe(pip) < 0) {
589 				if (prevfd >= 0)
590 					close(prevfd);
591 				error("Pipe call failed: %s", strerror(errno));
592 			}
593 		}
594 		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
595 			INTON;
596 			if (prevfd > 0) {
597 				dup2(prevfd, 0);
598 				close(prevfd);
599 			}
600 			if (pip[1] >= 0) {
601 				if (!(prevfd >= 0 && pip[0] == 0))
602 					close(pip[0]);
603 				if (pip[1] != 1) {
604 					dup2(pip[1], 1);
605 					close(pip[1]);
606 				}
607 			}
608 			evaltree(lp->n, EV_EXIT);
609 		}
610 		if (prevfd >= 0)
611 			close(prevfd);
612 		prevfd = pip[0];
613 		if (pip[1] != -1)
614 			close(pip[1]);
615 	}
616 	INTON;
617 	if (n->npipe.backgnd == 0) {
618 		INTOFF;
619 		exitstatus = waitforjob(jp, (int *)NULL);
620 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
621 		INTON;
622 	} else
623 		exitstatus = 0;
624 }
625 
626 
627 
628 static int
629 is_valid_fast_cmdsubst(union node *n)
630 {
631 
632 	return (n->type == NCMD);
633 }
634 
635 /*
636  * Execute a command inside back quotes.  If it's a builtin command, we
637  * want to save its output in a block obtained from malloc.  Otherwise
638  * we fork off a subprocess and get the output of the command via a pipe.
639  * Should be called with interrupts off.
640  */
641 
642 void
643 evalbackcmd(union node *n, struct backcmd *result)
644 {
645 	int pip[2];
646 	struct job *jp;
647 	struct stackmark smark;
648 	struct jmploc jmploc;
649 	struct jmploc *savehandler;
650 	struct localvar *savelocalvars;
651 
652 	result->fd = -1;
653 	result->buf = NULL;
654 	result->nleft = 0;
655 	result->jp = NULL;
656 	if (n == NULL) {
657 		exitstatus = 0;
658 		return;
659 	}
660 	setstackmark(&smark);
661 	exitstatus = oexitstatus;
662 	if (is_valid_fast_cmdsubst(n)) {
663 		savelocalvars = localvars;
664 		localvars = NULL;
665 		forcelocal++;
666 		savehandler = handler;
667 		if (setjmp(jmploc.loc)) {
668 			if (exception == EXERROR || exception == EXEXEC)
669 				exitstatus = 2;
670 			else if (exception != 0) {
671 				handler = savehandler;
672 				forcelocal--;
673 				poplocalvars();
674 				localvars = savelocalvars;
675 				longjmp(handler->loc, 1);
676 			}
677 		} else {
678 			handler = &jmploc;
679 			evalcommand(n, EV_BACKCMD, result);
680 		}
681 		handler = savehandler;
682 		forcelocal--;
683 		poplocalvars();
684 		localvars = savelocalvars;
685 	} else {
686 		if (pipe(pip) < 0)
687 			error("Pipe call failed: %s", strerror(errno));
688 		jp = makejob(n, 1);
689 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
690 			FORCEINTON;
691 			close(pip[0]);
692 			if (pip[1] != 1) {
693 				dup2(pip[1], 1);
694 				close(pip[1]);
695 			}
696 			evaltree(n, EV_EXIT);
697 		}
698 		close(pip[1]);
699 		result->fd = pip[0];
700 		result->jp = jp;
701 	}
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.optp = NULL;
1043 		shellparam.optnext = NULL;
1044 		INTOFF;
1045 		savelocalvars = localvars;
1046 		localvars = NULL;
1047 		reffunc(cmdentry.u.func);
1048 		savehandler = handler;
1049 		if (setjmp(jmploc.loc)) {
1050 			freeparam(&shellparam);
1051 			shellparam = saveparam;
1052 			popredir();
1053 			unreffunc(cmdentry.u.func);
1054 			poplocalvars();
1055 			localvars = savelocalvars;
1056 			funcnest--;
1057 			handler = savehandler;
1058 			longjmp(handler->loc, 1);
1059 		}
1060 		handler = &jmploc;
1061 		funcnest++;
1062 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
1063 		INTON;
1064 		for (sp = varlist.list ; sp ; sp = sp->next)
1065 			mklocal(sp->text);
1066 		exitstatus = oexitstatus;
1067 		evaltree(getfuncnode(cmdentry.u.func),
1068 		    flags & (EV_TESTED | EV_EXIT));
1069 		INTOFF;
1070 		unreffunc(cmdentry.u.func);
1071 		poplocalvars();
1072 		localvars = savelocalvars;
1073 		freeparam(&shellparam);
1074 		shellparam = saveparam;
1075 		handler = savehandler;
1076 		funcnest--;
1077 		popredir();
1078 		INTON;
1079 		if (evalskip == SKIPRETURN) {
1080 			evalskip = 0;
1081 			skipcount = 0;
1082 		}
1083 		if (jp)
1084 			exitshell(exitstatus);
1085 	} else if (cmdentry.cmdtype == CMDBUILTIN) {
1086 #ifdef DEBUG
1087 		trputs("builtin command:  ");  trargs(argv);
1088 #endif
1089 		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
1090 		if (flags == EV_BACKCMD) {
1091 			memout.nleft = 0;
1092 			memout.nextc = memout.buf;
1093 			memout.bufsize = 64;
1094 			mode |= REDIR_BACKQ;
1095 		}
1096 		savecmdname = commandname;
1097 		savetopfile = getcurrentfile();
1098 		cmdenviron = varlist.list;
1099 		e = -1;
1100 		savehandler = handler;
1101 		if (setjmp(jmploc.loc)) {
1102 			e = exception;
1103 			if (e == EXINT)
1104 				exitstatus = SIGINT+128;
1105 			else if (e != EXEXIT)
1106 				exitstatus = 2;
1107 			goto cmddone;
1108 		}
1109 		handler = &jmploc;
1110 		redirect(cmd->ncmd.redirect, mode);
1111 		outclearerror(out1);
1112 		/*
1113 		 * If there is no command word, redirection errors should
1114 		 * not be fatal but assignment errors should.
1115 		 */
1116 		if (argc == 0)
1117 			cmdentry.special = 1;
1118 		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1119 		if (argc > 0)
1120 			bltinsetlocale();
1121 		commandname = argv[0];
1122 		argptr = argv + 1;
1123 		nextopt_optptr = NULL;		/* initialize nextopt */
1124 		builtin_flags = flags;
1125 		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1126 		flushall();
1127 		if (outiserror(out1)) {
1128 			warning("write error on stdout");
1129 			if (exitstatus == 0 || exitstatus == 1)
1130 				exitstatus = 2;
1131 		}
1132 cmddone:
1133 		if (argc > 0)
1134 			bltinunsetlocale();
1135 		cmdenviron = NULL;
1136 		out1 = &output;
1137 		out2 = &errout;
1138 		freestdout();
1139 		handler = savehandler;
1140 		commandname = savecmdname;
1141 		if (jp)
1142 			exitshell(exitstatus);
1143 		if (flags == EV_BACKCMD) {
1144 			backcmd->buf = memout.buf;
1145 			backcmd->nleft = memout.nextc - memout.buf;
1146 			memout.buf = NULL;
1147 		}
1148 		if (cmdentry.u.index != EXECCMD)
1149 			popredir();
1150 		if (e != -1) {
1151 			if ((e != EXERROR && e != EXEXEC)
1152 			    || cmdentry.special)
1153 				exraise(e);
1154 			popfilesupto(savetopfile);
1155 			if (flags != EV_BACKCMD)
1156 				FORCEINTON;
1157 		}
1158 	} else {
1159 #ifdef DEBUG
1160 		trputs("normal command:  ");  trargs(argv);
1161 #endif
1162 		redirect(cmd->ncmd.redirect, 0);
1163 		for (sp = varlist.list ; sp ; sp = sp->next)
1164 			setvareq(sp->text, VEXPORT|VSTACK);
1165 		envp = environment();
1166 		shellexec(argv, envp, path, cmdentry.u.index);
1167 		/*NOTREACHED*/
1168 	}
1169 	goto out;
1170 
1171 parent:	/* parent process gets here (if we forked) */
1172 	if (mode == FORK_FG) {	/* argument to fork */
1173 		INTOFF;
1174 		exitstatus = waitforjob(jp, &realstatus);
1175 		INTON;
1176 		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1177 			evalskip = SKIPBREAK;
1178 			skipcount = loopnest;
1179 		}
1180 	} else if (mode == FORK_NOJOB) {
1181 		backcmd->fd = pip[0];
1182 		close(pip[1]);
1183 		backcmd->jp = jp;
1184 	}
1185 
1186 out:
1187 	if (lastarg)
1188 		setvar("_", lastarg, 0);
1189 	if (do_clearcmdentry)
1190 		clearcmdentry();
1191 }
1192 
1193 
1194 
1195 /*
1196  * Search for a command.  This is called before we fork so that the
1197  * location of the command will be available in the parent as well as
1198  * the child.  The check for "goodname" is an overly conservative
1199  * check that the name will not be subject to expansion.
1200  */
1201 
1202 static void
1203 prehash(union node *n)
1204 {
1205 	struct cmdentry entry;
1206 
1207 	if (n && n->type == NCMD && n->ncmd.args)
1208 		if (goodname(n->ncmd.args->narg.text))
1209 			find_command(n->ncmd.args->narg.text, &entry, 0,
1210 				     pathval());
1211 }
1212 
1213 
1214 
1215 /*
1216  * Builtin commands.  Builtin commands whose functions are closely
1217  * tied to evaluation are implemented here.
1218  */
1219 
1220 /*
1221  * No command given, a bltin command with no arguments, or a bltin command
1222  * with an invalid name.
1223  */
1224 
1225 int
1226 bltincmd(int argc, char **argv)
1227 {
1228 	if (argc > 1) {
1229 		out2fmt_flush("%s: not found\n", argv[1]);
1230 		return 127;
1231 	}
1232 	/*
1233 	 * Preserve exitstatus of a previous possible redirection
1234 	 * as POSIX mandates
1235 	 */
1236 	return exitstatus;
1237 }
1238 
1239 
1240 /*
1241  * Handle break and continue commands.  Break, continue, and return are
1242  * all handled by setting the evalskip flag.  The evaluation routines
1243  * above all check this flag, and if it is set they start skipping
1244  * commands rather than executing them.  The variable skipcount is
1245  * the number of loops to break/continue, or the number of function
1246  * levels to return.  (The latter is always 1.)  It should probably
1247  * be an error to break out of more loops than exist, but it isn't
1248  * in the standard shell so we don't make it one here.
1249  */
1250 
1251 int
1252 breakcmd(int argc, char **argv)
1253 {
1254 	long n;
1255 	char *end;
1256 
1257 	if (argc > 1) {
1258 		/* Allow arbitrarily large numbers. */
1259 		n = strtol(argv[1], &end, 10);
1260 		if (!is_digit(argv[1][0]) || *end != '\0')
1261 			error("Illegal number: %s", argv[1]);
1262 	} else
1263 		n = 1;
1264 	if (n > loopnest)
1265 		n = loopnest;
1266 	if (n > 0) {
1267 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1268 		skipcount = n;
1269 	}
1270 	return 0;
1271 }
1272 
1273 /*
1274  * The `command' command.
1275  */
1276 int
1277 commandcmd(int argc __unused, char **argv __unused)
1278 {
1279 	const char *path;
1280 	int ch;
1281 	int cmd = -1;
1282 
1283 	path = bltinlookup("PATH", 1);
1284 
1285 	while ((ch = nextopt("pvV")) != '\0') {
1286 		switch (ch) {
1287 		case 'p':
1288 			path = _PATH_STDPATH;
1289 			break;
1290 		case 'v':
1291 			cmd = TYPECMD_SMALLV;
1292 			break;
1293 		case 'V':
1294 			cmd = TYPECMD_BIGV;
1295 			break;
1296 		}
1297 	}
1298 
1299 	if (cmd != -1) {
1300 		if (*argptr == NULL || argptr[1] != NULL)
1301 			error("wrong number of arguments");
1302 		return typecmd_impl(2, argptr - 1, cmd, path);
1303 	}
1304 	if (*argptr != NULL)
1305 		error("commandcmd bad call");
1306 
1307 	/*
1308 	 * Do nothing successfully if no command was specified;
1309 	 * ksh also does this.
1310 	 */
1311 	return 0;
1312 }
1313 
1314 
1315 /*
1316  * The return command.
1317  */
1318 
1319 int
1320 returncmd(int argc, char **argv)
1321 {
1322 	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1323 
1324 	evalskip = SKIPRETURN;
1325 	skipcount = 1;
1326 	return ret;
1327 }
1328 
1329 
1330 int
1331 falsecmd(int argc __unused, char **argv __unused)
1332 {
1333 	return 1;
1334 }
1335 
1336 
1337 int
1338 truecmd(int argc __unused, char **argv __unused)
1339 {
1340 	return 0;
1341 }
1342 
1343 
1344 int
1345 execcmd(int argc, char **argv)
1346 {
1347 	/*
1348 	 * Because we have historically not supported any options,
1349 	 * only treat "--" specially.
1350 	 */
1351 	if (argc > 1 && strcmp(argv[1], "--") == 0)
1352 		argc--, argv++;
1353 	if (argc > 1) {
1354 		struct strlist *sp;
1355 
1356 		iflag = 0;		/* exit on error */
1357 		mflag = 0;
1358 		optschanged();
1359 		for (sp = cmdenviron; sp ; sp = sp->next)
1360 			setvareq(sp->text, VEXPORT|VSTACK);
1361 		shellexec(argv + 1, environment(), pathval(), 0);
1362 
1363 	}
1364 	return 0;
1365 }
1366 
1367 
1368 int
1369 timescmd(int argc __unused, char **argv __unused)
1370 {
1371 	struct rusage ru;
1372 	long shumins, shsmins, chumins, chsmins;
1373 	double shusecs, shssecs, chusecs, chssecs;
1374 
1375 	if (getrusage(RUSAGE_SELF, &ru) < 0)
1376 		return 1;
1377 	shumins = ru.ru_utime.tv_sec / 60;
1378 	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1379 	shsmins = ru.ru_stime.tv_sec / 60;
1380 	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1381 	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1382 		return 1;
1383 	chumins = ru.ru_utime.tv_sec / 60;
1384 	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1385 	chsmins = ru.ru_stime.tv_sec / 60;
1386 	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1387 	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1388 	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1389 	return 0;
1390 }
1391