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