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