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 */
78230212Sdumbbellint skipcount;			/* number of levels to skip */
79253658Sjillesstatic 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);
92230161Sjillesstatic union node *evalcase(union node *);
93213811Sobrienstatic void evalsubshell(union node *, int);
94213811Sobrienstatic void evalredir(union node *, int);
95246288Sjillesstatic void exphere(union node *, struct arglist *);
96213811Sobrienstatic void expredir(union node *);
97213811Sobrienstatic void evalpipe(union node *);
98216778Sjillesstatic int is_valid_fast_cmdsubst(union node *n);
99213811Sobrienstatic void evalcommand(union node *, int, struct backcmd *);
100213811Sobrienstatic void prehash(union node *);
1011556Srgrimes
1021556Srgrimes
1031556Srgrimes/*
1041556Srgrimes * Called to reset things after an exception.
1051556Srgrimes */
1061556Srgrimes
107253650Sjillesvoid
108253650Sjillesreseteval(void)
109253650Sjilles{
1101556Srgrimes	evalskip = 0;
1111556Srgrimes	loopnest = 0;
1121556Srgrimes}
1131556Srgrimes
1141556Srgrimes
1151556Srgrimes/*
11646684Skris * The eval command.
1171556Srgrimes */
1181556Srgrimes
11917987Speterint
12090111Simpevalcmd(int argc, char **argv)
1211556Srgrimes{
1221556Srgrimes        char *p;
1231556Srgrimes        char *concat;
1241556Srgrimes        char **ap;
1251556Srgrimes
1261556Srgrimes        if (argc > 1) {
1271556Srgrimes                p = argv[1];
1281556Srgrimes                if (argc > 2) {
1291556Srgrimes                        STARTSTACKSTR(concat);
1301556Srgrimes                        ap = argv + 2;
1311556Srgrimes                        for (;;) {
132215783Sjilles                                STPUTS(p, concat);
1331556Srgrimes                                if ((p = *ap++) == NULL)
1341556Srgrimes                                        break;
1351556Srgrimes                                STPUTC(' ', concat);
1361556Srgrimes                        }
1371556Srgrimes                        STPUTC('\0', concat);
1381556Srgrimes                        p = grabstackstr(concat);
1391556Srgrimes                }
140223163Sjilles                evalstring(p, builtin_flags);
141210829Sjilles        } else
142210829Sjilles                exitstatus = 0;
1431556Srgrimes        return exitstatus;
1441556Srgrimes}
1451556Srgrimes
1461556Srgrimes
1471556Srgrimes/*
1481556Srgrimes * Execute a command or commands contained in a string.
1491556Srgrimes */
1501556Srgrimes
1511556Srgrimesvoid
152193169Sstefanfevalstring(char *s, int flags)
15390111Simp{
1541556Srgrimes	union node *n;
1551556Srgrimes	struct stackmark smark;
156194128Sjilles	int flags_exit;
157210829Sjilles	int any;
1581556Srgrimes
159194128Sjilles	flags_exit = flags & EV_EXIT;
160194128Sjilles	flags &= ~EV_EXIT;
161210829Sjilles	any = 0;
1621556Srgrimes	setstackmark(&smark);
1631556Srgrimes	setinputstring(s, 1);
1641556Srgrimes	while ((n = parsecmd(0)) != NEOF) {
165222676Sjilles		if (n != NULL && !nflag) {
166194128Sjilles			if (flags_exit && preadateof())
167194128Sjilles				evaltree(n, flags | EV_EXIT);
168194128Sjilles			else
169194128Sjilles				evaltree(n, flags);
170210829Sjilles			any = 1;
171194128Sjilles		}
1721556Srgrimes		popstackmark(&smark);
173247013Sjilles		setstackmark(&smark);
1741556Srgrimes	}
1751556Srgrimes	popfile();
1761556Srgrimes	popstackmark(&smark);
177210829Sjilles	if (!any)
178210829Sjilles		exitstatus = 0;
179194128Sjilles	if (flags_exit)
180220978Sjilles		exraise(EXEXIT);
1811556Srgrimes}
1821556Srgrimes
1831556Srgrimes
1841556Srgrimes/*
1851556Srgrimes * Evaluate a parse tree.  The value is left in the global variable
1861556Srgrimes * exitstatus.
1871556Srgrimes */
1881556Srgrimes
1891556Srgrimesvoid
19090111Simpevaltree(union node *n, int flags)
19117987Speter{
192149927Sstefanf	int do_etest;
193214599Sjilles	union node *next;
194245698Sjilles	struct stackmark smark;
195149927Sstefanf
196245698Sjilles	setstackmark(&smark);
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:
259230161Sjilles			next = evalcase(n);
260214600Sjilles			break;
261230161Sjilles		case NCLIST:
262230161Sjilles			next = n->nclist.body;
263230161Sjilles			break;
264230161Sjilles		case NCLISTFALLTHRU:
265230161Sjilles			if (n->nclist.body) {
266230161Sjilles				evaltree(n->nclist.body, flags & ~EV_EXIT);
267230161Sjilles				if (evalskip)
268230161Sjilles					goto out;
269230161Sjilles			}
270230161Sjilles			next = n->nclist.next;
271230161Sjilles			break;
272214600Sjilles		case NDEFUN:
273214600Sjilles			defun(n->narg.text, n->narg.next);
27420425Ssteve			exitstatus = 0;
275214600Sjilles			break;
276214600Sjilles		case NNOT:
277214600Sjilles			evaltree(n->nnot.com, EV_TESTED);
278249407Sjilles			if (evalskip)
279249407Sjilles				goto out;
280214600Sjilles			exitstatus = !exitstatus;
281214600Sjilles			break;
2821556Srgrimes
283214600Sjilles		case NPIPE:
284214600Sjilles			evalpipe(n);
285214600Sjilles			do_etest = !(flags & EV_TESTED);
286214600Sjilles			break;
287214600Sjilles		case NCMD:
288214600Sjilles			evalcommand(n, flags, (struct backcmd *)NULL);
289214600Sjilles			do_etest = !(flags & EV_TESTED);
290214600Sjilles			break;
291214600Sjilles		default:
292214600Sjilles			out1fmt("Node type = %d\n", n->type);
293214600Sjilles			flushout(&output);
294214600Sjilles			break;
295214600Sjilles		}
296214600Sjilles		n = next;
297245698Sjilles		popstackmark(&smark);
298247013Sjilles		setstackmark(&smark);
299214599Sjilles	} while (n != NULL);
3001556Srgrimesout:
301245698Sjilles	popstackmark(&smark);
302247206Sjilles	if (pendingsig)
3031556Srgrimes		dotrap();
304220978Sjilles	if (eflag && exitstatus != 0 && do_etest)
3051556Srgrimes		exitshell(exitstatus);
306220978Sjilles	if (flags & EV_EXIT)
307220978Sjilles		exraise(EXEXIT);
3081556Srgrimes}
3091556Srgrimes
3101556Srgrimes
311213811Sobrienstatic void
312149933Sstefanfevalloop(union node *n, int flags)
31317987Speter{
3141556Srgrimes	int status;
3151556Srgrimes
3161556Srgrimes	loopnest++;
3171556Srgrimes	status = 0;
3181556Srgrimes	for (;;) {
3191556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
3201556Srgrimes		if (evalskip) {
3211556Srgrimesskipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
3221556Srgrimes				evalskip = 0;
3231556Srgrimes				continue;
3241556Srgrimes			}
3251556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3261556Srgrimes				evalskip = 0;
327255215Sjilles			if (evalskip == SKIPRETURN)
328212475Sjilles				status = exitstatus;
3291556Srgrimes			break;
3301556Srgrimes		}
3311556Srgrimes		if (n->type == NWHILE) {
3321556Srgrimes			if (exitstatus != 0)
3331556Srgrimes				break;
3341556Srgrimes		} else {
3351556Srgrimes			if (exitstatus == 0)
3361556Srgrimes				break;
3371556Srgrimes		}
338149933Sstefanf		evaltree(n->nbinary.ch2, flags);
3391556Srgrimes		status = exitstatus;
3401556Srgrimes		if (evalskip)
3411556Srgrimes			goto skipping;
3421556Srgrimes	}
3431556Srgrimes	loopnest--;
3441556Srgrimes	exitstatus = status;
3451556Srgrimes}
3461556Srgrimes
3471556Srgrimes
3481556Srgrimes
349213811Sobrienstatic void
350149933Sstefanfevalfor(union node *n, int flags)
35117987Speter{
3521556Srgrimes	struct arglist arglist;
3531556Srgrimes	union node *argp;
3541556Srgrimes	struct strlist *sp;
355230463Sjilles	int status;
3561556Srgrimes
3571556Srgrimes	arglist.lastp = &arglist.list;
3581556Srgrimes	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
35917987Speter		oexitstatus = exitstatus;
3601556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3611556Srgrimes	}
3621556Srgrimes	*arglist.lastp = NULL;
3631556Srgrimes
3641556Srgrimes	loopnest++;
365230463Sjilles	status = 0;
3661556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
3671556Srgrimes		setvar(n->nfor.var, sp->text, 0);
368149933Sstefanf		evaltree(n->nfor.body, flags);
369230463Sjilles		status = exitstatus;
3701556Srgrimes		if (evalskip) {
3711556Srgrimes			if (evalskip == SKIPCONT && --skipcount <= 0) {
3721556Srgrimes				evalskip = 0;
3731556Srgrimes				continue;
3741556Srgrimes			}
3751556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3761556Srgrimes				evalskip = 0;
3771556Srgrimes			break;
3781556Srgrimes		}
3791556Srgrimes	}
3801556Srgrimes	loopnest--;
381230463Sjilles	exitstatus = status;
3821556Srgrimes}
3831556Srgrimes
3841556Srgrimes
385230161Sjilles/*
386230161Sjilles * Evaluate a case statement, returning the selected tree.
387230161Sjilles *
388230161Sjilles * The exit status needs care to get right.
389230161Sjilles */
3901556Srgrimes
391228013Sjillesstatic union node *
392230161Sjillesevalcase(union node *n)
39317987Speter{
3941556Srgrimes	union node *cp;
3951556Srgrimes	union node *patp;
3961556Srgrimes	struct arglist arglist;
3971556Srgrimes
3981556Srgrimes	arglist.lastp = &arglist.list;
39917987Speter	oexitstatus = exitstatus;
4001556Srgrimes	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
401228013Sjilles	for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) {
4021556Srgrimes		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
4031556Srgrimes			if (casematch(patp, arglist.list->text)) {
404223186Sjilles				while (cp->nclist.next &&
405230161Sjilles				    cp->type == NCLISTFALLTHRU &&
406230161Sjilles				    cp->nclist.body == NULL)
407223186Sjilles					cp = cp->nclist.next;
408230161Sjilles				if (cp->nclist.next &&
409230161Sjilles				    cp->type == NCLISTFALLTHRU)
410230161Sjilles					return (cp);
411230154Sjilles				if (cp->nclist.body == NULL)
412230154Sjilles					exitstatus = 0;
413228013Sjilles				return (cp->nclist.body);
4141556Srgrimes			}
4151556Srgrimes		}
4161556Srgrimes	}
417230154Sjilles	exitstatus = 0;
418228013Sjilles	return (NULL);
4191556Srgrimes}
4201556Srgrimes
4211556Srgrimes
4221556Srgrimes
4231556Srgrimes/*
4241556Srgrimes * Kick off a subshell to evaluate a tree.
4251556Srgrimes */
4261556Srgrimes
427213811Sobrienstatic void
42890111Simpevalsubshell(union node *n, int flags)
42917987Speter{
4301556Srgrimes	struct job *jp;
4311556Srgrimes	int backgnd = (n->type == NBACKGND);
4321556Srgrimes
433222716Sjilles	oexitstatus = exitstatus;
4341556Srgrimes	expredir(n->nredir.redirect);
435194774Sjilles	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
436194774Sjilles			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
4371556Srgrimes		if (backgnd)
4381556Srgrimes			flags &=~ EV_TESTED;
4391556Srgrimes		redirect(n->nredir.redirect, 0);
4401556Srgrimes		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
441201053Sjilles	} else if (! backgnd) {
4421556Srgrimes		INTOFF;
44345916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
4441556Srgrimes		INTON;
445221027Sjilles	} else
446221027Sjilles		exitstatus = 0;
4471556Srgrimes}
4481556Srgrimes
4491556Srgrimes
450205154Sjilles/*
451205154Sjilles * Evaluate a redirected compound command.
452205154Sjilles */
4531556Srgrimes
454213811Sobrienstatic void
455205154Sjillesevalredir(union node *n, int flags)
456205154Sjilles{
457205154Sjilles	struct jmploc jmploc;
458205154Sjilles	struct jmploc *savehandler;
459205154Sjilles	volatile int in_redirect = 1;
460205154Sjilles
461222716Sjilles	oexitstatus = exitstatus;
462205154Sjilles	expredir(n->nredir.redirect);
463205154Sjilles	savehandler = handler;
464205154Sjilles	if (setjmp(jmploc.loc)) {
465205154Sjilles		int e;
466205154Sjilles
467205154Sjilles		handler = savehandler;
468205154Sjilles		e = exception;
469220978Sjilles		popredir();
470205154Sjilles		if (e == EXERROR || e == EXEXEC) {
471205154Sjilles			if (in_redirect) {
472205154Sjilles				exitstatus = 2;
473205154Sjilles				return;
474205154Sjilles			}
475205154Sjilles		}
476205154Sjilles		longjmp(handler->loc, 1);
477205154Sjilles	} else {
478205154Sjilles		INTOFF;
479205154Sjilles		handler = &jmploc;
480205154Sjilles		redirect(n->nredir.redirect, REDIR_PUSH);
481205154Sjilles		in_redirect = 0;
482205154Sjilles		INTON;
483205154Sjilles		evaltree(n->nredir.n, flags);
484205154Sjilles	}
485205154Sjilles	INTOFF;
486205154Sjilles	handler = savehandler;
487205154Sjilles	popredir();
488205154Sjilles	INTON;
489205154Sjilles}
490205154Sjilles
491205154Sjilles
492246288Sjillesstatic void
493246288Sjillesexphere(union node *redir, struct arglist *fn)
494246288Sjilles{
495246288Sjilles	struct jmploc jmploc;
496246288Sjilles	struct jmploc *savehandler;
497246288Sjilles	struct localvar *savelocalvars;
498246288Sjilles	int need_longjmp = 0;
499246288Sjilles
500246288Sjilles	redir->nhere.expdoc = nullstr;
501246288Sjilles	savelocalvars = localvars;
502246288Sjilles	localvars = NULL;
503246288Sjilles	forcelocal++;
504246288Sjilles	savehandler = handler;
505246288Sjilles	if (setjmp(jmploc.loc))
506246288Sjilles		need_longjmp = exception != EXERROR && exception != EXEXEC;
507246288Sjilles	else {
508246288Sjilles		handler = &jmploc;
509246288Sjilles		expandarg(redir->nhere.doc, fn, 0);
510246288Sjilles		redir->nhere.expdoc = fn->list->text;
511246288Sjilles		INTOFF;
512246288Sjilles	}
513246288Sjilles	handler = savehandler;
514246288Sjilles	forcelocal--;
515246288Sjilles	poplocalvars();
516246288Sjilles	localvars = savelocalvars;
517246288Sjilles	if (need_longjmp)
518246288Sjilles		longjmp(handler->loc, 1);
519246288Sjilles	INTON;
520246288Sjilles}
521246288Sjilles
522246288Sjilles
5231556Srgrimes/*
5241556Srgrimes * Compute the names of the files in a redirection list.
5251556Srgrimes */
5261556Srgrimes
527213811Sobrienstatic void
52890111Simpexpredir(union node *n)
52917987Speter{
53025222Ssteve	union node *redir;
5311556Srgrimes
5321556Srgrimes	for (redir = n ; redir ; redir = redir->nfile.next) {
53317987Speter		struct arglist fn;
53417987Speter		fn.lastp = &fn.list;
53517987Speter		switch (redir->type) {
53617987Speter		case NFROM:
53717987Speter		case NTO:
53866612Sbrian		case NFROMTO:
53917987Speter		case NAPPEND:
54096922Stjr		case NCLOBBER:
5411556Srgrimes			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
5421556Srgrimes			redir->nfile.expfname = fn.list->text;
54317987Speter			break;
54417987Speter		case NFROMFD:
54517987Speter		case NTOFD:
54617987Speter			if (redir->ndup.vname) {
547181017Sstefanf				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
54817987Speter				fixredir(redir, fn.list->text, 1);
54917987Speter			}
55017987Speter			break;
551246288Sjilles		case NXHERE:
552246288Sjilles			exphere(redir, &fn);
553246288Sjilles			break;
5541556Srgrimes		}
5551556Srgrimes	}
5561556Srgrimes}
5571556Srgrimes
5581556Srgrimes
5591556Srgrimes
5601556Srgrimes/*
5611556Srgrimes * Evaluate a pipeline.  All the processes in the pipeline are children
5621556Srgrimes * of the process creating the pipeline.  (This differs from some versions
5631556Srgrimes * of the shell, which make the last process in a pipeline the parent
5641556Srgrimes * of all the rest.)
5651556Srgrimes */
5661556Srgrimes
567213811Sobrienstatic void
56890111Simpevalpipe(union node *n)
56917987Speter{
5701556Srgrimes	struct job *jp;
5711556Srgrimes	struct nodelist *lp;
5721556Srgrimes	int pipelen;
5731556Srgrimes	int prevfd;
5741556Srgrimes	int pip[2];
5751556Srgrimes
576149802Sstefanf	TRACE(("evalpipe(%p) called\n", (void *)n));
5771556Srgrimes	pipelen = 0;
5781556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
5791556Srgrimes		pipelen++;
5801556Srgrimes	INTOFF;
5811556Srgrimes	jp = makejob(n, pipelen);
5821556Srgrimes	prevfd = -1;
5831556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
5841556Srgrimes		prehash(lp->n);
5851556Srgrimes		pip[1] = -1;
5861556Srgrimes		if (lp->next) {
5871556Srgrimes			if (pipe(pip) < 0) {
588252359Sjilles				if (prevfd >= 0)
589252359Sjilles					close(prevfd);
59053891Scracauer				error("Pipe call failed: %s", strerror(errno));
5911556Srgrimes			}
5921556Srgrimes		}
5931556Srgrimes		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
5941556Srgrimes			INTON;
5951556Srgrimes			if (prevfd > 0) {
596124780Sdes				dup2(prevfd, 0);
5971556Srgrimes				close(prevfd);
5981556Srgrimes			}
5991556Srgrimes			if (pip[1] >= 0) {
60053282Scracauer				if (!(prevfd >= 0 && pip[0] == 0))
60152900Scracauer					close(pip[0]);
6021556Srgrimes				if (pip[1] != 1) {
603124780Sdes					dup2(pip[1], 1);
6041556Srgrimes					close(pip[1]);
6051556Srgrimes				}
6061556Srgrimes			}
6071556Srgrimes			evaltree(lp->n, EV_EXIT);
6081556Srgrimes		}
6091556Srgrimes		if (prevfd >= 0)
6101556Srgrimes			close(prevfd);
6111556Srgrimes		prevfd = pip[0];
612221970Sjilles		if (pip[1] != -1)
613221970Sjilles			close(pip[1]);
6141556Srgrimes	}
6151556Srgrimes	INTON;
6161556Srgrimes	if (n->npipe.backgnd == 0) {
6171556Srgrimes		INTOFF;
61845916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
6191556Srgrimes		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
6201556Srgrimes		INTON;
621221027Sjilles	} else
622221027Sjilles		exitstatus = 0;
6231556Srgrimes}
6241556Srgrimes
6251556Srgrimes
6261556Srgrimes
627216778Sjillesstatic int
628216778Sjillesis_valid_fast_cmdsubst(union node *n)
629216778Sjilles{
630216778Sjilles
631223024Sjilles	return (n->type == NCMD);
632216778Sjilles}
633216778Sjilles
6341556Srgrimes/*
6351556Srgrimes * Execute a command inside back quotes.  If it's a builtin command, we
6361556Srgrimes * want to save its output in a block obtained from malloc.  Otherwise
6371556Srgrimes * we fork off a subprocess and get the output of the command via a pipe.
6381556Srgrimes * Should be called with interrupts off.
6391556Srgrimes */
6401556Srgrimes
6411556Srgrimesvoid
64290111Simpevalbackcmd(union node *n, struct backcmd *result)
64317987Speter{
6441556Srgrimes	int pip[2];
6451556Srgrimes	struct job *jp;
646245698Sjilles	struct stackmark smark;
647216761Sjilles	struct jmploc jmploc;
648216761Sjilles	struct jmploc *savehandler;
649223024Sjilles	struct localvar *savelocalvars;
6501556Srgrimes
6511556Srgrimes	setstackmark(&smark);
6521556Srgrimes	result->fd = -1;
6531556Srgrimes	result->buf = NULL;
6541556Srgrimes	result->nleft = 0;
6551556Srgrimes	result->jp = NULL;
65617987Speter	if (n == NULL) {
65717987Speter		exitstatus = 0;
6581556Srgrimes		goto out;
65917987Speter	}
660245422Sjilles	exitstatus = oexitstatus;
661216778Sjilles	if (is_valid_fast_cmdsubst(n)) {
662223024Sjilles		savelocalvars = localvars;
663223024Sjilles		localvars = NULL;
664223024Sjilles		forcelocal++;
665216761Sjilles		savehandler = handler;
666216761Sjilles		if (setjmp(jmploc.loc)) {
667216761Sjilles			if (exception == EXERROR || exception == EXEXEC)
668216761Sjilles				exitstatus = 2;
669216761Sjilles			else if (exception != 0) {
670216761Sjilles				handler = savehandler;
671223024Sjilles				forcelocal--;
672223024Sjilles				poplocalvars();
673223024Sjilles				localvars = savelocalvars;
674216761Sjilles				longjmp(handler->loc, 1);
675216761Sjilles			}
676216761Sjilles		} else {
677216761Sjilles			handler = &jmploc;
678216761Sjilles			evalcommand(n, EV_BACKCMD, result);
679216761Sjilles		}
680216761Sjilles		handler = savehandler;
681223024Sjilles		forcelocal--;
682223024Sjilles		poplocalvars();
683223024Sjilles		localvars = savelocalvars;
6841556Srgrimes	} else {
6851556Srgrimes		if (pipe(pip) < 0)
68653891Scracauer			error("Pipe call failed: %s", strerror(errno));
6871556Srgrimes		jp = makejob(n, 1);
6881556Srgrimes		if (forkshell(jp, n, FORK_NOJOB) == 0) {
6891556Srgrimes			FORCEINTON;
6901556Srgrimes			close(pip[0]);
6911556Srgrimes			if (pip[1] != 1) {
692124780Sdes				dup2(pip[1], 1);
6931556Srgrimes				close(pip[1]);
6941556Srgrimes			}
6951556Srgrimes			evaltree(n, EV_EXIT);
6961556Srgrimes		}
6971556Srgrimes		close(pip[1]);
6981556Srgrimes		result->fd = pip[0];
6991556Srgrimes		result->jp = jp;
7001556Srgrimes	}
7011556Srgrimesout:
7021556Srgrimes	popstackmark(&smark);
703109627Stjr	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
7041556Srgrimes		result->fd, result->buf, result->nleft, result->jp));
7051556Srgrimes}
7061556Srgrimes
707238468Sjillesstatic int
708238468Sjillesmustexpandto(const char *argtext, const char *mask)
709238468Sjilles{
710238468Sjilles	for (;;) {
711238468Sjilles		if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) {
712238468Sjilles			argtext++;
713238468Sjilles			continue;
714238468Sjilles		}
715238468Sjilles		if (*argtext == CTLESC)
716238468Sjilles			argtext++;
717238468Sjilles		else if (BASESYNTAX[(int)*argtext] == CCTL)
718238468Sjilles			return (0);
719238468Sjilles		if (*argtext != *mask)
720238468Sjilles			return (0);
721238468Sjilles		if (*argtext == '\0')
722238468Sjilles			return (1);
723238468Sjilles		argtext++;
724238468Sjilles		mask++;
725238468Sjilles	}
726238468Sjilles}
727238468Sjilles
728238468Sjillesstatic int
729238468Sjillesisdeclarationcmd(struct narg *arg)
730238468Sjilles{
731238468Sjilles	int have_command = 0;
732238468Sjilles
733238468Sjilles	if (arg == NULL)
734238468Sjilles		return (0);
735238468Sjilles	while (mustexpandto(arg->text, "command")) {
736238468Sjilles		have_command = 1;
737238468Sjilles		arg = &arg->next->narg;
738238468Sjilles		if (arg == NULL)
739238468Sjilles			return (0);
740238468Sjilles		/*
741238468Sjilles		 * To also allow "command -p" and "command --" as part of
742238468Sjilles		 * a declaration command, add code here.
743238468Sjilles		 * We do not do this, as ksh does not do it either and it
744238468Sjilles		 * is not required by POSIX.
745238468Sjilles		 */
746238468Sjilles	}
747238468Sjilles	return (mustexpandto(arg->text, "export") ||
748238468Sjilles	    mustexpandto(arg->text, "readonly") ||
749238468Sjilles	    (mustexpandto(arg->text, "local") &&
750238468Sjilles		(have_command || !isfunc("local"))));
751238468Sjilles}
752238468Sjilles
753262951Sjmmvstatic void
754262951Sjmmvxtracecommand(struct arglist *varlist, struct arglist *arglist)
755262951Sjmmv{
756262951Sjmmv	struct strlist *sp;
757262951Sjmmv	char sep = 0;
758262951Sjmmv	const char *p, *ps4;
759262951Sjmmv
760262951Sjmmv	ps4 = expandstr(ps4val());
761262951Sjmmv	out2str(ps4 != NULL ? ps4 : ps4val());
762262951Sjmmv	for (sp = varlist->list ; sp ; sp = sp->next) {
763262951Sjmmv		if (sep != 0)
764262951Sjmmv			out2c(' ');
765262951Sjmmv		p = strchr(sp->text, '=');
766262951Sjmmv		if (p != NULL) {
767262951Sjmmv			p++;
768262951Sjmmv			outbin(sp->text, p - sp->text, out2);
769262951Sjmmv			out2qstr(p);
770262951Sjmmv		} else
771262951Sjmmv			out2qstr(sp->text);
772262951Sjmmv		sep = ' ';
773262951Sjmmv	}
774262951Sjmmv	for (sp = arglist->list ; sp ; sp = sp->next) {
775262951Sjmmv		if (sep != 0)
776262951Sjmmv			out2c(' ');
777262951Sjmmv		/* Disambiguate command looking like assignment. */
778262951Sjmmv		if (sp == arglist->list &&
779262951Sjmmv				strchr(sp->text, '=') != NULL &&
780262951Sjmmv				strchr(sp->text, '\'') == NULL) {
781262951Sjmmv			out2c('\'');
782262951Sjmmv			out2str(sp->text);
783262951Sjmmv			out2c('\'');
784262951Sjmmv		} else
785262951Sjmmv			out2qstr(sp->text);
786262951Sjmmv		sep = ' ';
787262951Sjmmv	}
788262951Sjmmv	out2c('\n');
789262951Sjmmv	flushout(&errout);
790262951Sjmmv}
791262951Sjmmv
792216826Sjilles/*
793216826Sjilles * Check if a builtin can safely be executed in the same process,
794216826Sjilles * even though it should be in a subshell (command substitution).
795216826Sjilles * Note that jobid, jobs, times and trap can show information not
796216826Sjilles * available in a child process; this is deliberate.
797216826Sjilles * The arguments should already have been expanded.
798216826Sjilles */
799216826Sjillesstatic int
800216826Sjillessafe_builtin(int idx, int argc, char **argv)
801216826Sjilles{
802216826Sjilles	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
803216826Sjilles	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
804216826Sjilles	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
805216826Sjilles	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
806216826Sjilles	    idx == TYPECMD)
807216826Sjilles		return (1);
808216826Sjilles	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
809216826Sjilles	    idx == UMASKCMD)
810216826Sjilles		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
811216826Sjilles	if (idx == SETCMD)
812216826Sjilles		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
813216826Sjilles		    argv[1][0] == '+') && argv[1][1] == 'o' &&
814216826Sjilles		    argv[1][2] == '\0'));
815216826Sjilles	return (0);
816216826Sjilles}
8171556Srgrimes
8181556Srgrimes/*
8191556Srgrimes * Execute a simple command.
820217035Sjilles * Note: This may or may not return if (flags & EV_EXIT).
8211556Srgrimes */
8221556Srgrimes
823213811Sobrienstatic void
82490111Simpevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
82517987Speter{
8261556Srgrimes	union node *argp;
8271556Srgrimes	struct arglist arglist;
8281556Srgrimes	struct arglist varlist;
8291556Srgrimes	char **argv;
8301556Srgrimes	int argc;
8311556Srgrimes	char **envp;
8321556Srgrimes	int varflag;
8331556Srgrimes	struct strlist *sp;
8341556Srgrimes	int mode;
8351556Srgrimes	int pip[2];
8361556Srgrimes	struct cmdentry cmdentry;
8371556Srgrimes	struct job *jp;
8381556Srgrimes	struct jmploc jmploc;
839194765Sjilles	struct jmploc *savehandler;
840194765Sjilles	char *savecmdname;
841194765Sjilles	struct shparam saveparam;
842194765Sjilles	struct localvar *savelocalvars;
843199647Sjilles	struct parsefile *savetopfile;
8441556Srgrimes	volatile int e;
8451556Srgrimes	char *lastarg;
84645916Scracauer	int realstatus;
84754884Scracauer	int do_clearcmdentry;
848211287Sjilles	const char *path = pathval();
8491556Srgrimes
8501556Srgrimes	/* First expand the arguments. */
851149802Sstefanf	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
8521556Srgrimes	arglist.lastp = &arglist.list;
8531556Srgrimes	varlist.lastp = &varlist.list;
8541556Srgrimes	varflag = 1;
855217035Sjilles	jp = NULL;
85654884Scracauer	do_clearcmdentry = 0;
85717987Speter	oexitstatus = exitstatus;
85817987Speter	exitstatus = 0;
8591556Srgrimes	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
860222165Sjilles		if (varflag && isassignment(argp->narg.text)) {
861238468Sjilles			expandarg(argp, varflag == 1 ? &varlist : &arglist,
862238468Sjilles			    EXP_VARTILDE);
863222165Sjilles			continue;
864238468Sjilles		} else if (varflag == 1)
865238468Sjilles			varflag = isdeclarationcmd(&argp->narg) ? 2 : 0;
8661556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8671556Srgrimes	}
8681556Srgrimes	*arglist.lastp = NULL;
8691556Srgrimes	*varlist.lastp = NULL;
8701556Srgrimes	expredir(cmd->ncmd.redirect);
8711556Srgrimes	argc = 0;
8721556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next)
8731556Srgrimes		argc++;
874218306Sjilles	/* Add one slot at the beginning for tryexec(). */
875218306Sjilles	argv = stalloc(sizeof (char *) * (argc + 2));
876218306Sjilles	argv++;
8771556Srgrimes
8781556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
8791556Srgrimes		TRACE(("evalcommand arg: %s\n", sp->text));
8801556Srgrimes		*argv++ = sp->text;
8811556Srgrimes	}
8821556Srgrimes	*argv = NULL;
8831556Srgrimes	lastarg = NULL;
8841556Srgrimes	if (iflag && funcnest == 0 && argc > 0)
8851556Srgrimes		lastarg = argv[-1];
8861556Srgrimes	argv -= argc;
8871556Srgrimes
8881556Srgrimes	/* Print the command if xflag is set. */
889262951Sjmmv	if (xflag)
890262951Sjmmv		xtracecommand(&varlist, &arglist);
8911556Srgrimes
8921556Srgrimes	/* Now locate the command. */
8931556Srgrimes	if (argc == 0) {
894157601Sstefanf		/* Variable assignment(s) without command */
8951556Srgrimes		cmdentry.cmdtype = CMDBUILTIN;
8961556Srgrimes		cmdentry.u.index = BLTINCMD;
897205138Sjilles		cmdentry.special = 0;
8981556Srgrimes	} else {
89917987Speter		static const char PATH[] = "PATH=";
900204800Sjilles		int cmd_flags = 0, bltinonly = 0;
90117987Speter
90217987Speter		/*
90317987Speter		 * Modify the command lookup path, if a PATH= assignment
90417987Speter		 * is present
90517987Speter		 */
90617987Speter		for (sp = varlist.list ; sp ; sp = sp->next)
90754884Scracauer			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
90817987Speter				path = sp->text + sizeof(PATH) - 1;
909155301Sschweikh				/*
91054884Scracauer				 * On `PATH=... command`, we need to make
91154884Scracauer				 * sure that the command isn't using the
91254884Scracauer				 * non-updated hash table of the outer PATH
913155301Sschweikh				 * setting and we need to make sure that
91454884Scracauer				 * the hash table isn't filled with items
91554884Scracauer				 * from the temporary setting.
91654884Scracauer				 *
917155301Sschweikh				 * It would be better to forbit using and
91854884Scracauer				 * updating the table while this command
91954884Scracauer				 * runs, by the command finding mechanism
92054884Scracauer				 * is heavily integrated with hash handling,
92154884Scracauer				 * so we just delete the hash before and after
92254884Scracauer				 * the command runs. Partly deleting like
92354884Scracauer				 * changepatch() does doesn't seem worth the
92454884Scracauer				 * bookinging effort, since most such runs add
925123996Smaxim				 * directories in front of the new PATH.
92654884Scracauer				 */
927218324Sjilles				clearcmdentry();
92854884Scracauer				do_clearcmdentry = 1;
92954884Scracauer			}
93017987Speter
931204800Sjilles		for (;;) {
932204800Sjilles			if (bltinonly) {
933204800Sjilles				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
934204800Sjilles				if (cmdentry.u.index < 0) {
935201431Sjilles					cmdentry.u.index = BLTINCMD;
936201431Sjilles					argv--;
937201431Sjilles					argc++;
938201431Sjilles					break;
9391556Srgrimes				}
940204800Sjilles			} else
941204800Sjilles				find_command(argv[0], &cmdentry, cmd_flags, path);
942204800Sjilles			/* implement the bltin and command builtins here */
943204800Sjilles			if (cmdentry.cmdtype != CMDBUILTIN)
944204800Sjilles				break;
945204800Sjilles			if (cmdentry.u.index == BLTINCMD) {
946204800Sjilles				if (argc == 1)
9471556Srgrimes					break;
948204800Sjilles				argv++;
949204800Sjilles				argc--;
950204800Sjilles				bltinonly = 1;
951204800Sjilles			} else if (cmdentry.u.index == COMMANDCMD) {
952204800Sjilles				if (argc == 1)
953204800Sjilles					break;
954204800Sjilles				if (!strcmp(argv[1], "-p")) {
955204800Sjilles					if (argc == 2)
956204800Sjilles						break;
957204800Sjilles					if (argv[2][0] == '-') {
958204800Sjilles						if (strcmp(argv[2], "--"))
959204800Sjilles							break;
960204800Sjilles						if (argc == 3)
961204800Sjilles							break;
962204800Sjilles						argv += 3;
963204800Sjilles						argc -= 3;
964204800Sjilles					} else {
965204800Sjilles						argv += 2;
966204800Sjilles						argc -= 2;
967204800Sjilles					}
968204800Sjilles					path = _PATH_STDPATH;
969218324Sjilles					clearcmdentry();
970204800Sjilles					do_clearcmdentry = 1;
971204800Sjilles				} else if (!strcmp(argv[1], "--")) {
972204800Sjilles					if (argc == 2)
973204800Sjilles						break;
974204800Sjilles					argv += 2;
975204800Sjilles					argc -= 2;
976204800Sjilles				} else if (argv[1][0] == '-')
977204800Sjilles					break;
978204800Sjilles				else {
979204800Sjilles					argv++;
980204800Sjilles					argc--;
981204800Sjilles				}
982204800Sjilles				cmd_flags |= DO_NOFUNC;
983204800Sjilles				bltinonly = 0;
984204800Sjilles			} else
985204800Sjilles				break;
9861556Srgrimes		}
987204800Sjilles		/*
988204800Sjilles		 * Special builtins lose their special properties when
989204800Sjilles		 * called via 'command'.
990204800Sjilles		 */
991204800Sjilles		if (cmd_flags & DO_NOFUNC)
992204800Sjilles			cmdentry.special = 0;
9931556Srgrimes	}
9941556Srgrimes
9951556Srgrimes	/* Fork off a child process if necessary. */
996223282Sjilles	if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
997194127Sjilles	    && ((flags & EV_EXIT) == 0 || have_traps()))
99817987Speter	 || ((flags & EV_BACKCMD) != 0
999216826Sjilles	    && (cmdentry.cmdtype != CMDBUILTIN ||
1000216826Sjilles		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
10011556Srgrimes		jp = makejob(cmd, 1);
1002223282Sjilles		mode = FORK_FG;
10031556Srgrimes		if (flags & EV_BACKCMD) {
10041556Srgrimes			mode = FORK_NOJOB;
10051556Srgrimes			if (pipe(pip) < 0)
100653891Scracauer				error("Pipe call failed: %s", strerror(errno));
10071556Srgrimes		}
1008230998Sjilles		if (cmdentry.cmdtype == CMDNORMAL &&
1009230998Sjilles		    cmd->ncmd.redirect == NULL &&
1010230998Sjilles		    varlist.list == NULL &&
1011230998Sjilles		    (mode == FORK_FG || mode == FORK_NOJOB) &&
1012230998Sjilles		    !disvforkset() && !iflag && !mflag) {
1013230998Sjilles			vforkexecshell(jp, argv, environment(), path,
1014230998Sjilles			    cmdentry.u.index, flags & EV_BACKCMD ? pip : NULL);
1015230998Sjilles			goto parent;
1016230998Sjilles		}
10171556Srgrimes		if (forkshell(jp, cmd, mode) != 0)
10181556Srgrimes			goto parent;	/* at end of routine */
10191556Srgrimes		if (flags & EV_BACKCMD) {
10201556Srgrimes			FORCEINTON;
10211556Srgrimes			close(pip[0]);
10221556Srgrimes			if (pip[1] != 1) {
1023124780Sdes				dup2(pip[1], 1);
10241556Srgrimes				close(pip[1]);
10251556Srgrimes			}
1026223163Sjilles			flags &= ~EV_BACKCMD;
10271556Srgrimes		}
10281556Srgrimes		flags |= EV_EXIT;
10291556Srgrimes	}
10301556Srgrimes
10311556Srgrimes	/* This is the child process if a fork occurred. */
10321556Srgrimes	/* Execute the command. */
10331556Srgrimes	if (cmdentry.cmdtype == CMDFUNCTION) {
103420425Ssteve#ifdef DEBUG
10351556Srgrimes		trputs("Shell function:  ");  trargs(argv);
103620425Ssteve#endif
10371556Srgrimes		saveparam = shellparam;
10381556Srgrimes		shellparam.malloc = 0;
103920425Ssteve		shellparam.reset = 1;
10401556Srgrimes		shellparam.nparam = argc - 1;
10411556Srgrimes		shellparam.p = argv + 1;
10421556Srgrimes		shellparam.optnext = NULL;
10431556Srgrimes		INTOFF;
10441556Srgrimes		savelocalvars = localvars;
10451556Srgrimes		localvars = NULL;
1046196483Sjilles		reffunc(cmdentry.u.func);
1047194765Sjilles		savehandler = handler;
10481556Srgrimes		if (setjmp(jmploc.loc)) {
1049218306Sjilles			freeparam(&shellparam);
1050218306Sjilles			shellparam = saveparam;
1051220978Sjilles			popredir();
1052196483Sjilles			unreffunc(cmdentry.u.func);
10531556Srgrimes			poplocalvars();
10541556Srgrimes			localvars = savelocalvars;
1055201283Sjilles			funcnest--;
10561556Srgrimes			handler = savehandler;
10571556Srgrimes			longjmp(handler->loc, 1);
10581556Srgrimes		}
10591556Srgrimes		handler = &jmploc;
1060201283Sjilles		funcnest++;
1061204802Sjilles		redirect(cmd->ncmd.redirect, REDIR_PUSH);
1062199660Sjilles		INTON;
10631556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
10641556Srgrimes			mklocal(sp->text);
1065185231Sstefanf		exitstatus = oexitstatus;
1066220978Sjilles		evaltree(getfuncnode(cmdentry.u.func),
1067220978Sjilles		    flags & (EV_TESTED | EV_EXIT));
10681556Srgrimes		INTOFF;
1069196483Sjilles		unreffunc(cmdentry.u.func);
10701556Srgrimes		poplocalvars();
10711556Srgrimes		localvars = savelocalvars;
10721556Srgrimes		freeparam(&shellparam);
10731556Srgrimes		shellparam = saveparam;
10741556Srgrimes		handler = savehandler;
1075201283Sjilles		funcnest--;
10761556Srgrimes		popredir();
10771556Srgrimes		INTON;
1078255215Sjilles		if (evalskip == SKIPRETURN) {
10791556Srgrimes			evalskip = 0;
10801556Srgrimes			skipcount = 0;
10811556Srgrimes		}
1082217035Sjilles		if (jp)
10831556Srgrimes			exitshell(exitstatus);
10841556Srgrimes	} else if (cmdentry.cmdtype == CMDBUILTIN) {
108520425Ssteve#ifdef DEBUG
10861556Srgrimes		trputs("builtin command:  ");  trargs(argv);
108720425Ssteve#endif
10881556Srgrimes		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
10891556Srgrimes		if (flags == EV_BACKCMD) {
10901556Srgrimes			memout.nleft = 0;
10911556Srgrimes			memout.nextc = memout.buf;
10921556Srgrimes			memout.bufsize = 64;
10931556Srgrimes			mode |= REDIR_BACKQ;
10941556Srgrimes		}
10951556Srgrimes		savecmdname = commandname;
1096199647Sjilles		savetopfile = getcurrentfile();
10971556Srgrimes		cmdenviron = varlist.list;
10981556Srgrimes		e = -1;
1099194765Sjilles		savehandler = handler;
11001556Srgrimes		if (setjmp(jmploc.loc)) {
11011556Srgrimes			e = exception;
1102220978Sjilles			if (e == EXINT)
1103220978Sjilles				exitstatus = SIGINT+128;
1104220978Sjilles			else if (e != EXEXIT)
1105220978Sjilles				exitstatus = 2;
11061556Srgrimes			goto cmddone;
11071556Srgrimes		}
11081556Srgrimes		handler = &jmploc;
1109157601Sstefanf		redirect(cmd->ncmd.redirect, mode);
1110244162Sjilles		outclearerror(out1);
1111205138Sjilles		/*
1112205138Sjilles		 * If there is no command word, redirection errors should
1113205138Sjilles		 * not be fatal but assignment errors should.
1114205138Sjilles		 */
1115228937Sjilles		if (argc == 0)
1116205138Sjilles			cmdentry.special = 1;
1117216870Sjilles		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1118207678Sjilles		if (argc > 0)
1119207678Sjilles			bltinsetlocale();
11201556Srgrimes		commandname = argv[0];
11211556Srgrimes		argptr = argv + 1;
1122201053Sjilles		nextopt_optptr = NULL;		/* initialize nextopt */
1123193169Sstefanf		builtin_flags = flags;
11241556Srgrimes		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
11251556Srgrimes		flushall();
1126244162Sjilles		if (outiserror(out1)) {
1127244162Sjilles			warning("write error on stdout");
1128244162Sjilles			if (exitstatus == 0 || exitstatus == 1)
1129244162Sjilles				exitstatus = 2;
1130244162Sjilles		}
11311556Srgrimescmddone:
1132207678Sjilles		if (argc > 0)
1133207678Sjilles			bltinunsetlocale();
113460592Scracauer		cmdenviron = NULL;
11351556Srgrimes		out1 = &output;
11361556Srgrimes		out2 = &errout;
11371556Srgrimes		freestdout();
1138217035Sjilles		handler = savehandler;
1139218306Sjilles		commandname = savecmdname;
1140218306Sjilles		if (jp)
1141218306Sjilles			exitshell(exitstatus);
1142201366Sjilles		if (flags == EV_BACKCMD) {
1143201366Sjilles			backcmd->buf = memout.buf;
1144201366Sjilles			backcmd->nleft = memout.nextc - memout.buf;
1145201366Sjilles			memout.buf = NULL;
1146201366Sjilles		}
1147220978Sjilles		if (cmdentry.u.index != EXECCMD)
1148204801Sjilles			popredir();
11491556Srgrimes		if (e != -1) {
115020425Ssteve			if ((e != EXERROR && e != EXEXEC)
1151157601Sstefanf			    || cmdentry.special)
11521556Srgrimes				exraise(e);
1153199647Sjilles			popfilesupto(savetopfile);
1154201366Sjilles			if (flags != EV_BACKCMD)
1155201366Sjilles				FORCEINTON;
11561556Srgrimes		}
11571556Srgrimes	} else {
115820425Ssteve#ifdef DEBUG
11591556Srgrimes		trputs("normal command:  ");  trargs(argv);
116020425Ssteve#endif
11611556Srgrimes		redirect(cmd->ncmd.redirect, 0);
11621556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
11631556Srgrimes			setvareq(sp->text, VEXPORT|VSTACK);
11641556Srgrimes		envp = environment();
1165204800Sjilles		shellexec(argv, envp, path, cmdentry.u.index);
11661556Srgrimes		/*NOTREACHED*/
11671556Srgrimes	}
11681556Srgrimes	goto out;
11691556Srgrimes
11701556Srgrimesparent:	/* parent process gets here (if we forked) */
1171212214Sjilles	if (mode == FORK_FG) {	/* argument to fork */
11721556Srgrimes		INTOFF;
117345916Scracauer		exitstatus = waitforjob(jp, &realstatus);
11741556Srgrimes		INTON;
117545916Scracauer		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
117645266Scracauer			evalskip = SKIPBREAK;
117745266Scracauer			skipcount = loopnest;
117845266Scracauer		}
1179212214Sjilles	} else if (mode == FORK_NOJOB) {
11801556Srgrimes		backcmd->fd = pip[0];
11811556Srgrimes		close(pip[1]);
11821556Srgrimes		backcmd->jp = jp;
1183223282Sjilles	}
11841556Srgrimes
11851556Srgrimesout:
11861556Srgrimes	if (lastarg)
11871556Srgrimes		setvar("_", lastarg, 0);
118854884Scracauer	if (do_clearcmdentry)
1189218324Sjilles		clearcmdentry();
11901556Srgrimes}
11911556Srgrimes
11921556Srgrimes
11931556Srgrimes
11941556Srgrimes/*
11951556Srgrimes * Search for a command.  This is called before we fork so that the
11961556Srgrimes * location of the command will be available in the parent as well as
11971556Srgrimes * the child.  The check for "goodname" is an overly conservative
11981556Srgrimes * check that the name will not be subject to expansion.
11991556Srgrimes */
12001556Srgrimes
1201213811Sobrienstatic void
120290111Simpprehash(union node *n)
120317987Speter{
12041556Srgrimes	struct cmdentry entry;
12051556Srgrimes
1206159633Sstefanf	if (n && n->type == NCMD && n->ncmd.args)
120717987Speter		if (goodname(n->ncmd.args->narg.text))
120817987Speter			find_command(n->ncmd.args->narg.text, &entry, 0,
120917987Speter				     pathval());
12101556Srgrimes}
12111556Srgrimes
12121556Srgrimes
12131556Srgrimes
12141556Srgrimes/*
12151556Srgrimes * Builtin commands.  Builtin commands whose functions are closely
12161556Srgrimes * tied to evaluation are implemented here.
12171556Srgrimes */
12181556Srgrimes
12191556Srgrimes/*
1220201431Sjilles * No command given, a bltin command with no arguments, or a bltin command
1221201431Sjilles * with an invalid name.
12221556Srgrimes */
12231556Srgrimes
122417987Speterint
1225201431Sjillesbltincmd(int argc, char **argv)
122617987Speter{
1227201431Sjilles	if (argc > 1) {
1228201431Sjilles		out2fmt_flush("%s: not found\n", argv[1]);
1229201431Sjilles		return 127;
1230201431Sjilles	}
123120425Ssteve	/*
123217987Speter	 * Preserve exitstatus of a previous possible redirection
123320425Ssteve	 * as POSIX mandates
123417987Speter	 */
12351556Srgrimes	return exitstatus;
12361556Srgrimes}
12371556Srgrimes
12381556Srgrimes
12391556Srgrimes/*
12401556Srgrimes * Handle break and continue commands.  Break, continue, and return are
12411556Srgrimes * all handled by setting the evalskip flag.  The evaluation routines
12421556Srgrimes * above all check this flag, and if it is set they start skipping
12431556Srgrimes * commands rather than executing them.  The variable skipcount is
12441556Srgrimes * the number of loops to break/continue, or the number of function
12451556Srgrimes * levels to return.  (The latter is always 1.)  It should probably
12461556Srgrimes * be an error to break out of more loops than exist, but it isn't
12471556Srgrimes * in the standard shell so we don't make it one here.
12481556Srgrimes */
12491556Srgrimes
125017987Speterint
125190111Simpbreakcmd(int argc, char **argv)
125217987Speter{
125320425Ssteve	int n = argc > 1 ? number(argv[1]) : 1;
12541556Srgrimes
12551556Srgrimes	if (n > loopnest)
12561556Srgrimes		n = loopnest;
12571556Srgrimes	if (n > 0) {
12581556Srgrimes		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
12591556Srgrimes		skipcount = n;
12601556Srgrimes	}
12611556Srgrimes	return 0;
12621556Srgrimes}
12631556Srgrimes
1264100437Stjr/*
1265100437Stjr * The `command' command.
1266100437Stjr */
1267100437Stjrint
1268240541Sjillescommandcmd(int argc __unused, char **argv __unused)
1269100437Stjr{
1270207783Sjilles	const char *path;
1271100437Stjr	int ch;
1272151810Sstefanf	int cmd = -1;
12731556Srgrimes
1274204800Sjilles	path = bltinlookup("PATH", 1);
1275100437Stjr
1276240541Sjilles	while ((ch = nextopt("pvV")) != '\0') {
1277100437Stjr		switch (ch) {
1278100437Stjr		case 'p':
1279207783Sjilles			path = _PATH_STDPATH;
1280100437Stjr			break;
1281151810Sstefanf		case 'v':
1282151810Sstefanf			cmd = TYPECMD_SMALLV;
1283151810Sstefanf			break;
1284151810Sstefanf		case 'V':
1285151810Sstefanf			cmd = TYPECMD_BIGV;
1286151810Sstefanf			break;
1287100437Stjr		}
1288100437Stjr	}
1289100437Stjr
1290151810Sstefanf	if (cmd != -1) {
1291240541Sjilles		if (*argptr == NULL || argptr[1] != NULL)
1292151810Sstefanf			error("wrong number of arguments");
1293240541Sjilles		return typecmd_impl(2, argptr - 1, cmd, path);
1294151810Sstefanf	}
1295240541Sjilles	if (*argptr != NULL)
1296214538Sjilles		error("commandcmd bad call");
1297100437Stjr
1298100437Stjr	/*
1299100437Stjr	 * Do nothing successfully if no command was specified;
1300100437Stjr	 * ksh also does this.
1301100437Stjr	 */
1302204800Sjilles	return 0;
1303100437Stjr}
1304100437Stjr
1305100437Stjr
13061556Srgrimes/*
13071556Srgrimes * The return command.
13081556Srgrimes */
13091556Srgrimes
131017987Speterint
131190111Simpreturncmd(int argc, char **argv)
131217987Speter{
131320425Ssteve	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
13141556Srgrimes
1315255215Sjilles	evalskip = SKIPRETURN;
1316255215Sjilles	skipcount = 1;
13171556Srgrimes	return ret;
13181556Srgrimes}
13191556Srgrimes
13201556Srgrimes
132117987Speterint
132290111Simpfalsecmd(int argc __unused, char **argv __unused)
132317987Speter{
132417987Speter	return 1;
132517987Speter}
132617987Speter
132717987Speter
132817987Speterint
132990111Simptruecmd(int argc __unused, char **argv __unused)
133017987Speter{
13311556Srgrimes	return 0;
13321556Srgrimes}
13331556Srgrimes
13341556Srgrimes
133517987Speterint
133690111Simpexeccmd(int argc, char **argv)
133717987Speter{
1338208630Sjilles	/*
1339208630Sjilles	 * Because we have historically not supported any options,
1340208630Sjilles	 * only treat "--" specially.
1341208630Sjilles	 */
1342208630Sjilles	if (argc > 1 && strcmp(argv[1], "--") == 0)
1343208630Sjilles		argc--, argv++;
13441556Srgrimes	if (argc > 1) {
134517987Speter		struct strlist *sp;
134617987Speter
13471556Srgrimes		iflag = 0;		/* exit on error */
13481556Srgrimes		mflag = 0;
13491556Srgrimes		optschanged();
135017987Speter		for (sp = cmdenviron; sp ; sp = sp->next)
135117987Speter			setvareq(sp->text, VEXPORT|VSTACK);
13521556Srgrimes		shellexec(argv + 1, environment(), pathval(), 0);
13531556Srgrimes
13541556Srgrimes	}
13551556Srgrimes	return 0;
13561556Srgrimes}
1357153091Sstefanf
1358153091Sstefanf
1359153091Sstefanfint
1360153091Sstefanftimescmd(int argc __unused, char **argv __unused)
1361153091Sstefanf{
1362153091Sstefanf	struct rusage ru;
1363153091Sstefanf	long shumins, shsmins, chumins, chsmins;
1364153091Sstefanf	double shusecs, shssecs, chusecs, chssecs;
1365153091Sstefanf
1366153091Sstefanf	if (getrusage(RUSAGE_SELF, &ru) < 0)
1367153091Sstefanf		return 1;
1368153091Sstefanf	shumins = ru.ru_utime.tv_sec / 60;
1369153091Sstefanf	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1370153091Sstefanf	shsmins = ru.ru_stime.tv_sec / 60;
1371153091Sstefanf	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1372153091Sstefanf	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1373153091Sstefanf		return 1;
1374153091Sstefanf	chumins = ru.ru_utime.tv_sec / 60;
1375153091Sstefanf	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1376153091Sstefanf	chsmins = ru.ru_stime.tv_sec / 60;
1377153091Sstefanf	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1378153091Sstefanf	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1379153091Sstefanf	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1380153091Sstefanf	return 0;
1381153091Sstefanf}
1382