xref: /freebsd/bin/sh/eval.c (revision e28a4053)
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 static 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 void evalcase(union node *, int);
93 static void evalsubshell(union node *, int);
94 static void evalredir(union node *, int);
95 static void expredir(union node *);
96 static void evalpipe(union node *);
97 static void evalcommand(union node *, int, struct backcmd *);
98 static void prehash(union node *);
99 
100 
101 /*
102  * Called to reset things after an exception.
103  */
104 
105 #ifdef mkinit
106 INCLUDE "eval.h"
107 
108 RESET {
109 	evalskip = 0;
110 	loopnest = 0;
111 	funcnest = 0;
112 }
113 
114 SHELLPROC {
115 	exitstatus = 0;
116 }
117 #endif
118 
119 
120 
121 /*
122  * The eval command.
123  */
124 
125 int
126 evalcmd(int argc, char **argv)
127 {
128         char *p;
129         char *concat;
130         char **ap;
131 
132         if (argc > 1) {
133                 p = argv[1];
134                 if (argc > 2) {
135                         STARTSTACKSTR(concat);
136                         ap = argv + 2;
137                         for (;;) {
138                                 while (*p)
139                                         STPUTC(*p++, concat);
140                                 if ((p = *ap++) == NULL)
141                                         break;
142                                 STPUTC(' ', concat);
143                         }
144                         STPUTC('\0', concat);
145                         p = grabstackstr(concat);
146                 }
147                 evalstring(p, builtin_flags & EV_TESTED);
148         } else
149                 exitstatus = 0;
150         return exitstatus;
151 }
152 
153 
154 /*
155  * Execute a command or commands contained in a string.
156  */
157 
158 void
159 evalstring(char *s, int flags)
160 {
161 	union node *n;
162 	struct stackmark smark;
163 	int flags_exit;
164 	int any;
165 
166 	flags_exit = flags & EV_EXIT;
167 	flags &= ~EV_EXIT;
168 	any = 0;
169 	setstackmark(&smark);
170 	setinputstring(s, 1);
171 	while ((n = parsecmd(0)) != NEOF) {
172 		if (n != NULL) {
173 			if (flags_exit && preadateof())
174 				evaltree(n, flags | EV_EXIT);
175 			else
176 				evaltree(n, flags);
177 			any = 1;
178 		}
179 		popstackmark(&smark);
180 	}
181 	popfile();
182 	popstackmark(&smark);
183 	if (!any)
184 		exitstatus = 0;
185 	if (flags_exit)
186 		exitshell(exitstatus);
187 }
188 
189 
190 /*
191  * Evaluate a parse tree.  The value is left in the global variable
192  * exitstatus.
193  */
194 
195 void
196 evaltree(union node *n, int flags)
197 {
198 	int do_etest;
199 	union node *next;
200 
201 	do_etest = 0;
202 	if (n == NULL) {
203 		TRACE(("evaltree(NULL) called\n"));
204 		exitstatus = 0;
205 		goto out;
206 	}
207 	do {
208 		next = NULL;
209 #ifndef NO_HISTORY
210 		displayhist = 1;	/* show history substitutions done with fc */
211 #endif
212 		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
213 		switch (n->type) {
214 		case NSEMI:
215 			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
216 			if (evalskip)
217 				goto out;
218 			next = n->nbinary.ch2;
219 			break;
220 		case NAND:
221 			evaltree(n->nbinary.ch1, EV_TESTED);
222 			if (evalskip || exitstatus != 0) {
223 				goto out;
224 			}
225 			next = n->nbinary.ch2;
226 			break;
227 		case NOR:
228 			evaltree(n->nbinary.ch1, EV_TESTED);
229 			if (evalskip || exitstatus == 0)
230 				goto out;
231 			next = n->nbinary.ch2;
232 			break;
233 		case NREDIR:
234 			evalredir(n, flags);
235 			break;
236 		case NSUBSHELL:
237 			evalsubshell(n, flags);
238 			do_etest = !(flags & EV_TESTED);
239 			break;
240 		case NBACKGND:
241 			evalsubshell(n, flags);
242 			break;
243 		case NIF: {
244 			evaltree(n->nif.test, EV_TESTED);
245 			if (evalskip)
246 				goto out;
247 			if (exitstatus == 0)
248 				next = n->nif.ifpart;
249 			else if (n->nif.elsepart)
250 				next = n->nif.elsepart;
251 			else
252 				exitstatus = 0;
253 			break;
254 		}
255 		case NWHILE:
256 		case NUNTIL:
257 			evalloop(n, flags & ~EV_EXIT);
258 			break;
259 		case NFOR:
260 			evalfor(n, flags & ~EV_EXIT);
261 			break;
262 		case NCASE:
263 			evalcase(n, flags);
264 			break;
265 		case NDEFUN:
266 			defun(n->narg.text, n->narg.next);
267 			exitstatus = 0;
268 			break;
269 		case NNOT:
270 			evaltree(n->nnot.com, EV_TESTED);
271 			exitstatus = !exitstatus;
272 			break;
273 
274 		case NPIPE:
275 			evalpipe(n);
276 			do_etest = !(flags & EV_TESTED);
277 			break;
278 		case NCMD:
279 			evalcommand(n, flags, (struct backcmd *)NULL);
280 			do_etest = !(flags & EV_TESTED);
281 			break;
282 		default:
283 			out1fmt("Node type = %d\n", n->type);
284 			flushout(&output);
285 			break;
286 		}
287 		n = next;
288 	} while (n != NULL);
289 out:
290 	if (pendingsigs)
291 		dotrap();
292 	if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
293 		exitshell(exitstatus);
294 }
295 
296 
297 static void
298 evalloop(union node *n, int flags)
299 {
300 	int status;
301 
302 	loopnest++;
303 	status = 0;
304 	for (;;) {
305 		evaltree(n->nbinary.ch1, EV_TESTED);
306 		if (evalskip) {
307 skipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
308 				evalskip = 0;
309 				continue;
310 			}
311 			if (evalskip == SKIPBREAK && --skipcount <= 0)
312 				evalskip = 0;
313 			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
314 				status = exitstatus;
315 			break;
316 		}
317 		if (n->type == NWHILE) {
318 			if (exitstatus != 0)
319 				break;
320 		} else {
321 			if (exitstatus == 0)
322 				break;
323 		}
324 		evaltree(n->nbinary.ch2, flags);
325 		status = exitstatus;
326 		if (evalskip)
327 			goto skipping;
328 	}
329 	loopnest--;
330 	exitstatus = status;
331 }
332 
333 
334 
335 static void
336 evalfor(union node *n, int flags)
337 {
338 	struct arglist arglist;
339 	union node *argp;
340 	struct strlist *sp;
341 	struct stackmark smark;
342 
343 	setstackmark(&smark);
344 	arglist.lastp = &arglist.list;
345 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
346 		oexitstatus = exitstatus;
347 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
348 		if (evalskip)
349 			goto out;
350 	}
351 	*arglist.lastp = NULL;
352 
353 	exitstatus = 0;
354 	loopnest++;
355 	for (sp = arglist.list ; sp ; sp = sp->next) {
356 		setvar(n->nfor.var, sp->text, 0);
357 		evaltree(n->nfor.body, flags);
358 		if (evalskip) {
359 			if (evalskip == SKIPCONT && --skipcount <= 0) {
360 				evalskip = 0;
361 				continue;
362 			}
363 			if (evalskip == SKIPBREAK && --skipcount <= 0)
364 				evalskip = 0;
365 			break;
366 		}
367 	}
368 	loopnest--;
369 out:
370 	popstackmark(&smark);
371 }
372 
373 
374 
375 static void
376 evalcase(union node *n, int flags)
377 {
378 	union node *cp;
379 	union node *patp;
380 	struct arglist arglist;
381 	struct stackmark smark;
382 
383 	setstackmark(&smark);
384 	arglist.lastp = &arglist.list;
385 	oexitstatus = exitstatus;
386 	exitstatus = 0;
387 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
388 	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
389 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
390 			if (casematch(patp, arglist.list->text)) {
391 				if (evalskip == 0) {
392 					evaltree(cp->nclist.body, flags);
393 				}
394 				goto out;
395 			}
396 		}
397 	}
398 out:
399 	popstackmark(&smark);
400 }
401 
402 
403 
404 /*
405  * Kick off a subshell to evaluate a tree.
406  */
407 
408 static void
409 evalsubshell(union node *n, int flags)
410 {
411 	struct job *jp;
412 	int backgnd = (n->type == NBACKGND);
413 
414 	expredir(n->nredir.redirect);
415 	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
416 			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
417 		if (backgnd)
418 			flags &=~ EV_TESTED;
419 		redirect(n->nredir.redirect, 0);
420 		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
421 	} else if (! backgnd) {
422 		INTOFF;
423 		exitstatus = waitforjob(jp, (int *)NULL);
424 		INTON;
425 	}
426 }
427 
428 
429 /*
430  * Evaluate a redirected compound command.
431  */
432 
433 static void
434 evalredir(union node *n, int flags)
435 {
436 	struct jmploc jmploc;
437 	struct jmploc *savehandler;
438 	volatile int in_redirect = 1;
439 
440 	expredir(n->nredir.redirect);
441 	savehandler = handler;
442 	if (setjmp(jmploc.loc)) {
443 		int e;
444 
445 		handler = savehandler;
446 		e = exception;
447 		if (e == EXERROR || e == EXEXEC) {
448 			popredir();
449 			if (in_redirect) {
450 				exitstatus = 2;
451 				return;
452 			}
453 		}
454 		longjmp(handler->loc, 1);
455 	} else {
456 		INTOFF;
457 		handler = &jmploc;
458 		redirect(n->nredir.redirect, REDIR_PUSH);
459 		in_redirect = 0;
460 		INTON;
461 		evaltree(n->nredir.n, flags);
462 	}
463 	INTOFF;
464 	handler = savehandler;
465 	popredir();
466 	INTON;
467 }
468 
469 
470 /*
471  * Compute the names of the files in a redirection list.
472  */
473 
474 static void
475 expredir(union node *n)
476 {
477 	union node *redir;
478 
479 	for (redir = n ; redir ; redir = redir->nfile.next) {
480 		struct arglist fn;
481 		fn.lastp = &fn.list;
482 		oexitstatus = exitstatus;
483 		switch (redir->type) {
484 		case NFROM:
485 		case NTO:
486 		case NFROMTO:
487 		case NAPPEND:
488 		case NCLOBBER:
489 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
490 			redir->nfile.expfname = fn.list->text;
491 			break;
492 		case NFROMFD:
493 		case NTOFD:
494 			if (redir->ndup.vname) {
495 				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
496 				fixredir(redir, fn.list->text, 1);
497 			}
498 			break;
499 		}
500 	}
501 }
502 
503 
504 
505 /*
506  * Evaluate a pipeline.  All the processes in the pipeline are children
507  * of the process creating the pipeline.  (This differs from some versions
508  * of the shell, which make the last process in a pipeline the parent
509  * of all the rest.)
510  */
511 
512 static void
513 evalpipe(union node *n)
514 {
515 	struct job *jp;
516 	struct nodelist *lp;
517 	int pipelen;
518 	int prevfd;
519 	int pip[2];
520 
521 	TRACE(("evalpipe(%p) called\n", (void *)n));
522 	pipelen = 0;
523 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
524 		pipelen++;
525 	INTOFF;
526 	jp = makejob(n, pipelen);
527 	prevfd = -1;
528 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
529 		prehash(lp->n);
530 		pip[1] = -1;
531 		if (lp->next) {
532 			if (pipe(pip) < 0) {
533 				close(prevfd);
534 				error("Pipe call failed: %s", strerror(errno));
535 			}
536 		}
537 		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
538 			INTON;
539 			if (prevfd > 0) {
540 				dup2(prevfd, 0);
541 				close(prevfd);
542 			}
543 			if (pip[1] >= 0) {
544 				if (!(prevfd >= 0 && pip[0] == 0))
545 					close(pip[0]);
546 				if (pip[1] != 1) {
547 					dup2(pip[1], 1);
548 					close(pip[1]);
549 				}
550 			}
551 			evaltree(lp->n, EV_EXIT);
552 		}
553 		if (prevfd >= 0)
554 			close(prevfd);
555 		prevfd = pip[0];
556 		close(pip[1]);
557 	}
558 	INTON;
559 	if (n->npipe.backgnd == 0) {
560 		INTOFF;
561 		exitstatus = waitforjob(jp, (int *)NULL);
562 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
563 		INTON;
564 	}
565 }
566 
567 
568 
569 /*
570  * Execute a command inside back quotes.  If it's a builtin command, we
571  * want to save its output in a block obtained from malloc.  Otherwise
572  * we fork off a subprocess and get the output of the command via a pipe.
573  * Should be called with interrupts off.
574  */
575 
576 void
577 evalbackcmd(union node *n, struct backcmd *result)
578 {
579 	int pip[2];
580 	struct job *jp;
581 	struct stackmark smark;		/* unnecessary */
582 
583 	setstackmark(&smark);
584 	result->fd = -1;
585 	result->buf = NULL;
586 	result->nleft = 0;
587 	result->jp = NULL;
588 	if (n == NULL) {
589 		exitstatus = 0;
590 		goto out;
591 	}
592 	if (n->type == NCMD) {
593 		exitstatus = oexitstatus;
594 		evalcommand(n, EV_BACKCMD, result);
595 	} else {
596 		exitstatus = 0;
597 		if (pipe(pip) < 0)
598 			error("Pipe call failed: %s", strerror(errno));
599 		jp = makejob(n, 1);
600 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
601 			FORCEINTON;
602 			close(pip[0]);
603 			if (pip[1] != 1) {
604 				dup2(pip[1], 1);
605 				close(pip[1]);
606 			}
607 			evaltree(n, EV_EXIT);
608 		}
609 		close(pip[1]);
610 		result->fd = pip[0];
611 		result->jp = jp;
612 	}
613 out:
614 	popstackmark(&smark);
615 	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
616 		result->fd, result->buf, result->nleft, result->jp));
617 }
618 
619 
620 
621 /*
622  * Execute a simple command.
623  */
624 
625 static void
626 evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
627 {
628 	struct stackmark smark;
629 	union node *argp;
630 	struct arglist arglist;
631 	struct arglist varlist;
632 	char **argv;
633 	int argc;
634 	char **envp;
635 	int varflag;
636 	struct strlist *sp;
637 	int mode;
638 	int pip[2];
639 	struct cmdentry cmdentry;
640 	struct job *jp;
641 	struct jmploc jmploc;
642 	struct jmploc *savehandler;
643 	char *savecmdname;
644 	struct shparam saveparam;
645 	struct localvar *savelocalvars;
646 	struct parsefile *savetopfile;
647 	volatile int e;
648 	char *lastarg;
649 	int realstatus;
650 	int do_clearcmdentry;
651 	const char *path = pathval();
652 
653 	/* First expand the arguments. */
654 	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
655 	setstackmark(&smark);
656 	arglist.lastp = &arglist.list;
657 	varlist.lastp = &varlist.list;
658 	varflag = 1;
659 	do_clearcmdentry = 0;
660 	oexitstatus = exitstatus;
661 	exitstatus = 0;
662 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
663 		char *p = argp->narg.text;
664 		if (varflag && is_name(*p)) {
665 			do {
666 				p++;
667 			} while (is_in_name(*p));
668 			if (*p == '=') {
669 				expandarg(argp, &varlist, EXP_VARTILDE);
670 				continue;
671 			}
672 		}
673 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
674 		varflag = 0;
675 	}
676 	*arglist.lastp = NULL;
677 	*varlist.lastp = NULL;
678 	expredir(cmd->ncmd.redirect);
679 	argc = 0;
680 	for (sp = arglist.list ; sp ; sp = sp->next)
681 		argc++;
682 	argv = stalloc(sizeof (char *) * (argc + 1));
683 
684 	for (sp = arglist.list ; sp ; sp = sp->next) {
685 		TRACE(("evalcommand arg: %s\n", sp->text));
686 		*argv++ = sp->text;
687 	}
688 	*argv = NULL;
689 	lastarg = NULL;
690 	if (iflag && funcnest == 0 && argc > 0)
691 		lastarg = argv[-1];
692 	argv -= argc;
693 
694 	/* Print the command if xflag is set. */
695 	if (xflag) {
696 		char sep = 0;
697 		const char *p;
698 		out2str(ps4val());
699 		for (sp = varlist.list ; sp ; sp = sp->next) {
700 			if (sep != 0)
701 				out2c(' ');
702 			p = sp->text;
703 			while (*p != '=' && *p != '\0')
704 				out2c(*p++);
705 			if (*p != '\0') {
706 				out2c(*p++);
707 				out2qstr(p);
708 			}
709 			sep = ' ';
710 		}
711 		for (sp = arglist.list ; sp ; sp = sp->next) {
712 			if (sep != 0)
713 				out2c(' ');
714 			/* Disambiguate command looking like assignment. */
715 			if (sp == arglist.list &&
716 					strchr(sp->text, '=') != NULL &&
717 					strchr(sp->text, '\'') == NULL) {
718 				out2c('\'');
719 				out2str(sp->text);
720 				out2c('\'');
721 			} else
722 				out2qstr(sp->text);
723 			sep = ' ';
724 		}
725 		out2c('\n');
726 		flushout(&errout);
727 	}
728 
729 	/* Now locate the command. */
730 	if (argc == 0) {
731 		/* Variable assignment(s) without command */
732 		cmdentry.cmdtype = CMDBUILTIN;
733 		cmdentry.u.index = BLTINCMD;
734 		cmdentry.special = 0;
735 	} else {
736 		static const char PATH[] = "PATH=";
737 		int cmd_flags = 0, bltinonly = 0;
738 
739 		/*
740 		 * Modify the command lookup path, if a PATH= assignment
741 		 * is present
742 		 */
743 		for (sp = varlist.list ; sp ; sp = sp->next)
744 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
745 				path = sp->text + sizeof(PATH) - 1;
746 				/*
747 				 * On `PATH=... command`, we need to make
748 				 * sure that the command isn't using the
749 				 * non-updated hash table of the outer PATH
750 				 * setting and we need to make sure that
751 				 * the hash table isn't filled with items
752 				 * from the temporary setting.
753 				 *
754 				 * It would be better to forbit using and
755 				 * updating the table while this command
756 				 * runs, by the command finding mechanism
757 				 * is heavily integrated with hash handling,
758 				 * so we just delete the hash before and after
759 				 * the command runs. Partly deleting like
760 				 * changepatch() does doesn't seem worth the
761 				 * bookinging effort, since most such runs add
762 				 * directories in front of the new PATH.
763 				 */
764 				clearcmdentry(0);
765 				do_clearcmdentry = 1;
766 			}
767 
768 		for (;;) {
769 			if (bltinonly) {
770 				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
771 				if (cmdentry.u.index < 0) {
772 					cmdentry.u.index = BLTINCMD;
773 					argv--;
774 					argc++;
775 					break;
776 				}
777 			} else
778 				find_command(argv[0], &cmdentry, cmd_flags, path);
779 			/* implement the bltin and command builtins here */
780 			if (cmdentry.cmdtype != CMDBUILTIN)
781 				break;
782 			if (cmdentry.u.index == BLTINCMD) {
783 				if (argc == 1)
784 					break;
785 				argv++;
786 				argc--;
787 				bltinonly = 1;
788 			} else if (cmdentry.u.index == COMMANDCMD) {
789 				if (argc == 1)
790 					break;
791 				if (!strcmp(argv[1], "-p")) {
792 					if (argc == 2)
793 						break;
794 					if (argv[2][0] == '-') {
795 						if (strcmp(argv[2], "--"))
796 							break;
797 						if (argc == 3)
798 							break;
799 						argv += 3;
800 						argc -= 3;
801 					} else {
802 						argv += 2;
803 						argc -= 2;
804 					}
805 					path = _PATH_STDPATH;
806 					clearcmdentry(0);
807 					do_clearcmdentry = 1;
808 				} else if (!strcmp(argv[1], "--")) {
809 					if (argc == 2)
810 						break;
811 					argv += 2;
812 					argc -= 2;
813 				} else if (argv[1][0] == '-')
814 					break;
815 				else {
816 					argv++;
817 					argc--;
818 				}
819 				cmd_flags |= DO_NOFUNC;
820 				bltinonly = 0;
821 			} else
822 				break;
823 		}
824 		/*
825 		 * Special builtins lose their special properties when
826 		 * called via 'command'.
827 		 */
828 		if (cmd_flags & DO_NOFUNC)
829 			cmdentry.special = 0;
830 	}
831 
832 	/* Fork off a child process if necessary. */
833 	if (cmd->ncmd.backgnd
834 	 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
835 	    && ((flags & EV_EXIT) == 0 || have_traps()))
836 	 || ((flags & EV_BACKCMD) != 0
837 	    && (cmdentry.cmdtype != CMDBUILTIN
838 		 || cmdentry.u.index == CDCMD
839 		 || cmdentry.u.index == DOTCMD
840 		 || cmdentry.u.index == EVALCMD))) {
841 		jp = makejob(cmd, 1);
842 		mode = cmd->ncmd.backgnd;
843 		if (flags & EV_BACKCMD) {
844 			mode = FORK_NOJOB;
845 			if (pipe(pip) < 0)
846 				error("Pipe call failed: %s", strerror(errno));
847 		}
848 		if (forkshell(jp, cmd, mode) != 0)
849 			goto parent;	/* at end of routine */
850 		if (flags & EV_BACKCMD) {
851 			FORCEINTON;
852 			close(pip[0]);
853 			if (pip[1] != 1) {
854 				dup2(pip[1], 1);
855 				close(pip[1]);
856 			}
857 		}
858 		flags |= EV_EXIT;
859 	}
860 
861 	/* This is the child process if a fork occurred. */
862 	/* Execute the command. */
863 	if (cmdentry.cmdtype == CMDFUNCTION) {
864 #ifdef DEBUG
865 		trputs("Shell function:  ");  trargs(argv);
866 #endif
867 		saveparam = shellparam;
868 		shellparam.malloc = 0;
869 		shellparam.reset = 1;
870 		shellparam.nparam = argc - 1;
871 		shellparam.p = argv + 1;
872 		shellparam.optnext = NULL;
873 		INTOFF;
874 		savelocalvars = localvars;
875 		localvars = NULL;
876 		reffunc(cmdentry.u.func);
877 		savehandler = handler;
878 		if (setjmp(jmploc.loc)) {
879 			if (exception == EXSHELLPROC)
880 				freeparam(&saveparam);
881 			else {
882 				freeparam(&shellparam);
883 				shellparam = saveparam;
884 				if (exception == EXERROR || exception == EXEXEC)
885 					popredir();
886 			}
887 			unreffunc(cmdentry.u.func);
888 			poplocalvars();
889 			localvars = savelocalvars;
890 			funcnest--;
891 			handler = savehandler;
892 			longjmp(handler->loc, 1);
893 		}
894 		handler = &jmploc;
895 		funcnest++;
896 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
897 		INTON;
898 		for (sp = varlist.list ; sp ; sp = sp->next)
899 			mklocal(sp->text);
900 		exitstatus = oexitstatus;
901 		if (flags & EV_TESTED)
902 			evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
903 		else
904 			evaltree(getfuncnode(cmdentry.u.func), 0);
905 		INTOFF;
906 		unreffunc(cmdentry.u.func);
907 		poplocalvars();
908 		localvars = savelocalvars;
909 		freeparam(&shellparam);
910 		shellparam = saveparam;
911 		handler = savehandler;
912 		funcnest--;
913 		popredir();
914 		INTON;
915 		if (evalskip == SKIPFUNC) {
916 			evalskip = 0;
917 			skipcount = 0;
918 		}
919 		if (flags & EV_EXIT)
920 			exitshell(exitstatus);
921 	} else if (cmdentry.cmdtype == CMDBUILTIN) {
922 #ifdef DEBUG
923 		trputs("builtin command:  ");  trargs(argv);
924 #endif
925 		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
926 		if (flags == EV_BACKCMD) {
927 			memout.nleft = 0;
928 			memout.nextc = memout.buf;
929 			memout.bufsize = 64;
930 			mode |= REDIR_BACKQ;
931 			cmdentry.special = 0;
932 		}
933 		savecmdname = commandname;
934 		savetopfile = getcurrentfile();
935 		cmdenviron = varlist.list;
936 		e = -1;
937 		savehandler = handler;
938 		if (setjmp(jmploc.loc)) {
939 			e = exception;
940 			exitstatus = (e == EXINT)? SIGINT+128 : 2;
941 			goto cmddone;
942 		}
943 		handler = &jmploc;
944 		redirect(cmd->ncmd.redirect, mode);
945 		/*
946 		 * If there is no command word, redirection errors should
947 		 * not be fatal but assignment errors should.
948 		 */
949 		if (argc == 0 && !(flags & EV_BACKCMD))
950 			cmdentry.special = 1;
951 		if (cmdentry.special)
952 			listsetvar(cmdenviron);
953 		if (argc > 0)
954 			bltinsetlocale();
955 		commandname = argv[0];
956 		argptr = argv + 1;
957 		nextopt_optptr = NULL;		/* initialize nextopt */
958 		builtin_flags = flags;
959 		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
960 		flushall();
961 cmddone:
962 		if (argc > 0)
963 			bltinunsetlocale();
964 		cmdenviron = NULL;
965 		out1 = &output;
966 		out2 = &errout;
967 		freestdout();
968 		if (e != EXSHELLPROC) {
969 			commandname = savecmdname;
970 			if (flags & EV_EXIT) {
971 				exitshell(exitstatus);
972 			}
973 		}
974 		handler = savehandler;
975 		if (flags == EV_BACKCMD) {
976 			backcmd->buf = memout.buf;
977 			backcmd->nleft = memout.nextc - memout.buf;
978 			memout.buf = NULL;
979 		}
980 		if (cmdentry.u.index != EXECCMD &&
981 				(e == -1 || e == EXERROR || e == EXEXEC))
982 			popredir();
983 		if (e != -1) {
984 			if ((e != EXERROR && e != EXEXEC)
985 			    || cmdentry.special)
986 				exraise(e);
987 			popfilesupto(savetopfile);
988 			if (flags != EV_BACKCMD)
989 				FORCEINTON;
990 		}
991 	} else {
992 #ifdef DEBUG
993 		trputs("normal command:  ");  trargs(argv);
994 #endif
995 		redirect(cmd->ncmd.redirect, 0);
996 		for (sp = varlist.list ; sp ; sp = sp->next)
997 			setvareq(sp->text, VEXPORT|VSTACK);
998 		envp = environment();
999 		shellexec(argv, envp, path, cmdentry.u.index);
1000 		/*NOTREACHED*/
1001 	}
1002 	goto out;
1003 
1004 parent:	/* parent process gets here (if we forked) */
1005 	if (mode == FORK_FG) {	/* argument to fork */
1006 		INTOFF;
1007 		exitstatus = waitforjob(jp, &realstatus);
1008 		INTON;
1009 		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1010 			evalskip = SKIPBREAK;
1011 			skipcount = loopnest;
1012 		}
1013 	} else if (mode == FORK_NOJOB) {
1014 		backcmd->fd = pip[0];
1015 		close(pip[1]);
1016 		backcmd->jp = jp;
1017 	}
1018 
1019 out:
1020 	if (lastarg)
1021 		setvar("_", lastarg, 0);
1022 	if (do_clearcmdentry)
1023 		clearcmdentry(0);
1024 	popstackmark(&smark);
1025 }
1026 
1027 
1028 
1029 /*
1030  * Search for a command.  This is called before we fork so that the
1031  * location of the command will be available in the parent as well as
1032  * the child.  The check for "goodname" is an overly conservative
1033  * check that the name will not be subject to expansion.
1034  */
1035 
1036 static void
1037 prehash(union node *n)
1038 {
1039 	struct cmdentry entry;
1040 
1041 	if (n && n->type == NCMD && n->ncmd.args)
1042 		if (goodname(n->ncmd.args->narg.text))
1043 			find_command(n->ncmd.args->narg.text, &entry, 0,
1044 				     pathval());
1045 }
1046 
1047 
1048 
1049 /*
1050  * Builtin commands.  Builtin commands whose functions are closely
1051  * tied to evaluation are implemented here.
1052  */
1053 
1054 /*
1055  * No command given, a bltin command with no arguments, or a bltin command
1056  * with an invalid name.
1057  */
1058 
1059 int
1060 bltincmd(int argc, char **argv)
1061 {
1062 	if (argc > 1) {
1063 		out2fmt_flush("%s: not found\n", argv[1]);
1064 		return 127;
1065 	}
1066 	/*
1067 	 * Preserve exitstatus of a previous possible redirection
1068 	 * as POSIX mandates
1069 	 */
1070 	return exitstatus;
1071 }
1072 
1073 
1074 /*
1075  * Handle break and continue commands.  Break, continue, and return are
1076  * all handled by setting the evalskip flag.  The evaluation routines
1077  * above all check this flag, and if it is set they start skipping
1078  * commands rather than executing them.  The variable skipcount is
1079  * the number of loops to break/continue, or the number of function
1080  * levels to return.  (The latter is always 1.)  It should probably
1081  * be an error to break out of more loops than exist, but it isn't
1082  * in the standard shell so we don't make it one here.
1083  */
1084 
1085 int
1086 breakcmd(int argc, char **argv)
1087 {
1088 	int n = argc > 1 ? number(argv[1]) : 1;
1089 
1090 	if (n > loopnest)
1091 		n = loopnest;
1092 	if (n > 0) {
1093 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1094 		skipcount = n;
1095 	}
1096 	return 0;
1097 }
1098 
1099 /*
1100  * The `command' command.
1101  */
1102 int
1103 commandcmd(int argc, char **argv)
1104 {
1105 	const char *path;
1106 	int ch;
1107 	int cmd = -1;
1108 
1109 	path = bltinlookup("PATH", 1);
1110 
1111 	optind = optreset = 1;
1112 	opterr = 0;
1113 	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1114 		switch (ch) {
1115 		case 'p':
1116 			path = _PATH_STDPATH;
1117 			break;
1118 		case 'v':
1119 			cmd = TYPECMD_SMALLV;
1120 			break;
1121 		case 'V':
1122 			cmd = TYPECMD_BIGV;
1123 			break;
1124 		case '?':
1125 		default:
1126 			error("unknown option: -%c", optopt);
1127 		}
1128 	}
1129 	argc -= optind;
1130 	argv += optind;
1131 
1132 	if (cmd != -1) {
1133 		if (argc != 1)
1134 			error("wrong number of arguments");
1135 		return typecmd_impl(2, argv - 1, cmd, path);
1136 	}
1137 	if (argc != 0)
1138 		error("commandcmd bad call");
1139 
1140 	/*
1141 	 * Do nothing successfully if no command was specified;
1142 	 * ksh also does this.
1143 	 */
1144 	return 0;
1145 }
1146 
1147 
1148 /*
1149  * The return command.
1150  */
1151 
1152 int
1153 returncmd(int argc, char **argv)
1154 {
1155 	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1156 
1157 	if (funcnest) {
1158 		evalskip = SKIPFUNC;
1159 		skipcount = 1;
1160 	} else {
1161 		/* skip the rest of the file */
1162 		evalskip = SKIPFILE;
1163 		skipcount = 1;
1164 	}
1165 	return ret;
1166 }
1167 
1168 
1169 int
1170 falsecmd(int argc __unused, char **argv __unused)
1171 {
1172 	return 1;
1173 }
1174 
1175 
1176 int
1177 truecmd(int argc __unused, char **argv __unused)
1178 {
1179 	return 0;
1180 }
1181 
1182 
1183 int
1184 execcmd(int argc, char **argv)
1185 {
1186 	/*
1187 	 * Because we have historically not supported any options,
1188 	 * only treat "--" specially.
1189 	 */
1190 	if (argc > 1 && strcmp(argv[1], "--") == 0)
1191 		argc--, argv++;
1192 	if (argc > 1) {
1193 		struct strlist *sp;
1194 
1195 		iflag = 0;		/* exit on error */
1196 		mflag = 0;
1197 		optschanged();
1198 		for (sp = cmdenviron; sp ; sp = sp->next)
1199 			setvareq(sp->text, VEXPORT|VSTACK);
1200 		shellexec(argv + 1, environment(), pathval(), 0);
1201 
1202 	}
1203 	return 0;
1204 }
1205 
1206 
1207 int
1208 timescmd(int argc __unused, char **argv __unused)
1209 {
1210 	struct rusage ru;
1211 	long shumins, shsmins, chumins, chsmins;
1212 	double shusecs, shssecs, chusecs, chssecs;
1213 
1214 	if (getrusage(RUSAGE_SELF, &ru) < 0)
1215 		return 1;
1216 	shumins = ru.ru_utime.tv_sec / 60;
1217 	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1218 	shsmins = ru.ru_stime.tv_sec / 60;
1219 	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1220 	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1221 		return 1;
1222 	chumins = ru.ru_utime.tv_sec / 60;
1223 	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1224 	chsmins = ru.ru_stime.tv_sec / 60;
1225 	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1226 	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1227 	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1228 	return 0;
1229 }
1230