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