eval.c revision 221970
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/eval.c 221970 2011-05-15 17:00:43Z jilles $");
401556Srgrimes
41100437Stjr#include <paths.h>
4217987Speter#include <signal.h>
43102576Skeramida#include <stdlib.h>
4417987Speter#include <unistd.h>
45153091Sstefanf#include <sys/resource.h>
4645266Scracauer#include <sys/wait.h> /* For WIFSIGNALED(status) */
4753891Scracauer#include <errno.h>
4817987Speter
491556Srgrimes/*
501556Srgrimes * Evaluate a command.
511556Srgrimes */
521556Srgrimes
531556Srgrimes#include "shell.h"
541556Srgrimes#include "nodes.h"
551556Srgrimes#include "syntax.h"
561556Srgrimes#include "expand.h"
571556Srgrimes#include "parser.h"
581556Srgrimes#include "jobs.h"
591556Srgrimes#include "eval.h"
601556Srgrimes#include "builtins.h"
611556Srgrimes#include "options.h"
621556Srgrimes#include "exec.h"
631556Srgrimes#include "redir.h"
641556Srgrimes#include "input.h"
651556Srgrimes#include "output.h"
661556Srgrimes#include "trap.h"
671556Srgrimes#include "var.h"
681556Srgrimes#include "memalloc.h"
691556Srgrimes#include "error.h"
7017987Speter#include "show.h"
711556Srgrimes#include "mystring.h"
7217987Speter#ifndef NO_HISTORY
731556Srgrimes#include "myhistedit.h"
7417987Speter#endif
751556Srgrimes
761556Srgrimes
77201053Sjillesint evalskip;			/* set if we are skipping commands */
78213760Sobrienstatic int skipcount;		/* number of levels to skip */
791556SrgrimesMKINIT int loopnest;		/* current loop nesting level */
801556Srgrimesint funcnest;			/* depth of function calls */
81213760Sobrienstatic int builtin_flags;	/* evalcommand flags for builtins */
821556Srgrimes
831556Srgrimes
841556Srgrimeschar *commandname;
851556Srgrimesstruct strlist *cmdenviron;
861556Srgrimesint exitstatus;			/* exit status of last command */
8717987Speterint oexitstatus;		/* saved exit status */
881556Srgrimes
891556Srgrimes
90213811Sobrienstatic void evalloop(union node *, int);
91213811Sobrienstatic void evalfor(union node *, int);
92213811Sobrienstatic void evalcase(union node *, int);
93213811Sobrienstatic void evalsubshell(union node *, int);
94213811Sobrienstatic void evalredir(union node *, int);
95213811Sobrienstatic void expredir(union node *);
96213811Sobrienstatic void evalpipe(union node *);
97216778Sjillesstatic int is_valid_fast_cmdsubst(union node *n);
98213811Sobrienstatic void evalcommand(union node *, int, struct backcmd *);
99213811Sobrienstatic void prehash(union node *);
1001556Srgrimes
1011556Srgrimes
1021556Srgrimes/*
1031556Srgrimes * Called to reset things after an exception.
1041556Srgrimes */
1051556Srgrimes
1061556Srgrimes#ifdef mkinit
1071556SrgrimesINCLUDE "eval.h"
1081556Srgrimes
1091556SrgrimesRESET {
1101556Srgrimes	evalskip = 0;
1111556Srgrimes	loopnest = 0;
1121556Srgrimes	funcnest = 0;
1131556Srgrimes}
1141556Srgrimes#endif
1151556Srgrimes
1161556Srgrimes
1171556Srgrimes
1181556Srgrimes/*
11946684Skris * The eval command.
1201556Srgrimes */
1211556Srgrimes
12217987Speterint
12390111Simpevalcmd(int argc, char **argv)
1241556Srgrimes{
1251556Srgrimes        char *p;
1261556Srgrimes        char *concat;
1271556Srgrimes        char **ap;
1281556Srgrimes
1291556Srgrimes        if (argc > 1) {
1301556Srgrimes                p = argv[1];
1311556Srgrimes                if (argc > 2) {
1321556Srgrimes                        STARTSTACKSTR(concat);
1331556Srgrimes                        ap = argv + 2;
1341556Srgrimes                        for (;;) {
135215783Sjilles                                STPUTS(p, concat);
1361556Srgrimes                                if ((p = *ap++) == NULL)
1371556Srgrimes                                        break;
1381556Srgrimes                                STPUTC(' ', concat);
1391556Srgrimes                        }
1401556Srgrimes                        STPUTC('\0', concat);
1411556Srgrimes                        p = grabstackstr(concat);
1421556Srgrimes                }
143193169Sstefanf                evalstring(p, builtin_flags & EV_TESTED);
144210829Sjilles        } else
145210829Sjilles                exitstatus = 0;
1461556Srgrimes        return exitstatus;
1471556Srgrimes}
1481556Srgrimes
1491556Srgrimes
1501556Srgrimes/*
1511556Srgrimes * Execute a command or commands contained in a string.
1521556Srgrimes */
1531556Srgrimes
1541556Srgrimesvoid
155193169Sstefanfevalstring(char *s, int flags)
15690111Simp{
1571556Srgrimes	union node *n;
1581556Srgrimes	struct stackmark smark;
159194128Sjilles	int flags_exit;
160210829Sjilles	int any;
1611556Srgrimes
162194128Sjilles	flags_exit = flags & EV_EXIT;
163194128Sjilles	flags &= ~EV_EXIT;
164210829Sjilles	any = 0;
1651556Srgrimes	setstackmark(&smark);
1661556Srgrimes	setinputstring(s, 1);
1671556Srgrimes	while ((n = parsecmd(0)) != NEOF) {
168194128Sjilles		if (n != NULL) {
169194128Sjilles			if (flags_exit && preadateof())
170194128Sjilles				evaltree(n, flags | EV_EXIT);
171194128Sjilles			else
172194128Sjilles				evaltree(n, flags);
173210829Sjilles			any = 1;
174194128Sjilles		}
1751556Srgrimes		popstackmark(&smark);
1761556Srgrimes	}
1771556Srgrimes	popfile();
1781556Srgrimes	popstackmark(&smark);
179210829Sjilles	if (!any)
180210829Sjilles		exitstatus = 0;
181194128Sjilles	if (flags_exit)
182220978Sjilles		exraise(EXEXIT);
1831556Srgrimes}
1841556Srgrimes
1851556Srgrimes
1861556Srgrimes/*
1871556Srgrimes * Evaluate a parse tree.  The value is left in the global variable
1881556Srgrimes * exitstatus.
1891556Srgrimes */
1901556Srgrimes
1911556Srgrimesvoid
19290111Simpevaltree(union node *n, int flags)
19317987Speter{
194149927Sstefanf	int do_etest;
195214599Sjilles	union node *next;
196149927Sstefanf
197149927Sstefanf	do_etest = 0;
1981556Srgrimes	if (n == NULL) {
1991556Srgrimes		TRACE(("evaltree(NULL) called\n"));
2001556Srgrimes		exitstatus = 0;
2011556Srgrimes		goto out;
2021556Srgrimes	}
203214599Sjilles	do {
204214600Sjilles		next = NULL;
20517987Speter#ifndef NO_HISTORY
206214600Sjilles		displayhist = 1;	/* show history substitutions done with fc */
20717987Speter#endif
208214600Sjilles		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
209214600Sjilles		switch (n->type) {
210214600Sjilles		case NSEMI:
211214600Sjilles			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
212214600Sjilles			if (evalskip)
213214600Sjilles				goto out;
214214600Sjilles			next = n->nbinary.ch2;
215214600Sjilles			break;
216214600Sjilles		case NAND:
217214600Sjilles			evaltree(n->nbinary.ch1, EV_TESTED);
218214600Sjilles			if (evalskip || exitstatus != 0) {
219214600Sjilles				goto out;
220214600Sjilles			}
221214600Sjilles			next = n->nbinary.ch2;
222214600Sjilles			break;
223214600Sjilles		case NOR:
224214600Sjilles			evaltree(n->nbinary.ch1, EV_TESTED);
225214600Sjilles			if (evalskip || exitstatus == 0)
226214600Sjilles				goto out;
227214600Sjilles			next = n->nbinary.ch2;
228214600Sjilles			break;
229214600Sjilles		case NREDIR:
230214600Sjilles			evalredir(n, flags);
231214600Sjilles			break;
232214600Sjilles		case NSUBSHELL:
233214600Sjilles			evalsubshell(n, flags);
234214600Sjilles			do_etest = !(flags & EV_TESTED);
235214600Sjilles			break;
236214600Sjilles		case NBACKGND:
237214600Sjilles			evalsubshell(n, flags);
238214600Sjilles			break;
239214600Sjilles		case NIF: {
240214600Sjilles			evaltree(n->nif.test, EV_TESTED);
241214600Sjilles			if (evalskip)
242214600Sjilles				goto out;
243214600Sjilles			if (exitstatus == 0)
244214600Sjilles				next = n->nif.ifpart;
245214600Sjilles			else if (n->nif.elsepart)
246214600Sjilles				next = n->nif.elsepart;
247214600Sjilles			else
248214600Sjilles				exitstatus = 0;
249214600Sjilles			break;
25018754Ssteve		}
251214600Sjilles		case NWHILE:
252214600Sjilles		case NUNTIL:
253214600Sjilles			evalloop(n, flags & ~EV_EXIT);
254214600Sjilles			break;
255214600Sjilles		case NFOR:
256214600Sjilles			evalfor(n, flags & ~EV_EXIT);
257214600Sjilles			break;
258214600Sjilles		case NCASE:
259214600Sjilles			evalcase(n, flags);
260214600Sjilles			break;
261214600Sjilles		case NDEFUN:
262214600Sjilles			defun(n->narg.text, n->narg.next);
26320425Ssteve			exitstatus = 0;
264214600Sjilles			break;
265214600Sjilles		case NNOT:
266214600Sjilles			evaltree(n->nnot.com, EV_TESTED);
267214600Sjilles			exitstatus = !exitstatus;
268214600Sjilles			break;
2691556Srgrimes
270214600Sjilles		case NPIPE:
271214600Sjilles			evalpipe(n);
272214600Sjilles			do_etest = !(flags & EV_TESTED);
273214600Sjilles			break;
274214600Sjilles		case NCMD:
275214600Sjilles			evalcommand(n, flags, (struct backcmd *)NULL);
276214600Sjilles			do_etest = !(flags & EV_TESTED);
277214600Sjilles			break;
278214600Sjilles		default:
279214600Sjilles			out1fmt("Node type = %d\n", n->type);
280214600Sjilles			flushout(&output);
281214600Sjilles			break;
282214600Sjilles		}
283214600Sjilles		n = next;
284214599Sjilles	} while (n != NULL);
2851556Srgrimesout:
2861556Srgrimes	if (pendingsigs)
2871556Srgrimes		dotrap();
288220978Sjilles	if (eflag && exitstatus != 0 && do_etest)
2891556Srgrimes		exitshell(exitstatus);
290220978Sjilles	if (flags & EV_EXIT)
291220978Sjilles		exraise(EXEXIT);
2921556Srgrimes}
2931556Srgrimes
2941556Srgrimes
295213811Sobrienstatic void
296149933Sstefanfevalloop(union node *n, int flags)
29717987Speter{
2981556Srgrimes	int status;
2991556Srgrimes
3001556Srgrimes	loopnest++;
3011556Srgrimes	status = 0;
3021556Srgrimes	for (;;) {
3031556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
3041556Srgrimes		if (evalskip) {
3051556Srgrimesskipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
3061556Srgrimes				evalskip = 0;
3071556Srgrimes				continue;
3081556Srgrimes			}
3091556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3101556Srgrimes				evalskip = 0;
311212475Sjilles			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
312212475Sjilles				status = exitstatus;
3131556Srgrimes			break;
3141556Srgrimes		}
3151556Srgrimes		if (n->type == NWHILE) {
3161556Srgrimes			if (exitstatus != 0)
3171556Srgrimes				break;
3181556Srgrimes		} else {
3191556Srgrimes			if (exitstatus == 0)
3201556Srgrimes				break;
3211556Srgrimes		}
322149933Sstefanf		evaltree(n->nbinary.ch2, flags);
3231556Srgrimes		status = exitstatus;
3241556Srgrimes		if (evalskip)
3251556Srgrimes			goto skipping;
3261556Srgrimes	}
3271556Srgrimes	loopnest--;
3281556Srgrimes	exitstatus = status;
3291556Srgrimes}
3301556Srgrimes
3311556Srgrimes
3321556Srgrimes
333213811Sobrienstatic void
334149933Sstefanfevalfor(union node *n, int flags)
33517987Speter{
3361556Srgrimes	struct arglist arglist;
3371556Srgrimes	union node *argp;
3381556Srgrimes	struct strlist *sp;
3391556Srgrimes	struct stackmark smark;
3401556Srgrimes
3411556Srgrimes	setstackmark(&smark);
3421556Srgrimes	arglist.lastp = &arglist.list;
3431556Srgrimes	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
34417987Speter		oexitstatus = exitstatus;
3451556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3461556Srgrimes		if (evalskip)
3471556Srgrimes			goto out;
3481556Srgrimes	}
3491556Srgrimes	*arglist.lastp = NULL;
3501556Srgrimes
3511556Srgrimes	exitstatus = 0;
3521556Srgrimes	loopnest++;
3531556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
3541556Srgrimes		setvar(n->nfor.var, sp->text, 0);
355149933Sstefanf		evaltree(n->nfor.body, flags);
3561556Srgrimes		if (evalskip) {
3571556Srgrimes			if (evalskip == SKIPCONT && --skipcount <= 0) {
3581556Srgrimes				evalskip = 0;
3591556Srgrimes				continue;
3601556Srgrimes			}
3611556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3621556Srgrimes				evalskip = 0;
3631556Srgrimes			break;
3641556Srgrimes		}
3651556Srgrimes	}
3661556Srgrimes	loopnest--;
3671556Srgrimesout:
3681556Srgrimes	popstackmark(&smark);
3691556Srgrimes}
3701556Srgrimes
3711556Srgrimes
3721556Srgrimes
373213811Sobrienstatic void
37490111Simpevalcase(union node *n, int flags)
37517987Speter{
3761556Srgrimes	union node *cp;
3771556Srgrimes	union node *patp;
3781556Srgrimes	struct arglist arglist;
3791556Srgrimes	struct stackmark smark;
3801556Srgrimes
3811556Srgrimes	setstackmark(&smark);
3821556Srgrimes	arglist.lastp = &arglist.list;
38317987Speter	oexitstatus = exitstatus;
384172440Sstefanf	exitstatus = 0;
3851556Srgrimes	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
3861556Srgrimes	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
3871556Srgrimes		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
3881556Srgrimes			if (casematch(patp, arglist.list->text)) {
3891556Srgrimes				if (evalskip == 0) {
3901556Srgrimes					evaltree(cp->nclist.body, flags);
3911556Srgrimes				}
3921556Srgrimes				goto out;
3931556Srgrimes			}
3941556Srgrimes		}
3951556Srgrimes	}
3961556Srgrimesout:
3971556Srgrimes	popstackmark(&smark);
3981556Srgrimes}
3991556Srgrimes
4001556Srgrimes
4011556Srgrimes
4021556Srgrimes/*
4031556Srgrimes * Kick off a subshell to evaluate a tree.
4041556Srgrimes */
4051556Srgrimes
406213811Sobrienstatic void
40790111Simpevalsubshell(union node *n, int flags)
40817987Speter{
4091556Srgrimes	struct job *jp;
4101556Srgrimes	int backgnd = (n->type == NBACKGND);
4111556Srgrimes
4121556Srgrimes	expredir(n->nredir.redirect);
413194774Sjilles	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
414194774Sjilles			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
4151556Srgrimes		if (backgnd)
4161556Srgrimes			flags &=~ EV_TESTED;
4171556Srgrimes		redirect(n->nredir.redirect, 0);
4181556Srgrimes		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
419201053Sjilles	} else if (! backgnd) {
4201556Srgrimes		INTOFF;
42145916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
4221556Srgrimes		INTON;
423221027Sjilles	} else
424221027Sjilles		exitstatus = 0;
4251556Srgrimes}
4261556Srgrimes
4271556Srgrimes
428205154Sjilles/*
429205154Sjilles * Evaluate a redirected compound command.
430205154Sjilles */
4311556Srgrimes
432213811Sobrienstatic void
433205154Sjillesevalredir(union node *n, int flags)
434205154Sjilles{
435205154Sjilles	struct jmploc jmploc;
436205154Sjilles	struct jmploc *savehandler;
437205154Sjilles	volatile int in_redirect = 1;
438205154Sjilles
439205154Sjilles	expredir(n->nredir.redirect);
440205154Sjilles	savehandler = handler;
441205154Sjilles	if (setjmp(jmploc.loc)) {
442205154Sjilles		int e;
443205154Sjilles
444205154Sjilles		handler = savehandler;
445205154Sjilles		e = exception;
446220978Sjilles		popredir();
447205154Sjilles		if (e == EXERROR || e == EXEXEC) {
448205154Sjilles			if (in_redirect) {
449205154Sjilles				exitstatus = 2;
450205154Sjilles				return;
451205154Sjilles			}
452205154Sjilles		}
453205154Sjilles		longjmp(handler->loc, 1);
454205154Sjilles	} else {
455205154Sjilles		INTOFF;
456205154Sjilles		handler = &jmploc;
457205154Sjilles		redirect(n->nredir.redirect, REDIR_PUSH);
458205154Sjilles		in_redirect = 0;
459205154Sjilles		INTON;
460205154Sjilles		evaltree(n->nredir.n, flags);
461205154Sjilles	}
462205154Sjilles	INTOFF;
463205154Sjilles	handler = savehandler;
464205154Sjilles	popredir();
465205154Sjilles	INTON;
466205154Sjilles}
467205154Sjilles
468205154Sjilles
4691556Srgrimes/*
4701556Srgrimes * Compute the names of the files in a redirection list.
4711556Srgrimes */
4721556Srgrimes
473213811Sobrienstatic void
47490111Simpexpredir(union node *n)
47517987Speter{
47625222Ssteve	union node *redir;
4771556Srgrimes
4781556Srgrimes	for (redir = n ; redir ; redir = redir->nfile.next) {
47917987Speter		struct arglist fn;
48017987Speter		fn.lastp = &fn.list;
48117987Speter		oexitstatus = exitstatus;
48217987Speter		switch (redir->type) {
48317987Speter		case NFROM:
48417987Speter		case NTO:
48566612Sbrian		case NFROMTO:
48617987Speter		case NAPPEND:
48796922Stjr		case NCLOBBER:
4881556Srgrimes			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
4891556Srgrimes			redir->nfile.expfname = fn.list->text;
49017987Speter			break;
49117987Speter		case NFROMFD:
49217987Speter		case NTOFD:
49317987Speter			if (redir->ndup.vname) {
494181017Sstefanf				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
49517987Speter				fixredir(redir, fn.list->text, 1);
49617987Speter			}
49717987Speter			break;
4981556Srgrimes		}
4991556Srgrimes	}
5001556Srgrimes}
5011556Srgrimes
5021556Srgrimes
5031556Srgrimes
5041556Srgrimes/*
5051556Srgrimes * Evaluate a pipeline.  All the processes in the pipeline are children
5061556Srgrimes * of the process creating the pipeline.  (This differs from some versions
5071556Srgrimes * of the shell, which make the last process in a pipeline the parent
5081556Srgrimes * of all the rest.)
5091556Srgrimes */
5101556Srgrimes
511213811Sobrienstatic void
51290111Simpevalpipe(union node *n)
51317987Speter{
5141556Srgrimes	struct job *jp;
5151556Srgrimes	struct nodelist *lp;
5161556Srgrimes	int pipelen;
5171556Srgrimes	int prevfd;
5181556Srgrimes	int pip[2];
5191556Srgrimes
520149802Sstefanf	TRACE(("evalpipe(%p) called\n", (void *)n));
5211556Srgrimes	pipelen = 0;
5221556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
5231556Srgrimes		pipelen++;
5241556Srgrimes	INTOFF;
5251556Srgrimes	jp = makejob(n, pipelen);
5261556Srgrimes	prevfd = -1;
5271556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
5281556Srgrimes		prehash(lp->n);
5291556Srgrimes		pip[1] = -1;
5301556Srgrimes		if (lp->next) {
5311556Srgrimes			if (pipe(pip) < 0) {
5321556Srgrimes				close(prevfd);
53353891Scracauer				error("Pipe call failed: %s", strerror(errno));
5341556Srgrimes			}
5351556Srgrimes		}
5361556Srgrimes		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
5371556Srgrimes			INTON;
5381556Srgrimes			if (prevfd > 0) {
539124780Sdes				dup2(prevfd, 0);
5401556Srgrimes				close(prevfd);
5411556Srgrimes			}
5421556Srgrimes			if (pip[1] >= 0) {
54353282Scracauer				if (!(prevfd >= 0 && pip[0] == 0))
54452900Scracauer					close(pip[0]);
5451556Srgrimes				if (pip[1] != 1) {
546124780Sdes					dup2(pip[1], 1);
5471556Srgrimes					close(pip[1]);
5481556Srgrimes				}
5491556Srgrimes			}
5501556Srgrimes			evaltree(lp->n, EV_EXIT);
5511556Srgrimes		}
5521556Srgrimes		if (prevfd >= 0)
5531556Srgrimes			close(prevfd);
5541556Srgrimes		prevfd = pip[0];
555221970Sjilles		if (pip[1] != -1)
556221970Sjilles			close(pip[1]);
5571556Srgrimes	}
5581556Srgrimes	INTON;
5591556Srgrimes	if (n->npipe.backgnd == 0) {
5601556Srgrimes		INTOFF;
56145916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
5621556Srgrimes		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
5631556Srgrimes		INTON;
564221027Sjilles	} else
565221027Sjilles		exitstatus = 0;
5661556Srgrimes}
5671556Srgrimes
5681556Srgrimes
5691556Srgrimes
570216778Sjillesstatic int
571216778Sjillesis_valid_fast_cmdsubst(union node *n)
572216778Sjilles{
573216778Sjilles	union node *argp;
574216778Sjilles
575216778Sjilles	if (n->type != NCMD)
576216778Sjilles		return 0;
577216778Sjilles	for (argp = n->ncmd.args ; argp ; argp = argp->narg.next)
578216778Sjilles		if (expandhassideeffects(argp->narg.text))
579216778Sjilles			return 0;
580216778Sjilles	return 1;
581216778Sjilles}
582216778Sjilles
5831556Srgrimes/*
5841556Srgrimes * Execute a command inside back quotes.  If it's a builtin command, we
5851556Srgrimes * want to save its output in a block obtained from malloc.  Otherwise
5861556Srgrimes * we fork off a subprocess and get the output of the command via a pipe.
5871556Srgrimes * Should be called with interrupts off.
5881556Srgrimes */
5891556Srgrimes
5901556Srgrimesvoid
59190111Simpevalbackcmd(union node *n, struct backcmd *result)
59217987Speter{
5931556Srgrimes	int pip[2];
5941556Srgrimes	struct job *jp;
5951556Srgrimes	struct stackmark smark;		/* unnecessary */
596216761Sjilles	struct jmploc jmploc;
597216761Sjilles	struct jmploc *savehandler;
5981556Srgrimes
5991556Srgrimes	setstackmark(&smark);
6001556Srgrimes	result->fd = -1;
6011556Srgrimes	result->buf = NULL;
6021556Srgrimes	result->nleft = 0;
6031556Srgrimes	result->jp = NULL;
60417987Speter	if (n == NULL) {
60517987Speter		exitstatus = 0;
6061556Srgrimes		goto out;
60717987Speter	}
608216778Sjilles	if (is_valid_fast_cmdsubst(n)) {
60917987Speter		exitstatus = oexitstatus;
610216761Sjilles		savehandler = handler;
611216761Sjilles		if (setjmp(jmploc.loc)) {
612216761Sjilles			if (exception == EXERROR || exception == EXEXEC)
613216761Sjilles				exitstatus = 2;
614216761Sjilles			else if (exception != 0) {
615216761Sjilles				handler = savehandler;
616216761Sjilles				longjmp(handler->loc, 1);
617216761Sjilles			}
618216761Sjilles		} else {
619216761Sjilles			handler = &jmploc;
620216761Sjilles			evalcommand(n, EV_BACKCMD, result);
621216761Sjilles		}
622216761Sjilles		handler = savehandler;
6231556Srgrimes	} else {
62417987Speter		exitstatus = 0;
6251556Srgrimes		if (pipe(pip) < 0)
62653891Scracauer			error("Pipe call failed: %s", strerror(errno));
6271556Srgrimes		jp = makejob(n, 1);
6281556Srgrimes		if (forkshell(jp, n, FORK_NOJOB) == 0) {
6291556Srgrimes			FORCEINTON;
6301556Srgrimes			close(pip[0]);
6311556Srgrimes			if (pip[1] != 1) {
632124780Sdes				dup2(pip[1], 1);
6331556Srgrimes				close(pip[1]);
6341556Srgrimes			}
6351556Srgrimes			evaltree(n, EV_EXIT);
6361556Srgrimes		}
6371556Srgrimes		close(pip[1]);
6381556Srgrimes		result->fd = pip[0];
6391556Srgrimes		result->jp = jp;
6401556Srgrimes	}
6411556Srgrimesout:
6421556Srgrimes	popstackmark(&smark);
643109627Stjr	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
6441556Srgrimes		result->fd, result->buf, result->nleft, result->jp));
6451556Srgrimes}
6461556Srgrimes
647216826Sjilles/*
648216826Sjilles * Check if a builtin can safely be executed in the same process,
649216826Sjilles * even though it should be in a subshell (command substitution).
650216826Sjilles * Note that jobid, jobs, times and trap can show information not
651216826Sjilles * available in a child process; this is deliberate.
652216826Sjilles * The arguments should already have been expanded.
653216826Sjilles */
654216826Sjillesstatic int
655216826Sjillessafe_builtin(int idx, int argc, char **argv)
656216826Sjilles{
657216826Sjilles	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
658216826Sjilles	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
659216826Sjilles	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
660216826Sjilles	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
661216826Sjilles	    idx == TYPECMD)
662216826Sjilles		return (1);
663216826Sjilles	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
664216826Sjilles	    idx == UMASKCMD)
665216826Sjilles		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
666216826Sjilles	if (idx == SETCMD)
667216826Sjilles		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
668216826Sjilles		    argv[1][0] == '+') && argv[1][1] == 'o' &&
669216826Sjilles		    argv[1][2] == '\0'));
670216826Sjilles	return (0);
671216826Sjilles}
6721556Srgrimes
6731556Srgrimes/*
6741556Srgrimes * Execute a simple command.
675217035Sjilles * Note: This may or may not return if (flags & EV_EXIT).
6761556Srgrimes */
6771556Srgrimes
678213811Sobrienstatic void
67990111Simpevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
68017987Speter{
6811556Srgrimes	struct stackmark smark;
6821556Srgrimes	union node *argp;
6831556Srgrimes	struct arglist arglist;
6841556Srgrimes	struct arglist varlist;
6851556Srgrimes	char **argv;
6861556Srgrimes	int argc;
6871556Srgrimes	char **envp;
6881556Srgrimes	int varflag;
6891556Srgrimes	struct strlist *sp;
6901556Srgrimes	int mode;
6911556Srgrimes	int pip[2];
6921556Srgrimes	struct cmdentry cmdentry;
6931556Srgrimes	struct job *jp;
6941556Srgrimes	struct jmploc jmploc;
695194765Sjilles	struct jmploc *savehandler;
696194765Sjilles	char *savecmdname;
697194765Sjilles	struct shparam saveparam;
698194765Sjilles	struct localvar *savelocalvars;
699199647Sjilles	struct parsefile *savetopfile;
7001556Srgrimes	volatile int e;
7011556Srgrimes	char *lastarg;
70245916Scracauer	int realstatus;
70354884Scracauer	int do_clearcmdentry;
704211287Sjilles	const char *path = pathval();
7051556Srgrimes
7061556Srgrimes	/* First expand the arguments. */
707149802Sstefanf	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
7081556Srgrimes	setstackmark(&smark);
7091556Srgrimes	arglist.lastp = &arglist.list;
7101556Srgrimes	varlist.lastp = &varlist.list;
7111556Srgrimes	varflag = 1;
712217035Sjilles	jp = NULL;
71354884Scracauer	do_clearcmdentry = 0;
71417987Speter	oexitstatus = exitstatus;
71517987Speter	exitstatus = 0;
7161556Srgrimes	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
71717987Speter		char *p = argp->narg.text;
7181556Srgrimes		if (varflag && is_name(*p)) {
7191556Srgrimes			do {
7201556Srgrimes				p++;
7211556Srgrimes			} while (is_in_name(*p));
7221556Srgrimes			if (*p == '=') {
7231556Srgrimes				expandarg(argp, &varlist, EXP_VARTILDE);
7241556Srgrimes				continue;
7251556Srgrimes			}
7261556Srgrimes		}
7271556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
7281556Srgrimes		varflag = 0;
7291556Srgrimes	}
7301556Srgrimes	*arglist.lastp = NULL;
7311556Srgrimes	*varlist.lastp = NULL;
7321556Srgrimes	expredir(cmd->ncmd.redirect);
7331556Srgrimes	argc = 0;
7341556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next)
7351556Srgrimes		argc++;
736218306Sjilles	/* Add one slot at the beginning for tryexec(). */
737218306Sjilles	argv = stalloc(sizeof (char *) * (argc + 2));
738218306Sjilles	argv++;
7391556Srgrimes
7401556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
7411556Srgrimes		TRACE(("evalcommand arg: %s\n", sp->text));
7421556Srgrimes		*argv++ = sp->text;
7431556Srgrimes	}
7441556Srgrimes	*argv = NULL;
7451556Srgrimes	lastarg = NULL;
7461556Srgrimes	if (iflag && funcnest == 0 && argc > 0)
7471556Srgrimes		lastarg = argv[-1];
7481556Srgrimes	argv -= argc;
7491556Srgrimes
7501556Srgrimes	/* Print the command if xflag is set. */
7511556Srgrimes	if (xflag) {
752159632Sstefanf		char sep = 0;
753194786Sjilles		const char *p;
754159632Sstefanf		out2str(ps4val());
7551556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next) {
756159632Sstefanf			if (sep != 0)
757201366Sjilles				out2c(' ');
758215567Sjilles			p = strchr(sp->text, '=');
759215567Sjilles			if (p != NULL) {
760215567Sjilles				p++;
761215567Sjilles				outbin(sp->text, p - sp->text, out2);
762194786Sjilles				out2qstr(p);
763215567Sjilles			} else
764215567Sjilles				out2qstr(sp->text);
765159632Sstefanf			sep = ' ';
7661556Srgrimes		}
7671556Srgrimes		for (sp = arglist.list ; sp ; sp = sp->next) {
768159632Sstefanf			if (sep != 0)
769201366Sjilles				out2c(' ');
770194786Sjilles			/* Disambiguate command looking like assignment. */
771194786Sjilles			if (sp == arglist.list &&
772194786Sjilles					strchr(sp->text, '=') != NULL &&
773194786Sjilles					strchr(sp->text, '\'') == NULL) {
774194786Sjilles				out2c('\'');
775194786Sjilles				out2str(sp->text);
776194786Sjilles				out2c('\'');
777194786Sjilles			} else
778194786Sjilles				out2qstr(sp->text);
779159632Sstefanf			sep = ' ';
7801556Srgrimes		}
781201366Sjilles		out2c('\n');
7821556Srgrimes		flushout(&errout);
7831556Srgrimes	}
7841556Srgrimes
7851556Srgrimes	/* Now locate the command. */
7861556Srgrimes	if (argc == 0) {
787157601Sstefanf		/* Variable assignment(s) without command */
7881556Srgrimes		cmdentry.cmdtype = CMDBUILTIN;
7891556Srgrimes		cmdentry.u.index = BLTINCMD;
790205138Sjilles		cmdentry.special = 0;
7911556Srgrimes	} else {
79217987Speter		static const char PATH[] = "PATH=";
793204800Sjilles		int cmd_flags = 0, bltinonly = 0;
79417987Speter
79517987Speter		/*
79617987Speter		 * Modify the command lookup path, if a PATH= assignment
79717987Speter		 * is present
79817987Speter		 */
79917987Speter		for (sp = varlist.list ; sp ; sp = sp->next)
80054884Scracauer			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
80117987Speter				path = sp->text + sizeof(PATH) - 1;
802155301Sschweikh				/*
80354884Scracauer				 * On `PATH=... command`, we need to make
80454884Scracauer				 * sure that the command isn't using the
80554884Scracauer				 * non-updated hash table of the outer PATH
806155301Sschweikh				 * setting and we need to make sure that
80754884Scracauer				 * the hash table isn't filled with items
80854884Scracauer				 * from the temporary setting.
80954884Scracauer				 *
810155301Sschweikh				 * It would be better to forbit using and
81154884Scracauer				 * updating the table while this command
81254884Scracauer				 * runs, by the command finding mechanism
81354884Scracauer				 * is heavily integrated with hash handling,
81454884Scracauer				 * so we just delete the hash before and after
81554884Scracauer				 * the command runs. Partly deleting like
81654884Scracauer				 * changepatch() does doesn't seem worth the
81754884Scracauer				 * bookinging effort, since most such runs add
818123996Smaxim				 * directories in front of the new PATH.
81954884Scracauer				 */
820218324Sjilles				clearcmdentry();
82154884Scracauer				do_clearcmdentry = 1;
82254884Scracauer			}
82317987Speter
824204800Sjilles		for (;;) {
825204800Sjilles			if (bltinonly) {
826204800Sjilles				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
827204800Sjilles				if (cmdentry.u.index < 0) {
828201431Sjilles					cmdentry.u.index = BLTINCMD;
829201431Sjilles					argv--;
830201431Sjilles					argc++;
831201431Sjilles					break;
8321556Srgrimes				}
833204800Sjilles			} else
834204800Sjilles				find_command(argv[0], &cmdentry, cmd_flags, path);
835204800Sjilles			/* implement the bltin and command builtins here */
836204800Sjilles			if (cmdentry.cmdtype != CMDBUILTIN)
837204800Sjilles				break;
838204800Sjilles			if (cmdentry.u.index == BLTINCMD) {
839204800Sjilles				if (argc == 1)
8401556Srgrimes					break;
841204800Sjilles				argv++;
842204800Sjilles				argc--;
843204800Sjilles				bltinonly = 1;
844204800Sjilles			} else if (cmdentry.u.index == COMMANDCMD) {
845204800Sjilles				if (argc == 1)
846204800Sjilles					break;
847204800Sjilles				if (!strcmp(argv[1], "-p")) {
848204800Sjilles					if (argc == 2)
849204800Sjilles						break;
850204800Sjilles					if (argv[2][0] == '-') {
851204800Sjilles						if (strcmp(argv[2], "--"))
852204800Sjilles							break;
853204800Sjilles						if (argc == 3)
854204800Sjilles							break;
855204800Sjilles						argv += 3;
856204800Sjilles						argc -= 3;
857204800Sjilles					} else {
858204800Sjilles						argv += 2;
859204800Sjilles						argc -= 2;
860204800Sjilles					}
861204800Sjilles					path = _PATH_STDPATH;
862218324Sjilles					clearcmdentry();
863204800Sjilles					do_clearcmdentry = 1;
864204800Sjilles				} else if (!strcmp(argv[1], "--")) {
865204800Sjilles					if (argc == 2)
866204800Sjilles						break;
867204800Sjilles					argv += 2;
868204800Sjilles					argc -= 2;
869204800Sjilles				} else if (argv[1][0] == '-')
870204800Sjilles					break;
871204800Sjilles				else {
872204800Sjilles					argv++;
873204800Sjilles					argc--;
874204800Sjilles				}
875204800Sjilles				cmd_flags |= DO_NOFUNC;
876204800Sjilles				bltinonly = 0;
877204800Sjilles			} else
878204800Sjilles				break;
8791556Srgrimes		}
880204800Sjilles		/*
881204800Sjilles		 * Special builtins lose their special properties when
882204800Sjilles		 * called via 'command'.
883204800Sjilles		 */
884204800Sjilles		if (cmd_flags & DO_NOFUNC)
885204800Sjilles			cmdentry.special = 0;
8861556Srgrimes	}
8871556Srgrimes
8881556Srgrimes	/* Fork off a child process if necessary. */
8891556Srgrimes	if (cmd->ncmd.backgnd
890197820Sjilles	 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
891194127Sjilles	    && ((flags & EV_EXIT) == 0 || have_traps()))
89217987Speter	 || ((flags & EV_BACKCMD) != 0
893216826Sjilles	    && (cmdentry.cmdtype != CMDBUILTIN ||
894216826Sjilles		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
8951556Srgrimes		jp = makejob(cmd, 1);
8961556Srgrimes		mode = cmd->ncmd.backgnd;
8971556Srgrimes		if (flags & EV_BACKCMD) {
8981556Srgrimes			mode = FORK_NOJOB;
8991556Srgrimes			if (pipe(pip) < 0)
90053891Scracauer				error("Pipe call failed: %s", strerror(errno));
9011556Srgrimes		}
9021556Srgrimes		if (forkshell(jp, cmd, mode) != 0)
9031556Srgrimes			goto parent;	/* at end of routine */
9041556Srgrimes		if (flags & EV_BACKCMD) {
9051556Srgrimes			FORCEINTON;
9061556Srgrimes			close(pip[0]);
9071556Srgrimes			if (pip[1] != 1) {
908124780Sdes				dup2(pip[1], 1);
9091556Srgrimes				close(pip[1]);
9101556Srgrimes			}
9111556Srgrimes		}
9121556Srgrimes		flags |= EV_EXIT;
9131556Srgrimes	}
9141556Srgrimes
9151556Srgrimes	/* This is the child process if a fork occurred. */
9161556Srgrimes	/* Execute the command. */
9171556Srgrimes	if (cmdentry.cmdtype == CMDFUNCTION) {
91820425Ssteve#ifdef DEBUG
9191556Srgrimes		trputs("Shell function:  ");  trargs(argv);
92020425Ssteve#endif
9211556Srgrimes		saveparam = shellparam;
9221556Srgrimes		shellparam.malloc = 0;
92320425Ssteve		shellparam.reset = 1;
9241556Srgrimes		shellparam.nparam = argc - 1;
9251556Srgrimes		shellparam.p = argv + 1;
9261556Srgrimes		shellparam.optnext = NULL;
9271556Srgrimes		INTOFF;
9281556Srgrimes		savelocalvars = localvars;
9291556Srgrimes		localvars = NULL;
930196483Sjilles		reffunc(cmdentry.u.func);
931194765Sjilles		savehandler = handler;
9321556Srgrimes		if (setjmp(jmploc.loc)) {
933218306Sjilles			freeparam(&shellparam);
934218306Sjilles			shellparam = saveparam;
935220978Sjilles			popredir();
936196483Sjilles			unreffunc(cmdentry.u.func);
9371556Srgrimes			poplocalvars();
9381556Srgrimes			localvars = savelocalvars;
939201283Sjilles			funcnest--;
9401556Srgrimes			handler = savehandler;
9411556Srgrimes			longjmp(handler->loc, 1);
9421556Srgrimes		}
9431556Srgrimes		handler = &jmploc;
944201283Sjilles		funcnest++;
945204802Sjilles		redirect(cmd->ncmd.redirect, REDIR_PUSH);
946199660Sjilles		INTON;
9471556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
9481556Srgrimes			mklocal(sp->text);
949185231Sstefanf		exitstatus = oexitstatus;
950220978Sjilles		evaltree(getfuncnode(cmdentry.u.func),
951220978Sjilles		    flags & (EV_TESTED | EV_EXIT));
9521556Srgrimes		INTOFF;
953196483Sjilles		unreffunc(cmdentry.u.func);
9541556Srgrimes		poplocalvars();
9551556Srgrimes		localvars = savelocalvars;
9561556Srgrimes		freeparam(&shellparam);
9571556Srgrimes		shellparam = saveparam;
9581556Srgrimes		handler = savehandler;
959201283Sjilles		funcnest--;
9601556Srgrimes		popredir();
9611556Srgrimes		INTON;
9621556Srgrimes		if (evalskip == SKIPFUNC) {
9631556Srgrimes			evalskip = 0;
9641556Srgrimes			skipcount = 0;
9651556Srgrimes		}
966217035Sjilles		if (jp)
9671556Srgrimes			exitshell(exitstatus);
9681556Srgrimes	} else if (cmdentry.cmdtype == CMDBUILTIN) {
96920425Ssteve#ifdef DEBUG
9701556Srgrimes		trputs("builtin command:  ");  trargs(argv);
97120425Ssteve#endif
9721556Srgrimes		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
9731556Srgrimes		if (flags == EV_BACKCMD) {
9741556Srgrimes			memout.nleft = 0;
9751556Srgrimes			memout.nextc = memout.buf;
9761556Srgrimes			memout.bufsize = 64;
9771556Srgrimes			mode |= REDIR_BACKQ;
978201366Sjilles			cmdentry.special = 0;
9791556Srgrimes		}
9801556Srgrimes		savecmdname = commandname;
981199647Sjilles		savetopfile = getcurrentfile();
9821556Srgrimes		cmdenviron = varlist.list;
9831556Srgrimes		e = -1;
984194765Sjilles		savehandler = handler;
9851556Srgrimes		if (setjmp(jmploc.loc)) {
9861556Srgrimes			e = exception;
987220978Sjilles			if (e == EXINT)
988220978Sjilles				exitstatus = SIGINT+128;
989220978Sjilles			else if (e != EXEXIT)
990220978Sjilles				exitstatus = 2;
9911556Srgrimes			goto cmddone;
9921556Srgrimes		}
9931556Srgrimes		handler = &jmploc;
994157601Sstefanf		redirect(cmd->ncmd.redirect, mode);
995205138Sjilles		/*
996205138Sjilles		 * If there is no command word, redirection errors should
997205138Sjilles		 * not be fatal but assignment errors should.
998205138Sjilles		 */
999205138Sjilles		if (argc == 0 && !(flags & EV_BACKCMD))
1000205138Sjilles			cmdentry.special = 1;
1001216870Sjilles		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1002207678Sjilles		if (argc > 0)
1003207678Sjilles			bltinsetlocale();
10041556Srgrimes		commandname = argv[0];
10051556Srgrimes		argptr = argv + 1;
1006201053Sjilles		nextopt_optptr = NULL;		/* initialize nextopt */
1007193169Sstefanf		builtin_flags = flags;
10081556Srgrimes		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
10091556Srgrimes		flushall();
10101556Srgrimescmddone:
1011207678Sjilles		if (argc > 0)
1012207678Sjilles			bltinunsetlocale();
101360592Scracauer		cmdenviron = NULL;
10141556Srgrimes		out1 = &output;
10151556Srgrimes		out2 = &errout;
10161556Srgrimes		freestdout();
1017217035Sjilles		handler = savehandler;
1018218306Sjilles		commandname = savecmdname;
1019218306Sjilles		if (jp)
1020218306Sjilles			exitshell(exitstatus);
1021201366Sjilles		if (flags == EV_BACKCMD) {
1022201366Sjilles			backcmd->buf = memout.buf;
1023201366Sjilles			backcmd->nleft = memout.nextc - memout.buf;
1024201366Sjilles			memout.buf = NULL;
1025201366Sjilles		}
1026220978Sjilles		if (cmdentry.u.index != EXECCMD)
1027204801Sjilles			popredir();
10281556Srgrimes		if (e != -1) {
102920425Ssteve			if ((e != EXERROR && e != EXEXEC)
1030157601Sstefanf			    || cmdentry.special)
10311556Srgrimes				exraise(e);
1032199647Sjilles			popfilesupto(savetopfile);
1033201366Sjilles			if (flags != EV_BACKCMD)
1034201366Sjilles				FORCEINTON;
10351556Srgrimes		}
10361556Srgrimes	} else {
103720425Ssteve#ifdef DEBUG
10381556Srgrimes		trputs("normal command:  ");  trargs(argv);
103920425Ssteve#endif
10401556Srgrimes		redirect(cmd->ncmd.redirect, 0);
10411556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
10421556Srgrimes			setvareq(sp->text, VEXPORT|VSTACK);
10431556Srgrimes		envp = environment();
1044204800Sjilles		shellexec(argv, envp, path, cmdentry.u.index);
10451556Srgrimes		/*NOTREACHED*/
10461556Srgrimes	}
10471556Srgrimes	goto out;
10481556Srgrimes
10491556Srgrimesparent:	/* parent process gets here (if we forked) */
1050212214Sjilles	if (mode == FORK_FG) {	/* argument to fork */
10511556Srgrimes		INTOFF;
105245916Scracauer		exitstatus = waitforjob(jp, &realstatus);
10531556Srgrimes		INTON;
105445916Scracauer		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
105545266Scracauer			evalskip = SKIPBREAK;
105645266Scracauer			skipcount = loopnest;
105745266Scracauer		}
1058212214Sjilles	} else if (mode == FORK_NOJOB) {
10591556Srgrimes		backcmd->fd = pip[0];
10601556Srgrimes		close(pip[1]);
10611556Srgrimes		backcmd->jp = jp;
1062221027Sjilles	} else
1063221027Sjilles		exitstatus = 0;
10641556Srgrimes
10651556Srgrimesout:
10661556Srgrimes	if (lastarg)
10671556Srgrimes		setvar("_", lastarg, 0);
106854884Scracauer	if (do_clearcmdentry)
1069218324Sjilles		clearcmdentry();
10701556Srgrimes	popstackmark(&smark);
10711556Srgrimes}
10721556Srgrimes
10731556Srgrimes
10741556Srgrimes
10751556Srgrimes/*
10761556Srgrimes * Search for a command.  This is called before we fork so that the
10771556Srgrimes * location of the command will be available in the parent as well as
10781556Srgrimes * the child.  The check for "goodname" is an overly conservative
10791556Srgrimes * check that the name will not be subject to expansion.
10801556Srgrimes */
10811556Srgrimes
1082213811Sobrienstatic void
108390111Simpprehash(union node *n)
108417987Speter{
10851556Srgrimes	struct cmdentry entry;
10861556Srgrimes
1087159633Sstefanf	if (n && n->type == NCMD && n->ncmd.args)
108817987Speter		if (goodname(n->ncmd.args->narg.text))
108917987Speter			find_command(n->ncmd.args->narg.text, &entry, 0,
109017987Speter				     pathval());
10911556Srgrimes}
10921556Srgrimes
10931556Srgrimes
10941556Srgrimes
10951556Srgrimes/*
10961556Srgrimes * Builtin commands.  Builtin commands whose functions are closely
10971556Srgrimes * tied to evaluation are implemented here.
10981556Srgrimes */
10991556Srgrimes
11001556Srgrimes/*
1101201431Sjilles * No command given, a bltin command with no arguments, or a bltin command
1102201431Sjilles * with an invalid name.
11031556Srgrimes */
11041556Srgrimes
110517987Speterint
1106201431Sjillesbltincmd(int argc, char **argv)
110717987Speter{
1108201431Sjilles	if (argc > 1) {
1109201431Sjilles		out2fmt_flush("%s: not found\n", argv[1]);
1110201431Sjilles		return 127;
1111201431Sjilles	}
111220425Ssteve	/*
111317987Speter	 * Preserve exitstatus of a previous possible redirection
111420425Ssteve	 * as POSIX mandates
111517987Speter	 */
11161556Srgrimes	return exitstatus;
11171556Srgrimes}
11181556Srgrimes
11191556Srgrimes
11201556Srgrimes/*
11211556Srgrimes * Handle break and continue commands.  Break, continue, and return are
11221556Srgrimes * all handled by setting the evalskip flag.  The evaluation routines
11231556Srgrimes * above all check this flag, and if it is set they start skipping
11241556Srgrimes * commands rather than executing them.  The variable skipcount is
11251556Srgrimes * the number of loops to break/continue, or the number of function
11261556Srgrimes * levels to return.  (The latter is always 1.)  It should probably
11271556Srgrimes * be an error to break out of more loops than exist, but it isn't
11281556Srgrimes * in the standard shell so we don't make it one here.
11291556Srgrimes */
11301556Srgrimes
113117987Speterint
113290111Simpbreakcmd(int argc, char **argv)
113317987Speter{
113420425Ssteve	int n = argc > 1 ? number(argv[1]) : 1;
11351556Srgrimes
11361556Srgrimes	if (n > loopnest)
11371556Srgrimes		n = loopnest;
11381556Srgrimes	if (n > 0) {
11391556Srgrimes		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
11401556Srgrimes		skipcount = n;
11411556Srgrimes	}
11421556Srgrimes	return 0;
11431556Srgrimes}
11441556Srgrimes
1145100437Stjr/*
1146100437Stjr * The `command' command.
1147100437Stjr */
1148100437Stjrint
1149100437Stjrcommandcmd(int argc, char **argv)
1150100437Stjr{
1151207783Sjilles	const char *path;
1152100437Stjr	int ch;
1153151810Sstefanf	int cmd = -1;
11541556Srgrimes
1155204800Sjilles	path = bltinlookup("PATH", 1);
1156100437Stjr
1157100437Stjr	optind = optreset = 1;
1158100663Stjr	opterr = 0;
1159151810Sstefanf	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1160100437Stjr		switch (ch) {
1161100437Stjr		case 'p':
1162207783Sjilles			path = _PATH_STDPATH;
1163100437Stjr			break;
1164151810Sstefanf		case 'v':
1165151810Sstefanf			cmd = TYPECMD_SMALLV;
1166151810Sstefanf			break;
1167151810Sstefanf		case 'V':
1168151810Sstefanf			cmd = TYPECMD_BIGV;
1169151810Sstefanf			break;
1170100437Stjr		case '?':
1171100437Stjr		default:
1172100437Stjr			error("unknown option: -%c", optopt);
1173100437Stjr		}
1174100437Stjr	}
1175100437Stjr	argc -= optind;
1176100437Stjr	argv += optind;
1177100437Stjr
1178151810Sstefanf	if (cmd != -1) {
1179151810Sstefanf		if (argc != 1)
1180151810Sstefanf			error("wrong number of arguments");
1181201343Sjilles		return typecmd_impl(2, argv - 1, cmd, path);
1182151810Sstefanf	}
1183204800Sjilles	if (argc != 0)
1184214538Sjilles		error("commandcmd bad call");
1185100437Stjr
1186100437Stjr	/*
1187100437Stjr	 * Do nothing successfully if no command was specified;
1188100437Stjr	 * ksh also does this.
1189100437Stjr	 */
1190204800Sjilles	return 0;
1191100437Stjr}
1192100437Stjr
1193100437Stjr
11941556Srgrimes/*
11951556Srgrimes * The return command.
11961556Srgrimes */
11971556Srgrimes
119817987Speterint
119990111Simpreturncmd(int argc, char **argv)
120017987Speter{
120120425Ssteve	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
12021556Srgrimes
12031556Srgrimes	if (funcnest) {
12041556Srgrimes		evalskip = SKIPFUNC;
12051556Srgrimes		skipcount = 1;
120620425Ssteve	} else {
120720425Ssteve		/* skip the rest of the file */
120820425Ssteve		evalskip = SKIPFILE;
120920425Ssteve		skipcount = 1;
12101556Srgrimes	}
12111556Srgrimes	return ret;
12121556Srgrimes}
12131556Srgrimes
12141556Srgrimes
121517987Speterint
121690111Simpfalsecmd(int argc __unused, char **argv __unused)
121717987Speter{
121817987Speter	return 1;
121917987Speter}
122017987Speter
122117987Speter
122217987Speterint
122390111Simptruecmd(int argc __unused, char **argv __unused)
122417987Speter{
12251556Srgrimes	return 0;
12261556Srgrimes}
12271556Srgrimes
12281556Srgrimes
122917987Speterint
123090111Simpexeccmd(int argc, char **argv)
123117987Speter{
1232208630Sjilles	/*
1233208630Sjilles	 * Because we have historically not supported any options,
1234208630Sjilles	 * only treat "--" specially.
1235208630Sjilles	 */
1236208630Sjilles	if (argc > 1 && strcmp(argv[1], "--") == 0)
1237208630Sjilles		argc--, argv++;
12381556Srgrimes	if (argc > 1) {
123917987Speter		struct strlist *sp;
124017987Speter
12411556Srgrimes		iflag = 0;		/* exit on error */
12421556Srgrimes		mflag = 0;
12431556Srgrimes		optschanged();
124417987Speter		for (sp = cmdenviron; sp ; sp = sp->next)
124517987Speter			setvareq(sp->text, VEXPORT|VSTACK);
12461556Srgrimes		shellexec(argv + 1, environment(), pathval(), 0);
12471556Srgrimes
12481556Srgrimes	}
12491556Srgrimes	return 0;
12501556Srgrimes}
1251153091Sstefanf
1252153091Sstefanf
1253153091Sstefanfint
1254153091Sstefanftimescmd(int argc __unused, char **argv __unused)
1255153091Sstefanf{
1256153091Sstefanf	struct rusage ru;
1257153091Sstefanf	long shumins, shsmins, chumins, chsmins;
1258153091Sstefanf	double shusecs, shssecs, chusecs, chssecs;
1259153091Sstefanf
1260153091Sstefanf	if (getrusage(RUSAGE_SELF, &ru) < 0)
1261153091Sstefanf		return 1;
1262153091Sstefanf	shumins = ru.ru_utime.tv_sec / 60;
1263153091Sstefanf	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1264153091Sstefanf	shsmins = ru.ru_stime.tv_sec / 60;
1265153091Sstefanf	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1266153091Sstefanf	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1267153091Sstefanf		return 1;
1268153091Sstefanf	chumins = ru.ru_utime.tv_sec / 60;
1269153091Sstefanf	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1270153091Sstefanf	chsmins = ru.ru_stime.tv_sec / 60;
1271153091Sstefanf	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1272153091Sstefanf	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1273153091Sstefanf	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1274153091Sstefanf	return 0;
1275153091Sstefanf}
1276