eval.c revision 212214
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 212214 2010-09-04 21:23:46Z 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 */
781556SrgrimesSTATIC int skipcount;		/* number of levels to skip */
791556SrgrimesMKINIT int loopnest;		/* current loop nesting level */
801556Srgrimesint funcnest;			/* depth of function calls */
81193169SstefanfSTATIC 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
90149933SstefanfSTATIC void evalloop(union node *, int);
91149933SstefanfSTATIC void evalfor(union node *, int);
9290111SimpSTATIC void evalcase(union node *, int);
9390111SimpSTATIC void evalsubshell(union node *, int);
94205154SjillesSTATIC void evalredir(union node *, int);
9590111SimpSTATIC void expredir(union node *);
9690111SimpSTATIC void evalpipe(union node *);
9790111SimpSTATIC void evalcommand(union node *, int, struct backcmd *);
9890111SimpSTATIC void prehash(union node *);
991556Srgrimes
1001556Srgrimes
1011556Srgrimes/*
1021556Srgrimes * Called to reset things after an exception.
1031556Srgrimes */
1041556Srgrimes
1051556Srgrimes#ifdef mkinit
1061556SrgrimesINCLUDE "eval.h"
1071556Srgrimes
1081556SrgrimesRESET {
1091556Srgrimes	evalskip = 0;
1101556Srgrimes	loopnest = 0;
1111556Srgrimes	funcnest = 0;
1121556Srgrimes}
1131556Srgrimes
1141556SrgrimesSHELLPROC {
1151556Srgrimes	exitstatus = 0;
1161556Srgrimes}
1171556Srgrimes#endif
1181556Srgrimes
1191556Srgrimes
1201556Srgrimes
1211556Srgrimes/*
12246684Skris * The eval command.
1231556Srgrimes */
1241556Srgrimes
12517987Speterint
12690111Simpevalcmd(int argc, char **argv)
1271556Srgrimes{
1281556Srgrimes        char *p;
1291556Srgrimes        char *concat;
1301556Srgrimes        char **ap;
1311556Srgrimes
1321556Srgrimes        if (argc > 1) {
1331556Srgrimes                p = argv[1];
1341556Srgrimes                if (argc > 2) {
1351556Srgrimes                        STARTSTACKSTR(concat);
1361556Srgrimes                        ap = argv + 2;
1371556Srgrimes                        for (;;) {
1381556Srgrimes                                while (*p)
1391556Srgrimes                                        STPUTC(*p++, concat);
1401556Srgrimes                                if ((p = *ap++) == NULL)
1411556Srgrimes                                        break;
1421556Srgrimes                                STPUTC(' ', concat);
1431556Srgrimes                        }
1441556Srgrimes                        STPUTC('\0', concat);
1451556Srgrimes                        p = grabstackstr(concat);
1461556Srgrimes                }
147193169Sstefanf                evalstring(p, builtin_flags & EV_TESTED);
148210829Sjilles        } else
149210829Sjilles                exitstatus = 0;
1501556Srgrimes        return exitstatus;
1511556Srgrimes}
1521556Srgrimes
1531556Srgrimes
1541556Srgrimes/*
1551556Srgrimes * Execute a command or commands contained in a string.
1561556Srgrimes */
1571556Srgrimes
1581556Srgrimesvoid
159193169Sstefanfevalstring(char *s, int flags)
16090111Simp{
1611556Srgrimes	union node *n;
1621556Srgrimes	struct stackmark smark;
163194128Sjilles	int flags_exit;
164210829Sjilles	int any;
1651556Srgrimes
166194128Sjilles	flags_exit = flags & EV_EXIT;
167194128Sjilles	flags &= ~EV_EXIT;
168210829Sjilles	any = 0;
1691556Srgrimes	setstackmark(&smark);
1701556Srgrimes	setinputstring(s, 1);
1711556Srgrimes	while ((n = parsecmd(0)) != NEOF) {
172194128Sjilles		if (n != NULL) {
173194128Sjilles			if (flags_exit && preadateof())
174194128Sjilles				evaltree(n, flags | EV_EXIT);
175194128Sjilles			else
176194128Sjilles				evaltree(n, flags);
177210829Sjilles			any = 1;
178194128Sjilles		}
1791556Srgrimes		popstackmark(&smark);
1801556Srgrimes	}
1811556Srgrimes	popfile();
1821556Srgrimes	popstackmark(&smark);
183210829Sjilles	if (!any)
184210829Sjilles		exitstatus = 0;
185194128Sjilles	if (flags_exit)
186194128Sjilles		exitshell(exitstatus);
1871556Srgrimes}
1881556Srgrimes
1891556Srgrimes
1901556Srgrimes/*
1911556Srgrimes * Evaluate a parse tree.  The value is left in the global variable
1921556Srgrimes * exitstatus.
1931556Srgrimes */
1941556Srgrimes
1951556Srgrimesvoid
19690111Simpevaltree(union node *n, int flags)
19717987Speter{
198149927Sstefanf	int do_etest;
199149927Sstefanf
200149927Sstefanf	do_etest = 0;
2011556Srgrimes	if (n == NULL) {
2021556Srgrimes		TRACE(("evaltree(NULL) called\n"));
2031556Srgrimes		exitstatus = 0;
2041556Srgrimes		goto out;
2051556Srgrimes	}
20617987Speter#ifndef NO_HISTORY
2071556Srgrimes	displayhist = 1;	/* show history substitutions done with fc */
20817987Speter#endif
209149802Sstefanf	TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
2101556Srgrimes	switch (n->type) {
2111556Srgrimes	case NSEMI:
212149932Sstefanf		evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
2131556Srgrimes		if (evalskip)
2141556Srgrimes			goto out;
2151556Srgrimes		evaltree(n->nbinary.ch2, flags);
2161556Srgrimes		break;
2171556Srgrimes	case NAND:
2181556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
21918754Ssteve		if (evalskip || exitstatus != 0) {
2201556Srgrimes			goto out;
22118754Ssteve		}
2221556Srgrimes		evaltree(n->nbinary.ch2, flags);
2231556Srgrimes		break;
2241556Srgrimes	case NOR:
2251556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
2261556Srgrimes		if (evalskip || exitstatus == 0)
2271556Srgrimes			goto out;
2281556Srgrimes		evaltree(n->nbinary.ch2, flags);
2291556Srgrimes		break;
2301556Srgrimes	case NREDIR:
231205154Sjilles		evalredir(n, flags);
2321556Srgrimes		break;
2331556Srgrimes	case NSUBSHELL:
2341556Srgrimes		evalsubshell(n, flags);
235149927Sstefanf		do_etest = !(flags & EV_TESTED);
2361556Srgrimes		break;
2371556Srgrimes	case NBACKGND:
2381556Srgrimes		evalsubshell(n, flags);
2391556Srgrimes		break;
2401556Srgrimes	case NIF: {
2411556Srgrimes		evaltree(n->nif.test, EV_TESTED);
2421556Srgrimes		if (evalskip)
2431556Srgrimes			goto out;
24420425Ssteve		if (exitstatus == 0)
2451556Srgrimes			evaltree(n->nif.ifpart, flags);
24617987Speter		else if (n->nif.elsepart)
2471556Srgrimes			evaltree(n->nif.elsepart, flags);
24820425Ssteve		else
24920425Ssteve			exitstatus = 0;
2501556Srgrimes		break;
2511556Srgrimes	}
2521556Srgrimes	case NWHILE:
2531556Srgrimes	case NUNTIL:
254149933Sstefanf		evalloop(n, flags & ~EV_EXIT);
2551556Srgrimes		break;
2561556Srgrimes	case NFOR:
257149933Sstefanf		evalfor(n, flags & ~EV_EXIT);
2581556Srgrimes		break;
2591556Srgrimes	case NCASE:
2601556Srgrimes		evalcase(n, flags);
2611556Srgrimes		break;
2621556Srgrimes	case NDEFUN:
2631556Srgrimes		defun(n->narg.text, n->narg.next);
2641556Srgrimes		exitstatus = 0;
2651556Srgrimes		break;
2661556Srgrimes	case NNOT:
2671556Srgrimes		evaltree(n->nnot.com, EV_TESTED);
2681556Srgrimes		exitstatus = !exitstatus;
2691556Srgrimes		break;
2701556Srgrimes
2711556Srgrimes	case NPIPE:
2721556Srgrimes		evalpipe(n);
273149927Sstefanf		do_etest = !(flags & EV_TESTED);
2741556Srgrimes		break;
2751556Srgrimes	case NCMD:
2761556Srgrimes		evalcommand(n, flags, (struct backcmd *)NULL);
277149927Sstefanf		do_etest = !(flags & EV_TESTED);
2781556Srgrimes		break;
2791556Srgrimes	default:
2801556Srgrimes		out1fmt("Node type = %d\n", n->type);
2811556Srgrimes		flushout(&output);
2821556Srgrimes		break;
2831556Srgrimes	}
2841556Srgrimesout:
2851556Srgrimes	if (pendingsigs)
2861556Srgrimes		dotrap();
287149927Sstefanf	if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
2881556Srgrimes		exitshell(exitstatus);
2891556Srgrimes}
2901556Srgrimes
2911556Srgrimes
2921556SrgrimesSTATIC void
293149933Sstefanfevalloop(union node *n, int flags)
29417987Speter{
2951556Srgrimes	int status;
2961556Srgrimes
2971556Srgrimes	loopnest++;
2981556Srgrimes	status = 0;
2991556Srgrimes	for (;;) {
3001556Srgrimes		evaltree(n->nbinary.ch1, EV_TESTED);
3011556Srgrimes		if (evalskip) {
3021556Srgrimesskipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
3031556Srgrimes				evalskip = 0;
3041556Srgrimes				continue;
3051556Srgrimes			}
3061556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3071556Srgrimes				evalskip = 0;
3081556Srgrimes			break;
3091556Srgrimes		}
3101556Srgrimes		if (n->type == NWHILE) {
3111556Srgrimes			if (exitstatus != 0)
3121556Srgrimes				break;
3131556Srgrimes		} else {
3141556Srgrimes			if (exitstatus == 0)
3151556Srgrimes				break;
3161556Srgrimes		}
317149933Sstefanf		evaltree(n->nbinary.ch2, flags);
3181556Srgrimes		status = exitstatus;
3191556Srgrimes		if (evalskip)
3201556Srgrimes			goto skipping;
3211556Srgrimes	}
3221556Srgrimes	loopnest--;
3231556Srgrimes	exitstatus = status;
3241556Srgrimes}
3251556Srgrimes
3261556Srgrimes
3271556Srgrimes
3281556SrgrimesSTATIC void
329149933Sstefanfevalfor(union node *n, int flags)
33017987Speter{
3311556Srgrimes	struct arglist arglist;
3321556Srgrimes	union node *argp;
3331556Srgrimes	struct strlist *sp;
3341556Srgrimes	struct stackmark smark;
3351556Srgrimes
3361556Srgrimes	setstackmark(&smark);
3371556Srgrimes	arglist.lastp = &arglist.list;
3381556Srgrimes	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
33917987Speter		oexitstatus = exitstatus;
3401556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3411556Srgrimes		if (evalskip)
3421556Srgrimes			goto out;
3431556Srgrimes	}
3441556Srgrimes	*arglist.lastp = NULL;
3451556Srgrimes
3461556Srgrimes	exitstatus = 0;
3471556Srgrimes	loopnest++;
3481556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
3491556Srgrimes		setvar(n->nfor.var, sp->text, 0);
350149933Sstefanf		evaltree(n->nfor.body, flags);
3511556Srgrimes		if (evalskip) {
3521556Srgrimes			if (evalskip == SKIPCONT && --skipcount <= 0) {
3531556Srgrimes				evalskip = 0;
3541556Srgrimes				continue;
3551556Srgrimes			}
3561556Srgrimes			if (evalskip == SKIPBREAK && --skipcount <= 0)
3571556Srgrimes				evalskip = 0;
3581556Srgrimes			break;
3591556Srgrimes		}
3601556Srgrimes	}
3611556Srgrimes	loopnest--;
3621556Srgrimesout:
3631556Srgrimes	popstackmark(&smark);
3641556Srgrimes}
3651556Srgrimes
3661556Srgrimes
3671556Srgrimes
3681556SrgrimesSTATIC void
36990111Simpevalcase(union node *n, int flags)
37017987Speter{
3711556Srgrimes	union node *cp;
3721556Srgrimes	union node *patp;
3731556Srgrimes	struct arglist arglist;
3741556Srgrimes	struct stackmark smark;
3751556Srgrimes
3761556Srgrimes	setstackmark(&smark);
3771556Srgrimes	arglist.lastp = &arglist.list;
37817987Speter	oexitstatus = exitstatus;
379172440Sstefanf	exitstatus = 0;
3801556Srgrimes	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
3811556Srgrimes	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
3821556Srgrimes		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
3831556Srgrimes			if (casematch(patp, arglist.list->text)) {
3841556Srgrimes				if (evalskip == 0) {
3851556Srgrimes					evaltree(cp->nclist.body, flags);
3861556Srgrimes				}
3871556Srgrimes				goto out;
3881556Srgrimes			}
3891556Srgrimes		}
3901556Srgrimes	}
3911556Srgrimesout:
3921556Srgrimes	popstackmark(&smark);
3931556Srgrimes}
3941556Srgrimes
3951556Srgrimes
3961556Srgrimes
3971556Srgrimes/*
3981556Srgrimes * Kick off a subshell to evaluate a tree.
3991556Srgrimes */
4001556Srgrimes
4011556SrgrimesSTATIC void
40290111Simpevalsubshell(union node *n, int flags)
40317987Speter{
4041556Srgrimes	struct job *jp;
4051556Srgrimes	int backgnd = (n->type == NBACKGND);
4061556Srgrimes
4071556Srgrimes	expredir(n->nredir.redirect);
408194774Sjilles	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
409194774Sjilles			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
4101556Srgrimes		if (backgnd)
4111556Srgrimes			flags &=~ EV_TESTED;
4121556Srgrimes		redirect(n->nredir.redirect, 0);
4131556Srgrimes		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
414201053Sjilles	} else if (! backgnd) {
4151556Srgrimes		INTOFF;
41645916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
4171556Srgrimes		INTON;
4181556Srgrimes	}
4191556Srgrimes}
4201556Srgrimes
4211556Srgrimes
422205154Sjilles/*
423205154Sjilles * Evaluate a redirected compound command.
424205154Sjilles */
4251556Srgrimes
426205154SjillesSTATIC void
427205154Sjillesevalredir(union node *n, int flags)
428205154Sjilles{
429205154Sjilles	struct jmploc jmploc;
430205154Sjilles	struct jmploc *savehandler;
431205154Sjilles	volatile int in_redirect = 1;
432205154Sjilles
433205154Sjilles	expredir(n->nredir.redirect);
434205154Sjilles	savehandler = handler;
435205154Sjilles	if (setjmp(jmploc.loc)) {
436205154Sjilles		int e;
437205154Sjilles
438205154Sjilles		handler = savehandler;
439205154Sjilles		e = exception;
440205154Sjilles		if (e == EXERROR || e == EXEXEC) {
441205154Sjilles			popredir();
442205154Sjilles			if (in_redirect) {
443205154Sjilles				exitstatus = 2;
444205154Sjilles				return;
445205154Sjilles			}
446205154Sjilles		}
447205154Sjilles		longjmp(handler->loc, 1);
448205154Sjilles	} else {
449205154Sjilles		INTOFF;
450205154Sjilles		handler = &jmploc;
451205154Sjilles		redirect(n->nredir.redirect, REDIR_PUSH);
452205154Sjilles		in_redirect = 0;
453205154Sjilles		INTON;
454205154Sjilles		evaltree(n->nredir.n, flags);
455205154Sjilles	}
456205154Sjilles	INTOFF;
457205154Sjilles	handler = savehandler;
458205154Sjilles	popredir();
459205154Sjilles	INTON;
460205154Sjilles}
461205154Sjilles
462205154Sjilles
4631556Srgrimes/*
4641556Srgrimes * Compute the names of the files in a redirection list.
4651556Srgrimes */
4661556Srgrimes
4671556SrgrimesSTATIC void
46890111Simpexpredir(union node *n)
46917987Speter{
47025222Ssteve	union node *redir;
4711556Srgrimes
4721556Srgrimes	for (redir = n ; redir ; redir = redir->nfile.next) {
47317987Speter		struct arglist fn;
47417987Speter		fn.lastp = &fn.list;
47517987Speter		oexitstatus = exitstatus;
47617987Speter		switch (redir->type) {
47717987Speter		case NFROM:
47817987Speter		case NTO:
47966612Sbrian		case NFROMTO:
48017987Speter		case NAPPEND:
48196922Stjr		case NCLOBBER:
4821556Srgrimes			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
4831556Srgrimes			redir->nfile.expfname = fn.list->text;
48417987Speter			break;
48517987Speter		case NFROMFD:
48617987Speter		case NTOFD:
48717987Speter			if (redir->ndup.vname) {
488181017Sstefanf				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
48917987Speter				fixredir(redir, fn.list->text, 1);
49017987Speter			}
49117987Speter			break;
4921556Srgrimes		}
4931556Srgrimes	}
4941556Srgrimes}
4951556Srgrimes
4961556Srgrimes
4971556Srgrimes
4981556Srgrimes/*
4991556Srgrimes * Evaluate a pipeline.  All the processes in the pipeline are children
5001556Srgrimes * of the process creating the pipeline.  (This differs from some versions
5011556Srgrimes * of the shell, which make the last process in a pipeline the parent
5021556Srgrimes * of all the rest.)
5031556Srgrimes */
5041556Srgrimes
5051556SrgrimesSTATIC void
50690111Simpevalpipe(union node *n)
50717987Speter{
5081556Srgrimes	struct job *jp;
5091556Srgrimes	struct nodelist *lp;
5101556Srgrimes	int pipelen;
5111556Srgrimes	int prevfd;
5121556Srgrimes	int pip[2];
5131556Srgrimes
514149802Sstefanf	TRACE(("evalpipe(%p) called\n", (void *)n));
5151556Srgrimes	pipelen = 0;
5161556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
5171556Srgrimes		pipelen++;
5181556Srgrimes	INTOFF;
5191556Srgrimes	jp = makejob(n, pipelen);
5201556Srgrimes	prevfd = -1;
5211556Srgrimes	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
5221556Srgrimes		prehash(lp->n);
5231556Srgrimes		pip[1] = -1;
5241556Srgrimes		if (lp->next) {
5251556Srgrimes			if (pipe(pip) < 0) {
5261556Srgrimes				close(prevfd);
52753891Scracauer				error("Pipe call failed: %s", strerror(errno));
5281556Srgrimes			}
5291556Srgrimes		}
5301556Srgrimes		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
5311556Srgrimes			INTON;
5321556Srgrimes			if (prevfd > 0) {
533124780Sdes				dup2(prevfd, 0);
5341556Srgrimes				close(prevfd);
5351556Srgrimes			}
5361556Srgrimes			if (pip[1] >= 0) {
53753282Scracauer				if (!(prevfd >= 0 && pip[0] == 0))
53852900Scracauer					close(pip[0]);
5391556Srgrimes				if (pip[1] != 1) {
540124780Sdes					dup2(pip[1], 1);
5411556Srgrimes					close(pip[1]);
5421556Srgrimes				}
5431556Srgrimes			}
5441556Srgrimes			evaltree(lp->n, EV_EXIT);
5451556Srgrimes		}
5461556Srgrimes		if (prevfd >= 0)
5471556Srgrimes			close(prevfd);
5481556Srgrimes		prevfd = pip[0];
5491556Srgrimes		close(pip[1]);
5501556Srgrimes	}
5511556Srgrimes	INTON;
5521556Srgrimes	if (n->npipe.backgnd == 0) {
5531556Srgrimes		INTOFF;
55445916Scracauer		exitstatus = waitforjob(jp, (int *)NULL);
5551556Srgrimes		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
5561556Srgrimes		INTON;
5571556Srgrimes	}
5581556Srgrimes}
5591556Srgrimes
5601556Srgrimes
5611556Srgrimes
5621556Srgrimes/*
5631556Srgrimes * Execute a command inside back quotes.  If it's a builtin command, we
5641556Srgrimes * want to save its output in a block obtained from malloc.  Otherwise
5651556Srgrimes * we fork off a subprocess and get the output of the command via a pipe.
5661556Srgrimes * Should be called with interrupts off.
5671556Srgrimes */
5681556Srgrimes
5691556Srgrimesvoid
57090111Simpevalbackcmd(union node *n, struct backcmd *result)
57117987Speter{
5721556Srgrimes	int pip[2];
5731556Srgrimes	struct job *jp;
5741556Srgrimes	struct stackmark smark;		/* unnecessary */
5751556Srgrimes
5761556Srgrimes	setstackmark(&smark);
5771556Srgrimes	result->fd = -1;
5781556Srgrimes	result->buf = NULL;
5791556Srgrimes	result->nleft = 0;
5801556Srgrimes	result->jp = NULL;
58117987Speter	if (n == NULL) {
58217987Speter		exitstatus = 0;
5831556Srgrimes		goto out;
58417987Speter	}
5851556Srgrimes	if (n->type == NCMD) {
58617987Speter		exitstatus = oexitstatus;
5871556Srgrimes		evalcommand(n, EV_BACKCMD, result);
5881556Srgrimes	} else {
58917987Speter		exitstatus = 0;
5901556Srgrimes		if (pipe(pip) < 0)
59153891Scracauer			error("Pipe call failed: %s", strerror(errno));
5921556Srgrimes		jp = makejob(n, 1);
5931556Srgrimes		if (forkshell(jp, n, FORK_NOJOB) == 0) {
5941556Srgrimes			FORCEINTON;
5951556Srgrimes			close(pip[0]);
5961556Srgrimes			if (pip[1] != 1) {
597124780Sdes				dup2(pip[1], 1);
5981556Srgrimes				close(pip[1]);
5991556Srgrimes			}
6001556Srgrimes			evaltree(n, EV_EXIT);
6011556Srgrimes		}
6021556Srgrimes		close(pip[1]);
6031556Srgrimes		result->fd = pip[0];
6041556Srgrimes		result->jp = jp;
6051556Srgrimes	}
6061556Srgrimesout:
6071556Srgrimes	popstackmark(&smark);
608109627Stjr	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
6091556Srgrimes		result->fd, result->buf, result->nleft, result->jp));
6101556Srgrimes}
6111556Srgrimes
6121556Srgrimes
6131556Srgrimes
6141556Srgrimes/*
6151556Srgrimes * Execute a simple command.
6161556Srgrimes */
6171556Srgrimes
6181556SrgrimesSTATIC void
61990111Simpevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
62017987Speter{
6211556Srgrimes	struct stackmark smark;
6221556Srgrimes	union node *argp;
6231556Srgrimes	struct arglist arglist;
6241556Srgrimes	struct arglist varlist;
6251556Srgrimes	char **argv;
6261556Srgrimes	int argc;
6271556Srgrimes	char **envp;
6281556Srgrimes	int varflag;
6291556Srgrimes	struct strlist *sp;
6301556Srgrimes	int mode;
6311556Srgrimes	int pip[2];
6321556Srgrimes	struct cmdentry cmdentry;
6331556Srgrimes	struct job *jp;
6341556Srgrimes	struct jmploc jmploc;
635194765Sjilles	struct jmploc *savehandler;
636194765Sjilles	char *savecmdname;
637194765Sjilles	struct shparam saveparam;
638194765Sjilles	struct localvar *savelocalvars;
639199647Sjilles	struct parsefile *savetopfile;
6401556Srgrimes	volatile int e;
6411556Srgrimes	char *lastarg;
64245916Scracauer	int realstatus;
64354884Scracauer	int do_clearcmdentry;
644211287Sjilles	const char *path = pathval();
6451556Srgrimes
6461556Srgrimes	/* First expand the arguments. */
647149802Sstefanf	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
6481556Srgrimes	setstackmark(&smark);
6491556Srgrimes	arglist.lastp = &arglist.list;
6501556Srgrimes	varlist.lastp = &varlist.list;
6511556Srgrimes	varflag = 1;
65254884Scracauer	do_clearcmdentry = 0;
65317987Speter	oexitstatus = exitstatus;
65417987Speter	exitstatus = 0;
6551556Srgrimes	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
65617987Speter		char *p = argp->narg.text;
6571556Srgrimes		if (varflag && is_name(*p)) {
6581556Srgrimes			do {
6591556Srgrimes				p++;
6601556Srgrimes			} while (is_in_name(*p));
6611556Srgrimes			if (*p == '=') {
6621556Srgrimes				expandarg(argp, &varlist, EXP_VARTILDE);
6631556Srgrimes				continue;
6641556Srgrimes			}
6651556Srgrimes		}
6661556Srgrimes		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
6671556Srgrimes		varflag = 0;
6681556Srgrimes	}
6691556Srgrimes	*arglist.lastp = NULL;
6701556Srgrimes	*varlist.lastp = NULL;
6711556Srgrimes	expredir(cmd->ncmd.redirect);
6721556Srgrimes	argc = 0;
6731556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next)
6741556Srgrimes		argc++;
6751556Srgrimes	argv = stalloc(sizeof (char *) * (argc + 1));
6761556Srgrimes
6771556Srgrimes	for (sp = arglist.list ; sp ; sp = sp->next) {
6781556Srgrimes		TRACE(("evalcommand arg: %s\n", sp->text));
6791556Srgrimes		*argv++ = sp->text;
6801556Srgrimes	}
6811556Srgrimes	*argv = NULL;
6821556Srgrimes	lastarg = NULL;
6831556Srgrimes	if (iflag && funcnest == 0 && argc > 0)
6841556Srgrimes		lastarg = argv[-1];
6851556Srgrimes	argv -= argc;
6861556Srgrimes
6871556Srgrimes	/* Print the command if xflag is set. */
6881556Srgrimes	if (xflag) {
689159632Sstefanf		char sep = 0;
690194786Sjilles		const char *p;
691159632Sstefanf		out2str(ps4val());
6921556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next) {
693159632Sstefanf			if (sep != 0)
694201366Sjilles				out2c(' ');
695194786Sjilles			p = sp->text;
696194786Sjilles			while (*p != '=' && *p != '\0')
697194786Sjilles				out2c(*p++);
698194786Sjilles			if (*p != '\0') {
699194786Sjilles				out2c(*p++);
700194786Sjilles				out2qstr(p);
701194786Sjilles			}
702159632Sstefanf			sep = ' ';
7031556Srgrimes		}
7041556Srgrimes		for (sp = arglist.list ; sp ; sp = sp->next) {
705159632Sstefanf			if (sep != 0)
706201366Sjilles				out2c(' ');
707194786Sjilles			/* Disambiguate command looking like assignment. */
708194786Sjilles			if (sp == arglist.list &&
709194786Sjilles					strchr(sp->text, '=') != NULL &&
710194786Sjilles					strchr(sp->text, '\'') == NULL) {
711194786Sjilles				out2c('\'');
712194786Sjilles				out2str(sp->text);
713194786Sjilles				out2c('\'');
714194786Sjilles			} else
715194786Sjilles				out2qstr(sp->text);
716159632Sstefanf			sep = ' ';
7171556Srgrimes		}
718201366Sjilles		out2c('\n');
7191556Srgrimes		flushout(&errout);
7201556Srgrimes	}
7211556Srgrimes
7221556Srgrimes	/* Now locate the command. */
7231556Srgrimes	if (argc == 0) {
724157601Sstefanf		/* Variable assignment(s) without command */
7251556Srgrimes		cmdentry.cmdtype = CMDBUILTIN;
7261556Srgrimes		cmdentry.u.index = BLTINCMD;
727205138Sjilles		cmdentry.special = 0;
7281556Srgrimes	} else {
72917987Speter		static const char PATH[] = "PATH=";
730204800Sjilles		int cmd_flags = 0, bltinonly = 0;
73117987Speter
73217987Speter		/*
73317987Speter		 * Modify the command lookup path, if a PATH= assignment
73417987Speter		 * is present
73517987Speter		 */
73617987Speter		for (sp = varlist.list ; sp ; sp = sp->next)
73754884Scracauer			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
73817987Speter				path = sp->text + sizeof(PATH) - 1;
739155301Sschweikh				/*
74054884Scracauer				 * On `PATH=... command`, we need to make
74154884Scracauer				 * sure that the command isn't using the
74254884Scracauer				 * non-updated hash table of the outer PATH
743155301Sschweikh				 * setting and we need to make sure that
74454884Scracauer				 * the hash table isn't filled with items
74554884Scracauer				 * from the temporary setting.
74654884Scracauer				 *
747155301Sschweikh				 * It would be better to forbit using and
74854884Scracauer				 * updating the table while this command
74954884Scracauer				 * runs, by the command finding mechanism
75054884Scracauer				 * is heavily integrated with hash handling,
75154884Scracauer				 * so we just delete the hash before and after
75254884Scracauer				 * the command runs. Partly deleting like
75354884Scracauer				 * changepatch() does doesn't seem worth the
75454884Scracauer				 * bookinging effort, since most such runs add
755123996Smaxim				 * directories in front of the new PATH.
75654884Scracauer				 */
75754884Scracauer				clearcmdentry(0);
75854884Scracauer				do_clearcmdentry = 1;
75954884Scracauer			}
76017987Speter
761204800Sjilles		for (;;) {
762204800Sjilles			if (bltinonly) {
763204800Sjilles				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
764204800Sjilles				if (cmdentry.u.index < 0) {
765201431Sjilles					cmdentry.u.index = BLTINCMD;
766201431Sjilles					argv--;
767201431Sjilles					argc++;
768201431Sjilles					break;
7691556Srgrimes				}
770204800Sjilles			} else
771204800Sjilles				find_command(argv[0], &cmdentry, cmd_flags, path);
772204800Sjilles			/* implement the bltin and command builtins here */
773204800Sjilles			if (cmdentry.cmdtype != CMDBUILTIN)
774204800Sjilles				break;
775204800Sjilles			if (cmdentry.u.index == BLTINCMD) {
776204800Sjilles				if (argc == 1)
7771556Srgrimes					break;
778204800Sjilles				argv++;
779204800Sjilles				argc--;
780204800Sjilles				bltinonly = 1;
781204800Sjilles			} else if (cmdentry.u.index == COMMANDCMD) {
782204800Sjilles				if (argc == 1)
783204800Sjilles					break;
784204800Sjilles				if (!strcmp(argv[1], "-p")) {
785204800Sjilles					if (argc == 2)
786204800Sjilles						break;
787204800Sjilles					if (argv[2][0] == '-') {
788204800Sjilles						if (strcmp(argv[2], "--"))
789204800Sjilles							break;
790204800Sjilles						if (argc == 3)
791204800Sjilles							break;
792204800Sjilles						argv += 3;
793204800Sjilles						argc -= 3;
794204800Sjilles					} else {
795204800Sjilles						argv += 2;
796204800Sjilles						argc -= 2;
797204800Sjilles					}
798204800Sjilles					path = _PATH_STDPATH;
799204800Sjilles					clearcmdentry(0);
800204800Sjilles					do_clearcmdentry = 1;
801204800Sjilles				} else if (!strcmp(argv[1], "--")) {
802204800Sjilles					if (argc == 2)
803204800Sjilles						break;
804204800Sjilles					argv += 2;
805204800Sjilles					argc -= 2;
806204800Sjilles				} else if (argv[1][0] == '-')
807204800Sjilles					break;
808204800Sjilles				else {
809204800Sjilles					argv++;
810204800Sjilles					argc--;
811204800Sjilles				}
812204800Sjilles				cmd_flags |= DO_NOFUNC;
813204800Sjilles				bltinonly = 0;
814204800Sjilles			} else
815204800Sjilles				break;
8161556Srgrimes		}
817204800Sjilles		/*
818204800Sjilles		 * Special builtins lose their special properties when
819204800Sjilles		 * called via 'command'.
820204800Sjilles		 */
821204800Sjilles		if (cmd_flags & DO_NOFUNC)
822204800Sjilles			cmdentry.special = 0;
8231556Srgrimes	}
8241556Srgrimes
8251556Srgrimes	/* Fork off a child process if necessary. */
8261556Srgrimes	if (cmd->ncmd.backgnd
827197820Sjilles	 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
828194127Sjilles	    && ((flags & EV_EXIT) == 0 || have_traps()))
82917987Speter	 || ((flags & EV_BACKCMD) != 0
8301556Srgrimes	    && (cmdentry.cmdtype != CMDBUILTIN
83148896Ssheldonh		 || cmdentry.u.index == CDCMD
8321556Srgrimes		 || cmdentry.u.index == DOTCMD
833204800Sjilles		 || cmdentry.u.index == EVALCMD))) {
8341556Srgrimes		jp = makejob(cmd, 1);
8351556Srgrimes		mode = cmd->ncmd.backgnd;
8361556Srgrimes		if (flags & EV_BACKCMD) {
8371556Srgrimes			mode = FORK_NOJOB;
8381556Srgrimes			if (pipe(pip) < 0)
83953891Scracauer				error("Pipe call failed: %s", strerror(errno));
8401556Srgrimes		}
8411556Srgrimes		if (forkshell(jp, cmd, mode) != 0)
8421556Srgrimes			goto parent;	/* at end of routine */
8431556Srgrimes		if (flags & EV_BACKCMD) {
8441556Srgrimes			FORCEINTON;
8451556Srgrimes			close(pip[0]);
8461556Srgrimes			if (pip[1] != 1) {
847124780Sdes				dup2(pip[1], 1);
8481556Srgrimes				close(pip[1]);
8491556Srgrimes			}
8501556Srgrimes		}
8511556Srgrimes		flags |= EV_EXIT;
8521556Srgrimes	}
8531556Srgrimes
8541556Srgrimes	/* This is the child process if a fork occurred. */
8551556Srgrimes	/* Execute the command. */
8561556Srgrimes	if (cmdentry.cmdtype == CMDFUNCTION) {
85720425Ssteve#ifdef DEBUG
8581556Srgrimes		trputs("Shell function:  ");  trargs(argv);
85920425Ssteve#endif
8601556Srgrimes		saveparam = shellparam;
8611556Srgrimes		shellparam.malloc = 0;
86220425Ssteve		shellparam.reset = 1;
8631556Srgrimes		shellparam.nparam = argc - 1;
8641556Srgrimes		shellparam.p = argv + 1;
8651556Srgrimes		shellparam.optnext = NULL;
8661556Srgrimes		INTOFF;
8671556Srgrimes		savelocalvars = localvars;
8681556Srgrimes		localvars = NULL;
869196483Sjilles		reffunc(cmdentry.u.func);
870194765Sjilles		savehandler = handler;
8711556Srgrimes		if (setjmp(jmploc.loc)) {
8721556Srgrimes			if (exception == EXSHELLPROC)
873194765Sjilles				freeparam(&saveparam);
8741556Srgrimes			else {
8751556Srgrimes				freeparam(&shellparam);
8761556Srgrimes				shellparam = saveparam;
877204802Sjilles				if (exception == EXERROR || exception == EXEXEC)
878204802Sjilles					popredir();
8791556Srgrimes			}
880196483Sjilles			unreffunc(cmdentry.u.func);
8811556Srgrimes			poplocalvars();
8821556Srgrimes			localvars = savelocalvars;
883201283Sjilles			funcnest--;
8841556Srgrimes			handler = savehandler;
8851556Srgrimes			longjmp(handler->loc, 1);
8861556Srgrimes		}
8871556Srgrimes		handler = &jmploc;
888201283Sjilles		funcnest++;
889204802Sjilles		redirect(cmd->ncmd.redirect, REDIR_PUSH);
890199660Sjilles		INTON;
8911556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
8921556Srgrimes			mklocal(sp->text);
893185231Sstefanf		exitstatus = oexitstatus;
89435675Scracauer		if (flags & EV_TESTED)
895196634Sjilles			evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
89635675Scracauer		else
897196634Sjilles			evaltree(getfuncnode(cmdentry.u.func), 0);
8981556Srgrimes		INTOFF;
899196483Sjilles		unreffunc(cmdentry.u.func);
9001556Srgrimes		poplocalvars();
9011556Srgrimes		localvars = savelocalvars;
9021556Srgrimes		freeparam(&shellparam);
9031556Srgrimes		shellparam = saveparam;
9041556Srgrimes		handler = savehandler;
905201283Sjilles		funcnest--;
9061556Srgrimes		popredir();
9071556Srgrimes		INTON;
9081556Srgrimes		if (evalskip == SKIPFUNC) {
9091556Srgrimes			evalskip = 0;
9101556Srgrimes			skipcount = 0;
9111556Srgrimes		}
9121556Srgrimes		if (flags & EV_EXIT)
9131556Srgrimes			exitshell(exitstatus);
9141556Srgrimes	} else if (cmdentry.cmdtype == CMDBUILTIN) {
91520425Ssteve#ifdef DEBUG
9161556Srgrimes		trputs("builtin command:  ");  trargs(argv);
91720425Ssteve#endif
9181556Srgrimes		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
9191556Srgrimes		if (flags == EV_BACKCMD) {
9201556Srgrimes			memout.nleft = 0;
9211556Srgrimes			memout.nextc = memout.buf;
9221556Srgrimes			memout.bufsize = 64;
9231556Srgrimes			mode |= REDIR_BACKQ;
924201366Sjilles			cmdentry.special = 0;
9251556Srgrimes		}
9261556Srgrimes		savecmdname = commandname;
927199647Sjilles		savetopfile = getcurrentfile();
9281556Srgrimes		cmdenviron = varlist.list;
9291556Srgrimes		e = -1;
930194765Sjilles		savehandler = handler;
9311556Srgrimes		if (setjmp(jmploc.loc)) {
9321556Srgrimes			e = exception;
9331556Srgrimes			exitstatus = (e == EXINT)? SIGINT+128 : 2;
9341556Srgrimes			goto cmddone;
9351556Srgrimes		}
9361556Srgrimes		handler = &jmploc;
937157601Sstefanf		redirect(cmd->ncmd.redirect, mode);
938205138Sjilles		/*
939205138Sjilles		 * If there is no command word, redirection errors should
940205138Sjilles		 * not be fatal but assignment errors should.
941205138Sjilles		 */
942205138Sjilles		if (argc == 0 && !(flags & EV_BACKCMD))
943205138Sjilles			cmdentry.special = 1;
944157601Sstefanf		if (cmdentry.special)
945157601Sstefanf			listsetvar(cmdenviron);
946207678Sjilles		if (argc > 0)
947207678Sjilles			bltinsetlocale();
9481556Srgrimes		commandname = argv[0];
9491556Srgrimes		argptr = argv + 1;
950201053Sjilles		nextopt_optptr = NULL;		/* initialize nextopt */
951193169Sstefanf		builtin_flags = flags;
9521556Srgrimes		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
9531556Srgrimes		flushall();
9541556Srgrimescmddone:
955207678Sjilles		if (argc > 0)
956207678Sjilles			bltinunsetlocale();
95760592Scracauer		cmdenviron = NULL;
9581556Srgrimes		out1 = &output;
9591556Srgrimes		out2 = &errout;
9601556Srgrimes		freestdout();
9611556Srgrimes		if (e != EXSHELLPROC) {
9621556Srgrimes			commandname = savecmdname;
9631556Srgrimes			if (flags & EV_EXIT) {
9641556Srgrimes				exitshell(exitstatus);
9651556Srgrimes			}
9661556Srgrimes		}
9671556Srgrimes		handler = savehandler;
968201366Sjilles		if (flags == EV_BACKCMD) {
969201366Sjilles			backcmd->buf = memout.buf;
970201366Sjilles			backcmd->nleft = memout.nextc - memout.buf;
971201366Sjilles			memout.buf = NULL;
972201366Sjilles		}
973204801Sjilles		if (cmdentry.u.index != EXECCMD &&
974204801Sjilles				(e == -1 || e == EXERROR || e == EXEXEC))
975204801Sjilles			popredir();
9761556Srgrimes		if (e != -1) {
97720425Ssteve			if ((e != EXERROR && e != EXEXEC)
978157601Sstefanf			    || cmdentry.special)
9791556Srgrimes				exraise(e);
980199647Sjilles			popfilesupto(savetopfile);
981201366Sjilles			if (flags != EV_BACKCMD)
982201366Sjilles				FORCEINTON;
9831556Srgrimes		}
9841556Srgrimes	} else {
98520425Ssteve#ifdef DEBUG
9861556Srgrimes		trputs("normal command:  ");  trargs(argv);
98720425Ssteve#endif
9881556Srgrimes		redirect(cmd->ncmd.redirect, 0);
9891556Srgrimes		for (sp = varlist.list ; sp ; sp = sp->next)
9901556Srgrimes			setvareq(sp->text, VEXPORT|VSTACK);
9911556Srgrimes		envp = environment();
992204800Sjilles		shellexec(argv, envp, path, cmdentry.u.index);
9931556Srgrimes		/*NOTREACHED*/
9941556Srgrimes	}
9951556Srgrimes	goto out;
9961556Srgrimes
9971556Srgrimesparent:	/* parent process gets here (if we forked) */
998212214Sjilles	if (mode == FORK_FG) {	/* argument to fork */
9991556Srgrimes		INTOFF;
100045916Scracauer		exitstatus = waitforjob(jp, &realstatus);
10011556Srgrimes		INTON;
100245916Scracauer		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
100345266Scracauer			evalskip = SKIPBREAK;
100445266Scracauer			skipcount = loopnest;
100545266Scracauer		}
1006212214Sjilles	} else if (mode == FORK_NOJOB) {
10071556Srgrimes		backcmd->fd = pip[0];
10081556Srgrimes		close(pip[1]);
10091556Srgrimes		backcmd->jp = jp;
10101556Srgrimes	}
10111556Srgrimes
10121556Srgrimesout:
10131556Srgrimes	if (lastarg)
10141556Srgrimes		setvar("_", lastarg, 0);
101554884Scracauer	if (do_clearcmdentry)
101654884Scracauer		clearcmdentry(0);
10171556Srgrimes	popstackmark(&smark);
10181556Srgrimes}
10191556Srgrimes
10201556Srgrimes
10211556Srgrimes
10221556Srgrimes/*
10231556Srgrimes * Search for a command.  This is called before we fork so that the
10241556Srgrimes * location of the command will be available in the parent as well as
10251556Srgrimes * the child.  The check for "goodname" is an overly conservative
10261556Srgrimes * check that the name will not be subject to expansion.
10271556Srgrimes */
10281556Srgrimes
10291556SrgrimesSTATIC void
103090111Simpprehash(union node *n)
103117987Speter{
10321556Srgrimes	struct cmdentry entry;
10331556Srgrimes
1034159633Sstefanf	if (n && n->type == NCMD && n->ncmd.args)
103517987Speter		if (goodname(n->ncmd.args->narg.text))
103617987Speter			find_command(n->ncmd.args->narg.text, &entry, 0,
103717987Speter				     pathval());
10381556Srgrimes}
10391556Srgrimes
10401556Srgrimes
10411556Srgrimes
10421556Srgrimes/*
10431556Srgrimes * Builtin commands.  Builtin commands whose functions are closely
10441556Srgrimes * tied to evaluation are implemented here.
10451556Srgrimes */
10461556Srgrimes
10471556Srgrimes/*
1048201431Sjilles * No command given, a bltin command with no arguments, or a bltin command
1049201431Sjilles * with an invalid name.
10501556Srgrimes */
10511556Srgrimes
105217987Speterint
1053201431Sjillesbltincmd(int argc, char **argv)
105417987Speter{
1055201431Sjilles	if (argc > 1) {
1056201431Sjilles		out2fmt_flush("%s: not found\n", argv[1]);
1057201431Sjilles		return 127;
1058201431Sjilles	}
105920425Ssteve	/*
106017987Speter	 * Preserve exitstatus of a previous possible redirection
106120425Ssteve	 * as POSIX mandates
106217987Speter	 */
10631556Srgrimes	return exitstatus;
10641556Srgrimes}
10651556Srgrimes
10661556Srgrimes
10671556Srgrimes/*
10681556Srgrimes * Handle break and continue commands.  Break, continue, and return are
10691556Srgrimes * all handled by setting the evalskip flag.  The evaluation routines
10701556Srgrimes * above all check this flag, and if it is set they start skipping
10711556Srgrimes * commands rather than executing them.  The variable skipcount is
10721556Srgrimes * the number of loops to break/continue, or the number of function
10731556Srgrimes * levels to return.  (The latter is always 1.)  It should probably
10741556Srgrimes * be an error to break out of more loops than exist, but it isn't
10751556Srgrimes * in the standard shell so we don't make it one here.
10761556Srgrimes */
10771556Srgrimes
107817987Speterint
107990111Simpbreakcmd(int argc, char **argv)
108017987Speter{
108120425Ssteve	int n = argc > 1 ? number(argv[1]) : 1;
10821556Srgrimes
10831556Srgrimes	if (n > loopnest)
10841556Srgrimes		n = loopnest;
10851556Srgrimes	if (n > 0) {
10861556Srgrimes		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
10871556Srgrimes		skipcount = n;
10881556Srgrimes	}
10891556Srgrimes	return 0;
10901556Srgrimes}
10911556Srgrimes
1092100437Stjr/*
1093100437Stjr * The `command' command.
1094100437Stjr */
1095100437Stjrint
1096100437Stjrcommandcmd(int argc, char **argv)
1097100437Stjr{
1098207783Sjilles	const char *path;
1099100437Stjr	int ch;
1100151810Sstefanf	int cmd = -1;
11011556Srgrimes
1102204800Sjilles	path = bltinlookup("PATH", 1);
1103100437Stjr
1104100437Stjr	optind = optreset = 1;
1105100663Stjr	opterr = 0;
1106151810Sstefanf	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1107100437Stjr		switch (ch) {
1108100437Stjr		case 'p':
1109207783Sjilles			path = _PATH_STDPATH;
1110100437Stjr			break;
1111151810Sstefanf		case 'v':
1112151810Sstefanf			cmd = TYPECMD_SMALLV;
1113151810Sstefanf			break;
1114151810Sstefanf		case 'V':
1115151810Sstefanf			cmd = TYPECMD_BIGV;
1116151810Sstefanf			break;
1117100437Stjr		case '?':
1118100437Stjr		default:
1119100437Stjr			error("unknown option: -%c", optopt);
1120100437Stjr		}
1121100437Stjr	}
1122100437Stjr	argc -= optind;
1123100437Stjr	argv += optind;
1124100437Stjr
1125151810Sstefanf	if (cmd != -1) {
1126151810Sstefanf		if (argc != 1)
1127151810Sstefanf			error("wrong number of arguments");
1128201343Sjilles		return typecmd_impl(2, argv - 1, cmd, path);
1129151810Sstefanf	}
1130204800Sjilles	if (argc != 0)
1131204800Sjilles		error("commandcmd() called while it should not be");
1132100437Stjr
1133100437Stjr	/*
1134100437Stjr	 * Do nothing successfully if no command was specified;
1135100437Stjr	 * ksh also does this.
1136100437Stjr	 */
1137204800Sjilles	return 0;
1138100437Stjr}
1139100437Stjr
1140100437Stjr
11411556Srgrimes/*
11421556Srgrimes * The return command.
11431556Srgrimes */
11441556Srgrimes
114517987Speterint
114690111Simpreturncmd(int argc, char **argv)
114717987Speter{
114820425Ssteve	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
11491556Srgrimes
11501556Srgrimes	if (funcnest) {
11511556Srgrimes		evalskip = SKIPFUNC;
11521556Srgrimes		skipcount = 1;
115320425Ssteve	} else {
115420425Ssteve		/* skip the rest of the file */
115520425Ssteve		evalskip = SKIPFILE;
115620425Ssteve		skipcount = 1;
11571556Srgrimes	}
11581556Srgrimes	return ret;
11591556Srgrimes}
11601556Srgrimes
11611556Srgrimes
116217987Speterint
116390111Simpfalsecmd(int argc __unused, char **argv __unused)
116417987Speter{
116517987Speter	return 1;
116617987Speter}
116717987Speter
116817987Speter
116917987Speterint
117090111Simptruecmd(int argc __unused, char **argv __unused)
117117987Speter{
11721556Srgrimes	return 0;
11731556Srgrimes}
11741556Srgrimes
11751556Srgrimes
117617987Speterint
117790111Simpexeccmd(int argc, char **argv)
117817987Speter{
1179208630Sjilles	/*
1180208630Sjilles	 * Because we have historically not supported any options,
1181208630Sjilles	 * only treat "--" specially.
1182208630Sjilles	 */
1183208630Sjilles	if (argc > 1 && strcmp(argv[1], "--") == 0)
1184208630Sjilles		argc--, argv++;
11851556Srgrimes	if (argc > 1) {
118617987Speter		struct strlist *sp;
118717987Speter
11881556Srgrimes		iflag = 0;		/* exit on error */
11891556Srgrimes		mflag = 0;
11901556Srgrimes		optschanged();
119117987Speter		for (sp = cmdenviron; sp ; sp = sp->next)
119217987Speter			setvareq(sp->text, VEXPORT|VSTACK);
11931556Srgrimes		shellexec(argv + 1, environment(), pathval(), 0);
11941556Srgrimes
11951556Srgrimes	}
11961556Srgrimes	return 0;
11971556Srgrimes}
1198153091Sstefanf
1199153091Sstefanf
1200153091Sstefanfint
1201153091Sstefanftimescmd(int argc __unused, char **argv __unused)
1202153091Sstefanf{
1203153091Sstefanf	struct rusage ru;
1204153091Sstefanf	long shumins, shsmins, chumins, chsmins;
1205153091Sstefanf	double shusecs, shssecs, chusecs, chssecs;
1206153091Sstefanf
1207153091Sstefanf	if (getrusage(RUSAGE_SELF, &ru) < 0)
1208153091Sstefanf		return 1;
1209153091Sstefanf	shumins = ru.ru_utime.tv_sec / 60;
1210153091Sstefanf	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1211153091Sstefanf	shsmins = ru.ru_stime.tv_sec / 60;
1212153091Sstefanf	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1213153091Sstefanf	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1214153091Sstefanf		return 1;
1215153091Sstefanf	chumins = ru.ru_utime.tv_sec / 60;
1216153091Sstefanf	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1217153091Sstefanf	chsmins = ru.ru_stime.tv_sec / 60;
1218153091Sstefanf	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1219153091Sstefanf	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1220153091Sstefanf	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1221153091Sstefanf	return 0;
1222153091Sstefanf}
1223