eval.c revision 172440
1189251Ssam/*-
2189251Ssam * Copyright (c) 1993
3189251Ssam *	The Regents of the University of California.  All rights reserved.
4189251Ssam *
5252726Srpaulo * This code is derived from software contributed to Berkeley by
6252726Srpaulo * Kenneth Almquist.
7189251Ssam *
8189251Ssam * Redistribution and use in source and binary forms, with or without
9189251Ssam * modification, are permitted provided that the following conditions
10189251Ssam * are met:
11189251Ssam * 1. Redistributions of source code must retain the above copyright
12189251Ssam *    notice, this list of conditions and the following disclaimer.
13189251Ssam * 2. Redistributions in binary form must reproduce the above copyright
14189251Ssam *    notice, this list of conditions and the following disclaimer in the
15189251Ssam *    documentation and/or other materials provided with the distribution.
16189251Ssam * 4. Neither the name of the University nor the names of its contributors
17189251Ssam *    may be used to endorse or promote products derived from this software
18189251Ssam *    without specific prior written permission.
19189251Ssam *
20189251Ssam * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21189251Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22189251Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23189251Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24189251Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25189251Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26189251Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27189251Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28189251Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29189251Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30189251Ssam * SUCH DAMAGE.
31189251Ssam */
32189251Ssam
33189251Ssam#ifndef lint
34189251Ssam#if 0
35189251Ssamstatic char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
36189251Ssam#endif
37189251Ssam#endif /* not lint */
38189251Ssam#include <sys/cdefs.h>
39189251Ssam__FBSDID("$FreeBSD: head/bin/sh/eval.c 172440 2007-10-04 16:14:48Z stefanf $");
40189251Ssam
41189251Ssam#include <paths.h>
42189251Ssam#include <signal.h>
43189251Ssam#include <stdlib.h>
44189251Ssam#include <unistd.h>
45189251Ssam#include <sys/resource.h>
46189251Ssam#include <sys/wait.h> /* For WIFSIGNALED(status) */
47189251Ssam#include <errno.h>
48189251Ssam
49189251Ssam/*
50189251Ssam * Evaluate a command.
51189251Ssam */
52189251Ssam
53189251Ssam#include "shell.h"
54189251Ssam#include "nodes.h"
55189251Ssam#include "syntax.h"
56189251Ssam#include "expand.h"
57189251Ssam#include "parser.h"
58189251Ssam#include "jobs.h"
59189251Ssam#include "eval.h"
60189251Ssam#include "builtins.h"
61189251Ssam#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
82MKINIT int evalskip;		/* set if we are skipping commands */
83STATIC int skipcount;		/* number of levels to skip */
84MKINIT int loopnest;		/* current loop nesting level */
85int funcnest;			/* depth of function calls */
86
87
88char *commandname;
89struct strlist *cmdenviron;
90int exitstatus;			/* exit status of last command */
91int oexitstatus;		/* saved exit status */
92
93
94STATIC void evalloop(union node *, int);
95STATIC void evalfor(union node *, int);
96STATIC void evalcase(union node *, int);
97STATIC void evalsubshell(union node *, int);
98STATIC void expredir(union node *);
99STATIC void evalpipe(union node *);
100STATIC void evalcommand(union node *, int, struct backcmd *);
101STATIC void prehash(union node *);
102
103
104/*
105 * Called to reset things after an exception.
106 */
107
108#ifdef mkinit
109INCLUDE "eval.h"
110
111RESET {
112	evalskip = 0;
113	loopnest = 0;
114	funcnest = 0;
115}
116
117SHELLPROC {
118	exitstatus = 0;
119}
120#endif
121
122
123
124/*
125 * The eval command.
126 */
127
128int
129evalcmd(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
160void
161evalstring(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
183void
184evaltree(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	}
275out:
276	if (pendingsigs)
277		dotrap();
278	if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
279		exitshell(exitstatus);
280}
281
282
283STATIC void
284evalloop(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) {
293skipping:	  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
319STATIC void
320evalfor(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--;
353out:
354	popstackmark(&smark);
355}
356
357
358
359STATIC void
360evalcase(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	exitstatus = 0;
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	}
382out:
383	popstackmark(&smark);
384}
385
386
387
388/*
389 * Kick off a subshell to evaluate a tree.
390 */
391
392STATIC void
393evalsubshell(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
419STATIC void
420expredir(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
457STATIC void
458evalpipe(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				close(prevfd);
479				error("Pipe call failed: %s", strerror(errno));
480			}
481		}
482		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
483			INTON;
484			if (prevfd > 0) {
485				dup2(prevfd, 0);
486				close(prevfd);
487			}
488			if (pip[1] >= 0) {
489				if (!(prevfd >= 0 && pip[0] == 0))
490					close(pip[0]);
491				if (pip[1] != 1) {
492					dup2(pip[1], 1);
493					close(pip[1]);
494				}
495			}
496			evaltree(lp->n, EV_EXIT);
497		}
498		if (prevfd >= 0)
499			close(prevfd);
500		prevfd = pip[0];
501		close(pip[1]);
502	}
503	INTON;
504	if (n->npipe.backgnd == 0) {
505		INTOFF;
506		exitstatus = waitforjob(jp, (int *)NULL);
507		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
508		INTON;
509	}
510}
511
512
513
514/*
515 * Execute a command inside back quotes.  If it's a builtin command, we
516 * want to save its output in a block obtained from malloc.  Otherwise
517 * we fork off a subprocess and get the output of the command via a pipe.
518 * Should be called with interrupts off.
519 */
520
521void
522evalbackcmd(union node *n, struct backcmd *result)
523{
524	int pip[2];
525	struct job *jp;
526	struct stackmark smark;		/* unnecessary */
527
528	setstackmark(&smark);
529	result->fd = -1;
530	result->buf = NULL;
531	result->nleft = 0;
532	result->jp = NULL;
533	if (n == NULL) {
534		exitstatus = 0;
535		goto out;
536	}
537	if (n->type == NCMD) {
538		exitstatus = oexitstatus;
539		evalcommand(n, EV_BACKCMD, result);
540	} else {
541		exitstatus = 0;
542		if (pipe(pip) < 0)
543			error("Pipe call failed: %s", strerror(errno));
544		jp = makejob(n, 1);
545		if (forkshell(jp, n, FORK_NOJOB) == 0) {
546			FORCEINTON;
547			close(pip[0]);
548			if (pip[1] != 1) {
549				dup2(pip[1], 1);
550				close(pip[1]);
551			}
552			evaltree(n, EV_EXIT);
553		}
554		close(pip[1]);
555		result->fd = pip[0];
556		result->jp = jp;
557	}
558out:
559	popstackmark(&smark);
560	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
561		result->fd, result->buf, result->nleft, result->jp));
562}
563
564
565
566/*
567 * Execute a simple command.
568 */
569
570STATIC void
571evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
572{
573	struct stackmark smark;
574	union node *argp;
575	struct arglist arglist;
576	struct arglist varlist;
577	char **argv;
578	int argc;
579	char **envp;
580	int varflag;
581	struct strlist *sp;
582	int mode;
583	int pip[2];
584	struct cmdentry cmdentry;
585	struct job *jp;
586	struct jmploc jmploc;
587	struct jmploc *volatile savehandler;
588	char *volatile savecmdname;
589	volatile struct shparam saveparam;
590	struct localvar *volatile savelocalvars;
591	volatile int e;
592	char *lastarg;
593	int realstatus;
594	int do_clearcmdentry;
595#if __GNUC__
596	/* Avoid longjmp clobbering */
597	(void) &argv;
598	(void) &argc;
599	(void) &lastarg;
600	(void) &flags;
601	(void) &do_clearcmdentry;
602#endif
603
604	/* First expand the arguments. */
605	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
606	setstackmark(&smark);
607	arglist.lastp = &arglist.list;
608	varlist.lastp = &varlist.list;
609	varflag = 1;
610	do_clearcmdentry = 0;
611	oexitstatus = exitstatus;
612	exitstatus = 0;
613	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
614		char *p = argp->narg.text;
615		if (varflag && is_name(*p)) {
616			do {
617				p++;
618			} while (is_in_name(*p));
619			if (*p == '=') {
620				expandarg(argp, &varlist, EXP_VARTILDE);
621				continue;
622			}
623		}
624		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
625		varflag = 0;
626	}
627	*arglist.lastp = NULL;
628	*varlist.lastp = NULL;
629	expredir(cmd->ncmd.redirect);
630	argc = 0;
631	for (sp = arglist.list ; sp ; sp = sp->next)
632		argc++;
633	argv = stalloc(sizeof (char *) * (argc + 1));
634
635	for (sp = arglist.list ; sp ; sp = sp->next) {
636		TRACE(("evalcommand arg: %s\n", sp->text));
637		*argv++ = sp->text;
638	}
639	*argv = NULL;
640	lastarg = NULL;
641	if (iflag && funcnest == 0 && argc > 0)
642		lastarg = argv[-1];
643	argv -= argc;
644
645	/* Print the command if xflag is set. */
646	if (xflag) {
647		char sep = 0;
648		out2str(ps4val());
649		for (sp = varlist.list ; sp ; sp = sp->next) {
650			if (sep != 0)
651				outc(' ', &errout);
652			out2str(sp->text);
653			sep = ' ';
654		}
655		for (sp = arglist.list ; sp ; sp = sp->next) {
656			if (sep != 0)
657				outc(' ', &errout);
658			out2str(sp->text);
659			sep = ' ';
660		}
661		outc('\n', &errout);
662		flushout(&errout);
663	}
664
665	/* Now locate the command. */
666	if (argc == 0) {
667		/* Variable assignment(s) without command */
668		cmdentry.cmdtype = CMDBUILTIN;
669		cmdentry.u.index = BLTINCMD;
670		cmdentry.special = 1;
671	} else {
672		static const char PATH[] = "PATH=";
673		char *path = pathval();
674
675		/*
676		 * Modify the command lookup path, if a PATH= assignment
677		 * is present
678		 */
679		for (sp = varlist.list ; sp ; sp = sp->next)
680			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
681				path = sp->text + sizeof(PATH) - 1;
682				/*
683				 * On `PATH=... command`, we need to make
684				 * sure that the command isn't using the
685				 * non-updated hash table of the outer PATH
686				 * setting and we need to make sure that
687				 * the hash table isn't filled with items
688				 * from the temporary setting.
689				 *
690				 * It would be better to forbit using and
691				 * updating the table while this command
692				 * runs, by the command finding mechanism
693				 * is heavily integrated with hash handling,
694				 * so we just delete the hash before and after
695				 * the command runs. Partly deleting like
696				 * changepatch() does doesn't seem worth the
697				 * bookinging effort, since most such runs add
698				 * directories in front of the new PATH.
699				 */
700				clearcmdentry(0);
701				do_clearcmdentry = 1;
702			}
703
704		find_command(argv[0], &cmdentry, 1, path);
705		if (cmdentry.cmdtype == CMDUNKNOWN) {	/* command not found */
706			exitstatus = 127;
707			flushout(&errout);
708			return;
709		}
710		/* implement the bltin builtin here */
711		if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
712			for (;;) {
713				argv++;
714				if (--argc == 0)
715					break;
716				if ((cmdentry.u.index = find_builtin(*argv,
717				    &cmdentry.special)) < 0) {
718					outfmt(&errout, "%s: not found\n", *argv);
719					exitstatus = 127;
720					flushout(&errout);
721					return;
722				}
723				if (cmdentry.u.index != BLTINCMD)
724					break;
725			}
726		}
727	}
728
729	/* Fork off a child process if necessary. */
730	if (cmd->ncmd.backgnd
731	 || (cmdentry.cmdtype == CMDNORMAL
732	    && ((flags & EV_EXIT) == 0 || Tflag))
733	 || ((flags & EV_BACKCMD) != 0
734	    && (cmdentry.cmdtype != CMDBUILTIN
735		 || cmdentry.u.index == CDCMD
736		 || cmdentry.u.index == DOTCMD
737		 || cmdentry.u.index == EVALCMD))
738	 || (cmdentry.cmdtype == CMDBUILTIN &&
739	    cmdentry.u.index == COMMANDCMD)) {
740		jp = makejob(cmd, 1);
741		mode = cmd->ncmd.backgnd;
742		if (flags & EV_BACKCMD) {
743			mode = FORK_NOJOB;
744			if (pipe(pip) < 0)
745				error("Pipe call failed: %s", strerror(errno));
746		}
747		if (forkshell(jp, cmd, mode) != 0)
748			goto parent;	/* at end of routine */
749		if (flags & EV_BACKCMD) {
750			FORCEINTON;
751			close(pip[0]);
752			if (pip[1] != 1) {
753				dup2(pip[1], 1);
754				close(pip[1]);
755			}
756		}
757		flags |= EV_EXIT;
758	}
759
760	/* This is the child process if a fork occurred. */
761	/* Execute the command. */
762	if (cmdentry.cmdtype == CMDFUNCTION) {
763#ifdef DEBUG
764		trputs("Shell function:  ");  trargs(argv);
765#endif
766		redirect(cmd->ncmd.redirect, REDIR_PUSH);
767		saveparam = shellparam;
768		shellparam.malloc = 0;
769		shellparam.reset = 1;
770		shellparam.nparam = argc - 1;
771		shellparam.p = argv + 1;
772		shellparam.optnext = NULL;
773		INTOFF;
774		savelocalvars = localvars;
775		localvars = NULL;
776		INTON;
777		if (setjmp(jmploc.loc)) {
778			if (exception == EXSHELLPROC)
779				freeparam((struct shparam *)&saveparam);
780			else {
781				freeparam(&shellparam);
782				shellparam = saveparam;
783			}
784			poplocalvars();
785			localvars = savelocalvars;
786			handler = savehandler;
787			longjmp(handler->loc, 1);
788		}
789		savehandler = handler;
790		handler = &jmploc;
791		for (sp = varlist.list ; sp ; sp = sp->next)
792			mklocal(sp->text);
793		funcnest++;
794		if (flags & EV_TESTED)
795			evaltree(cmdentry.u.func, EV_TESTED);
796		else
797			evaltree(cmdentry.u.func, 0);
798		funcnest--;
799		INTOFF;
800		poplocalvars();
801		localvars = savelocalvars;
802		freeparam(&shellparam);
803		shellparam = saveparam;
804		handler = savehandler;
805		popredir();
806		INTON;
807		if (evalskip == SKIPFUNC) {
808			evalskip = 0;
809			skipcount = 0;
810		}
811		if (flags & EV_EXIT)
812			exitshell(exitstatus);
813	} else if (cmdentry.cmdtype == CMDBUILTIN) {
814#ifdef DEBUG
815		trputs("builtin command:  ");  trargs(argv);
816#endif
817		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
818		if (flags == EV_BACKCMD) {
819			memout.nleft = 0;
820			memout.nextc = memout.buf;
821			memout.bufsize = 64;
822			mode |= REDIR_BACKQ;
823		}
824		savecmdname = commandname;
825		cmdenviron = varlist.list;
826		e = -1;
827		if (setjmp(jmploc.loc)) {
828			e = exception;
829			exitstatus = (e == EXINT)? SIGINT+128 : 2;
830			goto cmddone;
831		}
832		savehandler = handler;
833		handler = &jmploc;
834		redirect(cmd->ncmd.redirect, mode);
835		if (cmdentry.special)
836			listsetvar(cmdenviron);
837		commandname = argv[0];
838		argptr = argv + 1;
839		optptr = NULL;			/* initialize nextopt */
840		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
841		flushall();
842cmddone:
843		cmdenviron = NULL;
844		out1 = &output;
845		out2 = &errout;
846		freestdout();
847		if (e != EXSHELLPROC) {
848			commandname = savecmdname;
849			if (flags & EV_EXIT) {
850				exitshell(exitstatus);
851			}
852		}
853		handler = savehandler;
854		if (e != -1) {
855			if ((e != EXERROR && e != EXEXEC)
856			    || cmdentry.special)
857				exraise(e);
858			FORCEINTON;
859		}
860		if (cmdentry.u.index != EXECCMD)
861			popredir();
862		if (flags == EV_BACKCMD) {
863			backcmd->buf = memout.buf;
864			backcmd->nleft = memout.nextc - memout.buf;
865			memout.buf = NULL;
866		}
867	} else {
868#ifdef DEBUG
869		trputs("normal command:  ");  trargs(argv);
870#endif
871		clearredir();
872		redirect(cmd->ncmd.redirect, 0);
873		for (sp = varlist.list ; sp ; sp = sp->next)
874			setvareq(sp->text, VEXPORT|VSTACK);
875		envp = environment();
876		shellexec(argv, envp, pathval(), cmdentry.u.index);
877		/*NOTREACHED*/
878	}
879	goto out;
880
881parent:	/* parent process gets here (if we forked) */
882	if (mode == 0) {	/* argument to fork */
883		INTOFF;
884		exitstatus = waitforjob(jp, &realstatus);
885		INTON;
886		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
887			evalskip = SKIPBREAK;
888			skipcount = loopnest;
889		}
890	} else if (mode == 2) {
891		backcmd->fd = pip[0];
892		close(pip[1]);
893		backcmd->jp = jp;
894	}
895
896out:
897	if (lastarg)
898		setvar("_", lastarg, 0);
899	if (do_clearcmdentry)
900		clearcmdentry(0);
901	popstackmark(&smark);
902}
903
904
905
906/*
907 * Search for a command.  This is called before we fork so that the
908 * location of the command will be available in the parent as well as
909 * the child.  The check for "goodname" is an overly conservative
910 * check that the name will not be subject to expansion.
911 */
912
913STATIC void
914prehash(union node *n)
915{
916	struct cmdentry entry;
917
918	if (n && n->type == NCMD && n->ncmd.args)
919		if (goodname(n->ncmd.args->narg.text))
920			find_command(n->ncmd.args->narg.text, &entry, 0,
921				     pathval());
922}
923
924
925
926/*
927 * Builtin commands.  Builtin commands whose functions are closely
928 * tied to evaluation are implemented here.
929 */
930
931/*
932 * No command given, or a bltin command with no arguments.
933 */
934
935int
936bltincmd(int argc __unused, char **argv __unused)
937{
938	/*
939	 * Preserve exitstatus of a previous possible redirection
940	 * as POSIX mandates
941	 */
942	return exitstatus;
943}
944
945
946/*
947 * Handle break and continue commands.  Break, continue, and return are
948 * all handled by setting the evalskip flag.  The evaluation routines
949 * above all check this flag, and if it is set they start skipping
950 * commands rather than executing them.  The variable skipcount is
951 * the number of loops to break/continue, or the number of function
952 * levels to return.  (The latter is always 1.)  It should probably
953 * be an error to break out of more loops than exist, but it isn't
954 * in the standard shell so we don't make it one here.
955 */
956
957int
958breakcmd(int argc, char **argv)
959{
960	int n = argc > 1 ? number(argv[1]) : 1;
961
962	if (n > loopnest)
963		n = loopnest;
964	if (n > 0) {
965		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
966		skipcount = n;
967	}
968	return 0;
969}
970
971/*
972 * The `command' command.
973 */
974int
975commandcmd(int argc, char **argv)
976{
977	static char stdpath[] = _PATH_STDPATH;
978	struct jmploc loc, *old;
979	struct strlist *sp;
980	char *path;
981	int ch;
982	int cmd = -1;
983
984	for (sp = cmdenviron; sp ; sp = sp->next)
985		setvareq(sp->text, VEXPORT|VSTACK);
986	path = pathval();
987
988	optind = optreset = 1;
989	opterr = 0;
990	while ((ch = getopt(argc, argv, "pvV")) != -1) {
991		switch (ch) {
992		case 'p':
993			path = stdpath;
994			break;
995		case 'v':
996			cmd = TYPECMD_SMALLV;
997			break;
998		case 'V':
999			cmd = TYPECMD_BIGV;
1000			break;
1001		case '?':
1002		default:
1003			error("unknown option: -%c", optopt);
1004		}
1005	}
1006	argc -= optind;
1007	argv += optind;
1008
1009	if (cmd != -1) {
1010		if (argc != 1)
1011			error("wrong number of arguments");
1012		return typecmd_impl(2, argv - 1, cmd);
1013	}
1014	if (argc != 0) {
1015		old = handler;
1016		handler = &loc;
1017		if (setjmp(handler->loc) == 0)
1018			shellexec(argv, environment(), path, 0);
1019		handler = old;
1020		if (exception == EXEXEC)
1021			exit(exerrno);
1022		exraise(exception);
1023	}
1024
1025	/*
1026	 * Do nothing successfully if no command was specified;
1027	 * ksh also does this.
1028	 */
1029	exit(0);
1030}
1031
1032
1033/*
1034 * The return command.
1035 */
1036
1037int
1038returncmd(int argc, char **argv)
1039{
1040	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1041
1042	if (funcnest) {
1043		evalskip = SKIPFUNC;
1044		skipcount = 1;
1045	} else {
1046		/* skip the rest of the file */
1047		evalskip = SKIPFILE;
1048		skipcount = 1;
1049	}
1050	return ret;
1051}
1052
1053
1054int
1055falsecmd(int argc __unused, char **argv __unused)
1056{
1057	return 1;
1058}
1059
1060
1061int
1062truecmd(int argc __unused, char **argv __unused)
1063{
1064	return 0;
1065}
1066
1067
1068int
1069execcmd(int argc, char **argv)
1070{
1071	if (argc > 1) {
1072		struct strlist *sp;
1073
1074		iflag = 0;		/* exit on error */
1075		mflag = 0;
1076		optschanged();
1077		for (sp = cmdenviron; sp ; sp = sp->next)
1078			setvareq(sp->text, VEXPORT|VSTACK);
1079		shellexec(argv + 1, environment(), pathval(), 0);
1080
1081	}
1082	return 0;
1083}
1084
1085
1086int
1087timescmd(int argc __unused, char **argv __unused)
1088{
1089	struct rusage ru;
1090	long shumins, shsmins, chumins, chsmins;
1091	double shusecs, shssecs, chusecs, chssecs;
1092
1093	if (getrusage(RUSAGE_SELF, &ru) < 0)
1094		return 1;
1095	shumins = ru.ru_utime.tv_sec / 60;
1096	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1097	shsmins = ru.ru_stime.tv_sec / 60;
1098	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1099	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1100		return 1;
1101	chumins = ru.ru_utime.tv_sec / 60;
1102	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1103	chsmins = ru.ru_stime.tv_sec / 60;
1104	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1105	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1106	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1107	return 0;
1108}
1109