eval.c revision 231085
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: stable/9/bin/sh/eval.c 231085 2012-02-06 13:29:50Z dumbbell $");
401556Srgrimes
41100437Stjr#include <paths.h>
4217987Speter#include <signal.h>
43102576Skeramida#include <stdlib.h>
4417987Speter#include <unistd.h>
45153091Sstefanf#include <sys/resource.h>
4645266Scracauer#include <sys/wait.h> /* For WIFSIGNALED(status) */
4753891Scracauer#include <errno.h>
4817987Speter
491556Srgrimes/*
501556Srgrimes * Evaluate a command.
511556Srgrimes */
521556Srgrimes
531556Srgrimes#include "shell.h"
541556Srgrimes#include "nodes.h"
551556Srgrimes#include "syntax.h"
561556Srgrimes#include "expand.h"
571556Srgrimes#include "parser.h"
581556Srgrimes#include "jobs.h"
591556Srgrimes#include "eval.h"
601556Srgrimes#include "builtins.h"
611556Srgrimes#include "options.h"
621556Srgrimes#include "exec.h"
631556Srgrimes#include "redir.h"
641556Srgrimes#include "input.h"
651556Srgrimes#include "output.h"
661556Srgrimes#include "trap.h"
671556Srgrimes#include "var.h"
681556Srgrimes#include "memalloc.h"
691556Srgrimes#include "error.h"
7017987Speter#include "show.h"
711556Srgrimes#include "mystring.h"
7217987Speter#ifndef NO_HISTORY
731556Srgrimes#include "myhistedit.h"
7417987Speter#endif
751556Srgrimes
761556Srgrimes
77201053Sjillesint evalskip;			/* set if we are skipping commands */
78231085Sdumbbellint skipcount;			/* number of levels to skip */
791556SrgrimesMKINIT int loopnest;		/* current loop nesting level */
801556Srgrimesint funcnest;			/* depth of function calls */
81213760Sobrienstatic int builtin_flags;	/* evalcommand flags for builtins */
821556Srgrimes
831556Srgrimes
841556Srgrimeschar *commandname;
851556Srgrimesstruct strlist *cmdenviron;
861556Srgrimesint exitstatus;			/* exit status of last command */
8717987Speterint oexitstatus;		/* saved exit status */
881556Srgrimes
891556Srgrimes
90213811Sobrienstatic void evalloop(union node *, int);
91213811Sobrienstatic void evalfor(union node *, int);
92213811Sobrienstatic void evalcase(union node *, int);
93213811Sobrienstatic void evalsubshell(union node *, int);
94213811Sobrienstatic void evalredir(union node *, int);
95213811Sobrienstatic void expredir(union node *);
96213811Sobrienstatic void evalpipe(union node *);
97216778Sjillesstatic int is_valid_fast_cmdsubst(union node *n);
98213811Sobrienstatic void evalcommand(union node *, int, struct backcmd *);
99213811Sobrienstatic void prehash(union node *);
1001556Srgrimes
1011556Srgrimes
1021556Srgrimes/*
1031556Srgrimes * Called to reset things after an exception.
1041556Srgrimes */
1051556Srgrimes
1061556Srgrimes#ifdef mkinit
1071556SrgrimesINCLUDE "eval.h"
1081556Srgrimes
1091556SrgrimesRESET {
1101556Srgrimes	evalskip = 0;
1111556Srgrimes	loopnest = 0;
1121556Srgrimes	funcnest = 0;
1131556Srgrimes}
1141556Srgrimes#endif
1151556Srgrimes
1161556Srgrimes
1171556Srgrimes
1181556Srgrimes/*
11946684Skris * The eval command.
1201556Srgrimes */
1211556Srgrimes
12217987Speterint
12390111Simpevalcmd(int argc, char **argv)
1241556Srgrimes{
1251556Srgrimes        char *p;
1261556Srgrimes        char *concat;
1271556Srgrimes        char **ap;
1281556Srgrimes
1291556Srgrimes        if (argc > 1) {
1301556Srgrimes                p = argv[1];
1311556Srgrimes                if (argc > 2) {
1321556Srgrimes                        STARTSTACKSTR(concat);
1331556Srgrimes                        ap = argv + 2;
1341556Srgrimes                        for (;;) {
135215783Sjilles                                STPUTS(p, concat);
1361556Srgrimes                                if ((p = *ap++) == NULL)
1371556Srgrimes                                        break;
1381556Srgrimes                                STPUTC(' ', concat);
1391556Srgrimes                        }
1401556Srgrimes                        STPUTC('\0', concat);
1411556Srgrimes                        p = grabstackstr(concat);
1421556Srgrimes                }
143223163Sjilles                evalstring(p, builtin_flags);
144210829Sjilles        } else
145210829Sjilles                exitstatus = 0;
1461556Srgrimes        return exitstatus;
1471556Srgrimes}
1481556Srgrimes
1491556Srgrimes
1501556Srgrimes/*
1511556Srgrimes * Execute a command or commands contained in a string.
1521556Srgrimes */
1531556Srgrimes
1541556Srgrimesvoid
155193169Sstefanfevalstring(char *s, int flags)
15690111Simp{
1571556Srgrimes	union node *n;
1581556Srgrimes	struct stackmark smark;
159194128Sjilles	int flags_exit;
160210829Sjilles	int any;
1611556Srgrimes
162194128Sjilles	flags_exit = flags & EV_EXIT;
163194128Sjilles	flags &= ~EV_EXIT;
164210829Sjilles	any = 0;
1651556Srgrimes	setstackmark(&smark);
1661556Srgrimes	setinputstring(s, 1);
1671556Srgrimes	while ((n = parsecmd(0)) != NEOF) {
168222676Sjilles		if (n != NULL && !nflag) {
169194128Sjilles			if (flags_exit && preadateof())
170194128Sjilles				evaltree(n, flags | EV_EXIT);
171194128Sjilles			else
172194128Sjilles				evaltree(n, flags);
173210829Sjilles			any = 1;
174194128Sjilles		}
1751556Srgrimes		popstackmark(&smark);
1761556Srgrimes	}
1771556Srgrimes	popfile();
1781556Srgrimes	popstackmark(&smark);
179210829Sjilles	if (!any)
180210829Sjilles		exitstatus = 0;
181194128Sjilles	if (flags_exit)
182220978Sjilles		exraise(EXEXIT);
1831556Srgrimes}
1841556Srgrimes
1851556Srgrimes
1861556Srgrimes/*
1871556Srgrimes * Evaluate a parse tree.  The value is left in the global variable
1881556Srgrimes * exitstatus.
1891556Srgrimes */
1901556Srgrimes
1911556Srgrimesvoid
19290111Simpevaltree(union node *n, int flags)
19317987Speter{
194149927Sstefanf	int do_etest;
195214599Sjilles	union node *next;
196149927Sstefanf
197149927Sstefanf	do_etest = 0;
1981556Srgrimes	if (n == NULL) {
1991556Srgrimes		TRACE(("evaltree(NULL) called\n"));
2001556Srgrimes		exitstatus = 0;
2011556Srgrimes		goto out;
2021556Srgrimes	}
203214599Sjilles	do {
204214600Sjilles		next = NULL;
20517987Speter#ifndef NO_HISTORY
206214600Sjilles		displayhist = 1;	/* show history substitutions done with fc */
20717987Speter#endif
208214600Sjilles		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
209214600Sjilles		switch (n->type) {
210214600Sjilles		case NSEMI:
211214600Sjilles			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
212214600Sjilles			if (evalskip)
213214600Sjilles				goto out;
214214600Sjilles			next = n->nbinary.ch2;
215214600Sjilles			break;
216214600Sjilles		case NAND:
217214600Sjilles			evaltree(n->nbinary.ch1, EV_TESTED);
218214600Sjilles			if (evalskip || exitstatus != 0) {
219214600Sjilles				goto out;
220214600Sjilles			}
221214600Sjilles			next = n->nbinary.ch2;
222214600Sjilles			break;
223214600Sjilles		case NOR:
224214600Sjilles			evaltree(n->nbinary.ch1, EV_TESTED);
225214600Sjilles			if (evalskip || exitstatus == 0)
226214600Sjilles				goto out;
227214600Sjilles			next = n->nbinary.ch2;
228214600Sjilles			break;
229214600Sjilles		case NREDIR:
230214600Sjilles			evalredir(n, flags);
231214600Sjilles			break;
232214600Sjilles		case NSUBSHELL:
233214600Sjilles			evalsubshell(n, flags);
234214600Sjilles			do_etest = !(flags & EV_TESTED);
235214600Sjilles			break;
236214600Sjilles		case NBACKGND:
237214600Sjilles			evalsubshell(n, flags);
238214600Sjilles			break;
239214600Sjilles		case NIF: {
240214600Sjilles			evaltree(n->nif.test, EV_TESTED);
241214600Sjilles			if (evalskip)
242214600Sjilles				goto out;
243214600Sjilles			if (exitstatus == 0)
244214600Sjilles				next = n->nif.ifpart;
245214600Sjilles			else if (n->nif.elsepart)
246214600Sjilles				next = n->nif.elsepart;
247214600Sjilles			else
248214600Sjilles				exitstatus = 0;
249214600Sjilles			break;
25018754Ssteve		}
251214600Sjilles		case NWHILE:
252214600Sjilles		case NUNTIL:
253214600Sjilles			evalloop(n, flags & ~EV_EXIT);
254214600Sjilles			break;
255214600Sjilles		case NFOR:
256214600Sjilles			evalfor(n, flags & ~EV_EXIT);
257214600Sjilles			break;
258214600Sjilles		case NCASE:
259214600Sjilles			evalcase(n, flags);
260214600Sjilles			break;
261214600Sjilles		case NDEFUN:
262214600Sjilles			defun(n->narg.text, n->narg.next);
26320425Ssteve			exitstatus = 0;
264214600Sjilles			break;
265214600Sjilles		case NNOT:
266214600Sjilles			evaltree(n->nnot.com, EV_TESTED);
267214600Sjilles			exitstatus = !exitstatus;
268214600Sjilles			break;
2691556Srgrimes
270214600Sjilles		case NPIPE:
271214600Sjilles			evalpipe(n);
272214600Sjilles			do_etest = !(flags & EV_TESTED);
273214600Sjilles			break;
274214600Sjilles		case NCMD:
275214600Sjilles			evalcommand(n, flags, (struct backcmd *)NULL);
276214600Sjilles			do_etest = !(flags & EV_TESTED);
277214600Sjilles			break;
278214600Sjilles		default:
279214600Sjilles			out1fmt("Node type = %d\n", n->type);
280214600Sjilles			flushout(&output);
281214600Sjilles			break;
282214600Sjilles		}
283214600Sjilles		n = next;
284214599Sjilles	} while (n != NULL);
2851556Srgrimesout:
2861556Srgrimes	if (pendingsigs)
2871556Srgrimes		dotrap();
288220978Sjilles	if (eflag && exitstatus != 0 && do_etest)
2891556Srgrimes		exitshell(exitstatus);
290220978Sjilles	if (flags & EV_EXIT)
291220978Sjilles		exraise(EXEXIT);
2921556Srgrimes}
2931556Srgrimes
2941556Srgrimes
295213811Sobrienstatic void
296149933Sstefanfevalloop(union node *n, int flags)
29717987Speter{
2981556Srgrimes	int status;
2991556Srgrimes
3001556Srgrimes	loopnest++;
3011556Srgrimes	status = 0;
3021556Srgrimes	for (;;) {
3031556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
3041556Srgrimes		if (evalskip) {
3051556Srgrimesskipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
3061556Srgrimes				evalskip = 0;
3071556Srgrimes				continue;
3081556Srgrimes			}
3091556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3101556Srgrimes				evalskip = 0;
311212475Sjilles			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
312212475Sjilles				status = exitstatus;
3131556Srgrimes			break;
3141556Srgrimes		}
3151556Srgrimes		if (n->type == NWHILE) {
3161556Srgrimes			if (exitstatus != 0)
3171556Srgrimes				break;
3181556Srgrimes		} else {
3191556Srgrimes			if (exitstatus == 0)
3201556Srgrimes				break;
3211556Srgrimes		}
322149933Sstefanf		evaltree(n->nbinary.ch2, flags);
3231556Srgrimes		status = exitstatus;
3241556Srgrimes		if (evalskip)
3251556Srgrimes			goto skipping;
3261556Srgrimes	}
3271556Srgrimes	loopnest--;
3281556Srgrimes	exitstatus = status;
3291556Srgrimes}
3301556Srgrimes
3311556Srgrimes
3321556Srgrimes
333213811Sobrienstatic void
334149933Sstefanfevalfor(union node *n, int flags)
33517987Speter{
3361556Srgrimes	struct arglist arglist;
3371556Srgrimes	union node *argp;
3381556Srgrimes	struct strlist *sp;
3391556Srgrimes	struct stackmark smark;
3401556Srgrimes
3411556Srgrimes	setstackmark(&smark);
3421556Srgrimes	arglist.lastp = &arglist.list;
3431556Srgrimes	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
34417987Speter		oexitstatus = exitstatus;
3451556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3461556Srgrimes		if (evalskip)
3471556Srgrimes			goto out;
3481556Srgrimes	}
3491556Srgrimes	*arglist.lastp = NULL;
3501556Srgrimes
3511556Srgrimes	exitstatus = 0;
3521556Srgrimes	loopnest++;
3531556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
3541556Srgrimes		setvar(n->nfor.var, sp->text, 0);
355149933Sstefanf		evaltree(n->nfor.body, flags);
3561556Srgrimes		if (evalskip) {
3571556Srgrimes			if (evalskip == SKIPCONT && --skipcount <= 0) {
3581556Srgrimes				evalskip = 0;
3591556Srgrimes				continue;
3601556Srgrimes			}
3611556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3621556Srgrimes				evalskip = 0;
3631556Srgrimes			break;
3641556Srgrimes		}
3651556Srgrimes	}
3661556Srgrimes	loopnest--;
3671556Srgrimesout:
3681556Srgrimes	popstackmark(&smark);
3691556Srgrimes}
3701556Srgrimes
3711556Srgrimes
3721556Srgrimes
373213811Sobrienstatic void
37490111Simpevalcase(union node *n, int flags)
37517987Speter{
3761556Srgrimes	union node *cp;
3771556Srgrimes	union node *patp;
3781556Srgrimes	struct arglist arglist;
3791556Srgrimes	struct stackmark smark;
3801556Srgrimes
3811556Srgrimes	setstackmark(&smark);
3821556Srgrimes	arglist.lastp = &arglist.list;
38317987Speter	oexitstatus = exitstatus;
384172440Sstefanf	exitstatus = 0;
3851556Srgrimes	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
3861556Srgrimes	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
3871556Srgrimes		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
3881556Srgrimes			if (casematch(patp, arglist.list->text)) {
389223186Sjilles				while (cp->nclist.next &&
390223186Sjilles				    cp->type == NCLISTFALLTHRU) {
391223186Sjilles					if (evalskip != 0)
392223186Sjilles						break;
393223186Sjilles					evaltree(cp->nclist.body,
394223186Sjilles					    flags & ~EV_EXIT);
395223186Sjilles					cp = cp->nclist.next;
396223186Sjilles				}
3971556Srgrimes				if (evalskip == 0) {
3981556Srgrimes					evaltree(cp->nclist.body, flags);
3991556Srgrimes				}
4001556Srgrimes				goto out;
4011556Srgrimes			}
4021556Srgrimes		}
4031556Srgrimes	}
4041556Srgrimesout:
4051556Srgrimes	popstackmark(&smark);
4061556Srgrimes}
4071556Srgrimes
4081556Srgrimes
4091556Srgrimes
4101556Srgrimes/*
4111556Srgrimes * Kick off a subshell to evaluate a tree.
4121556Srgrimes */
4131556Srgrimes
414213811Sobrienstatic void
41590111Simpevalsubshell(union node *n, int flags)
41617987Speter{
4171556Srgrimes	struct job *jp;
4181556Srgrimes	int backgnd = (n->type == NBACKGND);
4191556Srgrimes
420222716Sjilles	oexitstatus = exitstatus;
4211556Srgrimes	expredir(n->nredir.redirect);
422194774Sjilles	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
423194774Sjilles			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
4241556Srgrimes		if (backgnd)
4251556Srgrimes			flags &=~ EV_TESTED;
4261556Srgrimes		redirect(n->nredir.redirect, 0);
4271556Srgrimes		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
428201053Sjilles	} else if (! backgnd) {
4291556Srgrimes		INTOFF;
43045916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
4311556Srgrimes		INTON;
432221027Sjilles	} else
433221027Sjilles		exitstatus = 0;
4341556Srgrimes}
4351556Srgrimes
4361556Srgrimes
437205154Sjilles/*
438205154Sjilles * Evaluate a redirected compound command.
439205154Sjilles */
4401556Srgrimes
441213811Sobrienstatic void
442205154Sjillesevalredir(union node *n, int flags)
443205154Sjilles{
444205154Sjilles	struct jmploc jmploc;
445205154Sjilles	struct jmploc *savehandler;
446205154Sjilles	volatile int in_redirect = 1;
447205154Sjilles
448222716Sjilles	oexitstatus = exitstatus;
449205154Sjilles	expredir(n->nredir.redirect);
450205154Sjilles	savehandler = handler;
451205154Sjilles	if (setjmp(jmploc.loc)) {
452205154Sjilles		int e;
453205154Sjilles
454205154Sjilles		handler = savehandler;
455205154Sjilles		e = exception;
456220978Sjilles		popredir();
457205154Sjilles		if (e == EXERROR || e == EXEXEC) {
458205154Sjilles			if (in_redirect) {
459205154Sjilles				exitstatus = 2;
460205154Sjilles				return;
461205154Sjilles			}
462205154Sjilles		}
463205154Sjilles		longjmp(handler->loc, 1);
464205154Sjilles	} else {
465205154Sjilles		INTOFF;
466205154Sjilles		handler = &jmploc;
467205154Sjilles		redirect(n->nredir.redirect, REDIR_PUSH);
468205154Sjilles		in_redirect = 0;
469205154Sjilles		INTON;
470205154Sjilles		evaltree(n->nredir.n, flags);
471205154Sjilles	}
472205154Sjilles	INTOFF;
473205154Sjilles	handler = savehandler;
474205154Sjilles	popredir();
475205154Sjilles	INTON;
476205154Sjilles}
477205154Sjilles
478205154Sjilles
4791556Srgrimes/*
4801556Srgrimes * Compute the names of the files in a redirection list.
4811556Srgrimes */
4821556Srgrimes
483213811Sobrienstatic void
48490111Simpexpredir(union node *n)
48517987Speter{
48625222Ssteve	union node *redir;
4871556Srgrimes
4881556Srgrimes	for (redir = n ; redir ; redir = redir->nfile.next) {
48917987Speter		struct arglist fn;
49017987Speter		fn.lastp = &fn.list;
49117987Speter		switch (redir->type) {
49217987Speter		case NFROM:
49317987Speter		case NTO:
49466612Sbrian		case NFROMTO:
49517987Speter		case NAPPEND:
49696922Stjr		case NCLOBBER:
4971556Srgrimes			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
4981556Srgrimes			redir->nfile.expfname = fn.list->text;
49917987Speter			break;
50017987Speter		case NFROMFD:
50117987Speter		case NTOFD:
50217987Speter			if (redir->ndup.vname) {
503181017Sstefanf				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
50417987Speter				fixredir(redir, fn.list->text, 1);
50517987Speter			}
50617987Speter			break;
5071556Srgrimes		}
5081556Srgrimes	}
5091556Srgrimes}
5101556Srgrimes
5111556Srgrimes
5121556Srgrimes
5131556Srgrimes/*
5141556Srgrimes * Evaluate a pipeline.  All the processes in the pipeline are children
5151556Srgrimes * of the process creating the pipeline.  (This differs from some versions
5161556Srgrimes * of the shell, which make the last process in a pipeline the parent
5171556Srgrimes * of all the rest.)
5181556Srgrimes */
5191556Srgrimes
520213811Sobrienstatic void
52190111Simpevalpipe(union node *n)
52217987Speter{
5231556Srgrimes	struct job *jp;
5241556Srgrimes	struct nodelist *lp;
5251556Srgrimes	int pipelen;
5261556Srgrimes	int prevfd;
5271556Srgrimes	int pip[2];
5281556Srgrimes
529149802Sstefanf	TRACE(("evalpipe(%p) called\n", (void *)n));
5301556Srgrimes	pipelen = 0;
5311556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
5321556Srgrimes		pipelen++;
5331556Srgrimes	INTOFF;
5341556Srgrimes	jp = makejob(n, pipelen);
5351556Srgrimes	prevfd = -1;
5361556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
5371556Srgrimes		prehash(lp->n);
5381556Srgrimes		pip[1] = -1;
5391556Srgrimes		if (lp->next) {
5401556Srgrimes			if (pipe(pip) < 0) {
5411556Srgrimes				close(prevfd);
54253891Scracauer				error("Pipe call failed: %s", strerror(errno));
5431556Srgrimes			}
5441556Srgrimes		}
5451556Srgrimes		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
5461556Srgrimes			INTON;
5471556Srgrimes			if (prevfd > 0) {
548124780Sdes				dup2(prevfd, 0);
5491556Srgrimes				close(prevfd);
5501556Srgrimes			}
5511556Srgrimes			if (pip[1] >= 0) {
55253282Scracauer				if (!(prevfd >= 0 && pip[0] == 0))
55352900Scracauer					close(pip[0]);
5541556Srgrimes				if (pip[1] != 1) {
555124780Sdes					dup2(pip[1], 1);
5561556Srgrimes					close(pip[1]);
5571556Srgrimes				}
5581556Srgrimes			}
5591556Srgrimes			evaltree(lp->n, EV_EXIT);
5601556Srgrimes		}
5611556Srgrimes		if (prevfd >= 0)
5621556Srgrimes			close(prevfd);
5631556Srgrimes		prevfd = pip[0];
564221970Sjilles		if (pip[1] != -1)
565221970Sjilles			close(pip[1]);
5661556Srgrimes	}
5671556Srgrimes	INTON;
5681556Srgrimes	if (n->npipe.backgnd == 0) {
5691556Srgrimes		INTOFF;
57045916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
5711556Srgrimes		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
5721556Srgrimes		INTON;
573221027Sjilles	} else
574221027Sjilles		exitstatus = 0;
5751556Srgrimes}
5761556Srgrimes
5771556Srgrimes
5781556Srgrimes
579216778Sjillesstatic int
580216778Sjillesis_valid_fast_cmdsubst(union node *n)
581216778Sjilles{
582216778Sjilles
583223024Sjilles	return (n->type == NCMD);
584216778Sjilles}
585216778Sjilles
5861556Srgrimes/*
5871556Srgrimes * Execute a command inside back quotes.  If it's a builtin command, we
5881556Srgrimes * want to save its output in a block obtained from malloc.  Otherwise
5891556Srgrimes * we fork off a subprocess and get the output of the command via a pipe.
5901556Srgrimes * Should be called with interrupts off.
5911556Srgrimes */
5921556Srgrimes
5931556Srgrimesvoid
59490111Simpevalbackcmd(union node *n, struct backcmd *result)
59517987Speter{
5961556Srgrimes	int pip[2];
5971556Srgrimes	struct job *jp;
5981556Srgrimes	struct stackmark smark;		/* unnecessary */
599216761Sjilles	struct jmploc jmploc;
600216761Sjilles	struct jmploc *savehandler;
601223024Sjilles	struct localvar *savelocalvars;
6021556Srgrimes
6031556Srgrimes	setstackmark(&smark);
6041556Srgrimes	result->fd = -1;
6051556Srgrimes	result->buf = NULL;
6061556Srgrimes	result->nleft = 0;
6071556Srgrimes	result->jp = NULL;
60817987Speter	if (n == NULL) {
60917987Speter		exitstatus = 0;
6101556Srgrimes		goto out;
61117987Speter	}
612216778Sjilles	if (is_valid_fast_cmdsubst(n)) {
61317987Speter		exitstatus = oexitstatus;
614223024Sjilles		savelocalvars = localvars;
615223024Sjilles		localvars = NULL;
616223024Sjilles		forcelocal++;
617216761Sjilles		savehandler = handler;
618216761Sjilles		if (setjmp(jmploc.loc)) {
619216761Sjilles			if (exception == EXERROR || exception == EXEXEC)
620216761Sjilles				exitstatus = 2;
621216761Sjilles			else if (exception != 0) {
622216761Sjilles				handler = savehandler;
623223024Sjilles				forcelocal--;
624223024Sjilles				poplocalvars();
625223024Sjilles				localvars = savelocalvars;
626216761Sjilles				longjmp(handler->loc, 1);
627216761Sjilles			}
628216761Sjilles		} else {
629216761Sjilles			handler = &jmploc;
630216761Sjilles			evalcommand(n, EV_BACKCMD, result);
631216761Sjilles		}
632216761Sjilles		handler = savehandler;
633223024Sjilles		forcelocal--;
634223024Sjilles		poplocalvars();
635223024Sjilles		localvars = savelocalvars;
6361556Srgrimes	} else {
63717987Speter		exitstatus = 0;
6381556Srgrimes		if (pipe(pip) < 0)
63953891Scracauer			error("Pipe call failed: %s", strerror(errno));
6401556Srgrimes		jp = makejob(n, 1);
6411556Srgrimes		if (forkshell(jp, n, FORK_NOJOB) == 0) {
6421556Srgrimes			FORCEINTON;
6431556Srgrimes			close(pip[0]);
6441556Srgrimes			if (pip[1] != 1) {
645124780Sdes				dup2(pip[1], 1);
6461556Srgrimes				close(pip[1]);
6471556Srgrimes			}
6481556Srgrimes			evaltree(n, EV_EXIT);
6491556Srgrimes		}
6501556Srgrimes		close(pip[1]);
6511556Srgrimes		result->fd = pip[0];
6521556Srgrimes		result->jp = jp;
6531556Srgrimes	}
6541556Srgrimesout:
6551556Srgrimes	popstackmark(&smark);
656109627Stjr	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
6571556Srgrimes		result->fd, result->buf, result->nleft, result->jp));
6581556Srgrimes}
6591556Srgrimes
660216826Sjilles/*
661216826Sjilles * Check if a builtin can safely be executed in the same process,
662216826Sjilles * even though it should be in a subshell (command substitution).
663216826Sjilles * Note that jobid, jobs, times and trap can show information not
664216826Sjilles * available in a child process; this is deliberate.
665216826Sjilles * The arguments should already have been expanded.
666216826Sjilles */
667216826Sjillesstatic int
668216826Sjillessafe_builtin(int idx, int argc, char **argv)
669216826Sjilles{
670216826Sjilles	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
671216826Sjilles	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
672216826Sjilles	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
673216826Sjilles	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
674216826Sjilles	    idx == TYPECMD)
675216826Sjilles		return (1);
676216826Sjilles	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
677216826Sjilles	    idx == UMASKCMD)
678216826Sjilles		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
679216826Sjilles	if (idx == SETCMD)
680216826Sjilles		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
681216826Sjilles		    argv[1][0] == '+') && argv[1][1] == 'o' &&
682216826Sjilles		    argv[1][2] == '\0'));
683216826Sjilles	return (0);
684216826Sjilles}
6851556Srgrimes
6861556Srgrimes/*
6871556Srgrimes * Execute a simple command.
688217035Sjilles * Note: This may or may not return if (flags & EV_EXIT).
6891556Srgrimes */
6901556Srgrimes
691213811Sobrienstatic void
69290111Simpevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
69317987Speter{
6941556Srgrimes	struct stackmark smark;
6951556Srgrimes	union node *argp;
6961556Srgrimes	struct arglist arglist;
6971556Srgrimes	struct arglist varlist;
6981556Srgrimes	char **argv;
6991556Srgrimes	int argc;
7001556Srgrimes	char **envp;
7011556Srgrimes	int varflag;
7021556Srgrimes	struct strlist *sp;
7031556Srgrimes	int mode;
7041556Srgrimes	int pip[2];
7051556Srgrimes	struct cmdentry cmdentry;
7061556Srgrimes	struct job *jp;
7071556Srgrimes	struct jmploc jmploc;
708194765Sjilles	struct jmploc *savehandler;
709194765Sjilles	char *savecmdname;
710194765Sjilles	struct shparam saveparam;
711194765Sjilles	struct localvar *savelocalvars;
712199647Sjilles	struct parsefile *savetopfile;
7131556Srgrimes	volatile int e;
7141556Srgrimes	char *lastarg;
71545916Scracauer	int realstatus;
71654884Scracauer	int do_clearcmdentry;
717211287Sjilles	const char *path = pathval();
7181556Srgrimes
7191556Srgrimes	/* First expand the arguments. */
720149802Sstefanf	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
7211556Srgrimes	setstackmark(&smark);
7221556Srgrimes	arglist.lastp = &arglist.list;
7231556Srgrimes	varlist.lastp = &varlist.list;
7241556Srgrimes	varflag = 1;
725217035Sjilles	jp = NULL;
72654884Scracauer	do_clearcmdentry = 0;
72717987Speter	oexitstatus = exitstatus;
72817987Speter	exitstatus = 0;
7291556Srgrimes	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
730222165Sjilles		if (varflag && isassignment(argp->narg.text)) {
731222165Sjilles			expandarg(argp, &varlist, EXP_VARTILDE);
732222165Sjilles			continue;
7331556Srgrimes		}
7341556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
7351556Srgrimes		varflag = 0;
7361556Srgrimes	}
7371556Srgrimes	*arglist.lastp = NULL;
7381556Srgrimes	*varlist.lastp = NULL;
7391556Srgrimes	expredir(cmd->ncmd.redirect);
7401556Srgrimes	argc = 0;
7411556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next)
7421556Srgrimes		argc++;
743218306Sjilles	/* Add one slot at the beginning for tryexec(). */
744218306Sjilles	argv = stalloc(sizeof (char *) * (argc + 2));
745218306Sjilles	argv++;
7461556Srgrimes
7471556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
7481556Srgrimes		TRACE(("evalcommand arg: %s\n", sp->text));
7491556Srgrimes		*argv++ = sp->text;
7501556Srgrimes	}
7511556Srgrimes	*argv = NULL;
7521556Srgrimes	lastarg = NULL;
7531556Srgrimes	if (iflag && funcnest == 0 && argc > 0)
7541556Srgrimes		lastarg = argv[-1];
7551556Srgrimes	argv -= argc;
7561556Srgrimes
7571556Srgrimes	/* Print the command if xflag is set. */
7581556Srgrimes	if (xflag) {
759159632Sstefanf		char sep = 0;
760222907Sjilles		const char *p, *ps4;
761222907Sjilles		ps4 = expandstr(ps4val());
762222907Sjilles		out2str(ps4 != NULL ? ps4 : ps4val());
7631556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next) {
764159632Sstefanf			if (sep != 0)
765201366Sjilles				out2c(' ');
766215567Sjilles			p = strchr(sp->text, '=');
767215567Sjilles			if (p != NULL) {
768215567Sjilles				p++;
769215567Sjilles				outbin(sp->text, p - sp->text, out2);
770194786Sjilles				out2qstr(p);
771215567Sjilles			} else
772215567Sjilles				out2qstr(sp->text);
773159632Sstefanf			sep = ' ';
7741556Srgrimes		}
7751556Srgrimes		for (sp = arglist.list ; sp ; sp = sp->next) {
776159632Sstefanf			if (sep != 0)
777201366Sjilles				out2c(' ');
778194786Sjilles			/* Disambiguate command looking like assignment. */
779194786Sjilles			if (sp == arglist.list &&
780194786Sjilles					strchr(sp->text, '=') != NULL &&
781194786Sjilles					strchr(sp->text, '\'') == NULL) {
782194786Sjilles				out2c('\'');
783194786Sjilles				out2str(sp->text);
784194786Sjilles				out2c('\'');
785194786Sjilles			} else
786194786Sjilles				out2qstr(sp->text);
787159632Sstefanf			sep = ' ';
7881556Srgrimes		}
789201366Sjilles		out2c('\n');
7901556Srgrimes		flushout(&errout);
7911556Srgrimes	}
7921556Srgrimes
7931556Srgrimes	/* Now locate the command. */
7941556Srgrimes	if (argc == 0) {
795157601Sstefanf		/* Variable assignment(s) without command */
7961556Srgrimes		cmdentry.cmdtype = CMDBUILTIN;
7971556Srgrimes		cmdentry.u.index = BLTINCMD;
798205138Sjilles		cmdentry.special = 0;
7991556Srgrimes	} else {
80017987Speter		static const char PATH[] = "PATH=";
801204800Sjilles		int cmd_flags = 0, bltinonly = 0;
80217987Speter
80317987Speter		/*
80417987Speter		 * Modify the command lookup path, if a PATH= assignment
80517987Speter		 * is present
80617987Speter		 */
80717987Speter		for (sp = varlist.list ; sp ; sp = sp->next)
80854884Scracauer			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
80917987Speter				path = sp->text + sizeof(PATH) - 1;
810155301Sschweikh				/*
81154884Scracauer				 * On `PATH=... command`, we need to make
81254884Scracauer				 * sure that the command isn't using the
81354884Scracauer				 * non-updated hash table of the outer PATH
814155301Sschweikh				 * setting and we need to make sure that
81554884Scracauer				 * the hash table isn't filled with items
81654884Scracauer				 * from the temporary setting.
81754884Scracauer				 *
818155301Sschweikh				 * It would be better to forbit using and
81954884Scracauer				 * updating the table while this command
82054884Scracauer				 * runs, by the command finding mechanism
82154884Scracauer				 * is heavily integrated with hash handling,
82254884Scracauer				 * so we just delete the hash before and after
82354884Scracauer				 * the command runs. Partly deleting like
82454884Scracauer				 * changepatch() does doesn't seem worth the
82554884Scracauer				 * bookinging effort, since most such runs add
826123996Smaxim				 * directories in front of the new PATH.
82754884Scracauer				 */
828218324Sjilles				clearcmdentry();
82954884Scracauer				do_clearcmdentry = 1;
83054884Scracauer			}
83117987Speter
832204800Sjilles		for (;;) {
833204800Sjilles			if (bltinonly) {
834204800Sjilles				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
835204800Sjilles				if (cmdentry.u.index < 0) {
836201431Sjilles					cmdentry.u.index = BLTINCMD;
837201431Sjilles					argv--;
838201431Sjilles					argc++;
839201431Sjilles					break;
8401556Srgrimes				}
841204800Sjilles			} else
842204800Sjilles				find_command(argv[0], &cmdentry, cmd_flags, path);
843204800Sjilles			/* implement the bltin and command builtins here */
844204800Sjilles			if (cmdentry.cmdtype != CMDBUILTIN)
845204800Sjilles				break;
846204800Sjilles			if (cmdentry.u.index == BLTINCMD) {
847204800Sjilles				if (argc == 1)
8481556Srgrimes					break;
849204800Sjilles				argv++;
850204800Sjilles				argc--;
851204800Sjilles				bltinonly = 1;
852204800Sjilles			} else if (cmdentry.u.index == COMMANDCMD) {
853204800Sjilles				if (argc == 1)
854204800Sjilles					break;
855204800Sjilles				if (!strcmp(argv[1], "-p")) {
856204800Sjilles					if (argc == 2)
857204800Sjilles						break;
858204800Sjilles					if (argv[2][0] == '-') {
859204800Sjilles						if (strcmp(argv[2], "--"))
860204800Sjilles							break;
861204800Sjilles						if (argc == 3)
862204800Sjilles							break;
863204800Sjilles						argv += 3;
864204800Sjilles						argc -= 3;
865204800Sjilles					} else {
866204800Sjilles						argv += 2;
867204800Sjilles						argc -= 2;
868204800Sjilles					}
869204800Sjilles					path = _PATH_STDPATH;
870218324Sjilles					clearcmdentry();
871204800Sjilles					do_clearcmdentry = 1;
872204800Sjilles				} else if (!strcmp(argv[1], "--")) {
873204800Sjilles					if (argc == 2)
874204800Sjilles						break;
875204800Sjilles					argv += 2;
876204800Sjilles					argc -= 2;
877204800Sjilles				} else if (argv[1][0] == '-')
878204800Sjilles					break;
879204800Sjilles				else {
880204800Sjilles					argv++;
881204800Sjilles					argc--;
882204800Sjilles				}
883204800Sjilles				cmd_flags |= DO_NOFUNC;
884204800Sjilles				bltinonly = 0;
885204800Sjilles			} else
886204800Sjilles				break;
8871556Srgrimes		}
888204800Sjilles		/*
889204800Sjilles		 * Special builtins lose their special properties when
890204800Sjilles		 * called via 'command'.
891204800Sjilles		 */
892204800Sjilles		if (cmd_flags & DO_NOFUNC)
893204800Sjilles			cmdentry.special = 0;
8941556Srgrimes	}
8951556Srgrimes
8961556Srgrimes	/* Fork off a child process if necessary. */
897223282Sjilles	if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
898194127Sjilles	    && ((flags & EV_EXIT) == 0 || have_traps()))
89917987Speter	 || ((flags & EV_BACKCMD) != 0
900216826Sjilles	    && (cmdentry.cmdtype != CMDBUILTIN ||
901216826Sjilles		 !safe_builtin(cmdentry.u.index, argc, argv)))) {
9021556Srgrimes		jp = makejob(cmd, 1);
903223282Sjilles		mode = FORK_FG;
9041556Srgrimes		if (flags & EV_BACKCMD) {
9051556Srgrimes			mode = FORK_NOJOB;
9061556Srgrimes			if (pipe(pip) < 0)
90753891Scracauer				error("Pipe call failed: %s", strerror(errno));
9081556Srgrimes		}
9091556Srgrimes		if (forkshell(jp, cmd, mode) != 0)
9101556Srgrimes			goto parent;	/* at end of routine */
9111556Srgrimes		if (flags & EV_BACKCMD) {
9121556Srgrimes			FORCEINTON;
9131556Srgrimes			close(pip[0]);
9141556Srgrimes			if (pip[1] != 1) {
915124780Sdes				dup2(pip[1], 1);
9161556Srgrimes				close(pip[1]);
9171556Srgrimes			}
918223163Sjilles			flags &= ~EV_BACKCMD;
9191556Srgrimes		}
9201556Srgrimes		flags |= EV_EXIT;
9211556Srgrimes	}
9221556Srgrimes
9231556Srgrimes	/* This is the child process if a fork occurred. */
9241556Srgrimes	/* Execute the command. */
9251556Srgrimes	if (cmdentry.cmdtype == CMDFUNCTION) {
92620425Ssteve#ifdef DEBUG
9271556Srgrimes		trputs("Shell function:  ");  trargs(argv);
92820425Ssteve#endif
9291556Srgrimes		saveparam = shellparam;
9301556Srgrimes		shellparam.malloc = 0;
93120425Ssteve		shellparam.reset = 1;
9321556Srgrimes		shellparam.nparam = argc - 1;
9331556Srgrimes		shellparam.p = argv + 1;
9341556Srgrimes		shellparam.optnext = NULL;
9351556Srgrimes		INTOFF;
9361556Srgrimes		savelocalvars = localvars;
9371556Srgrimes		localvars = NULL;
938196483Sjilles		reffunc(cmdentry.u.func);
939194765Sjilles		savehandler = handler;
9401556Srgrimes		if (setjmp(jmploc.loc)) {
941218306Sjilles			freeparam(&shellparam);
942218306Sjilles			shellparam = saveparam;
943220978Sjilles			popredir();
944196483Sjilles			unreffunc(cmdentry.u.func);
9451556Srgrimes			poplocalvars();
9461556Srgrimes			localvars = savelocalvars;
947201283Sjilles			funcnest--;
9481556Srgrimes			handler = savehandler;
9491556Srgrimes			longjmp(handler->loc, 1);
9501556Srgrimes		}
9511556Srgrimes		handler = &jmploc;
952201283Sjilles		funcnest++;
953204802Sjilles		redirect(cmd->ncmd.redirect, REDIR_PUSH);
954199660Sjilles		INTON;
9551556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
9561556Srgrimes			mklocal(sp->text);
957185231Sstefanf		exitstatus = oexitstatus;
958220978Sjilles		evaltree(getfuncnode(cmdentry.u.func),
959220978Sjilles		    flags & (EV_TESTED | EV_EXIT));
9601556Srgrimes		INTOFF;
961196483Sjilles		unreffunc(cmdentry.u.func);
9621556Srgrimes		poplocalvars();
9631556Srgrimes		localvars = savelocalvars;
9641556Srgrimes		freeparam(&shellparam);
9651556Srgrimes		shellparam = saveparam;
9661556Srgrimes		handler = savehandler;
967201283Sjilles		funcnest--;
9681556Srgrimes		popredir();
9691556Srgrimes		INTON;
9701556Srgrimes		if (evalskip == SKIPFUNC) {
9711556Srgrimes			evalskip = 0;
9721556Srgrimes			skipcount = 0;
9731556Srgrimes		}
974217035Sjilles		if (jp)
9751556Srgrimes			exitshell(exitstatus);
9761556Srgrimes	} else if (cmdentry.cmdtype == CMDBUILTIN) {
97720425Ssteve#ifdef DEBUG
9781556Srgrimes		trputs("builtin command:  ");  trargs(argv);
97920425Ssteve#endif
9801556Srgrimes		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
9811556Srgrimes		if (flags == EV_BACKCMD) {
9821556Srgrimes			memout.nleft = 0;
9831556Srgrimes			memout.nextc = memout.buf;
9841556Srgrimes			memout.bufsize = 64;
9851556Srgrimes			mode |= REDIR_BACKQ;
9861556Srgrimes		}
9871556Srgrimes		savecmdname = commandname;
988199647Sjilles		savetopfile = getcurrentfile();
9891556Srgrimes		cmdenviron = varlist.list;
9901556Srgrimes		e = -1;
991194765Sjilles		savehandler = handler;
9921556Srgrimes		if (setjmp(jmploc.loc)) {
9931556Srgrimes			e = exception;
994220978Sjilles			if (e == EXINT)
995220978Sjilles				exitstatus = SIGINT+128;
996220978Sjilles			else if (e != EXEXIT)
997220978Sjilles				exitstatus = 2;
9981556Srgrimes			goto cmddone;
9991556Srgrimes		}
10001556Srgrimes		handler = &jmploc;
1001157601Sstefanf		redirect(cmd->ncmd.redirect, mode);
1002205138Sjilles		/*
1003205138Sjilles		 * If there is no command word, redirection errors should
1004205138Sjilles		 * not be fatal but assignment errors should.
1005205138Sjilles		 */
1006230625Sjilles		if (argc == 0)
1007205138Sjilles			cmdentry.special = 1;
1008216870Sjilles		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
1009207678Sjilles		if (argc > 0)
1010207678Sjilles			bltinsetlocale();
10111556Srgrimes		commandname = argv[0];
10121556Srgrimes		argptr = argv + 1;
1013201053Sjilles		nextopt_optptr = NULL;		/* initialize nextopt */
1014193169Sstefanf		builtin_flags = flags;
10151556Srgrimes		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
10161556Srgrimes		flushall();
10171556Srgrimescmddone:
1018207678Sjilles		if (argc > 0)
1019207678Sjilles			bltinunsetlocale();
102060592Scracauer		cmdenviron = NULL;
10211556Srgrimes		out1 = &output;
10221556Srgrimes		out2 = &errout;
10231556Srgrimes		freestdout();
1024217035Sjilles		handler = savehandler;
1025218306Sjilles		commandname = savecmdname;
1026218306Sjilles		if (jp)
1027218306Sjilles			exitshell(exitstatus);
1028201366Sjilles		if (flags == EV_BACKCMD) {
1029201366Sjilles			backcmd->buf = memout.buf;
1030201366Sjilles			backcmd->nleft = memout.nextc - memout.buf;
1031201366Sjilles			memout.buf = NULL;
1032201366Sjilles		}
1033220978Sjilles		if (cmdentry.u.index != EXECCMD)
1034204801Sjilles			popredir();
10351556Srgrimes		if (e != -1) {
103620425Ssteve			if ((e != EXERROR && e != EXEXEC)
1037157601Sstefanf			    || cmdentry.special)
10381556Srgrimes				exraise(e);
1039199647Sjilles			popfilesupto(savetopfile);
1040201366Sjilles			if (flags != EV_BACKCMD)
1041201366Sjilles				FORCEINTON;
10421556Srgrimes		}
10431556Srgrimes	} else {
104420425Ssteve#ifdef DEBUG
10451556Srgrimes		trputs("normal command:  ");  trargs(argv);
104620425Ssteve#endif
10471556Srgrimes		redirect(cmd->ncmd.redirect, 0);
10481556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
10491556Srgrimes			setvareq(sp->text, VEXPORT|VSTACK);
10501556Srgrimes		envp = environment();
1051204800Sjilles		shellexec(argv, envp, path, cmdentry.u.index);
10521556Srgrimes		/*NOTREACHED*/
10531556Srgrimes	}
10541556Srgrimes	goto out;
10551556Srgrimes
10561556Srgrimesparent:	/* parent process gets here (if we forked) */
1057212214Sjilles	if (mode == FORK_FG) {	/* argument to fork */
10581556Srgrimes		INTOFF;
105945916Scracauer		exitstatus = waitforjob(jp, &realstatus);
10601556Srgrimes		INTON;
106145916Scracauer		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
106245266Scracauer			evalskip = SKIPBREAK;
106345266Scracauer			skipcount = loopnest;
106445266Scracauer		}
1065212214Sjilles	} else if (mode == FORK_NOJOB) {
10661556Srgrimes		backcmd->fd = pip[0];
10671556Srgrimes		close(pip[1]);
10681556Srgrimes		backcmd->jp = jp;
1069223282Sjilles	}
10701556Srgrimes
10711556Srgrimesout:
10721556Srgrimes	if (lastarg)
10731556Srgrimes		setvar("_", lastarg, 0);
107454884Scracauer	if (do_clearcmdentry)
1075218324Sjilles		clearcmdentry();
10761556Srgrimes	popstackmark(&smark);
10771556Srgrimes}
10781556Srgrimes
10791556Srgrimes
10801556Srgrimes
10811556Srgrimes/*
10821556Srgrimes * Search for a command.  This is called before we fork so that the
10831556Srgrimes * location of the command will be available in the parent as well as
10841556Srgrimes * the child.  The check for "goodname" is an overly conservative
10851556Srgrimes * check that the name will not be subject to expansion.
10861556Srgrimes */
10871556Srgrimes
1088213811Sobrienstatic void
108990111Simpprehash(union node *n)
109017987Speter{
10911556Srgrimes	struct cmdentry entry;
10921556Srgrimes
1093159633Sstefanf	if (n && n->type == NCMD && n->ncmd.args)
109417987Speter		if (goodname(n->ncmd.args->narg.text))
109517987Speter			find_command(n->ncmd.args->narg.text, &entry, 0,
109617987Speter				     pathval());
10971556Srgrimes}
10981556Srgrimes
10991556Srgrimes
11001556Srgrimes
11011556Srgrimes/*
11021556Srgrimes * Builtin commands.  Builtin commands whose functions are closely
11031556Srgrimes * tied to evaluation are implemented here.
11041556Srgrimes */
11051556Srgrimes
11061556Srgrimes/*
1107201431Sjilles * No command given, a bltin command with no arguments, or a bltin command
1108201431Sjilles * with an invalid name.
11091556Srgrimes */
11101556Srgrimes
111117987Speterint
1112201431Sjillesbltincmd(int argc, char **argv)
111317987Speter{
1114201431Sjilles	if (argc > 1) {
1115201431Sjilles		out2fmt_flush("%s: not found\n", argv[1]);
1116201431Sjilles		return 127;
1117201431Sjilles	}
111820425Ssteve	/*
111917987Speter	 * Preserve exitstatus of a previous possible redirection
112020425Ssteve	 * as POSIX mandates
112117987Speter	 */
11221556Srgrimes	return exitstatus;
11231556Srgrimes}
11241556Srgrimes
11251556Srgrimes
11261556Srgrimes/*
11271556Srgrimes * Handle break and continue commands.  Break, continue, and return are
11281556Srgrimes * all handled by setting the evalskip flag.  The evaluation routines
11291556Srgrimes * above all check this flag, and if it is set they start skipping
11301556Srgrimes * commands rather than executing them.  The variable skipcount is
11311556Srgrimes * the number of loops to break/continue, or the number of function
11321556Srgrimes * levels to return.  (The latter is always 1.)  It should probably
11331556Srgrimes * be an error to break out of more loops than exist, but it isn't
11341556Srgrimes * in the standard shell so we don't make it one here.
11351556Srgrimes */
11361556Srgrimes
113717987Speterint
113890111Simpbreakcmd(int argc, char **argv)
113917987Speter{
114020425Ssteve	int n = argc > 1 ? number(argv[1]) : 1;
11411556Srgrimes
11421556Srgrimes	if (n > loopnest)
11431556Srgrimes		n = loopnest;
11441556Srgrimes	if (n > 0) {
11451556Srgrimes		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
11461556Srgrimes		skipcount = n;
11471556Srgrimes	}
11481556Srgrimes	return 0;
11491556Srgrimes}
11501556Srgrimes
1151100437Stjr/*
1152100437Stjr * The `command' command.
1153100437Stjr */
1154100437Stjrint
1155100437Stjrcommandcmd(int argc, char **argv)
1156100437Stjr{
1157207783Sjilles	const char *path;
1158100437Stjr	int ch;
1159151810Sstefanf	int cmd = -1;
11601556Srgrimes
1161204800Sjilles	path = bltinlookup("PATH", 1);
1162100437Stjr
1163100437Stjr	optind = optreset = 1;
1164100663Stjr	opterr = 0;
1165151810Sstefanf	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1166100437Stjr		switch (ch) {
1167100437Stjr		case 'p':
1168207783Sjilles			path = _PATH_STDPATH;
1169100437Stjr			break;
1170151810Sstefanf		case 'v':
1171151810Sstefanf			cmd = TYPECMD_SMALLV;
1172151810Sstefanf			break;
1173151810Sstefanf		case 'V':
1174151810Sstefanf			cmd = TYPECMD_BIGV;
1175151810Sstefanf			break;
1176100437Stjr		case '?':
1177100437Stjr		default:
1178100437Stjr			error("unknown option: -%c", optopt);
1179100437Stjr		}
1180100437Stjr	}
1181100437Stjr	argc -= optind;
1182100437Stjr	argv += optind;
1183100437Stjr
1184151810Sstefanf	if (cmd != -1) {
1185151810Sstefanf		if (argc != 1)
1186151810Sstefanf			error("wrong number of arguments");
1187201343Sjilles		return typecmd_impl(2, argv - 1, cmd, path);
1188151810Sstefanf	}
1189204800Sjilles	if (argc != 0)
1190214538Sjilles		error("commandcmd bad call");
1191100437Stjr
1192100437Stjr	/*
1193100437Stjr	 * Do nothing successfully if no command was specified;
1194100437Stjr	 * ksh also does this.
1195100437Stjr	 */
1196204800Sjilles	return 0;
1197100437Stjr}
1198100437Stjr
1199100437Stjr
12001556Srgrimes/*
12011556Srgrimes * The return command.
12021556Srgrimes */
12031556Srgrimes
120417987Speterint
120590111Simpreturncmd(int argc, char **argv)
120617987Speter{
120720425Ssteve	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
12081556Srgrimes
12091556Srgrimes	if (funcnest) {
12101556Srgrimes		evalskip = SKIPFUNC;
12111556Srgrimes		skipcount = 1;
121220425Ssteve	} else {
121320425Ssteve		/* skip the rest of the file */
121420425Ssteve		evalskip = SKIPFILE;
121520425Ssteve		skipcount = 1;
12161556Srgrimes	}
12171556Srgrimes	return ret;
12181556Srgrimes}
12191556Srgrimes
12201556Srgrimes
122117987Speterint
122290111Simpfalsecmd(int argc __unused, char **argv __unused)
122317987Speter{
122417987Speter	return 1;
122517987Speter}
122617987Speter
122717987Speter
122817987Speterint
122990111Simptruecmd(int argc __unused, char **argv __unused)
123017987Speter{
12311556Srgrimes	return 0;
12321556Srgrimes}
12331556Srgrimes
12341556Srgrimes
123517987Speterint
123690111Simpexeccmd(int argc, char **argv)
123717987Speter{
1238208630Sjilles	/*
1239208630Sjilles	 * Because we have historically not supported any options,
1240208630Sjilles	 * only treat "--" specially.
1241208630Sjilles	 */
1242208630Sjilles	if (argc > 1 && strcmp(argv[1], "--") == 0)
1243208630Sjilles		argc--, argv++;
12441556Srgrimes	if (argc > 1) {
124517987Speter		struct strlist *sp;
124617987Speter
12471556Srgrimes		iflag = 0;		/* exit on error */
12481556Srgrimes		mflag = 0;
12491556Srgrimes		optschanged();
125017987Speter		for (sp = cmdenviron; sp ; sp = sp->next)
125117987Speter			setvareq(sp->text, VEXPORT|VSTACK);
12521556Srgrimes		shellexec(argv + 1, environment(), pathval(), 0);
12531556Srgrimes
12541556Srgrimes	}
12551556Srgrimes	return 0;
12561556Srgrimes}
1257153091Sstefanf
1258153091Sstefanf
1259153091Sstefanfint
1260153091Sstefanftimescmd(int argc __unused, char **argv __unused)
1261153091Sstefanf{
1262153091Sstefanf	struct rusage ru;
1263153091Sstefanf	long shumins, shsmins, chumins, chsmins;
1264153091Sstefanf	double shusecs, shssecs, chusecs, chssecs;
1265153091Sstefanf
1266153091Sstefanf	if (getrusage(RUSAGE_SELF, &ru) < 0)
1267153091Sstefanf		return 1;
1268153091Sstefanf	shumins = ru.ru_utime.tv_sec / 60;
1269153091Sstefanf	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1270153091Sstefanf	shsmins = ru.ru_stime.tv_sec / 60;
1271153091Sstefanf	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1272153091Sstefanf	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1273153091Sstefanf		return 1;
1274153091Sstefanf	chumins = ru.ru_utime.tv_sec / 60;
1275153091Sstefanf	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1276153091Sstefanf	chsmins = ru.ru_stime.tv_sec / 60;
1277153091Sstefanf	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1278153091Sstefanf	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1279153091Sstefanf	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1280153091Sstefanf	return 0;
1281153091Sstefanf}
1282