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