eval.c revision 222907
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/eval.c 222907 2011-06-09 23:12:23Z jilles $");
401556Srgrimes
41100437Stjr#include <paths.h>
4217987Speter#include <signal.h>
43102576Skeramida#include <stdlib.h>
4417987Speter#include <unistd.h>
45153091Sstefanf#include <sys/resource.h>
4645266Scracauer#include <sys/wait.h> /* For WIFSIGNALED(status) */
4753891Scracauer#include <errno.h>
4817987Speter
491556Srgrimes/*
501556Srgrimes * Evaluate a command.
511556Srgrimes */
521556Srgrimes
531556Srgrimes#include "shell.h"
541556Srgrimes#include "nodes.h"
551556Srgrimes#include "syntax.h"
561556Srgrimes#include "expand.h"
571556Srgrimes#include "parser.h"
581556Srgrimes#include "jobs.h"
591556Srgrimes#include "eval.h"
601556Srgrimes#include "builtins.h"
611556Srgrimes#include "options.h"
621556Srgrimes#include "exec.h"
631556Srgrimes#include "redir.h"
641556Srgrimes#include "input.h"
651556Srgrimes#include "output.h"
661556Srgrimes#include "trap.h"
671556Srgrimes#include "var.h"
681556Srgrimes#include "memalloc.h"
691556Srgrimes#include "error.h"
7017987Speter#include "show.h"
711556Srgrimes#include "mystring.h"
7217987Speter#ifndef NO_HISTORY
731556Srgrimes#include "myhistedit.h"
7417987Speter#endif
751556Srgrimes
761556Srgrimes
77201053Sjillesint evalskip;			/* set if we are skipping commands */
78213760Sobrienstatic int skipcount;		/* number of levels to skip */
791556SrgrimesMKINIT int loopnest;		/* current loop nesting level */
801556Srgrimesint funcnest;			/* depth of function calls */
81213760Sobrienstatic int builtin_flags;	/* evalcommand flags for builtins */
821556Srgrimes
831556Srgrimes
841556Srgrimeschar *commandname;
851556Srgrimesstruct strlist *cmdenviron;
861556Srgrimesint exitstatus;			/* exit status of last command */
8717987Speterint oexitstatus;		/* saved exit status */
881556Srgrimes
891556Srgrimes
90213811Sobrienstatic void evalloop(union node *, int);
91213811Sobrienstatic void evalfor(union node *, int);
92213811Sobrienstatic void evalcase(union node *, int);
93213811Sobrienstatic void evalsubshell(union node *, int);
94213811Sobrienstatic void evalredir(union node *, int);
95213811Sobrienstatic void expredir(union node *);
96213811Sobrienstatic void evalpipe(union node *);
97216778Sjillesstatic int is_valid_fast_cmdsubst(union node *n);
98213811Sobrienstatic void evalcommand(union node *, int, struct backcmd *);
99213811Sobrienstatic void prehash(union node *);
1001556Srgrimes
1011556Srgrimes
1021556Srgrimes/*
1031556Srgrimes * Called to reset things after an exception.
1041556Srgrimes */
1051556Srgrimes
1061556Srgrimes#ifdef mkinit
1071556SrgrimesINCLUDE "eval.h"
1081556Srgrimes
1091556SrgrimesRESET {
1101556Srgrimes	evalskip = 0;
1111556Srgrimes	loopnest = 0;
1121556Srgrimes	funcnest = 0;
1131556Srgrimes}
1141556Srgrimes#endif
1151556Srgrimes
1161556Srgrimes
1171556Srgrimes
1181556Srgrimes/*
11946684Skris * The eval command.
1201556Srgrimes */
1211556Srgrimes
12217987Speterint
12390111Simpevalcmd(int argc, char **argv)
1241556Srgrimes{
1251556Srgrimes        char *p;
1261556Srgrimes        char *concat;
1271556Srgrimes        char **ap;
1281556Srgrimes
1291556Srgrimes        if (argc > 1) {
1301556Srgrimes                p = argv[1];
1311556Srgrimes                if (argc > 2) {
1321556Srgrimes                        STARTSTACKSTR(concat);
1331556Srgrimes                        ap = argv + 2;
1341556Srgrimes                        for (;;) {
135215783Sjilles                                STPUTS(p, concat);
1361556Srgrimes                                if ((p = *ap++) == NULL)
1371556Srgrimes                                        break;
1381556Srgrimes                                STPUTC(' ', concat);
1391556Srgrimes                        }
1401556Srgrimes                        STPUTC('\0', concat);
1411556Srgrimes                        p = grabstackstr(concat);
1421556Srgrimes                }
143193169Sstefanf                evalstring(p, builtin_flags & EV_TESTED);
144210829Sjilles        } else
145210829Sjilles                exitstatus = 0;
1461556Srgrimes        return exitstatus;
1471556Srgrimes}
1481556Srgrimes
1491556Srgrimes
1501556Srgrimes/*
1511556Srgrimes * Execute a command or commands contained in a string.
1521556Srgrimes */
1531556Srgrimes
1541556Srgrimesvoid
155193169Sstefanfevalstring(char *s, int flags)
15690111Simp{
1571556Srgrimes	union node *n;
1581556Srgrimes	struct stackmark smark;
159194128Sjilles	int flags_exit;
160210829Sjilles	int any;
1611556Srgrimes
162194128Sjilles	flags_exit = flags & EV_EXIT;
163194128Sjilles	flags &= ~EV_EXIT;
164210829Sjilles	any = 0;
1651556Srgrimes	setstackmark(&smark);
1661556Srgrimes	setinputstring(s, 1);
1671556Srgrimes	while ((n = parsecmd(0)) != NEOF) {
168222676Sjilles		if (n != NULL && !nflag) {
169194128Sjilles			if (flags_exit && preadateof())
170194128Sjilles				evaltree(n, flags | EV_EXIT);
171194128Sjilles			else
172194128Sjilles				evaltree(n, flags);
173210829Sjilles			any = 1;
174194128Sjilles		}
1751556Srgrimes		popstackmark(&smark);
1761556Srgrimes	}
1771556Srgrimes	popfile();
1781556Srgrimes	popstackmark(&smark);
179210829Sjilles	if (!any)
180210829Sjilles		exitstatus = 0;
181194128Sjilles	if (flags_exit)
182220978Sjilles		exraise(EXEXIT);
1831556Srgrimes}
1841556Srgrimes
1851556Srgrimes
1861556Srgrimes/*
1871556Srgrimes * Evaluate a parse tree.  The value is left in the global variable
1881556Srgrimes * exitstatus.
1891556Srgrimes */
1901556Srgrimes
1911556Srgrimesvoid
19290111Simpevaltree(union node *n, int flags)
19317987Speter{
194149927Sstefanf	int do_etest;
195214599Sjilles	union node *next;
196149927Sstefanf
197149927Sstefanf	do_etest = 0;
1981556Srgrimes	if (n == NULL) {
1991556Srgrimes		TRACE(("evaltree(NULL) called\n"));
2001556Srgrimes		exitstatus = 0;
2011556Srgrimes		goto out;
2021556Srgrimes	}
203214599Sjilles	do {
204214600Sjilles		next = NULL;
20517987Speter#ifndef NO_HISTORY
206214600Sjilles		displayhist = 1;	/* show history substitutions done with fc */
20717987Speter#endif
208214600Sjilles		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
209214600Sjilles		switch (n->type) {
210214600Sjilles		case NSEMI:
211214600Sjilles			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
212214600Sjilles			if (evalskip)
213214600Sjilles				goto out;
214214600Sjilles			next = n->nbinary.ch2;
215214600Sjilles			break;
216214600Sjilles		case NAND:
217214600Sjilles			evaltree(n->nbinary.ch1, EV_TESTED);
218214600Sjilles			if (evalskip || exitstatus != 0) {
219214600Sjilles				goto out;
220214600Sjilles			}
221214600Sjilles			next = n->nbinary.ch2;
222214600Sjilles			break;
223214600Sjilles		case NOR:
224214600Sjilles			evaltree(n->nbinary.ch1, EV_TESTED);
225214600Sjilles			if (evalskip || exitstatus == 0)
226214600Sjilles				goto out;
227214600Sjilles			next = n->nbinary.ch2;
228214600Sjilles			break;
229214600Sjilles		case NREDIR:
230214600Sjilles			evalredir(n, flags);
231214600Sjilles			break;
232214600Sjilles		case NSUBSHELL:
233214600Sjilles			evalsubshell(n, flags);
234214600Sjilles			do_etest = !(flags & EV_TESTED);
235214600Sjilles			break;
236214600Sjilles		case NBACKGND:
237214600Sjilles			evalsubshell(n, flags);
238214600Sjilles			break;
239214600Sjilles		case NIF: {
240214600Sjilles			evaltree(n->nif.test, EV_TESTED);
241214600Sjilles			if (evalskip)
242214600Sjilles				goto out;
243214600Sjilles			if (exitstatus == 0)
244214600Sjilles				next = n->nif.ifpart;
245214600Sjilles			else if (n->nif.elsepart)
246214600Sjilles				next = n->nif.elsepart;
247214600Sjilles			else
248214600Sjilles				exitstatus = 0;
249214600Sjilles			break;
25018754Ssteve		}
251214600Sjilles		case NWHILE:
252214600Sjilles		case NUNTIL:
253214600Sjilles			evalloop(n, flags & ~EV_EXIT);
254214600Sjilles			break;
255214600Sjilles		case NFOR:
256214600Sjilles			evalfor(n, flags & ~EV_EXIT);
257214600Sjilles			break;
258214600Sjilles		case NCASE:
259214600Sjilles			evalcase(n, flags);
260214600Sjilles			break;
261214600Sjilles		case NDEFUN:
262214600Sjilles			defun(n->narg.text, n->narg.next);
26320425Ssteve			exitstatus = 0;
264214600Sjilles			break;
265214600Sjilles		case NNOT:
266214600Sjilles			evaltree(n->nnot.com, EV_TESTED);
267214600Sjilles			exitstatus = !exitstatus;
268214600Sjilles			break;
2691556Srgrimes
270214600Sjilles		case NPIPE:
271214600Sjilles			evalpipe(n);
272214600Sjilles			do_etest = !(flags & EV_TESTED);
273214600Sjilles			break;
274214600Sjilles		case NCMD:
275214600Sjilles			evalcommand(n, flags, (struct backcmd *)NULL);
276214600Sjilles			do_etest = !(flags & EV_TESTED);
277214600Sjilles			break;
278214600Sjilles		default:
279214600Sjilles			out1fmt("Node type = %d\n", n->type);
280214600Sjilles			flushout(&output);
281214600Sjilles			break;
282214600Sjilles		}
283214600Sjilles		n = next;
284214599Sjilles	} while (n != NULL);
2851556Srgrimesout:
2861556Srgrimes	if (pendingsigs)
2871556Srgrimes		dotrap();
288220978Sjilles	if (eflag && exitstatus != 0 && do_etest)
2891556Srgrimes		exitshell(exitstatus);
290220978Sjilles	if (flags & EV_EXIT)
291220978Sjilles		exraise(EXEXIT);
2921556Srgrimes}
2931556Srgrimes
2941556Srgrimes
295213811Sobrienstatic void
296149933Sstefanfevalloop(union node *n, int flags)
29717987Speter{
2981556Srgrimes	int status;
2991556Srgrimes
3001556Srgrimes	loopnest++;
3011556Srgrimes	status = 0;
3021556Srgrimes	for (;;) {
3031556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
3041556Srgrimes		if (evalskip) {
3051556Srgrimesskipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
3061556Srgrimes				evalskip = 0;
3071556Srgrimes				continue;
3081556Srgrimes			}
3091556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3101556Srgrimes				evalskip = 0;
311212475Sjilles			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
312212475Sjilles				status = exitstatus;
3131556Srgrimes			break;
3141556Srgrimes		}
3151556Srgrimes		if (n->type == NWHILE) {
3161556Srgrimes			if (exitstatus != 0)
3171556Srgrimes				break;
3181556Srgrimes		} else {
3191556Srgrimes			if (exitstatus == 0)
3201556Srgrimes				break;
3211556Srgrimes		}
322149933Sstefanf		evaltree(n->nbinary.ch2, flags);
3231556Srgrimes		status = exitstatus;
3241556Srgrimes		if (evalskip)
3251556Srgrimes			goto skipping;
3261556Srgrimes	}
3271556Srgrimes	loopnest--;
3281556Srgrimes	exitstatus = status;
3291556Srgrimes}
3301556Srgrimes
3311556Srgrimes
3321556Srgrimes
333213811Sobrienstatic void
334149933Sstefanfevalfor(union node *n, int flags)
33517987Speter{
3361556Srgrimes	struct arglist arglist;
3371556Srgrimes	union node *argp;
3381556Srgrimes	struct strlist *sp;
3391556Srgrimes	struct stackmark smark;
3401556Srgrimes
3411556Srgrimes	setstackmark(&smark);
3421556Srgrimes	arglist.lastp = &arglist.list;
3431556Srgrimes	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
34417987Speter		oexitstatus = exitstatus;
3451556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3461556Srgrimes		if (evalskip)
3471556Srgrimes			goto out;
3481556Srgrimes	}
3491556Srgrimes	*arglist.lastp = NULL;
3501556Srgrimes
3511556Srgrimes	exitstatus = 0;
3521556Srgrimes	loopnest++;
3531556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
3541556Srgrimes		setvar(n->nfor.var, sp->text, 0);
355149933Sstefanf		evaltree(n->nfor.body, flags);
3561556Srgrimes		if (evalskip) {
3571556Srgrimes			if (evalskip == SKIPCONT && --skipcount <= 0) {
3581556Srgrimes				evalskip = 0;
3591556Srgrimes				continue;
3601556Srgrimes			}
3611556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3621556Srgrimes				evalskip = 0;
3631556Srgrimes			break;
3641556Srgrimes		}
3651556Srgrimes	}
3661556Srgrimes	loopnest--;
3671556Srgrimesout:
3681556Srgrimes	popstackmark(&smark);
3691556Srgrimes}
3701556Srgrimes
3711556Srgrimes
3721556Srgrimes
373213811Sobrienstatic void
37490111Simpevalcase(union node *n, int flags)
37517987Speter{
3761556Srgrimes	union node *cp;
3771556Srgrimes	union node *patp;
3781556Srgrimes	struct arglist arglist;
3791556Srgrimes	struct stackmark smark;
3801556Srgrimes
3811556Srgrimes	setstackmark(&smark);
3821556Srgrimes	arglist.lastp = &arglist.list;
38317987Speter	oexitstatus = exitstatus;
384172440Sstefanf	exitstatus = 0;
3851556Srgrimes	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
3861556Srgrimes	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
3871556Srgrimes		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
3881556Srgrimes			if (casematch(patp, arglist.list->text)) {
3891556Srgrimes				if (evalskip == 0) {
3901556Srgrimes					evaltree(cp->nclist.body, flags);
3911556Srgrimes				}
3921556Srgrimes				goto out;
3931556Srgrimes			}
3941556Srgrimes		}
3951556Srgrimes	}
3961556Srgrimesout:
3971556Srgrimes	popstackmark(&smark);
3981556Srgrimes}
3991556Srgrimes
4001556Srgrimes
4011556Srgrimes
4021556Srgrimes/*
4031556Srgrimes * Kick off a subshell to evaluate a tree.
4041556Srgrimes */
4051556Srgrimes
406213811Sobrienstatic void
40790111Simpevalsubshell(union node *n, int flags)
40817987Speter{
4091556Srgrimes	struct job *jp;
4101556Srgrimes	int backgnd = (n->type == NBACKGND);
4111556Srgrimes
412222716Sjilles	oexitstatus = exitstatus;
4131556Srgrimes	expredir(n->nredir.redirect);
414194774Sjilles	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
415194774Sjilles			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
4161556Srgrimes		if (backgnd)
4171556Srgrimes			flags &=~ EV_TESTED;
4181556Srgrimes		redirect(n->nredir.redirect, 0);
4191556Srgrimes		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
420201053Sjilles	} else if (! backgnd) {
4211556Srgrimes		INTOFF;
42245916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
4231556Srgrimes		INTON;
424221027Sjilles	} else
425221027Sjilles		exitstatus = 0;
4261556Srgrimes}
4271556Srgrimes
4281556Srgrimes
429205154Sjilles/*
430205154Sjilles * Evaluate a redirected compound command.
431205154Sjilles */
4321556Srgrimes
433213811Sobrienstatic void
434205154Sjillesevalredir(union node *n, int flags)
435205154Sjilles{
436205154Sjilles	struct jmploc jmploc;
437205154Sjilles	struct jmploc *savehandler;
438205154Sjilles	volatile int in_redirect = 1;
439205154Sjilles
440222716Sjilles	oexitstatus = exitstatus;
441205154Sjilles	expredir(n->nredir.redirect);
442205154Sjilles	savehandler = handler;
443205154Sjilles	if (setjmp(jmploc.loc)) {
444205154Sjilles		int e;
445205154Sjilles
446205154Sjilles		handler = savehandler;
447205154Sjilles		e = exception;
448220978Sjilles		popredir();
449205154Sjilles		if (e == EXERROR || e == EXEXEC) {
450205154Sjilles			if (in_redirect) {
451205154Sjilles				exitstatus = 2;
452205154Sjilles				return;
453205154Sjilles			}
454205154Sjilles		}
455205154Sjilles		longjmp(handler->loc, 1);
456205154Sjilles	} else {
457205154Sjilles		INTOFF;
458205154Sjilles		handler = &jmploc;
459205154Sjilles		redirect(n->nredir.redirect, REDIR_PUSH);
460205154Sjilles		in_redirect = 0;
461205154Sjilles		INTON;
462205154Sjilles		evaltree(n->nredir.n, flags);
463205154Sjilles	}
464205154Sjilles	INTOFF;
465205154Sjilles	handler = savehandler;
466205154Sjilles	popredir();
467205154Sjilles	INTON;
468205154Sjilles}
469205154Sjilles
470205154Sjilles
4711556Srgrimes/*
4721556Srgrimes * Compute the names of the files in a redirection list.
4731556Srgrimes */
4741556Srgrimes
475213811Sobrienstatic void
47690111Simpexpredir(union node *n)
47717987Speter{
47825222Ssteve	union node *redir;
4791556Srgrimes
4801556Srgrimes	for (redir = n ; redir ; redir = redir->nfile.next) {
48117987Speter		struct arglist fn;
48217987Speter		fn.lastp = &fn.list;
48317987Speter		switch (redir->type) {
48417987Speter		case NFROM:
48517987Speter		case NTO:
48666612Sbrian		case NFROMTO:
48717987Speter		case NAPPEND:
48896922Stjr		case NCLOBBER:
4891556Srgrimes			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
4901556Srgrimes			redir->nfile.expfname = fn.list->text;
49117987Speter			break;
49217987Speter		case NFROMFD:
49317987Speter		case NTOFD:
49417987Speter			if (redir->ndup.vname) {
495181017Sstefanf				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
49617987Speter				fixredir(redir, fn.list->text, 1);
49717987Speter			}
49817987Speter			break;
4991556Srgrimes		}
5001556Srgrimes	}
5011556Srgrimes}
5021556Srgrimes
5031556Srgrimes
5041556Srgrimes
5051556Srgrimes/*
5061556Srgrimes * Evaluate a pipeline.  All the processes in the pipeline are children
5071556Srgrimes * of the process creating the pipeline.  (This differs from some versions
5081556Srgrimes * of the shell, which make the last process in a pipeline the parent
5091556Srgrimes * of all the rest.)
5101556Srgrimes */
5111556Srgrimes
512213811Sobrienstatic void
51390111Simpevalpipe(union node *n)
51417987Speter{
5151556Srgrimes	struct job *jp;
5161556Srgrimes	struct nodelist *lp;
5171556Srgrimes	int pipelen;
5181556Srgrimes	int prevfd;
5191556Srgrimes	int pip[2];
5201556Srgrimes
521149802Sstefanf	TRACE(("evalpipe(%p) called\n", (void *)n));
5221556Srgrimes	pipelen = 0;
5231556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
5241556Srgrimes		pipelen++;
5251556Srgrimes	INTOFF;
5261556Srgrimes	jp = makejob(n, pipelen);
5271556Srgrimes	prevfd = -1;
5281556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
5291556Srgrimes		prehash(lp->n);
5301556Srgrimes		pip[1] = -1;
5311556Srgrimes		if (lp->next) {
5321556Srgrimes			if (pipe(pip) < 0) {
5331556Srgrimes				close(prevfd);
53453891Scracauer				error("Pipe call failed: %s", strerror(errno));
5351556Srgrimes			}
5361556Srgrimes		}
5371556Srgrimes		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
5381556Srgrimes			INTON;
5391556Srgrimes			if (prevfd > 0) {
540124780Sdes				dup2(prevfd, 0);
5411556Srgrimes				close(prevfd);
5421556Srgrimes			}
5431556Srgrimes			if (pip[1] >= 0) {
54453282Scracauer				if (!(prevfd >= 0 && pip[0] == 0))
54552900Scracauer					close(pip[0]);
5461556Srgrimes				if (pip[1] != 1) {
547124780Sdes					dup2(pip[1], 1);
5481556Srgrimes					close(pip[1]);
5491556Srgrimes				}
5501556Srgrimes			}
5511556Srgrimes			evaltree(lp->n, EV_EXIT);
5521556Srgrimes		}
5531556Srgrimes		if (prevfd >= 0)
5541556Srgrimes			close(prevfd);
5551556Srgrimes		prevfd = pip[0];
556221970Sjilles		if (pip[1] != -1)
557221970Sjilles			close(pip[1]);
5581556Srgrimes	}
5591556Srgrimes	INTON;
5601556Srgrimes	if (n->npipe.backgnd == 0) {
5611556Srgrimes		INTOFF;
56245916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
5631556Srgrimes		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
5641556Srgrimes		INTON;
565221027Sjilles	} else
566221027Sjilles		exitstatus = 0;
5671556Srgrimes}
5681556Srgrimes
5691556Srgrimes
5701556Srgrimes
571216778Sjillesstatic int
572216778Sjillesis_valid_fast_cmdsubst(union node *n)
573216778Sjilles{
574216778Sjilles	union node *argp;
575216778Sjilles
576216778Sjilles	if (n->type != NCMD)
577216778Sjilles		return 0;
578216778Sjilles	for (argp = n->ncmd.args ; argp ; argp = argp->narg.next)
579216778Sjilles		if (expandhassideeffects(argp->narg.text))
580216778Sjilles			return 0;
581216778Sjilles	return 1;
582216778Sjilles}
583216778Sjilles
5841556Srgrimes/*
5851556Srgrimes * Execute a command inside back quotes.  If it's a builtin command, we
5861556Srgrimes * want to save its output in a block obtained from malloc.  Otherwise
5871556Srgrimes * we fork off a subprocess and get the output of the command via a pipe.
5881556Srgrimes * Should be called with interrupts off.
5891556Srgrimes */
5901556Srgrimes
5911556Srgrimesvoid
59290111Simpevalbackcmd(union node *n, struct backcmd *result)
59317987Speter{
5941556Srgrimes	int pip[2];
5951556Srgrimes	struct job *jp;
5961556Srgrimes	struct stackmark smark;		/* unnecessary */
597216761Sjilles	struct jmploc jmploc;
598216761Sjilles	struct jmploc *savehandler;
5991556Srgrimes
6001556Srgrimes	setstackmark(&smark);
6011556Srgrimes	result->fd = -1;
6021556Srgrimes	result->buf = NULL;
6031556Srgrimes	result->nleft = 0;
6041556Srgrimes	result->jp = NULL;
60517987Speter	if (n == NULL) {
60617987Speter		exitstatus = 0;
6071556Srgrimes		goto out;
60817987Speter	}
609216778Sjilles	if (is_valid_fast_cmdsubst(n)) {
61017987Speter		exitstatus = oexitstatus;
611216761Sjilles		savehandler = handler;
612216761Sjilles		if (setjmp(jmploc.loc)) {
613216761Sjilles			if (exception == EXERROR || exception == EXEXEC)
614216761Sjilles				exitstatus = 2;
615216761Sjilles			else if (exception != 0) {
616216761Sjilles				handler = savehandler;
617216761Sjilles				longjmp(handler->loc, 1);
618216761Sjilles			}
619216761Sjilles		} else {
620216761Sjilles			handler = &jmploc;
621216761Sjilles			evalcommand(n, EV_BACKCMD, result);
622216761Sjilles		}
623216761Sjilles		handler = savehandler;
6241556Srgrimes	} else {
62517987Speter		exitstatus = 0;
6261556Srgrimes		if (pipe(pip) < 0)
62753891Scracauer			error("Pipe call failed: %s", strerror(errno));
6281556Srgrimes		jp = makejob(n, 1);
6291556Srgrimes		if (forkshell(jp, n, FORK_NOJOB) == 0) {
6301556Srgrimes			FORCEINTON;
6311556Srgrimes			close(pip[0]);
6321556Srgrimes			if (pip[1] != 1) {
633124780Sdes				dup2(pip[1], 1);
6341556Srgrimes				close(pip[1]);
6351556Srgrimes			}
6361556Srgrimes			evaltree(n, EV_EXIT);
6371556Srgrimes		}
6381556Srgrimes		close(pip[1]);
6391556Srgrimes		result->fd = pip[0];
6401556Srgrimes		result->jp = jp;
6411556Srgrimes	}
6421556Srgrimesout:
6431556Srgrimes	popstackmark(&smark);
644109627Stjr	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
6451556Srgrimes		result->fd, result->buf, result->nleft, result->jp));
6461556Srgrimes}
6471556Srgrimes
648216826Sjilles/*
649216826Sjilles * Check if a builtin can safely be executed in the same process,
650216826Sjilles * even though it should be in a subshell (command substitution).
651216826Sjilles * Note that jobid, jobs, times and trap can show information not
652216826Sjilles * available in a child process; this is deliberate.
653216826Sjilles * The arguments should already have been expanded.
654216826Sjilles */
655216826Sjillesstatic int
656216826Sjillessafe_builtin(int idx, int argc, char **argv)
657216826Sjilles{
658216826Sjilles	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
659216826Sjilles	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
660216826Sjilles	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
661216826Sjilles	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
662216826Sjilles	    idx == TYPECMD)
663216826Sjilles		return (1);
664216826Sjilles	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
665216826Sjilles	    idx == UMASKCMD)
666216826Sjilles		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
667216826Sjilles	if (idx == SETCMD)
668216826Sjilles		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
669216826Sjilles		    argv[1][0] == '+') && argv[1][1] == 'o' &&
670216826Sjilles		    argv[1][2] == '\0'));
671216826Sjilles	return (0);
672216826Sjilles}
6731556Srgrimes
6741556Srgrimes/*
6751556Srgrimes * Execute a simple command.
676217035Sjilles * Note: This may or may not return if (flags & EV_EXIT).
6771556Srgrimes */
6781556Srgrimes
679213811Sobrienstatic void
68090111Simpevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
68117987Speter{
6821556Srgrimes	struct stackmark smark;
6831556Srgrimes	union node *argp;
6841556Srgrimes	struct arglist arglist;
6851556Srgrimes	struct arglist varlist;
6861556Srgrimes	char **argv;
6871556Srgrimes	int argc;
6881556Srgrimes	char **envp;
6891556Srgrimes	int varflag;
6901556Srgrimes	struct strlist *sp;
6911556Srgrimes	int mode;
6921556Srgrimes	int pip[2];
6931556Srgrimes	struct cmdentry cmdentry;
6941556Srgrimes	struct job *jp;
6951556Srgrimes	struct jmploc jmploc;
696194765Sjilles	struct jmploc *savehandler;
697194765Sjilles	char *savecmdname;
698194765Sjilles	struct shparam saveparam;
699194765Sjilles	struct localvar *savelocalvars;
700199647Sjilles	struct parsefile *savetopfile;
7011556Srgrimes	volatile int e;
7021556Srgrimes	char *lastarg;
70345916Scracauer	int realstatus;
70454884Scracauer	int do_clearcmdentry;
705211287Sjilles	const char *path = pathval();
7061556Srgrimes
7071556Srgrimes	/* First expand the arguments. */
708149802Sstefanf	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
7091556Srgrimes	setstackmark(&smark);
7101556Srgrimes	arglist.lastp = &arglist.list;
7111556Srgrimes	varlist.lastp = &varlist.list;
7121556Srgrimes	varflag = 1;
713217035Sjilles	jp = NULL;
71454884Scracauer	do_clearcmdentry = 0;
71517987Speter	oexitstatus = exitstatus;
71617987Speter	exitstatus = 0;
7171556Srgrimes	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
718222165Sjilles		if (varflag && isassignment(argp->narg.text)) {
719222165Sjilles			expandarg(argp, &varlist, EXP_VARTILDE);
720222165Sjilles			continue;
7211556Srgrimes		}
7221556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
7231556Srgrimes		varflag = 0;
7241556Srgrimes	}
7251556Srgrimes	*arglist.lastp = NULL;
7261556Srgrimes	*varlist.lastp = NULL;
7271556Srgrimes	expredir(cmd->ncmd.redirect);
7281556Srgrimes	argc = 0;
7291556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next)
7301556Srgrimes		argc++;
731218306Sjilles	/* Add one slot at the beginning for tryexec(). */
732218306Sjilles	argv = stalloc(sizeof (char *) * (argc + 2));
733218306Sjilles	argv++;
7341556Srgrimes
7351556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
7361556Srgrimes		TRACE(("evalcommand arg: %s\n", sp->text));
7371556Srgrimes		*argv++ = sp->text;
7381556Srgrimes	}
7391556Srgrimes	*argv = NULL;
7401556Srgrimes	lastarg = NULL;
7411556Srgrimes	if (iflag && funcnest == 0 && argc > 0)
7421556Srgrimes		lastarg = argv[-1];
7431556Srgrimes	argv -= argc;
7441556Srgrimes
7451556Srgrimes	/* Print the command if xflag is set. */
7461556Srgrimes	if (xflag) {
747159632Sstefanf		char sep = 0;
748222907Sjilles		const char *p, *ps4;
749222907Sjilles		ps4 = expandstr(ps4val());
750222907Sjilles		out2str(ps4 != NULL ? ps4 : ps4val());
7511556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next) {
752159632Sstefanf			if (sep != 0)
753201366Sjilles				out2c(' ');
754215567Sjilles			p = strchr(sp->text, '=');
755215567Sjilles			if (p != NULL) {
756215567Sjilles				p++;
757215567Sjilles				outbin(sp->text, p - sp->text, out2);
758194786Sjilles				out2qstr(p);
759215567Sjilles			} else
760215567Sjilles				out2qstr(sp->text);
761159632Sstefanf			sep = ' ';
7621556Srgrimes		}
7631556Srgrimes		for (sp = arglist.list ; sp ; sp = sp->next) {
764159632Sstefanf			if (sep != 0)
765201366Sjilles				out2c(' ');
766194786Sjilles			/* Disambiguate command looking like assignment. */
767194786Sjilles			if (sp == arglist.list &&
768194786Sjilles					strchr(sp->text, '=') != NULL &&
769194786Sjilles					strchr(sp->text, '\'') == NULL) {
770194786Sjilles				out2c('\'');
771194786Sjilles				out2str(sp->text);
772194786Sjilles				out2c('\'');
773194786Sjilles			} else
774194786Sjilles				out2qstr(sp->text);
775159632Sstefanf			sep = ' ';
7761556Srgrimes		}
777201366Sjilles		out2c('\n');
7781556Srgrimes		flushout(&errout);
7791556Srgrimes	}
7801556Srgrimes
7811556Srgrimes	/* Now locate the command. */
7821556Srgrimes	if (argc == 0) {
783157601Sstefanf		/* Variable assignment(s) without command */
7841556Srgrimes		cmdentry.cmdtype = CMDBUILTIN;
7851556Srgrimes		cmdentry.u.index = BLTINCMD;
786205138Sjilles		cmdentry.special = 0;
7871556Srgrimes	} else {
78817987Speter		static const char PATH[] = "PATH=";
789204800Sjilles		int cmd_flags = 0, bltinonly = 0;
79017987Speter
79117987Speter		/*
79217987Speter		 * Modify the command lookup path, if a PATH= assignment
79317987Speter		 * is present
79417987Speter		 */
79517987Speter		for (sp = varlist.list ; sp ; sp = sp->next)
79654884Scracauer			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
79717987Speter				path = sp->text + sizeof(PATH) - 1;
798155301Sschweikh				/*
79954884Scracauer				 * On `PATH=... command`, we need to make
80054884Scracauer				 * sure that the command isn't using the
80154884Scracauer				 * non-updated hash table of the outer PATH
802155301Sschweikh				 * setting and we need to make sure that
80354884Scracauer				 * the hash table isn't filled with items
80454884Scracauer				 * from the temporary setting.
80554884Scracauer				 *
806155301Sschweikh				 * It would be better to forbit using and
80754884Scracauer				 * updating the table while this command
80854884Scracauer				 * runs, by the command finding mechanism
80954884Scracauer				 * is heavily integrated with hash handling,
81054884Scracauer				 * so we just delete the hash before and after
81154884Scracauer				 * the command runs. Partly deleting like
81254884Scracauer				 * changepatch() does doesn't seem worth the
81354884Scracauer				 * bookinging effort, since most such runs add
814123996Smaxim				 * directories in front of the new PATH.
81554884Scracauer				 */
816218324Sjilles				clearcmdentry();
81754884Scracauer				do_clearcmdentry = 1;
81854884Scracauer			}
81917987Speter
820204800Sjilles		for (;;) {
821204800Sjilles			if (bltinonly) {
822204800Sjilles				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
823204800Sjilles				if (cmdentry.u.index < 0) {
824201431Sjilles					cmdentry.u.index = BLTINCMD;
825201431Sjilles					argv--;
826201431Sjilles					argc++;
827201431Sjilles					break;
8281556Srgrimes				}
829204800Sjilles			} else
830204800Sjilles				find_command(argv[0], &cmdentry, cmd_flags, path);
831204800Sjilles			/* implement the bltin and command builtins here */
832204800Sjilles			if (cmdentry.cmdtype != CMDBUILTIN)
833204800Sjilles				break;
834204800Sjilles			if (cmdentry.u.index == BLTINCMD) {
835204800Sjilles				if (argc == 1)
8361556Srgrimes					break;
837204800Sjilles				argv++;
838204800Sjilles				argc--;
839204800Sjilles				bltinonly = 1;
840204800Sjilles			} else if (cmdentry.u.index == COMMANDCMD) {
841204800Sjilles				if (argc == 1)
842204800Sjilles					break;
843204800Sjilles				if (!strcmp(argv[1], "-p")) {
844204800Sjilles					if (argc == 2)
845204800Sjilles						break;
846204800Sjilles					if (argv[2][0] == '-') {
847204800Sjilles						if (strcmp(argv[2], "--"))
848204800Sjilles							break;
849204800Sjilles						if (argc == 3)
850204800Sjilles							break;
851204800Sjilles						argv += 3;
852204800Sjilles						argc -= 3;
853204800Sjilles					} else {
854204800Sjilles						argv += 2;
855204800Sjilles						argc -= 2;
856204800Sjilles					}
857204800Sjilles					path = _PATH_STDPATH;
858218324Sjilles					clearcmdentry();
859204800Sjilles					do_clearcmdentry = 1;
860204800Sjilles				} else if (!strcmp(argv[1], "--")) {
861204800Sjilles					if (argc == 2)
862204800Sjilles						break;
863204800Sjilles					argv += 2;
864204800Sjilles					argc -= 2;
865204800Sjilles				} else if (argv[1][0] == '-')
866204800Sjilles					break;
867204800Sjilles				else {
868204800Sjilles					argv++;
869204800Sjilles					argc--;
870204800Sjilles				}
871204800Sjilles				cmd_flags |= DO_NOFUNC;
872204800Sjilles				bltinonly = 0;
873204800Sjilles			} else
874204800Sjilles				break;
8751556Srgrimes		}
876204800Sjilles		/*
877204800Sjilles		 * Special builtins lose their special properties when
878204800Sjilles		 * called via 'command'.
879204800Sjilles		 */
880204800Sjilles		if (cmd_flags & DO_NOFUNC)
881204800Sjilles			cmdentry.special = 0;
8821556Srgrimes	}
8831556Srgrimes
8841556Srgrimes	/* Fork off a child process if necessary. */
8851556Srgrimes	if (cmd->ncmd.backgnd
886197820Sjilles	 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
887194127Sjilles	    && ((flags & EV_EXIT) == 0 || have_traps()))
88817987Speter	 || ((flags & EV_BACKCMD) != 0
889216826Sjilles	    && (cmdentry.cmdtype != CMDBUILTIN ||
890216826Sjilles		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
8911556Srgrimes		jp = makejob(cmd, 1);
8921556Srgrimes		mode = cmd->ncmd.backgnd;
8931556Srgrimes		if (flags & EV_BACKCMD) {
8941556Srgrimes			mode = FORK_NOJOB;
8951556Srgrimes			if (pipe(pip) < 0)
89653891Scracauer				error("Pipe call failed: %s", strerror(errno));
8971556Srgrimes		}
8981556Srgrimes		if (forkshell(jp, cmd, mode) != 0)
8991556Srgrimes			goto parent;	/* at end of routine */
9001556Srgrimes		if (flags & EV_BACKCMD) {
9011556Srgrimes			FORCEINTON;
9021556Srgrimes			close(pip[0]);
9031556Srgrimes			if (pip[1] != 1) {
904124780Sdes				dup2(pip[1], 1);
9051556Srgrimes				close(pip[1]);
9061556Srgrimes			}
9071556Srgrimes		}
9081556Srgrimes		flags |= EV_EXIT;
9091556Srgrimes	}
9101556Srgrimes
9111556Srgrimes	/* This is the child process if a fork occurred. */
9121556Srgrimes	/* Execute the command. */
9131556Srgrimes	if (cmdentry.cmdtype == CMDFUNCTION) {
91420425Ssteve#ifdef DEBUG
9151556Srgrimes		trputs("Shell function:  ");  trargs(argv);
91620425Ssteve#endif
9171556Srgrimes		saveparam = shellparam;
9181556Srgrimes		shellparam.malloc = 0;
91920425Ssteve		shellparam.reset = 1;
9201556Srgrimes		shellparam.nparam = argc - 1;
9211556Srgrimes		shellparam.p = argv + 1;
9221556Srgrimes		shellparam.optnext = NULL;
9231556Srgrimes		INTOFF;
9241556Srgrimes		savelocalvars = localvars;
9251556Srgrimes		localvars = NULL;
926196483Sjilles		reffunc(cmdentry.u.func);
927194765Sjilles		savehandler = handler;
9281556Srgrimes		if (setjmp(jmploc.loc)) {
929218306Sjilles			freeparam(&shellparam);
930218306Sjilles			shellparam = saveparam;
931220978Sjilles			popredir();
932196483Sjilles			unreffunc(cmdentry.u.func);
9331556Srgrimes			poplocalvars();
9341556Srgrimes			localvars = savelocalvars;
935201283Sjilles			funcnest--;
9361556Srgrimes			handler = savehandler;
9371556Srgrimes			longjmp(handler->loc, 1);
9381556Srgrimes		}
9391556Srgrimes		handler = &jmploc;
940201283Sjilles		funcnest++;
941204802Sjilles		redirect(cmd->ncmd.redirect, REDIR_PUSH);
942199660Sjilles		INTON;
9431556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
9441556Srgrimes			mklocal(sp->text);
945185231Sstefanf		exitstatus = oexitstatus;
946220978Sjilles		evaltree(getfuncnode(cmdentry.u.func),
947220978Sjilles		    flags & (EV_TESTED | EV_EXIT));
9481556Srgrimes		INTOFF;
949196483Sjilles		unreffunc(cmdentry.u.func);
9501556Srgrimes		poplocalvars();
9511556Srgrimes		localvars = savelocalvars;
9521556Srgrimes		freeparam(&shellparam);
9531556Srgrimes		shellparam = saveparam;
9541556Srgrimes		handler = savehandler;
955201283Sjilles		funcnest--;
9561556Srgrimes		popredir();
9571556Srgrimes		INTON;
9581556Srgrimes		if (evalskip == SKIPFUNC) {
9591556Srgrimes			evalskip = 0;
9601556Srgrimes			skipcount = 0;
9611556Srgrimes		}
962217035Sjilles		if (jp)
9631556Srgrimes			exitshell(exitstatus);
9641556Srgrimes	} else if (cmdentry.cmdtype == CMDBUILTIN) {
96520425Ssteve#ifdef DEBUG
9661556Srgrimes		trputs("builtin command:  ");  trargs(argv);
96720425Ssteve#endif
9681556Srgrimes		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
9691556Srgrimes		if (flags == EV_BACKCMD) {
9701556Srgrimes			memout.nleft = 0;
9711556Srgrimes			memout.nextc = memout.buf;
9721556Srgrimes			memout.bufsize = 64;
9731556Srgrimes			mode |= REDIR_BACKQ;
974201366Sjilles			cmdentry.special = 0;
9751556Srgrimes		}
9761556Srgrimes		savecmdname = commandname;
977199647Sjilles		savetopfile = getcurrentfile();
9781556Srgrimes		cmdenviron = varlist.list;
9791556Srgrimes		e = -1;
980194765Sjilles		savehandler = handler;
9811556Srgrimes		if (setjmp(jmploc.loc)) {
9821556Srgrimes			e = exception;
983220978Sjilles			if (e == EXINT)
984220978Sjilles				exitstatus = SIGINT+128;
985220978Sjilles			else if (e != EXEXIT)
986220978Sjilles				exitstatus = 2;
9871556Srgrimes			goto cmddone;
9881556Srgrimes		}
9891556Srgrimes		handler = &jmploc;
990157601Sstefanf		redirect(cmd->ncmd.redirect, mode);
991205138Sjilles		/*
992205138Sjilles		 * If there is no command word, redirection errors should
993205138Sjilles		 * not be fatal but assignment errors should.
994205138Sjilles		 */
995205138Sjilles		if (argc == 0 && !(flags & EV_BACKCMD))
996205138Sjilles			cmdentry.special = 1;
997216870Sjilles		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
998207678Sjilles		if (argc > 0)
999207678Sjilles			bltinsetlocale();
10001556Srgrimes		commandname = argv[0];
10011556Srgrimes		argptr = argv + 1;
1002201053Sjilles		nextopt_optptr = NULL;		/* initialize nextopt */
1003193169Sstefanf		builtin_flags = flags;
10041556Srgrimes		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
10051556Srgrimes		flushall();
10061556Srgrimescmddone:
1007207678Sjilles		if (argc > 0)
1008207678Sjilles			bltinunsetlocale();
100960592Scracauer		cmdenviron = NULL;
10101556Srgrimes		out1 = &output;
10111556Srgrimes		out2 = &errout;
10121556Srgrimes		freestdout();
1013217035Sjilles		handler = savehandler;
1014218306Sjilles		commandname = savecmdname;
1015218306Sjilles		if (jp)
1016218306Sjilles			exitshell(exitstatus);
1017201366Sjilles		if (flags == EV_BACKCMD) {
1018201366Sjilles			backcmd->buf = memout.buf;
1019201366Sjilles			backcmd->nleft = memout.nextc - memout.buf;
1020201366Sjilles			memout.buf = NULL;
1021201366Sjilles		}
1022220978Sjilles		if (cmdentry.u.index != EXECCMD)
1023204801Sjilles			popredir();
10241556Srgrimes		if (e != -1) {
102520425Ssteve			if ((e != EXERROR && e != EXEXEC)
1026157601Sstefanf			    || cmdentry.special)
10271556Srgrimes				exraise(e);
1028199647Sjilles			popfilesupto(savetopfile);
1029201366Sjilles			if (flags != EV_BACKCMD)
1030201366Sjilles				FORCEINTON;
10311556Srgrimes		}
10321556Srgrimes	} else {
103320425Ssteve#ifdef DEBUG
10341556Srgrimes		trputs("normal command:  ");  trargs(argv);
103520425Ssteve#endif
10361556Srgrimes		redirect(cmd->ncmd.redirect, 0);
10371556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
10381556Srgrimes			setvareq(sp->text, VEXPORT|VSTACK);
10391556Srgrimes		envp = environment();
1040204800Sjilles		shellexec(argv, envp, path, cmdentry.u.index);
10411556Srgrimes		/*NOTREACHED*/
10421556Srgrimes	}
10431556Srgrimes	goto out;
10441556Srgrimes
10451556Srgrimesparent:	/* parent process gets here (if we forked) */
1046212214Sjilles	if (mode == FORK_FG) {	/* argument to fork */
10471556Srgrimes		INTOFF;
104845916Scracauer		exitstatus = waitforjob(jp, &realstatus);
10491556Srgrimes		INTON;
105045916Scracauer		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
105145266Scracauer			evalskip = SKIPBREAK;
105245266Scracauer			skipcount = loopnest;
105345266Scracauer		}
1054212214Sjilles	} else if (mode == FORK_NOJOB) {
10551556Srgrimes		backcmd->fd = pip[0];
10561556Srgrimes		close(pip[1]);
10571556Srgrimes		backcmd->jp = jp;
1058221027Sjilles	} else
1059221027Sjilles		exitstatus = 0;
10601556Srgrimes
10611556Srgrimesout:
10621556Srgrimes	if (lastarg)
10631556Srgrimes		setvar("_", lastarg, 0);
106454884Scracauer	if (do_clearcmdentry)
1065218324Sjilles		clearcmdentry();
10661556Srgrimes	popstackmark(&smark);
10671556Srgrimes}
10681556Srgrimes
10691556Srgrimes
10701556Srgrimes
10711556Srgrimes/*
10721556Srgrimes * Search for a command.  This is called before we fork so that the
10731556Srgrimes * location of the command will be available in the parent as well as
10741556Srgrimes * the child.  The check for "goodname" is an overly conservative
10751556Srgrimes * check that the name will not be subject to expansion.
10761556Srgrimes */
10771556Srgrimes
1078213811Sobrienstatic void
107990111Simpprehash(union node *n)
108017987Speter{
10811556Srgrimes	struct cmdentry entry;
10821556Srgrimes
1083159633Sstefanf	if (n && n->type == NCMD && n->ncmd.args)
108417987Speter		if (goodname(n->ncmd.args->narg.text))
108517987Speter			find_command(n->ncmd.args->narg.text, &entry, 0,
108617987Speter				     pathval());
10871556Srgrimes}
10881556Srgrimes
10891556Srgrimes
10901556Srgrimes
10911556Srgrimes/*
10921556Srgrimes * Builtin commands.  Builtin commands whose functions are closely
10931556Srgrimes * tied to evaluation are implemented here.
10941556Srgrimes */
10951556Srgrimes
10961556Srgrimes/*
1097201431Sjilles * No command given, a bltin command with no arguments, or a bltin command
1098201431Sjilles * with an invalid name.
10991556Srgrimes */
11001556Srgrimes
110117987Speterint
1102201431Sjillesbltincmd(int argc, char **argv)
110317987Speter{
1104201431Sjilles	if (argc > 1) {
1105201431Sjilles		out2fmt_flush("%s: not found\n", argv[1]);
1106201431Sjilles		return 127;
1107201431Sjilles	}
110820425Ssteve	/*
110917987Speter	 * Preserve exitstatus of a previous possible redirection
111020425Ssteve	 * as POSIX mandates
111117987Speter	 */
11121556Srgrimes	return exitstatus;
11131556Srgrimes}
11141556Srgrimes
11151556Srgrimes
11161556Srgrimes/*
11171556Srgrimes * Handle break and continue commands.  Break, continue, and return are
11181556Srgrimes * all handled by setting the evalskip flag.  The evaluation routines
11191556Srgrimes * above all check this flag, and if it is set they start skipping
11201556Srgrimes * commands rather than executing them.  The variable skipcount is
11211556Srgrimes * the number of loops to break/continue, or the number of function
11221556Srgrimes * levels to return.  (The latter is always 1.)  It should probably
11231556Srgrimes * be an error to break out of more loops than exist, but it isn't
11241556Srgrimes * in the standard shell so we don't make it one here.
11251556Srgrimes */
11261556Srgrimes
112717987Speterint
112890111Simpbreakcmd(int argc, char **argv)
112917987Speter{
113020425Ssteve	int n = argc > 1 ? number(argv[1]) : 1;
11311556Srgrimes
11321556Srgrimes	if (n > loopnest)
11331556Srgrimes		n = loopnest;
11341556Srgrimes	if (n > 0) {
11351556Srgrimes		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
11361556Srgrimes		skipcount = n;
11371556Srgrimes	}
11381556Srgrimes	return 0;
11391556Srgrimes}
11401556Srgrimes
1141100437Stjr/*
1142100437Stjr * The `command' command.
1143100437Stjr */
1144100437Stjrint
1145100437Stjrcommandcmd(int argc, char **argv)
1146100437Stjr{
1147207783Sjilles	const char *path;
1148100437Stjr	int ch;
1149151810Sstefanf	int cmd = -1;
11501556Srgrimes
1151204800Sjilles	path = bltinlookup("PATH", 1);
1152100437Stjr
1153100437Stjr	optind = optreset = 1;
1154100663Stjr	opterr = 0;
1155151810Sstefanf	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1156100437Stjr		switch (ch) {
1157100437Stjr		case 'p':
1158207783Sjilles			path = _PATH_STDPATH;
1159100437Stjr			break;
1160151810Sstefanf		case 'v':
1161151810Sstefanf			cmd = TYPECMD_SMALLV;
1162151810Sstefanf			break;
1163151810Sstefanf		case 'V':
1164151810Sstefanf			cmd = TYPECMD_BIGV;
1165151810Sstefanf			break;
1166100437Stjr		case '?':
1167100437Stjr		default:
1168100437Stjr			error("unknown option: -%c", optopt);
1169100437Stjr		}
1170100437Stjr	}
1171100437Stjr	argc -= optind;
1172100437Stjr	argv += optind;
1173100437Stjr
1174151810Sstefanf	if (cmd != -1) {
1175151810Sstefanf		if (argc != 1)
1176151810Sstefanf			error("wrong number of arguments");
1177201343Sjilles		return typecmd_impl(2, argv - 1, cmd, path);
1178151810Sstefanf	}
1179204800Sjilles	if (argc != 0)
1180214538Sjilles		error("commandcmd bad call");
1181100437Stjr
1182100437Stjr	/*
1183100437Stjr	 * Do nothing successfully if no command was specified;
1184100437Stjr	 * ksh also does this.
1185100437Stjr	 */
1186204800Sjilles	return 0;
1187100437Stjr}
1188100437Stjr
1189100437Stjr
11901556Srgrimes/*
11911556Srgrimes * The return command.
11921556Srgrimes */
11931556Srgrimes
119417987Speterint
119590111Simpreturncmd(int argc, char **argv)
119617987Speter{
119720425Ssteve	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
11981556Srgrimes
11991556Srgrimes	if (funcnest) {
12001556Srgrimes		evalskip = SKIPFUNC;
12011556Srgrimes		skipcount = 1;
120220425Ssteve	} else {
120320425Ssteve		/* skip the rest of the file */
120420425Ssteve		evalskip = SKIPFILE;
120520425Ssteve		skipcount = 1;
12061556Srgrimes	}
12071556Srgrimes	return ret;
12081556Srgrimes}
12091556Srgrimes
12101556Srgrimes
121117987Speterint
121290111Simpfalsecmd(int argc __unused, char **argv __unused)
121317987Speter{
121417987Speter	return 1;
121517987Speter}
121617987Speter
121717987Speter
121817987Speterint
121990111Simptruecmd(int argc __unused, char **argv __unused)
122017987Speter{
12211556Srgrimes	return 0;
12221556Srgrimes}
12231556Srgrimes
12241556Srgrimes
122517987Speterint
122690111Simpexeccmd(int argc, char **argv)
122717987Speter{
1228208630Sjilles	/*
1229208630Sjilles	 * Because we have historically not supported any options,
1230208630Sjilles	 * only treat "--" specially.
1231208630Sjilles	 */
1232208630Sjilles	if (argc > 1 && strcmp(argv[1], "--") == 0)
1233208630Sjilles		argc--, argv++;
12341556Srgrimes	if (argc > 1) {
123517987Speter		struct strlist *sp;
123617987Speter
12371556Srgrimes		iflag = 0;		/* exit on error */
12381556Srgrimes		mflag = 0;
12391556Srgrimes		optschanged();
124017987Speter		for (sp = cmdenviron; sp ; sp = sp->next)
124117987Speter			setvareq(sp->text, VEXPORT|VSTACK);
12421556Srgrimes		shellexec(argv + 1, environment(), pathval(), 0);
12431556Srgrimes
12441556Srgrimes	}
12451556Srgrimes	return 0;
12461556Srgrimes}
1247153091Sstefanf
1248153091Sstefanf
1249153091Sstefanfint
1250153091Sstefanftimescmd(int argc __unused, char **argv __unused)
1251153091Sstefanf{
1252153091Sstefanf	struct rusage ru;
1253153091Sstefanf	long shumins, shsmins, chumins, chsmins;
1254153091Sstefanf	double shusecs, shssecs, chusecs, chssecs;
1255153091Sstefanf
1256153091Sstefanf	if (getrusage(RUSAGE_SELF, &ru) < 0)
1257153091Sstefanf		return 1;
1258153091Sstefanf	shumins = ru.ru_utime.tv_sec / 60;
1259153091Sstefanf	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1260153091Sstefanf	shsmins = ru.ru_stime.tv_sec / 60;
1261153091Sstefanf	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1262153091Sstefanf	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1263153091Sstefanf		return 1;
1264153091Sstefanf	chumins = ru.ru_utime.tv_sec / 60;
1265153091Sstefanf	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1266153091Sstefanf	chsmins = ru.ru_stime.tv_sec / 60;
1267153091Sstefanf	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1268153091Sstefanf	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1269153091Sstefanf	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1270153091Sstefanf	return 0;
1271153091Sstefanf}
1272