xref: /freebsd/bin/sh/eval.c (revision f5f7c05209ca2c3748fd8b27c5e80ffad49120eb)
1 /*-
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include <paths.h>
42 #include <signal.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <sys/resource.h>
46 #include <sys/wait.h> /* For WIFSIGNALED(status) */
47 #include <errno.h>
48 
49 /*
50  * Evaluate a command.
51  */
52 
53 #include "shell.h"
54 #include "nodes.h"
55 #include "syntax.h"
56 #include "expand.h"
57 #include "parser.h"
58 #include "jobs.h"
59 #include "eval.h"
60 #include "builtins.h"
61 #include "options.h"
62 #include "exec.h"
63 #include "redir.h"
64 #include "input.h"
65 #include "output.h"
66 #include "trap.h"
67 #include "var.h"
68 #include "memalloc.h"
69 #include "error.h"
70 #include "show.h"
71 #include "mystring.h"
72 #ifndef NO_HISTORY
73 #include "myhistedit.h"
74 #endif
75 
76 
77 int evalskip;			/* set if we are skipping commands */
78 int skipcount;			/* number of levels to skip */
79 MKINIT int loopnest;		/* current loop nesting level */
80 int funcnest;			/* depth of function calls */
81 static int builtin_flags;	/* evalcommand flags for builtins */
82 
83 
84 char *commandname;
85 struct strlist *cmdenviron;
86 int exitstatus;			/* exit status of last command */
87 int oexitstatus;		/* saved exit status */
88 
89 
90 static void evalloop(union node *, int);
91 static void evalfor(union node *, int);
92 static union node *evalcase(union node *);
93 static void evalsubshell(union node *, int);
94 static void evalredir(union node *, int);
95 static void 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 #ifdef mkinit
108 INCLUDE "eval.h"
109 
110 RESET {
111 	evalskip = 0;
112 	loopnest = 0;
113 	funcnest = 0;
114 }
115 #endif
116 
117 
118 
119 /*
120  * The eval command.
121  */
122 
123 int
124 evalcmd(int argc, char **argv)
125 {
126         char *p;
127         char *concat;
128         char **ap;
129 
130         if (argc > 1) {
131                 p = argv[1];
132                 if (argc > 2) {
133                         STARTSTACKSTR(concat);
134                         ap = argv + 2;
135                         for (;;) {
136                                 STPUTS(p, concat);
137                                 if ((p = *ap++) == NULL)
138                                         break;
139                                 STPUTC(' ', concat);
140                         }
141                         STPUTC('\0', concat);
142                         p = grabstackstr(concat);
143                 }
144                 evalstring(p, builtin_flags);
145         } else
146                 exitstatus = 0;
147         return exitstatus;
148 }
149 
150 
151 /*
152  * Execute a command or commands contained in a string.
153  */
154 
155 void
156 evalstring(char *s, int flags)
157 {
158 	union node *n;
159 	struct stackmark smark;
160 	int flags_exit;
161 	int any;
162 
163 	flags_exit = flags & EV_EXIT;
164 	flags &= ~EV_EXIT;
165 	any = 0;
166 	setstackmark(&smark);
167 	setinputstring(s, 1);
168 	while ((n = parsecmd(0)) != NEOF) {
169 		if (n != NULL && !nflag) {
170 			if (flags_exit && preadateof())
171 				evaltree(n, flags | EV_EXIT);
172 			else
173 				evaltree(n, flags);
174 			any = 1;
175 		}
176 		popstackmark(&smark);
177 	}
178 	popfile();
179 	popstackmark(&smark);
180 	if (!any)
181 		exitstatus = 0;
182 	if (flags_exit)
183 		exraise(EXEXIT);
184 }
185 
186 
187 /*
188  * Evaluate a parse tree.  The value is left in the global variable
189  * exitstatus.
190  */
191 
192 void
193 evaltree(union node *n, int flags)
194 {
195 	int do_etest;
196 	union node *next;
197 	struct stackmark smark;
198 
199 	setstackmark(&smark);
200 	do_etest = 0;
201 	if (n == NULL) {
202 		TRACE(("evaltree(NULL) called\n"));
203 		exitstatus = 0;
204 		goto out;
205 	}
206 	do {
207 		next = NULL;
208 #ifndef NO_HISTORY
209 		displayhist = 1;	/* show history substitutions done with fc */
210 #endif
211 		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
212 		switch (n->type) {
213 		case NSEMI:
214 			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
215 			if (evalskip)
216 				goto out;
217 			next = n->nbinary.ch2;
218 			break;
219 		case NAND:
220 			evaltree(n->nbinary.ch1, EV_TESTED);
221 			if (evalskip || exitstatus != 0) {
222 				goto out;
223 			}
224 			next = n->nbinary.ch2;
225 			break;
226 		case NOR:
227 			evaltree(n->nbinary.ch1, EV_TESTED);
228 			if (evalskip || exitstatus == 0)
229 				goto out;
230 			next = n->nbinary.ch2;
231 			break;
232 		case NREDIR:
233 			evalredir(n, flags);
234 			break;
235 		case NSUBSHELL:
236 			evalsubshell(n, flags);
237 			do_etest = !(flags & EV_TESTED);
238 			break;
239 		case NBACKGND:
240 			evalsubshell(n, flags);
241 			break;
242 		case NIF: {
243 			evaltree(n->nif.test, EV_TESTED);
244 			if (evalskip)
245 				goto out;
246 			if (exitstatus == 0)
247 				next = n->nif.ifpart;
248 			else if (n->nif.elsepart)
249 				next = n->nif.elsepart;
250 			else
251 				exitstatus = 0;
252 			break;
253 		}
254 		case NWHILE:
255 		case NUNTIL:
256 			evalloop(n, flags & ~EV_EXIT);
257 			break;
258 		case NFOR:
259 			evalfor(n, flags & ~EV_EXIT);
260 			break;
261 		case NCASE:
262 			next = evalcase(n);
263 			break;
264 		case NCLIST:
265 			next = n->nclist.body;
266 			break;
267 		case NCLISTFALLTHRU:
268 			if (n->nclist.body) {
269 				evaltree(n->nclist.body, flags & ~EV_EXIT);
270 				if (evalskip)
271 					goto out;
272 			}
273 			next = n->nclist.next;
274 			break;
275 		case NDEFUN:
276 			defun(n->narg.text, n->narg.next);
277 			exitstatus = 0;
278 			break;
279 		case NNOT:
280 			evaltree(n->nnot.com, EV_TESTED);
281 			exitstatus = !exitstatus;
282 			break;
283 
284 		case NPIPE:
285 			evalpipe(n);
286 			do_etest = !(flags & EV_TESTED);
287 			break;
288 		case NCMD:
289 			evalcommand(n, flags, (struct backcmd *)NULL);
290 			do_etest = !(flags & EV_TESTED);
291 			break;
292 		default:
293 			out1fmt("Node type = %d\n", n->type);
294 			flushout(&output);
295 			break;
296 		}
297 		n = next;
298 		popstackmark(&smark);
299 	} while (n != NULL);
300 out:
301 	popstackmark(&smark);
302 	if (pendingsigs)
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 == SKIPFUNC || evalskip == SKIPFILE)
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 				close(prevfd);
589 				error("Pipe call failed: %s", strerror(errno));
590 			}
591 		}
592 		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
593 			INTON;
594 			if (prevfd > 0) {
595 				dup2(prevfd, 0);
596 				close(prevfd);
597 			}
598 			if (pip[1] >= 0) {
599 				if (!(prevfd >= 0 && pip[0] == 0))
600 					close(pip[0]);
601 				if (pip[1] != 1) {
602 					dup2(pip[1], 1);
603 					close(pip[1]);
604 				}
605 			}
606 			evaltree(lp->n, EV_EXIT);
607 		}
608 		if (prevfd >= 0)
609 			close(prevfd);
610 		prevfd = pip[0];
611 		if (pip[1] != -1)
612 			close(pip[1]);
613 	}
614 	INTON;
615 	if (n->npipe.backgnd == 0) {
616 		INTOFF;
617 		exitstatus = waitforjob(jp, (int *)NULL);
618 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
619 		INTON;
620 	} else
621 		exitstatus = 0;
622 }
623 
624 
625 
626 static int
627 is_valid_fast_cmdsubst(union node *n)
628 {
629 
630 	return (n->type == NCMD);
631 }
632 
633 /*
634  * Execute a command inside back quotes.  If it's a builtin command, we
635  * want to save its output in a block obtained from malloc.  Otherwise
636  * we fork off a subprocess and get the output of the command via a pipe.
637  * Should be called with interrupts off.
638  */
639 
640 void
641 evalbackcmd(union node *n, struct backcmd *result)
642 {
643 	int pip[2];
644 	struct job *jp;
645 	struct stackmark smark;
646 	struct jmploc jmploc;
647 	struct jmploc *savehandler;
648 	struct localvar *savelocalvars;
649 
650 	setstackmark(&smark);
651 	result->fd = -1;
652 	result->buf = NULL;
653 	result->nleft = 0;
654 	result->jp = NULL;
655 	if (n == NULL) {
656 		exitstatus = 0;
657 		goto out;
658 	}
659 	exitstatus = oexitstatus;
660 	if (is_valid_fast_cmdsubst(n)) {
661 		savelocalvars = localvars;
662 		localvars = NULL;
663 		forcelocal++;
664 		savehandler = handler;
665 		if (setjmp(jmploc.loc)) {
666 			if (exception == EXERROR || exception == EXEXEC)
667 				exitstatus = 2;
668 			else if (exception != 0) {
669 				handler = savehandler;
670 				forcelocal--;
671 				poplocalvars();
672 				localvars = savelocalvars;
673 				longjmp(handler->loc, 1);
674 			}
675 		} else {
676 			handler = &jmploc;
677 			evalcommand(n, EV_BACKCMD, result);
678 		}
679 		handler = savehandler;
680 		forcelocal--;
681 		poplocalvars();
682 		localvars = savelocalvars;
683 	} else {
684 		if (pipe(pip) < 0)
685 			error("Pipe call failed: %s", strerror(errno));
686 		jp = makejob(n, 1);
687 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
688 			FORCEINTON;
689 			close(pip[0]);
690 			if (pip[1] != 1) {
691 				dup2(pip[1], 1);
692 				close(pip[1]);
693 			}
694 			evaltree(n, EV_EXIT);
695 		}
696 		close(pip[1]);
697 		result->fd = pip[0];
698 		result->jp = jp;
699 	}
700 out:
701 	popstackmark(&smark);
702 	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
703 		result->fd, result->buf, result->nleft, result->jp));
704 }
705 
706 static int
707 mustexpandto(const char *argtext, const char *mask)
708 {
709 	for (;;) {
710 		if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) {
711 			argtext++;
712 			continue;
713 		}
714 		if (*argtext == CTLESC)
715 			argtext++;
716 		else if (BASESYNTAX[(int)*argtext] == CCTL)
717 			return (0);
718 		if (*argtext != *mask)
719 			return (0);
720 		if (*argtext == '\0')
721 			return (1);
722 		argtext++;
723 		mask++;
724 	}
725 }
726 
727 static int
728 isdeclarationcmd(struct narg *arg)
729 {
730 	int have_command = 0;
731 
732 	if (arg == NULL)
733 		return (0);
734 	while (mustexpandto(arg->text, "command")) {
735 		have_command = 1;
736 		arg = &arg->next->narg;
737 		if (arg == NULL)
738 			return (0);
739 		/*
740 		 * To also allow "command -p" and "command --" as part of
741 		 * a declaration command, add code here.
742 		 * We do not do this, as ksh does not do it either and it
743 		 * is not required by POSIX.
744 		 */
745 	}
746 	return (mustexpandto(arg->text, "export") ||
747 	    mustexpandto(arg->text, "readonly") ||
748 	    (mustexpandto(arg->text, "local") &&
749 		(have_command || !isfunc("local"))));
750 }
751 
752 /*
753  * Check if a builtin can safely be executed in the same process,
754  * even though it should be in a subshell (command substitution).
755  * Note that jobid, jobs, times and trap can show information not
756  * available in a child process; this is deliberate.
757  * The arguments should already have been expanded.
758  */
759 static int
760 safe_builtin(int idx, int argc, char **argv)
761 {
762 	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
763 	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
764 	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
765 	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
766 	    idx == TYPECMD)
767 		return (1);
768 	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
769 	    idx == UMASKCMD)
770 		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
771 	if (idx == SETCMD)
772 		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
773 		    argv[1][0] == '+') && argv[1][1] == 'o' &&
774 		    argv[1][2] == '\0'));
775 	return (0);
776 }
777 
778 /*
779  * Execute a simple command.
780  * Note: This may or may not return if (flags & EV_EXIT).
781  */
782 
783 static void
784 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
785 {
786 	union node *argp;
787 	struct arglist arglist;
788 	struct arglist varlist;
789 	char **argv;
790 	int argc;
791 	char **envp;
792 	int varflag;
793 	struct strlist *sp;
794 	int mode;
795 	int pip[2];
796 	struct cmdentry cmdentry;
797 	struct job *jp;
798 	struct jmploc jmploc;
799 	struct jmploc *savehandler;
800 	char *savecmdname;
801 	struct shparam saveparam;
802 	struct localvar *savelocalvars;
803 	struct parsefile *savetopfile;
804 	volatile int e;
805 	char *lastarg;
806 	int realstatus;
807 	int do_clearcmdentry;
808 	const char *path = pathval();
809 
810 	/* First expand the arguments. */
811 	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
812 	arglist.lastp = &arglist.list;
813 	varlist.lastp = &varlist.list;
814 	varflag = 1;
815 	jp = NULL;
816 	do_clearcmdentry = 0;
817 	oexitstatus = exitstatus;
818 	exitstatus = 0;
819 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
820 		if (varflag && isassignment(argp->narg.text)) {
821 			expandarg(argp, varflag == 1 ? &varlist : &arglist,
822 			    EXP_VARTILDE);
823 			continue;
824 		} else if (varflag == 1)
825 			varflag = isdeclarationcmd(&argp->narg) ? 2 : 0;
826 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
827 	}
828 	*arglist.lastp = NULL;
829 	*varlist.lastp = NULL;
830 	expredir(cmd->ncmd.redirect);
831 	argc = 0;
832 	for (sp = arglist.list ; sp ; sp = sp->next)
833 		argc++;
834 	/* Add one slot at the beginning for tryexec(). */
835 	argv = stalloc(sizeof (char *) * (argc + 2));
836 	argv++;
837 
838 	for (sp = arglist.list ; sp ; sp = sp->next) {
839 		TRACE(("evalcommand arg: %s\n", sp->text));
840 		*argv++ = sp->text;
841 	}
842 	*argv = NULL;
843 	lastarg = NULL;
844 	if (iflag && funcnest == 0 && argc > 0)
845 		lastarg = argv[-1];
846 	argv -= argc;
847 
848 	/* Print the command if xflag is set. */
849 	if (xflag) {
850 		char sep = 0;
851 		const char *p, *ps4;
852 		ps4 = expandstr(ps4val());
853 		out2str(ps4 != NULL ? ps4 : ps4val());
854 		for (sp = varlist.list ; sp ; sp = sp->next) {
855 			if (sep != 0)
856 				out2c(' ');
857 			p = strchr(sp->text, '=');
858 			if (p != NULL) {
859 				p++;
860 				outbin(sp->text, p - sp->text, out2);
861 				out2qstr(p);
862 			} else
863 				out2qstr(sp->text);
864 			sep = ' ';
865 		}
866 		for (sp = arglist.list ; sp ; sp = sp->next) {
867 			if (sep != 0)
868 				out2c(' ');
869 			/* Disambiguate command looking like assignment. */
870 			if (sp == arglist.list &&
871 					strchr(sp->text, '=') != NULL &&
872 					strchr(sp->text, '\'') == NULL) {
873 				out2c('\'');
874 				out2str(sp->text);
875 				out2c('\'');
876 			} else
877 				out2qstr(sp->text);
878 			sep = ' ';
879 		}
880 		out2c('\n');
881 		flushout(&errout);
882 	}
883 
884 	/* Now locate the command. */
885 	if (argc == 0) {
886 		/* Variable assignment(s) without command */
887 		cmdentry.cmdtype = CMDBUILTIN;
888 		cmdentry.u.index = BLTINCMD;
889 		cmdentry.special = 0;
890 	} else {
891 		static const char PATH[] = "PATH=";
892 		int cmd_flags = 0, bltinonly = 0;
893 
894 		/*
895 		 * Modify the command lookup path, if a PATH= assignment
896 		 * is present
897 		 */
898 		for (sp = varlist.list ; sp ; sp = sp->next)
899 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
900 				path = sp->text + sizeof(PATH) - 1;
901 				/*
902 				 * On `PATH=... command`, we need to make
903 				 * sure that the command isn't using the
904 				 * non-updated hash table of the outer PATH
905 				 * setting and we need to make sure that
906 				 * the hash table isn't filled with items
907 				 * from the temporary setting.
908 				 *
909 				 * It would be better to forbit using and
910 				 * updating the table while this command
911 				 * runs, by the command finding mechanism
912 				 * is heavily integrated with hash handling,
913 				 * so we just delete the hash before and after
914 				 * the command runs. Partly deleting like
915 				 * changepatch() does doesn't seem worth the
916 				 * bookinging effort, since most such runs add
917 				 * directories in front of the new PATH.
918 				 */
919 				clearcmdentry();
920 				do_clearcmdentry = 1;
921 			}
922 
923 		for (;;) {
924 			if (bltinonly) {
925 				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
926 				if (cmdentry.u.index < 0) {
927 					cmdentry.u.index = BLTINCMD;
928 					argv--;
929 					argc++;
930 					break;
931 				}
932 			} else
933 				find_command(argv[0], &cmdentry, cmd_flags, path);
934 			/* implement the bltin and command builtins here */
935 			if (cmdentry.cmdtype != CMDBUILTIN)
936 				break;
937 			if (cmdentry.u.index == BLTINCMD) {
938 				if (argc == 1)
939 					break;
940 				argv++;
941 				argc--;
942 				bltinonly = 1;
943 			} else if (cmdentry.u.index == COMMANDCMD) {
944 				if (argc == 1)
945 					break;
946 				if (!strcmp(argv[1], "-p")) {
947 					if (argc == 2)
948 						break;
949 					if (argv[2][0] == '-') {
950 						if (strcmp(argv[2], "--"))
951 							break;
952 						if (argc == 3)
953 							break;
954 						argv += 3;
955 						argc -= 3;
956 					} else {
957 						argv += 2;
958 						argc -= 2;
959 					}
960 					path = _PATH_STDPATH;
961 					clearcmdentry();
962 					do_clearcmdentry = 1;
963 				} else if (!strcmp(argv[1], "--")) {
964 					if (argc == 2)
965 						break;
966 					argv += 2;
967 					argc -= 2;
968 				} else if (argv[1][0] == '-')
969 					break;
970 				else {
971 					argv++;
972 					argc--;
973 				}
974 				cmd_flags |= DO_NOFUNC;
975 				bltinonly = 0;
976 			} else
977 				break;
978 		}
979 		/*
980 		 * Special builtins lose their special properties when
981 		 * called via 'command'.
982 		 */
983 		if (cmd_flags & DO_NOFUNC)
984 			cmdentry.special = 0;
985 	}
986 
987 	/* Fork off a child process if necessary. */
988 	if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
989 	    && ((flags & EV_EXIT) == 0 || have_traps()))
990 	 || ((flags & EV_BACKCMD) != 0
991 	    && (cmdentry.cmdtype != CMDBUILTIN ||
992 		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
993 		jp = makejob(cmd, 1);
994 		mode = FORK_FG;
995 		if (flags & EV_BACKCMD) {
996 			mode = FORK_NOJOB;
997 			if (pipe(pip) < 0)
998 				error("Pipe call failed: %s", strerror(errno));
999 		}
1000 		if (cmdentry.cmdtype == CMDNORMAL &&
1001 		    cmd->ncmd.redirect == NULL &&
1002 		    varlist.list == NULL &&
1003 		    (mode == FORK_FG || mode == FORK_NOJOB) &&
1004 		    !disvforkset() && !iflag && !mflag) {
1005 			vforkexecshell(jp, argv, environment(), path,
1006 			    cmdentry.u.index, flags & EV_BACKCMD ? pip : NULL);
1007 			goto parent;
1008 		}
1009 		if (forkshell(jp, cmd, mode) != 0)
1010 			goto parent;	/* at end of routine */
1011 		if (flags & EV_BACKCMD) {
1012 			FORCEINTON;
1013 			close(pip[0]);
1014 			if (pip[1] != 1) {
1015 				dup2(pip[1], 1);
1016 				close(pip[1]);
1017 			}
1018 			flags &= ~EV_BACKCMD;
1019 		}
1020 		flags |= EV_EXIT;
1021 	}
1022 
1023 	/* This is the child process if a fork occurred. */
1024 	/* Execute the command. */
1025 	if (cmdentry.cmdtype == CMDFUNCTION) {
1026 #ifdef DEBUG
1027 		trputs("Shell function:  ");  trargs(argv);
1028 #endif
1029 		saveparam = shellparam;
1030 		shellparam.malloc = 0;
1031 		shellparam.reset = 1;
1032 		shellparam.nparam = argc - 1;
1033 		shellparam.p = argv + 1;
1034 		shellparam.optnext = NULL;
1035 		INTOFF;
1036 		savelocalvars = localvars;
1037 		localvars = NULL;
1038 		reffunc(cmdentry.u.func);
1039 		savehandler = handler;
1040 		if (setjmp(jmploc.loc)) {
1041 			freeparam(&shellparam);
1042 			shellparam = saveparam;
1043 			popredir();
1044 			unreffunc(cmdentry.u.func);
1045 			poplocalvars();
1046 			localvars = savelocalvars;
1047 			funcnest--;
1048 			handler = savehandler;
1049 			longjmp(handler->loc, 1);
1050 		}
1051 		handler = &jmploc;
1052 		funcnest++;
1053 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
1054 		INTON;
1055 		for (sp = varlist.list ; sp ; sp = sp->next)
1056 			mklocal(sp->text);
1057 		exitstatus = oexitstatus;
1058 		evaltree(getfuncnode(cmdentry.u.func),
1059 		    flags & (EV_TESTED | EV_EXIT));
1060 		INTOFF;
1061 		unreffunc(cmdentry.u.func);
1062 		poplocalvars();
1063 		localvars = savelocalvars;
1064 		freeparam(&shellparam);
1065 		shellparam = saveparam;
1066 		handler = savehandler;
1067 		funcnest--;
1068 		popredir();
1069 		INTON;
1070 		if (evalskip == SKIPFUNC) {
1071 			evalskip = 0;
1072 			skipcount = 0;
1073 		}
1074 		if (jp)
1075 			exitshell(exitstatus);
1076 	} else if (cmdentry.cmdtype == CMDBUILTIN) {
1077 #ifdef DEBUG
1078 		trputs("builtin command:  ");  trargs(argv);
1079 #endif
1080 		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
1081 		if (flags == EV_BACKCMD) {
1082 			memout.nleft = 0;
1083 			memout.nextc = memout.buf;
1084 			memout.bufsize = 64;
1085 			mode |= REDIR_BACKQ;
1086 		}
1087 		savecmdname = commandname;
1088 		savetopfile = getcurrentfile();
1089 		cmdenviron = varlist.list;
1090 		e = -1;
1091 		savehandler = handler;
1092 		if (setjmp(jmploc.loc)) {
1093 			e = exception;
1094 			if (e == EXINT)
1095 				exitstatus = SIGINT+128;
1096 			else if (e != EXEXIT)
1097 				exitstatus = 2;
1098 			goto cmddone;
1099 		}
1100 		handler = &jmploc;
1101 		redirect(cmd->ncmd.redirect, mode);
1102 		outclearerror(out1);
1103 		/*
1104 		 * If there is no command word, redirection errors should
1105 		 * not be fatal but assignment errors should.
1106 		 */
1107 		if (argc == 0)
1108 			cmdentry.special = 1;
1109 		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1110 		if (argc > 0)
1111 			bltinsetlocale();
1112 		commandname = argv[0];
1113 		argptr = argv + 1;
1114 		nextopt_optptr = NULL;		/* initialize nextopt */
1115 		builtin_flags = flags;
1116 		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1117 		flushall();
1118 		if (outiserror(out1)) {
1119 			warning("write error on stdout");
1120 			if (exitstatus == 0 || exitstatus == 1)
1121 				exitstatus = 2;
1122 		}
1123 cmddone:
1124 		if (argc > 0)
1125 			bltinunsetlocale();
1126 		cmdenviron = NULL;
1127 		out1 = &output;
1128 		out2 = &errout;
1129 		freestdout();
1130 		handler = savehandler;
1131 		commandname = savecmdname;
1132 		if (jp)
1133 			exitshell(exitstatus);
1134 		if (flags == EV_BACKCMD) {
1135 			backcmd->buf = memout.buf;
1136 			backcmd->nleft = memout.nextc - memout.buf;
1137 			memout.buf = NULL;
1138 		}
1139 		if (cmdentry.u.index != EXECCMD)
1140 			popredir();
1141 		if (e != -1) {
1142 			if ((e != EXERROR && e != EXEXEC)
1143 			    || cmdentry.special)
1144 				exraise(e);
1145 			popfilesupto(savetopfile);
1146 			if (flags != EV_BACKCMD)
1147 				FORCEINTON;
1148 		}
1149 	} else {
1150 #ifdef DEBUG
1151 		trputs("normal command:  ");  trargs(argv);
1152 #endif
1153 		redirect(cmd->ncmd.redirect, 0);
1154 		for (sp = varlist.list ; sp ; sp = sp->next)
1155 			setvareq(sp->text, VEXPORT|VSTACK);
1156 		envp = environment();
1157 		shellexec(argv, envp, path, cmdentry.u.index);
1158 		/*NOTREACHED*/
1159 	}
1160 	goto out;
1161 
1162 parent:	/* parent process gets here (if we forked) */
1163 	if (mode == FORK_FG) {	/* argument to fork */
1164 		INTOFF;
1165 		exitstatus = waitforjob(jp, &realstatus);
1166 		INTON;
1167 		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1168 			evalskip = SKIPBREAK;
1169 			skipcount = loopnest;
1170 		}
1171 	} else if (mode == FORK_NOJOB) {
1172 		backcmd->fd = pip[0];
1173 		close(pip[1]);
1174 		backcmd->jp = jp;
1175 	}
1176 
1177 out:
1178 	if (lastarg)
1179 		setvar("_", lastarg, 0);
1180 	if (do_clearcmdentry)
1181 		clearcmdentry();
1182 }
1183 
1184 
1185 
1186 /*
1187  * Search for a command.  This is called before we fork so that the
1188  * location of the command will be available in the parent as well as
1189  * the child.  The check for "goodname" is an overly conservative
1190  * check that the name will not be subject to expansion.
1191  */
1192 
1193 static void
1194 prehash(union node *n)
1195 {
1196 	struct cmdentry entry;
1197 
1198 	if (n && n->type == NCMD && n->ncmd.args)
1199 		if (goodname(n->ncmd.args->narg.text))
1200 			find_command(n->ncmd.args->narg.text, &entry, 0,
1201 				     pathval());
1202 }
1203 
1204 
1205 
1206 /*
1207  * Builtin commands.  Builtin commands whose functions are closely
1208  * tied to evaluation are implemented here.
1209  */
1210 
1211 /*
1212  * No command given, a bltin command with no arguments, or a bltin command
1213  * with an invalid name.
1214  */
1215 
1216 int
1217 bltincmd(int argc, char **argv)
1218 {
1219 	if (argc > 1) {
1220 		out2fmt_flush("%s: not found\n", argv[1]);
1221 		return 127;
1222 	}
1223 	/*
1224 	 * Preserve exitstatus of a previous possible redirection
1225 	 * as POSIX mandates
1226 	 */
1227 	return exitstatus;
1228 }
1229 
1230 
1231 /*
1232  * Handle break and continue commands.  Break, continue, and return are
1233  * all handled by setting the evalskip flag.  The evaluation routines
1234  * above all check this flag, and if it is set they start skipping
1235  * commands rather than executing them.  The variable skipcount is
1236  * the number of loops to break/continue, or the number of function
1237  * levels to return.  (The latter is always 1.)  It should probably
1238  * be an error to break out of more loops than exist, but it isn't
1239  * in the standard shell so we don't make it one here.
1240  */
1241 
1242 int
1243 breakcmd(int argc, char **argv)
1244 {
1245 	int n = argc > 1 ? number(argv[1]) : 1;
1246 
1247 	if (n > loopnest)
1248 		n = loopnest;
1249 	if (n > 0) {
1250 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1251 		skipcount = n;
1252 	}
1253 	return 0;
1254 }
1255 
1256 /*
1257  * The `command' command.
1258  */
1259 int
1260 commandcmd(int argc __unused, char **argv __unused)
1261 {
1262 	const char *path;
1263 	int ch;
1264 	int cmd = -1;
1265 
1266 	path = bltinlookup("PATH", 1);
1267 
1268 	while ((ch = nextopt("pvV")) != '\0') {
1269 		switch (ch) {
1270 		case 'p':
1271 			path = _PATH_STDPATH;
1272 			break;
1273 		case 'v':
1274 			cmd = TYPECMD_SMALLV;
1275 			break;
1276 		case 'V':
1277 			cmd = TYPECMD_BIGV;
1278 			break;
1279 		}
1280 	}
1281 
1282 	if (cmd != -1) {
1283 		if (*argptr == NULL || argptr[1] != NULL)
1284 			error("wrong number of arguments");
1285 		return typecmd_impl(2, argptr - 1, cmd, path);
1286 	}
1287 	if (*argptr != NULL)
1288 		error("commandcmd bad call");
1289 
1290 	/*
1291 	 * Do nothing successfully if no command was specified;
1292 	 * ksh also does this.
1293 	 */
1294 	return 0;
1295 }
1296 
1297 
1298 /*
1299  * The return command.
1300  */
1301 
1302 int
1303 returncmd(int argc, char **argv)
1304 {
1305 	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1306 
1307 	if (funcnest) {
1308 		evalskip = SKIPFUNC;
1309 		skipcount = 1;
1310 	} else {
1311 		/* skip the rest of the file */
1312 		evalskip = SKIPFILE;
1313 		skipcount = 1;
1314 	}
1315 	return ret;
1316 }
1317 
1318 
1319 int
1320 falsecmd(int argc __unused, char **argv __unused)
1321 {
1322 	return 1;
1323 }
1324 
1325 
1326 int
1327 truecmd(int argc __unused, char **argv __unused)
1328 {
1329 	return 0;
1330 }
1331 
1332 
1333 int
1334 execcmd(int argc, char **argv)
1335 {
1336 	/*
1337 	 * Because we have historically not supported any options,
1338 	 * only treat "--" specially.
1339 	 */
1340 	if (argc > 1 && strcmp(argv[1], "--") == 0)
1341 		argc--, argv++;
1342 	if (argc > 1) {
1343 		struct strlist *sp;
1344 
1345 		iflag = 0;		/* exit on error */
1346 		mflag = 0;
1347 		optschanged();
1348 		for (sp = cmdenviron; sp ; sp = sp->next)
1349 			setvareq(sp->text, VEXPORT|VSTACK);
1350 		shellexec(argv + 1, environment(), pathval(), 0);
1351 
1352 	}
1353 	return 0;
1354 }
1355 
1356 
1357 int
1358 timescmd(int argc __unused, char **argv __unused)
1359 {
1360 	struct rusage ru;
1361 	long shumins, shsmins, chumins, chsmins;
1362 	double shusecs, shssecs, chusecs, chssecs;
1363 
1364 	if (getrusage(RUSAGE_SELF, &ru) < 0)
1365 		return 1;
1366 	shumins = ru.ru_utime.tv_sec / 60;
1367 	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1368 	shsmins = ru.ru_stime.tv_sec / 60;
1369 	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1370 	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1371 		return 1;
1372 	chumins = ru.ru_utime.tv_sec / 60;
1373 	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1374 	chsmins = ru.ru_stime.tv_sec / 60;
1375 	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1376 	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1377 	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1378 	return 0;
1379 }
1380