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$");
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 */
78231085Sdumbbellint 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                }
143223163Sjilles                evalstring(p, builtin_flags);
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)) {
389223186Sjilles				while (cp->nclist.next &&
390223186Sjilles				    cp->type == NCLISTFALLTHRU) {
391223186Sjilles					if (evalskip != 0)
392223186Sjilles						break;
393223186Sjilles					evaltree(cp->nclist.body,
394223186Sjilles					    flags & ~EV_EXIT);
395223186Sjilles					cp = cp->nclist.next;
396223186Sjilles				}
3971556Srgrimes				if (evalskip == 0) {
3981556Srgrimes					evaltree(cp->nclist.body, flags);
3991556Srgrimes				}
4001556Srgrimes				goto out;
4011556Srgrimes			}
4021556Srgrimes		}
4031556Srgrimes	}
4041556Srgrimesout:
4051556Srgrimes	popstackmark(&smark);
4061556Srgrimes}
4071556Srgrimes
4081556Srgrimes
4091556Srgrimes
4101556Srgrimes/*
4111556Srgrimes * Kick off a subshell to evaluate a tree.
4121556Srgrimes */
4131556Srgrimes
414213811Sobrienstatic void
41590111Simpevalsubshell(union node *n, int flags)
41617987Speter{
4171556Srgrimes	struct job *jp;
4181556Srgrimes	int backgnd = (n->type == NBACKGND);
4191556Srgrimes
420222716Sjilles	oexitstatus = exitstatus;
4211556Srgrimes	expredir(n->nredir.redirect);
422194774Sjilles	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
423194774Sjilles			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
4241556Srgrimes		if (backgnd)
4251556Srgrimes			flags &=~ EV_TESTED;
4261556Srgrimes		redirect(n->nredir.redirect, 0);
4271556Srgrimes		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
428201053Sjilles	} else if (! backgnd) {
4291556Srgrimes		INTOFF;
43045916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
4311556Srgrimes		INTON;
432221027Sjilles	} else
433221027Sjilles		exitstatus = 0;
4341556Srgrimes}
4351556Srgrimes
4361556Srgrimes
437205154Sjilles/*
438205154Sjilles * Evaluate a redirected compound command.
439205154Sjilles */
4401556Srgrimes
441213811Sobrienstatic void
442205154Sjillesevalredir(union node *n, int flags)
443205154Sjilles{
444205154Sjilles	struct jmploc jmploc;
445205154Sjilles	struct jmploc *savehandler;
446205154Sjilles	volatile int in_redirect = 1;
447205154Sjilles
448222716Sjilles	oexitstatus = exitstatus;
449205154Sjilles	expredir(n->nredir.redirect);
450205154Sjilles	savehandler = handler;
451205154Sjilles	if (setjmp(jmploc.loc)) {
452205154Sjilles		int e;
453205154Sjilles
454205154Sjilles		handler = savehandler;
455205154Sjilles		e = exception;
456220978Sjilles		popredir();
457205154Sjilles		if (e == EXERROR || e == EXEXEC) {
458205154Sjilles			if (in_redirect) {
459205154Sjilles				exitstatus = 2;
460205154Sjilles				return;
461205154Sjilles			}
462205154Sjilles		}
463205154Sjilles		longjmp(handler->loc, 1);
464205154Sjilles	} else {
465205154Sjilles		INTOFF;
466205154Sjilles		handler = &jmploc;
467205154Sjilles		redirect(n->nredir.redirect, REDIR_PUSH);
468205154Sjilles		in_redirect = 0;
469205154Sjilles		INTON;
470205154Sjilles		evaltree(n->nredir.n, flags);
471205154Sjilles	}
472205154Sjilles	INTOFF;
473205154Sjilles	handler = savehandler;
474205154Sjilles	popredir();
475205154Sjilles	INTON;
476205154Sjilles}
477205154Sjilles
478205154Sjilles
4791556Srgrimes/*
4801556Srgrimes * Compute the names of the files in a redirection list.
4811556Srgrimes */
4821556Srgrimes
483213811Sobrienstatic void
48490111Simpexpredir(union node *n)
48517987Speter{
48625222Ssteve	union node *redir;
4871556Srgrimes
4881556Srgrimes	for (redir = n ; redir ; redir = redir->nfile.next) {
48917987Speter		struct arglist fn;
49017987Speter		fn.lastp = &fn.list;
49117987Speter		switch (redir->type) {
49217987Speter		case NFROM:
49317987Speter		case NTO:
49466612Sbrian		case NFROMTO:
49517987Speter		case NAPPEND:
49696922Stjr		case NCLOBBER:
4971556Srgrimes			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
4981556Srgrimes			redir->nfile.expfname = fn.list->text;
49917987Speter			break;
50017987Speter		case NFROMFD:
50117987Speter		case NTOFD:
50217987Speter			if (redir->ndup.vname) {
503181017Sstefanf				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
50417987Speter				fixredir(redir, fn.list->text, 1);
50517987Speter			}
50617987Speter			break;
5071556Srgrimes		}
5081556Srgrimes	}
5091556Srgrimes}
5101556Srgrimes
5111556Srgrimes
5121556Srgrimes
5131556Srgrimes/*
5141556Srgrimes * Evaluate a pipeline.  All the processes in the pipeline are children
5151556Srgrimes * of the process creating the pipeline.  (This differs from some versions
5161556Srgrimes * of the shell, which make the last process in a pipeline the parent
5171556Srgrimes * of all the rest.)
5181556Srgrimes */
5191556Srgrimes
520213811Sobrienstatic void
52190111Simpevalpipe(union node *n)
52217987Speter{
5231556Srgrimes	struct job *jp;
5241556Srgrimes	struct nodelist *lp;
5251556Srgrimes	int pipelen;
5261556Srgrimes	int prevfd;
5271556Srgrimes	int pip[2];
5281556Srgrimes
529149802Sstefanf	TRACE(("evalpipe(%p) called\n", (void *)n));
5301556Srgrimes	pipelen = 0;
5311556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
5321556Srgrimes		pipelen++;
5331556Srgrimes	INTOFF;
5341556Srgrimes	jp = makejob(n, pipelen);
5351556Srgrimes	prevfd = -1;
5361556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
5371556Srgrimes		prehash(lp->n);
5381556Srgrimes		pip[1] = -1;
5391556Srgrimes		if (lp->next) {
5401556Srgrimes			if (pipe(pip) < 0) {
5411556Srgrimes				close(prevfd);
54253891Scracauer				error("Pipe call failed: %s", strerror(errno));
5431556Srgrimes			}
5441556Srgrimes		}
5451556Srgrimes		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
5461556Srgrimes			INTON;
5471556Srgrimes			if (prevfd > 0) {
548124780Sdes				dup2(prevfd, 0);
5491556Srgrimes				close(prevfd);
5501556Srgrimes			}
5511556Srgrimes			if (pip[1] >= 0) {
55253282Scracauer				if (!(prevfd >= 0 && pip[0] == 0))
55352900Scracauer					close(pip[0]);
5541556Srgrimes				if (pip[1] != 1) {
555124780Sdes					dup2(pip[1], 1);
5561556Srgrimes					close(pip[1]);
5571556Srgrimes				}
5581556Srgrimes			}
5591556Srgrimes			evaltree(lp->n, EV_EXIT);
5601556Srgrimes		}
5611556Srgrimes		if (prevfd >= 0)
5621556Srgrimes			close(prevfd);
5631556Srgrimes		prevfd = pip[0];
564221970Sjilles		if (pip[1] != -1)
565221970Sjilles			close(pip[1]);
5661556Srgrimes	}
5671556Srgrimes	INTON;
5681556Srgrimes	if (n->npipe.backgnd == 0) {
5691556Srgrimes		INTOFF;
57045916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
5711556Srgrimes		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
5721556Srgrimes		INTON;
573221027Sjilles	} else
574221027Sjilles		exitstatus = 0;
5751556Srgrimes}
5761556Srgrimes
5771556Srgrimes
5781556Srgrimes
579216778Sjillesstatic int
580216778Sjillesis_valid_fast_cmdsubst(union node *n)
581216778Sjilles{
582216778Sjilles
583223024Sjilles	return (n->type == NCMD);
584216778Sjilles}
585216778Sjilles
5861556Srgrimes/*
5871556Srgrimes * Execute a command inside back quotes.  If it's a builtin command, we
5881556Srgrimes * want to save its output in a block obtained from malloc.  Otherwise
5891556Srgrimes * we fork off a subprocess and get the output of the command via a pipe.
5901556Srgrimes * Should be called with interrupts off.
5911556Srgrimes */
5921556Srgrimes
5931556Srgrimesvoid
59490111Simpevalbackcmd(union node *n, struct backcmd *result)
59517987Speter{
5961556Srgrimes	int pip[2];
5971556Srgrimes	struct job *jp;
5981556Srgrimes	struct stackmark smark;		/* unnecessary */
599216761Sjilles	struct jmploc jmploc;
600216761Sjilles	struct jmploc *savehandler;
601223024Sjilles	struct localvar *savelocalvars;
6021556Srgrimes
6031556Srgrimes	setstackmark(&smark);
6041556Srgrimes	result->fd = -1;
6051556Srgrimes	result->buf = NULL;
6061556Srgrimes	result->nleft = 0;
6071556Srgrimes	result->jp = NULL;
60817987Speter	if (n == NULL) {
60917987Speter		exitstatus = 0;
6101556Srgrimes		goto out;
61117987Speter	}
612216778Sjilles	if (is_valid_fast_cmdsubst(n)) {
61317987Speter		exitstatus = oexitstatus;
614223024Sjilles		savelocalvars = localvars;
615223024Sjilles		localvars = NULL;
616223024Sjilles		forcelocal++;
617216761Sjilles		savehandler = handler;
618216761Sjilles		if (setjmp(jmploc.loc)) {
619216761Sjilles			if (exception == EXERROR || exception == EXEXEC)
620216761Sjilles				exitstatus = 2;
621216761Sjilles			else if (exception != 0) {
622216761Sjilles				handler = savehandler;
623223024Sjilles				forcelocal--;
624223024Sjilles				poplocalvars();
625223024Sjilles				localvars = savelocalvars;
626216761Sjilles				longjmp(handler->loc, 1);
627216761Sjilles			}
628216761Sjilles		} else {
629216761Sjilles			handler = &jmploc;
630216761Sjilles			evalcommand(n, EV_BACKCMD, result);
631216761Sjilles		}
632216761Sjilles		handler = savehandler;
633223024Sjilles		forcelocal--;
634223024Sjilles		poplocalvars();
635223024Sjilles		localvars = savelocalvars;
6361556Srgrimes	} else {
63717987Speter		exitstatus = 0;
6381556Srgrimes		if (pipe(pip) < 0)
63953891Scracauer			error("Pipe call failed: %s", strerror(errno));
6401556Srgrimes		jp = makejob(n, 1);
6411556Srgrimes		if (forkshell(jp, n, FORK_NOJOB) == 0) {
6421556Srgrimes			FORCEINTON;
6431556Srgrimes			close(pip[0]);
6441556Srgrimes			if (pip[1] != 1) {
645124780Sdes				dup2(pip[1], 1);
6461556Srgrimes				close(pip[1]);
6471556Srgrimes			}
6481556Srgrimes			evaltree(n, EV_EXIT);
6491556Srgrimes		}
6501556Srgrimes		close(pip[1]);
6511556Srgrimes		result->fd = pip[0];
6521556Srgrimes		result->jp = jp;
6531556Srgrimes	}
6541556Srgrimesout:
6551556Srgrimes	popstackmark(&smark);
656109627Stjr	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
6571556Srgrimes		result->fd, result->buf, result->nleft, result->jp));
6581556Srgrimes}
6591556Srgrimes
660264423Sjillesstatic int
661264423Sjillesmustexpandto(const char *argtext, const char *mask)
662264423Sjilles{
663264423Sjilles	for (;;) {
664264423Sjilles		if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) {
665264423Sjilles			argtext++;
666264423Sjilles			continue;
667264423Sjilles		}
668264423Sjilles		if (*argtext == CTLESC)
669264423Sjilles			argtext++;
670264423Sjilles		else if (BASESYNTAX[(int)*argtext] == CCTL)
671264423Sjilles			return (0);
672264423Sjilles		if (*argtext != *mask)
673264423Sjilles			return (0);
674264423Sjilles		if (*argtext == '\0')
675264423Sjilles			return (1);
676264423Sjilles		argtext++;
677264423Sjilles		mask++;
678264423Sjilles	}
679264423Sjilles}
680264423Sjilles
681264423Sjillesstatic int
682264423Sjillesisdeclarationcmd(struct narg *arg)
683264423Sjilles{
684264423Sjilles	int have_command = 0;
685264423Sjilles
686264423Sjilles	if (arg == NULL)
687264423Sjilles		return (0);
688264423Sjilles	while (mustexpandto(arg->text, "command")) {
689264423Sjilles		have_command = 1;
690264423Sjilles		arg = &arg->next->narg;
691264423Sjilles		if (arg == NULL)
692264423Sjilles			return (0);
693264423Sjilles		/*
694264423Sjilles		 * To also allow "command -p" and "command --" as part of
695264423Sjilles		 * a declaration command, add code here.
696264423Sjilles		 * We do not do this, as ksh does not do it either and it
697264423Sjilles		 * is not required by POSIX.
698264423Sjilles		 */
699264423Sjilles	}
700264423Sjilles	return (mustexpandto(arg->text, "export") ||
701264423Sjilles	    mustexpandto(arg->text, "readonly") ||
702264423Sjilles	    (mustexpandto(arg->text, "local") &&
703264423Sjilles		(have_command || !isfunc("local"))));
704264423Sjilles}
705264423Sjilles
706216826Sjilles/*
707216826Sjilles * Check if a builtin can safely be executed in the same process,
708216826Sjilles * even though it should be in a subshell (command substitution).
709216826Sjilles * Note that jobid, jobs, times and trap can show information not
710216826Sjilles * available in a child process; this is deliberate.
711216826Sjilles * The arguments should already have been expanded.
712216826Sjilles */
713216826Sjillesstatic int
714216826Sjillessafe_builtin(int idx, int argc, char **argv)
715216826Sjilles{
716216826Sjilles	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
717216826Sjilles	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
718216826Sjilles	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
719216826Sjilles	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
720216826Sjilles	    idx == TYPECMD)
721216826Sjilles		return (1);
722216826Sjilles	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
723216826Sjilles	    idx == UMASKCMD)
724216826Sjilles		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
725216826Sjilles	if (idx == SETCMD)
726216826Sjilles		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
727216826Sjilles		    argv[1][0] == '+') && argv[1][1] == 'o' &&
728216826Sjilles		    argv[1][2] == '\0'));
729216826Sjilles	return (0);
730216826Sjilles}
7311556Srgrimes
7321556Srgrimes/*
7331556Srgrimes * Execute a simple command.
734217035Sjilles * Note: This may or may not return if (flags & EV_EXIT).
7351556Srgrimes */
7361556Srgrimes
737213811Sobrienstatic void
73890111Simpevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
73917987Speter{
7401556Srgrimes	struct stackmark smark;
7411556Srgrimes	union node *argp;
7421556Srgrimes	struct arglist arglist;
7431556Srgrimes	struct arglist varlist;
7441556Srgrimes	char **argv;
7451556Srgrimes	int argc;
7461556Srgrimes	char **envp;
7471556Srgrimes	int varflag;
7481556Srgrimes	struct strlist *sp;
7491556Srgrimes	int mode;
7501556Srgrimes	int pip[2];
7511556Srgrimes	struct cmdentry cmdentry;
7521556Srgrimes	struct job *jp;
7531556Srgrimes	struct jmploc jmploc;
754194765Sjilles	struct jmploc *savehandler;
755194765Sjilles	char *savecmdname;
756194765Sjilles	struct shparam saveparam;
757194765Sjilles	struct localvar *savelocalvars;
758199647Sjilles	struct parsefile *savetopfile;
7591556Srgrimes	volatile int e;
7601556Srgrimes	char *lastarg;
76145916Scracauer	int realstatus;
76254884Scracauer	int do_clearcmdentry;
763211287Sjilles	const char *path = pathval();
7641556Srgrimes
7651556Srgrimes	/* First expand the arguments. */
766149802Sstefanf	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
7671556Srgrimes	setstackmark(&smark);
7681556Srgrimes	arglist.lastp = &arglist.list;
7691556Srgrimes	varlist.lastp = &varlist.list;
7701556Srgrimes	varflag = 1;
771217035Sjilles	jp = NULL;
77254884Scracauer	do_clearcmdentry = 0;
77317987Speter	oexitstatus = exitstatus;
77417987Speter	exitstatus = 0;
7751556Srgrimes	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
776222165Sjilles		if (varflag && isassignment(argp->narg.text)) {
777264423Sjilles			expandarg(argp, varflag == 1 ? &varlist : &arglist,
778264423Sjilles			    EXP_VARTILDE);
779222165Sjilles			continue;
780264423Sjilles		} else if (varflag == 1)
781264423Sjilles			varflag = isdeclarationcmd(&argp->narg) ? 2 : 0;
7821556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
7831556Srgrimes	}
7841556Srgrimes	*arglist.lastp = NULL;
7851556Srgrimes	*varlist.lastp = NULL;
7861556Srgrimes	expredir(cmd->ncmd.redirect);
7871556Srgrimes	argc = 0;
7881556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next)
7891556Srgrimes		argc++;
790218306Sjilles	/* Add one slot at the beginning for tryexec(). */
791218306Sjilles	argv = stalloc(sizeof (char *) * (argc + 2));
792218306Sjilles	argv++;
7931556Srgrimes
7941556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
7951556Srgrimes		TRACE(("evalcommand arg: %s\n", sp->text));
7961556Srgrimes		*argv++ = sp->text;
7971556Srgrimes	}
7981556Srgrimes	*argv = NULL;
7991556Srgrimes	lastarg = NULL;
8001556Srgrimes	if (iflag && funcnest == 0 && argc > 0)
8011556Srgrimes		lastarg = argv[-1];
8021556Srgrimes	argv -= argc;
8031556Srgrimes
8041556Srgrimes	/* Print the command if xflag is set. */
8051556Srgrimes	if (xflag) {
806159632Sstefanf		char sep = 0;
807222907Sjilles		const char *p, *ps4;
808222907Sjilles		ps4 = expandstr(ps4val());
809222907Sjilles		out2str(ps4 != NULL ? ps4 : ps4val());
8101556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next) {
811159632Sstefanf			if (sep != 0)
812201366Sjilles				out2c(' ');
813215567Sjilles			p = strchr(sp->text, '=');
814215567Sjilles			if (p != NULL) {
815215567Sjilles				p++;
816215567Sjilles				outbin(sp->text, p - sp->text, out2);
817194786Sjilles				out2qstr(p);
818215567Sjilles			} else
819215567Sjilles				out2qstr(sp->text);
820159632Sstefanf			sep = ' ';
8211556Srgrimes		}
8221556Srgrimes		for (sp = arglist.list ; sp ; sp = sp->next) {
823159632Sstefanf			if (sep != 0)
824201366Sjilles				out2c(' ');
825194786Sjilles			/* Disambiguate command looking like assignment. */
826194786Sjilles			if (sp == arglist.list &&
827194786Sjilles					strchr(sp->text, '=') != NULL &&
828194786Sjilles					strchr(sp->text, '\'') == NULL) {
829194786Sjilles				out2c('\'');
830194786Sjilles				out2str(sp->text);
831194786Sjilles				out2c('\'');
832194786Sjilles			} else
833194786Sjilles				out2qstr(sp->text);
834159632Sstefanf			sep = ' ';
8351556Srgrimes		}
836201366Sjilles		out2c('\n');
8371556Srgrimes		flushout(&errout);
8381556Srgrimes	}
8391556Srgrimes
8401556Srgrimes	/* Now locate the command. */
8411556Srgrimes	if (argc == 0) {
842157601Sstefanf		/* Variable assignment(s) without command */
8431556Srgrimes		cmdentry.cmdtype = CMDBUILTIN;
8441556Srgrimes		cmdentry.u.index = BLTINCMD;
845205138Sjilles		cmdentry.special = 0;
8461556Srgrimes	} else {
84717987Speter		static const char PATH[] = "PATH=";
848204800Sjilles		int cmd_flags = 0, bltinonly = 0;
84917987Speter
85017987Speter		/*
85117987Speter		 * Modify the command lookup path, if a PATH= assignment
85217987Speter		 * is present
85317987Speter		 */
85417987Speter		for (sp = varlist.list ; sp ; sp = sp->next)
85554884Scracauer			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
85617987Speter				path = sp->text + sizeof(PATH) - 1;
857155301Sschweikh				/*
85854884Scracauer				 * On `PATH=... command`, we need to make
85954884Scracauer				 * sure that the command isn't using the
86054884Scracauer				 * non-updated hash table of the outer PATH
861155301Sschweikh				 * setting and we need to make sure that
86254884Scracauer				 * the hash table isn't filled with items
86354884Scracauer				 * from the temporary setting.
86454884Scracauer				 *
865155301Sschweikh				 * It would be better to forbit using and
86654884Scracauer				 * updating the table while this command
86754884Scracauer				 * runs, by the command finding mechanism
86854884Scracauer				 * is heavily integrated with hash handling,
86954884Scracauer				 * so we just delete the hash before and after
87054884Scracauer				 * the command runs. Partly deleting like
87154884Scracauer				 * changepatch() does doesn't seem worth the
87254884Scracauer				 * bookinging effort, since most such runs add
873123996Smaxim				 * directories in front of the new PATH.
87454884Scracauer				 */
875218324Sjilles				clearcmdentry();
87654884Scracauer				do_clearcmdentry = 1;
87754884Scracauer			}
87817987Speter
879204800Sjilles		for (;;) {
880204800Sjilles			if (bltinonly) {
881204800Sjilles				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
882204800Sjilles				if (cmdentry.u.index < 0) {
883201431Sjilles					cmdentry.u.index = BLTINCMD;
884201431Sjilles					argv--;
885201431Sjilles					argc++;
886201431Sjilles					break;
8871556Srgrimes				}
888204800Sjilles			} else
889204800Sjilles				find_command(argv[0], &cmdentry, cmd_flags, path);
890204800Sjilles			/* implement the bltin and command builtins here */
891204800Sjilles			if (cmdentry.cmdtype != CMDBUILTIN)
892204800Sjilles				break;
893204800Sjilles			if (cmdentry.u.index == BLTINCMD) {
894204800Sjilles				if (argc == 1)
8951556Srgrimes					break;
896204800Sjilles				argv++;
897204800Sjilles				argc--;
898204800Sjilles				bltinonly = 1;
899204800Sjilles			} else if (cmdentry.u.index == COMMANDCMD) {
900204800Sjilles				if (argc == 1)
901204800Sjilles					break;
902204800Sjilles				if (!strcmp(argv[1], "-p")) {
903204800Sjilles					if (argc == 2)
904204800Sjilles						break;
905204800Sjilles					if (argv[2][0] == '-') {
906204800Sjilles						if (strcmp(argv[2], "--"))
907204800Sjilles							break;
908204800Sjilles						if (argc == 3)
909204800Sjilles							break;
910204800Sjilles						argv += 3;
911204800Sjilles						argc -= 3;
912204800Sjilles					} else {
913204800Sjilles						argv += 2;
914204800Sjilles						argc -= 2;
915204800Sjilles					}
916204800Sjilles					path = _PATH_STDPATH;
917218324Sjilles					clearcmdentry();
918204800Sjilles					do_clearcmdentry = 1;
919204800Sjilles				} else if (!strcmp(argv[1], "--")) {
920204800Sjilles					if (argc == 2)
921204800Sjilles						break;
922204800Sjilles					argv += 2;
923204800Sjilles					argc -= 2;
924204800Sjilles				} else if (argv[1][0] == '-')
925204800Sjilles					break;
926204800Sjilles				else {
927204800Sjilles					argv++;
928204800Sjilles					argc--;
929204800Sjilles				}
930204800Sjilles				cmd_flags |= DO_NOFUNC;
931204800Sjilles				bltinonly = 0;
932204800Sjilles			} else
933204800Sjilles				break;
9341556Srgrimes		}
935204800Sjilles		/*
936204800Sjilles		 * Special builtins lose their special properties when
937204800Sjilles		 * called via 'command'.
938204800Sjilles		 */
939204800Sjilles		if (cmd_flags & DO_NOFUNC)
940204800Sjilles			cmdentry.special = 0;
9411556Srgrimes	}
9421556Srgrimes
9431556Srgrimes	/* Fork off a child process if necessary. */
944223282Sjilles	if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
945194127Sjilles	    && ((flags & EV_EXIT) == 0 || have_traps()))
94617987Speter	 || ((flags & EV_BACKCMD) != 0
947216826Sjilles	    && (cmdentry.cmdtype != CMDBUILTIN ||
948216826Sjilles		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
9491556Srgrimes		jp = makejob(cmd, 1);
950223282Sjilles		mode = FORK_FG;
9511556Srgrimes		if (flags & EV_BACKCMD) {
9521556Srgrimes			mode = FORK_NOJOB;
9531556Srgrimes			if (pipe(pip) < 0)
95453891Scracauer				error("Pipe call failed: %s", strerror(errno));
9551556Srgrimes		}
956249242Sjilles		if (cmdentry.cmdtype == CMDNORMAL &&
957249242Sjilles		    cmd->ncmd.redirect == NULL &&
958249242Sjilles		    varlist.list == NULL &&
959249242Sjilles		    (mode == FORK_FG || mode == FORK_NOJOB) &&
960249242Sjilles		    !disvforkset() && !iflag && !mflag) {
961249242Sjilles			vforkexecshell(jp, argv, environment(), path,
962249242Sjilles			    cmdentry.u.index, flags & EV_BACKCMD ? pip : NULL);
963249242Sjilles			goto parent;
964249242Sjilles		}
9651556Srgrimes		if (forkshell(jp, cmd, mode) != 0)
9661556Srgrimes			goto parent;	/* at end of routine */
9671556Srgrimes		if (flags & EV_BACKCMD) {
9681556Srgrimes			FORCEINTON;
9691556Srgrimes			close(pip[0]);
9701556Srgrimes			if (pip[1] != 1) {
971124780Sdes				dup2(pip[1], 1);
9721556Srgrimes				close(pip[1]);
9731556Srgrimes			}
974223163Sjilles			flags &= ~EV_BACKCMD;
9751556Srgrimes		}
9761556Srgrimes		flags |= EV_EXIT;
9771556Srgrimes	}
9781556Srgrimes
9791556Srgrimes	/* This is the child process if a fork occurred. */
9801556Srgrimes	/* Execute the command. */
9811556Srgrimes	if (cmdentry.cmdtype == CMDFUNCTION) {
98220425Ssteve#ifdef DEBUG
9831556Srgrimes		trputs("Shell function:  ");  trargs(argv);
98420425Ssteve#endif
9851556Srgrimes		saveparam = shellparam;
9861556Srgrimes		shellparam.malloc = 0;
98720425Ssteve		shellparam.reset = 1;
9881556Srgrimes		shellparam.nparam = argc - 1;
9891556Srgrimes		shellparam.p = argv + 1;
9901556Srgrimes		shellparam.optnext = NULL;
9911556Srgrimes		INTOFF;
9921556Srgrimes		savelocalvars = localvars;
9931556Srgrimes		localvars = NULL;
994196483Sjilles		reffunc(cmdentry.u.func);
995194765Sjilles		savehandler = handler;
9961556Srgrimes		if (setjmp(jmploc.loc)) {
997218306Sjilles			freeparam(&shellparam);
998218306Sjilles			shellparam = saveparam;
999220978Sjilles			popredir();
1000196483Sjilles			unreffunc(cmdentry.u.func);
10011556Srgrimes			poplocalvars();
10021556Srgrimes			localvars = savelocalvars;
1003201283Sjilles			funcnest--;
10041556Srgrimes			handler = savehandler;
10051556Srgrimes			longjmp(handler->loc, 1);
10061556Srgrimes		}
10071556Srgrimes		handler = &jmploc;
1008201283Sjilles		funcnest++;
1009204802Sjilles		redirect(cmd->ncmd.redirect, REDIR_PUSH);
1010199660Sjilles		INTON;
10111556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
10121556Srgrimes			mklocal(sp->text);
1013185231Sstefanf		exitstatus = oexitstatus;
1014220978Sjilles		evaltree(getfuncnode(cmdentry.u.func),
1015220978Sjilles		    flags & (EV_TESTED | EV_EXIT));
10161556Srgrimes		INTOFF;
1017196483Sjilles		unreffunc(cmdentry.u.func);
10181556Srgrimes		poplocalvars();
10191556Srgrimes		localvars = savelocalvars;
10201556Srgrimes		freeparam(&shellparam);
10211556Srgrimes		shellparam = saveparam;
10221556Srgrimes		handler = savehandler;
1023201283Sjilles		funcnest--;
10241556Srgrimes		popredir();
10251556Srgrimes		INTON;
10261556Srgrimes		if (evalskip == SKIPFUNC) {
10271556Srgrimes			evalskip = 0;
10281556Srgrimes			skipcount = 0;
10291556Srgrimes		}
1030217035Sjilles		if (jp)
10311556Srgrimes			exitshell(exitstatus);
10321556Srgrimes	} else if (cmdentry.cmdtype == CMDBUILTIN) {
103320425Ssteve#ifdef DEBUG
10341556Srgrimes		trputs("builtin command:  ");  trargs(argv);
103520425Ssteve#endif
10361556Srgrimes		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
10371556Srgrimes		if (flags == EV_BACKCMD) {
10381556Srgrimes			memout.nleft = 0;
10391556Srgrimes			memout.nextc = memout.buf;
10401556Srgrimes			memout.bufsize = 64;
10411556Srgrimes			mode |= REDIR_BACKQ;
10421556Srgrimes		}
10431556Srgrimes		savecmdname = commandname;
1044199647Sjilles		savetopfile = getcurrentfile();
10451556Srgrimes		cmdenviron = varlist.list;
10461556Srgrimes		e = -1;
1047194765Sjilles		savehandler = handler;
10481556Srgrimes		if (setjmp(jmploc.loc)) {
10491556Srgrimes			e = exception;
1050220978Sjilles			if (e == EXINT)
1051220978Sjilles				exitstatus = SIGINT+128;
1052220978Sjilles			else if (e != EXEXIT)
1053220978Sjilles				exitstatus = 2;
10541556Srgrimes			goto cmddone;
10551556Srgrimes		}
10561556Srgrimes		handler = &jmploc;
1057157601Sstefanf		redirect(cmd->ncmd.redirect, mode);
1058205138Sjilles		/*
1059205138Sjilles		 * If there is no command word, redirection errors should
1060205138Sjilles		 * not be fatal but assignment errors should.
1061205138Sjilles		 */
1062230625Sjilles		if (argc == 0)
1063205138Sjilles			cmdentry.special = 1;
1064216870Sjilles		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1065207678Sjilles		if (argc > 0)
1066207678Sjilles			bltinsetlocale();
10671556Srgrimes		commandname = argv[0];
10681556Srgrimes		argptr = argv + 1;
1069201053Sjilles		nextopt_optptr = NULL;		/* initialize nextopt */
1070193169Sstefanf		builtin_flags = flags;
10711556Srgrimes		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
10721556Srgrimes		flushall();
10731556Srgrimescmddone:
1074207678Sjilles		if (argc > 0)
1075207678Sjilles			bltinunsetlocale();
107660592Scracauer		cmdenviron = NULL;
10771556Srgrimes		out1 = &output;
10781556Srgrimes		out2 = &errout;
10791556Srgrimes		freestdout();
1080217035Sjilles		handler = savehandler;
1081218306Sjilles		commandname = savecmdname;
1082218306Sjilles		if (jp)
1083218306Sjilles			exitshell(exitstatus);
1084201366Sjilles		if (flags == EV_BACKCMD) {
1085201366Sjilles			backcmd->buf = memout.buf;
1086201366Sjilles			backcmd->nleft = memout.nextc - memout.buf;
1087201366Sjilles			memout.buf = NULL;
1088201366Sjilles		}
1089220978Sjilles		if (cmdentry.u.index != EXECCMD)
1090204801Sjilles			popredir();
10911556Srgrimes		if (e != -1) {
109220425Ssteve			if ((e != EXERROR && e != EXEXEC)
1093157601Sstefanf			    || cmdentry.special)
10941556Srgrimes				exraise(e);
1095199647Sjilles			popfilesupto(savetopfile);
1096201366Sjilles			if (flags != EV_BACKCMD)
1097201366Sjilles				FORCEINTON;
10981556Srgrimes		}
10991556Srgrimes	} else {
110020425Ssteve#ifdef DEBUG
11011556Srgrimes		trputs("normal command:  ");  trargs(argv);
110220425Ssteve#endif
11031556Srgrimes		redirect(cmd->ncmd.redirect, 0);
11041556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
11051556Srgrimes			setvareq(sp->text, VEXPORT|VSTACK);
11061556Srgrimes		envp = environment();
1107204800Sjilles		shellexec(argv, envp, path, cmdentry.u.index);
11081556Srgrimes		/*NOTREACHED*/
11091556Srgrimes	}
11101556Srgrimes	goto out;
11111556Srgrimes
11121556Srgrimesparent:	/* parent process gets here (if we forked) */
1113212214Sjilles	if (mode == FORK_FG) {	/* argument to fork */
11141556Srgrimes		INTOFF;
111545916Scracauer		exitstatus = waitforjob(jp, &realstatus);
11161556Srgrimes		INTON;
111745916Scracauer		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
111845266Scracauer			evalskip = SKIPBREAK;
111945266Scracauer			skipcount = loopnest;
112045266Scracauer		}
1121212214Sjilles	} else if (mode == FORK_NOJOB) {
11221556Srgrimes		backcmd->fd = pip[0];
11231556Srgrimes		close(pip[1]);
11241556Srgrimes		backcmd->jp = jp;
1125223282Sjilles	}
11261556Srgrimes
11271556Srgrimesout:
11281556Srgrimes	if (lastarg)
11291556Srgrimes		setvar("_", lastarg, 0);
113054884Scracauer	if (do_clearcmdentry)
1131218324Sjilles		clearcmdentry();
11321556Srgrimes	popstackmark(&smark);
11331556Srgrimes}
11341556Srgrimes
11351556Srgrimes
11361556Srgrimes
11371556Srgrimes/*
11381556Srgrimes * Search for a command.  This is called before we fork so that the
11391556Srgrimes * location of the command will be available in the parent as well as
11401556Srgrimes * the child.  The check for "goodname" is an overly conservative
11411556Srgrimes * check that the name will not be subject to expansion.
11421556Srgrimes */
11431556Srgrimes
1144213811Sobrienstatic void
114590111Simpprehash(union node *n)
114617987Speter{
11471556Srgrimes	struct cmdentry entry;
11481556Srgrimes
1149159633Sstefanf	if (n && n->type == NCMD && n->ncmd.args)
115017987Speter		if (goodname(n->ncmd.args->narg.text))
115117987Speter			find_command(n->ncmd.args->narg.text, &entry, 0,
115217987Speter				     pathval());
11531556Srgrimes}
11541556Srgrimes
11551556Srgrimes
11561556Srgrimes
11571556Srgrimes/*
11581556Srgrimes * Builtin commands.  Builtin commands whose functions are closely
11591556Srgrimes * tied to evaluation are implemented here.
11601556Srgrimes */
11611556Srgrimes
11621556Srgrimes/*
1163201431Sjilles * No command given, a bltin command with no arguments, or a bltin command
1164201431Sjilles * with an invalid name.
11651556Srgrimes */
11661556Srgrimes
116717987Speterint
1168201431Sjillesbltincmd(int argc, char **argv)
116917987Speter{
1170201431Sjilles	if (argc > 1) {
1171201431Sjilles		out2fmt_flush("%s: not found\n", argv[1]);
1172201431Sjilles		return 127;
1173201431Sjilles	}
117420425Ssteve	/*
117517987Speter	 * Preserve exitstatus of a previous possible redirection
117620425Ssteve	 * as POSIX mandates
117717987Speter	 */
11781556Srgrimes	return exitstatus;
11791556Srgrimes}
11801556Srgrimes
11811556Srgrimes
11821556Srgrimes/*
11831556Srgrimes * Handle break and continue commands.  Break, continue, and return are
11841556Srgrimes * all handled by setting the evalskip flag.  The evaluation routines
11851556Srgrimes * above all check this flag, and if it is set they start skipping
11861556Srgrimes * commands rather than executing them.  The variable skipcount is
11871556Srgrimes * the number of loops to break/continue, or the number of function
11881556Srgrimes * levels to return.  (The latter is always 1.)  It should probably
11891556Srgrimes * be an error to break out of more loops than exist, but it isn't
11901556Srgrimes * in the standard shell so we don't make it one here.
11911556Srgrimes */
11921556Srgrimes
119317987Speterint
119490111Simpbreakcmd(int argc, char **argv)
119517987Speter{
119620425Ssteve	int n = argc > 1 ? number(argv[1]) : 1;
11971556Srgrimes
11981556Srgrimes	if (n > loopnest)
11991556Srgrimes		n = loopnest;
12001556Srgrimes	if (n > 0) {
12011556Srgrimes		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
12021556Srgrimes		skipcount = n;
12031556Srgrimes	}
12041556Srgrimes	return 0;
12051556Srgrimes}
12061556Srgrimes
1207100437Stjr/*
1208100437Stjr * The `command' command.
1209100437Stjr */
1210100437Stjrint
1211100437Stjrcommandcmd(int argc, char **argv)
1212100437Stjr{
1213207783Sjilles	const char *path;
1214100437Stjr	int ch;
1215151810Sstefanf	int cmd = -1;
12161556Srgrimes
1217204800Sjilles	path = bltinlookup("PATH", 1);
1218100437Stjr
1219100437Stjr	optind = optreset = 1;
1220100663Stjr	opterr = 0;
1221151810Sstefanf	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1222100437Stjr		switch (ch) {
1223100437Stjr		case 'p':
1224207783Sjilles			path = _PATH_STDPATH;
1225100437Stjr			break;
1226151810Sstefanf		case 'v':
1227151810Sstefanf			cmd = TYPECMD_SMALLV;
1228151810Sstefanf			break;
1229151810Sstefanf		case 'V':
1230151810Sstefanf			cmd = TYPECMD_BIGV;
1231151810Sstefanf			break;
1232100437Stjr		case '?':
1233100437Stjr		default:
1234100437Stjr			error("unknown option: -%c", optopt);
1235100437Stjr		}
1236100437Stjr	}
1237100437Stjr	argc -= optind;
1238100437Stjr	argv += optind;
1239100437Stjr
1240151810Sstefanf	if (cmd != -1) {
1241151810Sstefanf		if (argc != 1)
1242151810Sstefanf			error("wrong number of arguments");
1243201343Sjilles		return typecmd_impl(2, argv - 1, cmd, path);
1244151810Sstefanf	}
1245204800Sjilles	if (argc != 0)
1246214538Sjilles		error("commandcmd bad call");
1247100437Stjr
1248100437Stjr	/*
1249100437Stjr	 * Do nothing successfully if no command was specified;
1250100437Stjr	 * ksh also does this.
1251100437Stjr	 */
1252204800Sjilles	return 0;
1253100437Stjr}
1254100437Stjr
1255100437Stjr
12561556Srgrimes/*
12571556Srgrimes * The return command.
12581556Srgrimes */
12591556Srgrimes
126017987Speterint
126190111Simpreturncmd(int argc, char **argv)
126217987Speter{
126320425Ssteve	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
12641556Srgrimes
12651556Srgrimes	if (funcnest) {
12661556Srgrimes		evalskip = SKIPFUNC;
12671556Srgrimes		skipcount = 1;
126820425Ssteve	} else {
126920425Ssteve		/* skip the rest of the file */
127020425Ssteve		evalskip = SKIPFILE;
127120425Ssteve		skipcount = 1;
12721556Srgrimes	}
12731556Srgrimes	return ret;
12741556Srgrimes}
12751556Srgrimes
12761556Srgrimes
127717987Speterint
127890111Simpfalsecmd(int argc __unused, char **argv __unused)
127917987Speter{
128017987Speter	return 1;
128117987Speter}
128217987Speter
128317987Speter
128417987Speterint
128590111Simptruecmd(int argc __unused, char **argv __unused)
128617987Speter{
12871556Srgrimes	return 0;
12881556Srgrimes}
12891556Srgrimes
12901556Srgrimes
129117987Speterint
129290111Simpexeccmd(int argc, char **argv)
129317987Speter{
1294208630Sjilles	/*
1295208630Sjilles	 * Because we have historically not supported any options,
1296208630Sjilles	 * only treat "--" specially.
1297208630Sjilles	 */
1298208630Sjilles	if (argc > 1 && strcmp(argv[1], "--") == 0)
1299208630Sjilles		argc--, argv++;
13001556Srgrimes	if (argc > 1) {
130117987Speter		struct strlist *sp;
130217987Speter
13031556Srgrimes		iflag = 0;		/* exit on error */
13041556Srgrimes		mflag = 0;
13051556Srgrimes		optschanged();
130617987Speter		for (sp = cmdenviron; sp ; sp = sp->next)
130717987Speter			setvareq(sp->text, VEXPORT|VSTACK);
13081556Srgrimes		shellexec(argv + 1, environment(), pathval(), 0);
13091556Srgrimes
13101556Srgrimes	}
13111556Srgrimes	return 0;
13121556Srgrimes}
1313153091Sstefanf
1314153091Sstefanf
1315153091Sstefanfint
1316153091Sstefanftimescmd(int argc __unused, char **argv __unused)
1317153091Sstefanf{
1318153091Sstefanf	struct rusage ru;
1319153091Sstefanf	long shumins, shsmins, chumins, chsmins;
1320153091Sstefanf	double shusecs, shssecs, chusecs, chssecs;
1321153091Sstefanf
1322153091Sstefanf	if (getrusage(RUSAGE_SELF, &ru) < 0)
1323153091Sstefanf		return 1;
1324153091Sstefanf	shumins = ru.ru_utime.tv_sec / 60;
1325153091Sstefanf	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1326153091Sstefanf	shsmins = ru.ru_stime.tv_sec / 60;
1327153091Sstefanf	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1328153091Sstefanf	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1329153091Sstefanf		return 1;
1330153091Sstefanf	chumins = ru.ru_utime.tv_sec / 60;
1331153091Sstefanf	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1332153091Sstefanf	chsmins = ru.ru_stime.tv_sec / 60;
1333153091Sstefanf	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1334153091Sstefanf	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1335153091Sstefanf	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1336153091Sstefanf	return 0;
1337153091Sstefanf}
1338