eval.c revision 194127
1175164Sjhb/*-
2175164Sjhb * Copyright (c) 1993
3175164Sjhb *	The Regents of the University of California.  All rights reserved.
4175164Sjhb *
5175164Sjhb * This code is derived from software contributed to Berkeley by
6175164Sjhb * Kenneth Almquist.
7175164Sjhb *
8175164Sjhb * Redistribution and use in source and binary forms, with or without
9175164Sjhb * modification, are permitted provided that the following conditions
10175164Sjhb * are met:
11175164Sjhb * 1. Redistributions of source code must retain the above copyright
12175164Sjhb *    notice, this list of conditions and the following disclaimer.
13175164Sjhb * 2. Redistributions in binary form must reproduce the above copyright
14175164Sjhb *    notice, this list of conditions and the following disclaimer in the
15175164Sjhb *    documentation and/or other materials provided with the distribution.
16175164Sjhb * 4. Neither the name of the University nor the names of its contributors
17175164Sjhb *    may be used to endorse or promote products derived from this software
18175164Sjhb *    without specific prior written permission.
19175164Sjhb *
20175164Sjhb * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21175164Sjhb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22175164Sjhb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23175164Sjhb * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24175164Sjhb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25175164Sjhb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26175164Sjhb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27175164Sjhb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28175164Sjhb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29175164Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30175164Sjhb * SUCH DAMAGE.
31175164Sjhb */
32175164Sjhb
33175164Sjhb#ifndef lint
34175164Sjhb#if 0
35175164Sjhbstatic char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
36175164Sjhb#endif
37175164Sjhb#endif /* not lint */
38175164Sjhb#include <sys/cdefs.h>
39175164Sjhb__FBSDID("$FreeBSD: head/bin/sh/eval.c 194127 2009-06-13 21:10:41Z jilles $");
40175164Sjhb
41175164Sjhb#include <paths.h>
42175164Sjhb#include <signal.h>
43175164Sjhb#include <stdlib.h>
44175164Sjhb#include <unistd.h>
45175164Sjhb#include <sys/resource.h>
46175164Sjhb#include <sys/wait.h> /* For WIFSIGNALED(status) */
47175164Sjhb#include <errno.h>
48175164Sjhb
49180059Sjhb/*
50180059Sjhb * Evaluate a command.
51180059Sjhb */
52180059Sjhb
53175164Sjhb#include "shell.h"
54175164Sjhb#include "nodes.h"
55175164Sjhb#include "syntax.h"
56175164Sjhb#include "expand.h"
57175164Sjhb#include "parser.h"
58175164Sjhb#include "jobs.h"
59175164Sjhb#include "eval.h"
60175164Sjhb#include "builtins.h"
61175164Sjhb#include "options.h"
62175164Sjhb#include "exec.h"
63175164Sjhb#include "redir.h"
64175164Sjhb#include "input.h"
65175164Sjhb#include "output.h"
66175164Sjhb#include "trap.h"
67175164Sjhb#include "var.h"
68175164Sjhb#include "memalloc.h"
69175164Sjhb#include "error.h"
70175164Sjhb#include "show.h"
71175164Sjhb#include "mystring.h"
72175164Sjhb#ifndef NO_HISTORY
73175164Sjhb#include "myhistedit.h"
74175164Sjhb#endif
75175164Sjhb
76175164Sjhb
77175164Sjhb/* flags in argument to evaltree */
78175164Sjhb#define EV_EXIT 01		/* exit after evaluating tree */
79175164Sjhb#define EV_TESTED 02		/* exit status is checked; ignore -e flag */
80175164Sjhb#define EV_BACKCMD 04		/* command executing within back quotes */
81175164Sjhb
82175164SjhbMKINIT int evalskip;		/* set if we are skipping commands */
83175164SjhbSTATIC int skipcount;		/* number of levels to skip */
84175164SjhbMKINIT int loopnest;		/* current loop nesting level */
85175164Sjhbint funcnest;			/* depth of function calls */
86175164SjhbSTATIC int builtin_flags;	/* evalcommand flags for builtins */
87175164Sjhb
88175164Sjhb
89175164Sjhbchar *commandname;
90175164Sjhbstruct strlist *cmdenviron;
91175164Sjhbint exitstatus;			/* exit status of last command */
92175164Sjhbint oexitstatus;		/* saved exit status */
93175164Sjhb
94175164Sjhb
95175164SjhbSTATIC void evalloop(union node *, int);
96175164SjhbSTATIC void evalfor(union node *, int);
97175164SjhbSTATIC void evalcase(union node *, int);
98175164SjhbSTATIC void evalsubshell(union node *, int);
99175164SjhbSTATIC void expredir(union node *);
100175164SjhbSTATIC void evalpipe(union node *);
101175164SjhbSTATIC void evalcommand(union node *, int, struct backcmd *);
102175164SjhbSTATIC void prehash(union node *);
103175164Sjhb
104175164Sjhb
105175164Sjhb/*
106175164Sjhb * Called to reset things after an exception.
107175164Sjhb */
108175164Sjhb
109175164Sjhb#ifdef mkinit
110175164SjhbINCLUDE "eval.h"
111175164Sjhb
112175164SjhbRESET {
113194766Skib	evalskip = 0;
114175164Sjhb	loopnest = 0;
115175164Sjhb	funcnest = 0;
116175164Sjhb}
117175164Sjhb
118175164SjhbSHELLPROC {
119175164Sjhb	exitstatus = 0;
120175164Sjhb}
121175164Sjhb#endif
122175164Sjhb
123175164Sjhb
124175164Sjhb
125175164Sjhb/*
126175164Sjhb * The eval command.
127175164Sjhb */
128175164Sjhb
129175164Sjhbint
130175164Sjhbevalcmd(int argc, char **argv)
131175164Sjhb{
132175164Sjhb        char *p;
133175164Sjhb        char *concat;
134175164Sjhb        char **ap;
135175164Sjhb
136175164Sjhb        if (argc > 1) {
137175164Sjhb                p = argv[1];
138175164Sjhb                if (argc > 2) {
139175164Sjhb                        STARTSTACKSTR(concat);
140175164Sjhb                        ap = argv + 2;
141175164Sjhb                        for (;;) {
142175164Sjhb                                while (*p)
143175164Sjhb                                        STPUTC(*p++, concat);
144175164Sjhb                                if ((p = *ap++) == NULL)
145175164Sjhb                                        break;
146175164Sjhb                                STPUTC(' ', concat);
147175164Sjhb                        }
148175164Sjhb                        STPUTC('\0', concat);
149175164Sjhb                        p = grabstackstr(concat);
150175164Sjhb                }
151175164Sjhb                evalstring(p, builtin_flags & EV_TESTED);
152175164Sjhb        }
153175164Sjhb        return exitstatus;
154175164Sjhb}
155175164Sjhb
156175164Sjhb
157175164Sjhb/*
158175164Sjhb * Execute a command or commands contained in a string.
159175164Sjhb */
160175164Sjhb
161175164Sjhbvoid
162175164Sjhbevalstring(char *s, int flags)
163175164Sjhb{
164175164Sjhb	union node *n;
165175164Sjhb	struct stackmark smark;
166175164Sjhb
167175164Sjhb	setstackmark(&smark);
168175164Sjhb	setinputstring(s, 1);
169175164Sjhb	while ((n = parsecmd(0)) != NEOF) {
170194766Skib		if (n != NULL)
171175164Sjhb			evaltree(n, flags);
172175164Sjhb		popstackmark(&smark);
173175164Sjhb	}
174175164Sjhb	popfile();
175175164Sjhb	popstackmark(&smark);
176175164Sjhb}
177175164Sjhb
178175164Sjhb
179175164Sjhb
180175164Sjhb/*
181175164Sjhb * Evaluate a parse tree.  The value is left in the global variable
182175164Sjhb * exitstatus.
183175164Sjhb */
184175164Sjhb
185175164Sjhbvoid
186175164Sjhbevaltree(union node *n, int flags)
187175164Sjhb{
188175164Sjhb	int do_etest;
189175164Sjhb
190175164Sjhb	do_etest = 0;
191175164Sjhb	if (n == NULL) {
192175164Sjhb		TRACE(("evaltree(NULL) called\n"));
193175164Sjhb		exitstatus = 0;
194175164Sjhb		goto out;
195175164Sjhb	}
196175164Sjhb#ifndef NO_HISTORY
197175164Sjhb	displayhist = 1;	/* show history substitutions done with fc */
198175164Sjhb#endif
199175164Sjhb	TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
200175164Sjhb	switch (n->type) {
201175164Sjhb	case NSEMI:
202175164Sjhb		evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
203175164Sjhb		if (evalskip)
204175164Sjhb			goto out;
205175164Sjhb		evaltree(n->nbinary.ch2, flags);
206175164Sjhb		break;
207175164Sjhb	case NAND:
208175164Sjhb		evaltree(n->nbinary.ch1, EV_TESTED);
209175164Sjhb		if (evalskip || exitstatus != 0) {
210175164Sjhb			goto out;
211175164Sjhb		}
212175164Sjhb		evaltree(n->nbinary.ch2, flags);
213175164Sjhb		break;
214175164Sjhb	case NOR:
215175164Sjhb		evaltree(n->nbinary.ch1, EV_TESTED);
216175164Sjhb		if (evalskip || exitstatus == 0)
217175164Sjhb			goto out;
218175164Sjhb		evaltree(n->nbinary.ch2, flags);
219175164Sjhb		break;
220175164Sjhb	case NREDIR:
221175164Sjhb		expredir(n->nredir.redirect);
222205792Sed		redirect(n->nredir.redirect, REDIR_PUSH);
223205792Sed		evaltree(n->nredir.n, flags);
224205792Sed		popredir();
225205792Sed		break;
226175164Sjhb	case NSUBSHELL:
227175164Sjhb		evalsubshell(n, flags);
228175164Sjhb		do_etest = !(flags & EV_TESTED);
229175164Sjhb		break;
230175164Sjhb	case NBACKGND:
231175164Sjhb		evalsubshell(n, flags);
232175164Sjhb		break;
233175164Sjhb	case NIF: {
234175164Sjhb		evaltree(n->nif.test, EV_TESTED);
235175164Sjhb		if (evalskip)
236175164Sjhb			goto out;
237175164Sjhb		if (exitstatus == 0)
238175164Sjhb			evaltree(n->nif.ifpart, flags);
239175164Sjhb		else if (n->nif.elsepart)
240175164Sjhb			evaltree(n->nif.elsepart, flags);
241175164Sjhb		else
242175164Sjhb			exitstatus = 0;
243175164Sjhb		break;
244194766Skib	}
245175164Sjhb	case NWHILE:
246175164Sjhb	case NUNTIL:
247175164Sjhb		evalloop(n, flags & ~EV_EXIT);
248175164Sjhb		break;
249175164Sjhb	case NFOR:
250194766Skib		evalfor(n, flags & ~EV_EXIT);
251175164Sjhb		break;
252175164Sjhb	case NCASE:
253175164Sjhb		evalcase(n, flags);
254175164Sjhb		break;
255175164Sjhb	case NDEFUN:
256194766Skib		defun(n->narg.text, n->narg.next);
257175164Sjhb		exitstatus = 0;
258175164Sjhb		break;
259175164Sjhb	case NNOT:
260175164Sjhb		evaltree(n->nnot.com, EV_TESTED);
261175164Sjhb		exitstatus = !exitstatus;
262194766Skib		break;
263194766Skib
264175164Sjhb	case NPIPE:
265175164Sjhb		evalpipe(n);
266175164Sjhb		do_etest = !(flags & EV_TESTED);
267175164Sjhb		break;
268175164Sjhb	case NCMD:
269175164Sjhb		evalcommand(n, flags, (struct backcmd *)NULL);
270175164Sjhb		do_etest = !(flags & EV_TESTED);
271194766Skib		break;
272175164Sjhb	default:
273194766Skib		out1fmt("Node type = %d\n", n->type);
274216128Strasz		flushout(&output);
275194766Skib		break;
276194766Skib	}
277175164Sjhbout:
278175164Sjhb	if (pendingsigs)
279175164Sjhb		dotrap();
280193303Salc	if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
281175164Sjhb		exitshell(exitstatus);
282175164Sjhb}
283175164Sjhb
284175164Sjhb
285175164SjhbSTATIC void
286175164Sjhbevalloop(union node *n, int flags)
287175164Sjhb{
288175164Sjhb	int status;
289175164Sjhb
290175164Sjhb	loopnest++;
291175164Sjhb	status = 0;
292193303Salc	for (;;) {
293193303Salc		evaltree(n->nbinary.ch1, EV_TESTED);
294193303Salc		if (evalskip) {
295193303Salcskipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
296193303Salc				evalskip = 0;
297193303Salc				continue;
298193303Salc			}
299193303Salc			if (evalskip == SKIPBREAK && --skipcount <= 0)
300193303Salc				evalskip = 0;
301193303Salc			break;
302193303Salc		}
303193303Salc		if (n->type == NWHILE) {
304193303Salc			if (exitstatus != 0)
305193303Salc				break;
306193303Salc		} else {
307193303Salc			if (exitstatus == 0)
308176075Salc				break;
309176075Salc		}
310176075Salc		evaltree(n->nbinary.ch2, flags);
311176075Salc		status = exitstatus;
312175164Sjhb		if (evalskip)
313194766Skib			goto skipping;
314194766Skib	}
315194766Skib	loopnest--;
316194766Skib	exitstatus = status;
317216128Strasz}
318194766Skib
319194766Skib
320194766Skib
321194766SkibSTATIC void
322175164Sjhbevalfor(union node *n, int flags)
323175164Sjhb{
324175164Sjhb	struct arglist arglist;
325175164Sjhb	union node *argp;
326175164Sjhb	struct strlist *sp;
327175164Sjhb	struct stackmark smark;
328175164Sjhb
329175164Sjhb	setstackmark(&smark);
330194766Skib	arglist.lastp = &arglist.list;
331175164Sjhb	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
332175164Sjhb		oexitstatus = exitstatus;
333175164Sjhb		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
334175164Sjhb		if (evalskip)
335175164Sjhb			goto out;
336175164Sjhb	}
337175164Sjhb	*arglist.lastp = NULL;
338175164Sjhb
339175164Sjhb	exitstatus = 0;
340175164Sjhb	loopnest++;
341175164Sjhb	for (sp = arglist.list ; sp ; sp = sp->next) {
342175164Sjhb		setvar(n->nfor.var, sp->text, 0);
343175164Sjhb		evaltree(n->nfor.body, flags);
344175164Sjhb		if (evalskip) {
345175164Sjhb			if (evalskip == SKIPCONT && --skipcount <= 0) {
346175164Sjhb				evalskip = 0;
347175164Sjhb				continue;
348194766Skib			}
349175164Sjhb			if (evalskip == SKIPBREAK && --skipcount <= 0)
350178181Salc				evalskip = 0;
351178181Salc			break;
352178181Salc		}
353178181Salc	}
354175164Sjhb	loopnest--;
355175164Sjhbout:
356175164Sjhb	popstackmark(&smark);
357175164Sjhb}
358175164Sjhb
359175164Sjhb
360175164Sjhb
361175164SjhbSTATIC void
362175164Sjhbevalcase(union node *n, int flags)
363175164Sjhb{
364175164Sjhb	union node *cp;
365175164Sjhb	union node *patp;
366175164Sjhb	struct arglist arglist;
367175164Sjhb	struct stackmark smark;
368175164Sjhb
369175164Sjhb	setstackmark(&smark);
370175164Sjhb	arglist.lastp = &arglist.list;
371175164Sjhb	oexitstatus = exitstatus;
372175164Sjhb	exitstatus = 0;
373175164Sjhb	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
374175164Sjhb	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
375175164Sjhb		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
376175164Sjhb			if (casematch(patp, arglist.list->text)) {
377175164Sjhb				if (evalskip == 0) {
378175164Sjhb					evaltree(cp->nclist.body, flags);
379175164Sjhb				}
380175164Sjhb				goto out;
381175164Sjhb			}
382175164Sjhb		}
383175164Sjhb	}
384175164Sjhbout:
385175164Sjhb	popstackmark(&smark);
386175164Sjhb}
387175164Sjhb
388175164Sjhb
389175164Sjhb
390175164Sjhb/*
391175164Sjhb * Kick off a subshell to evaluate a tree.
392175164Sjhb */
393175164Sjhb
394184413StraszSTATIC void
395175164Sjhbevalsubshell(union node *n, int flags)
396184413Strasz{
397175164Sjhb	struct job *jp;
398184413Strasz	int backgnd = (n->type == NBACKGND);
399175164Sjhb
400184413Strasz	expredir(n->nredir.redirect);
401175164Sjhb	jp = makejob(n, 1);
402184413Strasz	if (forkshell(jp, n, backgnd) == 0) {
403175164Sjhb		if (backgnd)
404175164Sjhb			flags &=~ EV_TESTED;
405175164Sjhb		redirect(n->nredir.redirect, 0);
406175164Sjhb		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
407175164Sjhb	}
408175164Sjhb	if (! backgnd) {
409175164Sjhb		INTOFF;
410175164Sjhb		exitstatus = waitforjob(jp, (int *)NULL);
411175164Sjhb		INTON;
412175164Sjhb	}
413175164Sjhb}
414175164Sjhb
415175164Sjhb
416175164Sjhb
417175164Sjhb/*
418175164Sjhb * Compute the names of the files in a redirection list.
419175164Sjhb */
420175164Sjhb
421175164SjhbSTATIC void
422175164Sjhbexpredir(union node *n)
423175164Sjhb{
424175164Sjhb	union node *redir;
425175164Sjhb
426175164Sjhb	for (redir = n ; redir ; redir = redir->nfile.next) {
427175164Sjhb		struct arglist fn;
428175164Sjhb		fn.lastp = &fn.list;
429175164Sjhb		oexitstatus = exitstatus;
430175164Sjhb		switch (redir->type) {
431175164Sjhb		case NFROM:
432175164Sjhb		case NTO:
433175164Sjhb		case NFROMTO:
434175164Sjhb		case NAPPEND:
435175164Sjhb		case NCLOBBER:
436175164Sjhb			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
437175164Sjhb			redir->nfile.expfname = fn.list->text;
438175164Sjhb			break;
439175164Sjhb		case NFROMFD:
440175164Sjhb		case NTOFD:
441175164Sjhb			if (redir->ndup.vname) {
442175164Sjhb				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
443175164Sjhb				fixredir(redir, fn.list->text, 1);
444175164Sjhb			}
445175164Sjhb			break;
446175164Sjhb		}
447175164Sjhb	}
448175164Sjhb}
449175164Sjhb
450175164Sjhb
451175164Sjhb
452175164Sjhb/*
453175164Sjhb * Evaluate a pipeline.  All the processes in the pipeline are children
454175164Sjhb * of the process creating the pipeline.  (This differs from some versions
455175164Sjhb * of the shell, which make the last process in a pipeline the parent
456175164Sjhb * of all the rest.)
457175164Sjhb */
458175164Sjhb
459175164SjhbSTATIC void
460175164Sjhbevalpipe(union node *n)
461175164Sjhb{
462175164Sjhb	struct job *jp;
463175164Sjhb	struct nodelist *lp;
464175164Sjhb	int pipelen;
465175164Sjhb	int prevfd;
466175164Sjhb	int pip[2];
467175164Sjhb
468175164Sjhb	TRACE(("evalpipe(%p) called\n", (void *)n));
469175164Sjhb	pipelen = 0;
470175164Sjhb	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
471175164Sjhb		pipelen++;
472175164Sjhb	INTOFF;
473175164Sjhb	jp = makejob(n, pipelen);
474175164Sjhb	prevfd = -1;
475175164Sjhb	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
476175164Sjhb		prehash(lp->n);
477175164Sjhb		pip[1] = -1;
478175164Sjhb		if (lp->next) {
479175164Sjhb			if (pipe(pip) < 0) {
480175164Sjhb				close(prevfd);
481175164Sjhb				error("Pipe call failed: %s", strerror(errno));
482175164Sjhb			}
483175164Sjhb		}
484175164Sjhb		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
485175164Sjhb			INTON;
486175164Sjhb			if (prevfd > 0) {
487175164Sjhb				dup2(prevfd, 0);
488175164Sjhb				close(prevfd);
489175164Sjhb			}
490175164Sjhb			if (pip[1] >= 0) {
491175164Sjhb				if (!(prevfd >= 0 && pip[0] == 0))
492175164Sjhb					close(pip[0]);
493175164Sjhb				if (pip[1] != 1) {
494175164Sjhb					dup2(pip[1], 1);
495175164Sjhb					close(pip[1]);
496175164Sjhb				}
497175164Sjhb			}
498175164Sjhb			evaltree(lp->n, EV_EXIT);
499175164Sjhb		}
500175164Sjhb		if (prevfd >= 0)
501175164Sjhb			close(prevfd);
502175164Sjhb		prevfd = pip[0];
503175164Sjhb		close(pip[1]);
504175164Sjhb	}
505175164Sjhb	INTON;
506175164Sjhb	if (n->npipe.backgnd == 0) {
507175164Sjhb		INTOFF;
508175164Sjhb		exitstatus = waitforjob(jp, (int *)NULL);
509175164Sjhb		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
510175164Sjhb		INTON;
511175164Sjhb	}
512175164Sjhb}
513175164Sjhb
514175164Sjhb
515175164Sjhb
516175164Sjhb/*
517175164Sjhb * Execute a command inside back quotes.  If it's a builtin command, we
518175164Sjhb * want to save its output in a block obtained from malloc.  Otherwise
519175164Sjhb * we fork off a subprocess and get the output of the command via a pipe.
520175164Sjhb * Should be called with interrupts off.
521175164Sjhb */
522175164Sjhb
523175164Sjhbvoid
524175164Sjhbevalbackcmd(union node *n, struct backcmd *result)
525175164Sjhb{
526175164Sjhb	int pip[2];
527175164Sjhb	struct job *jp;
528175164Sjhb	struct stackmark smark;		/* unnecessary */
529175164Sjhb
530175164Sjhb	setstackmark(&smark);
531175164Sjhb	result->fd = -1;
532175164Sjhb	result->buf = NULL;
533175164Sjhb	result->nleft = 0;
534175164Sjhb	result->jp = NULL;
535175164Sjhb	if (n == NULL) {
536175164Sjhb		exitstatus = 0;
537175164Sjhb		goto out;
538175164Sjhb	}
539175164Sjhb	if (n->type == NCMD) {
540175164Sjhb		exitstatus = oexitstatus;
541175164Sjhb		evalcommand(n, EV_BACKCMD, result);
542175164Sjhb	} else {
543175164Sjhb		exitstatus = 0;
544175164Sjhb		if (pipe(pip) < 0)
545175164Sjhb			error("Pipe call failed: %s", strerror(errno));
546175164Sjhb		jp = makejob(n, 1);
547175164Sjhb		if (forkshell(jp, n, FORK_NOJOB) == 0) {
548175164Sjhb			FORCEINTON;
549175164Sjhb			close(pip[0]);
550175164Sjhb			if (pip[1] != 1) {
551175164Sjhb				dup2(pip[1], 1);
552175164Sjhb				close(pip[1]);
553175164Sjhb			}
554175164Sjhb			evaltree(n, EV_EXIT);
555175164Sjhb		}
556175164Sjhb		close(pip[1]);
557175164Sjhb		result->fd = pip[0];
558175164Sjhb		result->jp = jp;
559175164Sjhb	}
560175164Sjhbout:
561175164Sjhb	popstackmark(&smark);
562175164Sjhb	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
563175164Sjhb		result->fd, result->buf, result->nleft, result->jp));
564175164Sjhb}
565175164Sjhb
566175164Sjhb
567175164Sjhb
568175164Sjhb/*
569175164Sjhb * Execute a simple command.
570175164Sjhb */
571175164Sjhb
572175164SjhbSTATIC void
573175164Sjhbevalcommand(union node *cmd, int flags, struct backcmd *backcmd)
574175164Sjhb{
575175164Sjhb	struct stackmark smark;
576175164Sjhb	union node *argp;
577175164Sjhb	struct arglist arglist;
578175164Sjhb	struct arglist varlist;
579175164Sjhb	char **argv;
580175164Sjhb	int argc;
581175164Sjhb	char **envp;
582175164Sjhb	int varflag;
583175164Sjhb	struct strlist *sp;
584175164Sjhb	int mode;
585175164Sjhb	int pip[2];
586175164Sjhb	struct cmdentry cmdentry;
587175164Sjhb	struct job *jp;
588175164Sjhb	struct jmploc jmploc;
589175164Sjhb	struct jmploc *volatile savehandler;
590175164Sjhb	char *volatile savecmdname;
591175164Sjhb	volatile struct shparam saveparam;
592175164Sjhb	struct localvar *volatile savelocalvars;
593175164Sjhb	volatile int e;
594175164Sjhb	char *lastarg;
595175164Sjhb	int realstatus;
596175164Sjhb	int do_clearcmdentry;
597175164Sjhb#ifdef __GNUC__
598175164Sjhb	/* Avoid longjmp clobbering */
599175164Sjhb	(void) &argv;
600175164Sjhb	(void) &argc;
601175164Sjhb	(void) &lastarg;
602175164Sjhb	(void) &flags;
603175164Sjhb	(void) &do_clearcmdentry;
604175164Sjhb#endif
605175164Sjhb
606175164Sjhb	/* First expand the arguments. */
607175164Sjhb	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
608175164Sjhb	setstackmark(&smark);
609175164Sjhb	arglist.lastp = &arglist.list;
610175164Sjhb	varlist.lastp = &varlist.list;
611175164Sjhb	varflag = 1;
612175164Sjhb	do_clearcmdentry = 0;
613175164Sjhb	oexitstatus = exitstatus;
614175164Sjhb	exitstatus = 0;
615175164Sjhb	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
616175164Sjhb		char *p = argp->narg.text;
617175164Sjhb		if (varflag && is_name(*p)) {
618175164Sjhb			do {
619175164Sjhb				p++;
620175164Sjhb			} while (is_in_name(*p));
621175164Sjhb			if (*p == '=') {
622175164Sjhb				expandarg(argp, &varlist, EXP_VARTILDE);
623175164Sjhb				continue;
624175164Sjhb			}
625175164Sjhb		}
626175164Sjhb		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
627175164Sjhb		varflag = 0;
628175164Sjhb	}
629175164Sjhb	*arglist.lastp = NULL;
630175164Sjhb	*varlist.lastp = NULL;
631175164Sjhb	expredir(cmd->ncmd.redirect);
632185533Skan	argc = 0;
633185533Skan	for (sp = arglist.list ; sp ; sp = sp->next)
634175164Sjhb		argc++;
635175164Sjhb	argv = stalloc(sizeof (char *) * (argc + 1));
636175164Sjhb
637175164Sjhb	for (sp = arglist.list ; sp ; sp = sp->next) {
638175164Sjhb		TRACE(("evalcommand arg: %s\n", sp->text));
639175164Sjhb		*argv++ = sp->text;
640175164Sjhb	}
641175164Sjhb	*argv = NULL;
642175164Sjhb	lastarg = NULL;
643	if (iflag && funcnest == 0 && argc > 0)
644		lastarg = argv[-1];
645	argv -= argc;
646
647	/* Print the command if xflag is set. */
648	if (xflag) {
649		char sep = 0;
650		out2str(ps4val());
651		for (sp = varlist.list ; sp ; sp = sp->next) {
652			if (sep != 0)
653				outc(' ', &errout);
654			out2str(sp->text);
655			sep = ' ';
656		}
657		for (sp = arglist.list ; sp ; sp = sp->next) {
658			if (sep != 0)
659				outc(' ', &errout);
660			out2str(sp->text);
661			sep = ' ';
662		}
663		outc('\n', &errout);
664		flushout(&errout);
665	}
666
667	/* Now locate the command. */
668	if (argc == 0) {
669		/* Variable assignment(s) without command */
670		cmdentry.cmdtype = CMDBUILTIN;
671		cmdentry.u.index = BLTINCMD;
672		cmdentry.special = 1;
673	} else {
674		static const char PATH[] = "PATH=";
675		char *path = pathval();
676
677		/*
678		 * Modify the command lookup path, if a PATH= assignment
679		 * is present
680		 */
681		for (sp = varlist.list ; sp ; sp = sp->next)
682			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
683				path = sp->text + sizeof(PATH) - 1;
684				/*
685				 * On `PATH=... command`, we need to make
686				 * sure that the command isn't using the
687				 * non-updated hash table of the outer PATH
688				 * setting and we need to make sure that
689				 * the hash table isn't filled with items
690				 * from the temporary setting.
691				 *
692				 * It would be better to forbit using and
693				 * updating the table while this command
694				 * runs, by the command finding mechanism
695				 * is heavily integrated with hash handling,
696				 * so we just delete the hash before and after
697				 * the command runs. Partly deleting like
698				 * changepatch() does doesn't seem worth the
699				 * bookinging effort, since most such runs add
700				 * directories in front of the new PATH.
701				 */
702				clearcmdentry(0);
703				do_clearcmdentry = 1;
704			}
705
706		find_command(argv[0], &cmdentry, 1, path);
707		if (cmdentry.cmdtype == CMDUNKNOWN) {	/* command not found */
708			exitstatus = 127;
709			flushout(&errout);
710			return;
711		}
712		/* implement the bltin builtin here */
713		if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
714			for (;;) {
715				argv++;
716				if (--argc == 0)
717					break;
718				if ((cmdentry.u.index = find_builtin(*argv,
719				    &cmdentry.special)) < 0) {
720					outfmt(&errout, "%s: not found\n", *argv);
721					exitstatus = 127;
722					flushout(&errout);
723					return;
724				}
725				if (cmdentry.u.index != BLTINCMD)
726					break;
727			}
728		}
729	}
730
731	/* Fork off a child process if necessary. */
732	if (cmd->ncmd.backgnd
733	 || (cmdentry.cmdtype == CMDNORMAL
734	    && ((flags & EV_EXIT) == 0 || have_traps()))
735	 || ((flags & EV_BACKCMD) != 0
736	    && (cmdentry.cmdtype != CMDBUILTIN
737		 || cmdentry.u.index == CDCMD
738		 || cmdentry.u.index == DOTCMD
739		 || cmdentry.u.index == EVALCMD))
740	 || (cmdentry.cmdtype == CMDBUILTIN &&
741	    cmdentry.u.index == COMMANDCMD)) {
742		jp = makejob(cmd, 1);
743		mode = cmd->ncmd.backgnd;
744		if (flags & EV_BACKCMD) {
745			mode = FORK_NOJOB;
746			if (pipe(pip) < 0)
747				error("Pipe call failed: %s", strerror(errno));
748		}
749		if (forkshell(jp, cmd, mode) != 0)
750			goto parent;	/* at end of routine */
751		if (flags & EV_BACKCMD) {
752			FORCEINTON;
753			close(pip[0]);
754			if (pip[1] != 1) {
755				dup2(pip[1], 1);
756				close(pip[1]);
757			}
758		}
759		flags |= EV_EXIT;
760	}
761
762	/* This is the child process if a fork occurred. */
763	/* Execute the command. */
764	if (cmdentry.cmdtype == CMDFUNCTION) {
765#ifdef DEBUG
766		trputs("Shell function:  ");  trargs(argv);
767#endif
768		redirect(cmd->ncmd.redirect, REDIR_PUSH);
769		saveparam = shellparam;
770		shellparam.malloc = 0;
771		shellparam.reset = 1;
772		shellparam.nparam = argc - 1;
773		shellparam.p = argv + 1;
774		shellparam.optnext = NULL;
775		INTOFF;
776		savelocalvars = localvars;
777		localvars = NULL;
778		INTON;
779		if (setjmp(jmploc.loc)) {
780			if (exception == EXSHELLPROC)
781				freeparam((struct shparam *)&saveparam);
782			else {
783				freeparam(&shellparam);
784				shellparam = saveparam;
785			}
786			poplocalvars();
787			localvars = savelocalvars;
788			handler = savehandler;
789			longjmp(handler->loc, 1);
790		}
791		savehandler = handler;
792		handler = &jmploc;
793		for (sp = varlist.list ; sp ; sp = sp->next)
794			mklocal(sp->text);
795		funcnest++;
796		exitstatus = oexitstatus;
797		if (flags & EV_TESTED)
798			evaltree(cmdentry.u.func, EV_TESTED);
799		else
800			evaltree(cmdentry.u.func, 0);
801		funcnest--;
802		INTOFF;
803		poplocalvars();
804		localvars = savelocalvars;
805		freeparam(&shellparam);
806		shellparam = saveparam;
807		handler = savehandler;
808		popredir();
809		INTON;
810		if (evalskip == SKIPFUNC) {
811			evalskip = 0;
812			skipcount = 0;
813		}
814		if (flags & EV_EXIT)
815			exitshell(exitstatus);
816	} else if (cmdentry.cmdtype == CMDBUILTIN) {
817#ifdef DEBUG
818		trputs("builtin command:  ");  trargs(argv);
819#endif
820		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
821		if (flags == EV_BACKCMD) {
822			memout.nleft = 0;
823			memout.nextc = memout.buf;
824			memout.bufsize = 64;
825			mode |= REDIR_BACKQ;
826		}
827		savecmdname = commandname;
828		cmdenviron = varlist.list;
829		e = -1;
830		if (setjmp(jmploc.loc)) {
831			e = exception;
832			exitstatus = (e == EXINT)? SIGINT+128 : 2;
833			goto cmddone;
834		}
835		savehandler = handler;
836		handler = &jmploc;
837		redirect(cmd->ncmd.redirect, mode);
838		if (cmdentry.special)
839			listsetvar(cmdenviron);
840		commandname = argv[0];
841		argptr = argv + 1;
842		optptr = NULL;			/* initialize nextopt */
843		builtin_flags = flags;
844		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
845		flushall();
846cmddone:
847		cmdenviron = NULL;
848		out1 = &output;
849		out2 = &errout;
850		freestdout();
851		if (e != EXSHELLPROC) {
852			commandname = savecmdname;
853			if (flags & EV_EXIT) {
854				exitshell(exitstatus);
855			}
856		}
857		handler = savehandler;
858		if (e != -1) {
859			if ((e != EXERROR && e != EXEXEC)
860			    || cmdentry.special)
861				exraise(e);
862			FORCEINTON;
863		}
864		if (cmdentry.u.index != EXECCMD)
865			popredir();
866		if (flags == EV_BACKCMD) {
867			backcmd->buf = memout.buf;
868			backcmd->nleft = memout.nextc - memout.buf;
869			memout.buf = NULL;
870		}
871	} else {
872#ifdef DEBUG
873		trputs("normal command:  ");  trargs(argv);
874#endif
875		clearredir();
876		redirect(cmd->ncmd.redirect, 0);
877		for (sp = varlist.list ; sp ; sp = sp->next)
878			setvareq(sp->text, VEXPORT|VSTACK);
879		envp = environment();
880		shellexec(argv, envp, pathval(), cmdentry.u.index);
881		/*NOTREACHED*/
882	}
883	goto out;
884
885parent:	/* parent process gets here (if we forked) */
886	if (mode == 0) {	/* argument to fork */
887		INTOFF;
888		exitstatus = waitforjob(jp, &realstatus);
889		INTON;
890		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
891			evalskip = SKIPBREAK;
892			skipcount = loopnest;
893		}
894	} else if (mode == 2) {
895		backcmd->fd = pip[0];
896		close(pip[1]);
897		backcmd->jp = jp;
898	}
899
900out:
901	if (lastarg)
902		setvar("_", lastarg, 0);
903	if (do_clearcmdentry)
904		clearcmdentry(0);
905	popstackmark(&smark);
906}
907
908
909
910/*
911 * Search for a command.  This is called before we fork so that the
912 * location of the command will be available in the parent as well as
913 * the child.  The check for "goodname" is an overly conservative
914 * check that the name will not be subject to expansion.
915 */
916
917STATIC void
918prehash(union node *n)
919{
920	struct cmdentry entry;
921
922	if (n && n->type == NCMD && n->ncmd.args)
923		if (goodname(n->ncmd.args->narg.text))
924			find_command(n->ncmd.args->narg.text, &entry, 0,
925				     pathval());
926}
927
928
929
930/*
931 * Builtin commands.  Builtin commands whose functions are closely
932 * tied to evaluation are implemented here.
933 */
934
935/*
936 * No command given, or a bltin command with no arguments.
937 */
938
939int
940bltincmd(int argc __unused, char **argv __unused)
941{
942	/*
943	 * Preserve exitstatus of a previous possible redirection
944	 * as POSIX mandates
945	 */
946	return exitstatus;
947}
948
949
950/*
951 * Handle break and continue commands.  Break, continue, and return are
952 * all handled by setting the evalskip flag.  The evaluation routines
953 * above all check this flag, and if it is set they start skipping
954 * commands rather than executing them.  The variable skipcount is
955 * the number of loops to break/continue, or the number of function
956 * levels to return.  (The latter is always 1.)  It should probably
957 * be an error to break out of more loops than exist, but it isn't
958 * in the standard shell so we don't make it one here.
959 */
960
961int
962breakcmd(int argc, char **argv)
963{
964	int n = argc > 1 ? number(argv[1]) : 1;
965
966	if (n > loopnest)
967		n = loopnest;
968	if (n > 0) {
969		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
970		skipcount = n;
971	}
972	return 0;
973}
974
975/*
976 * The `command' command.
977 */
978int
979commandcmd(int argc, char **argv)
980{
981	static char stdpath[] = _PATH_STDPATH;
982	struct jmploc loc, *old;
983	struct strlist *sp;
984	char *path;
985	int ch;
986	int cmd = -1;
987
988	for (sp = cmdenviron; sp ; sp = sp->next)
989		setvareq(sp->text, VEXPORT|VSTACK);
990	path = pathval();
991
992	optind = optreset = 1;
993	opterr = 0;
994	while ((ch = getopt(argc, argv, "pvV")) != -1) {
995		switch (ch) {
996		case 'p':
997			path = stdpath;
998			break;
999		case 'v':
1000			cmd = TYPECMD_SMALLV;
1001			break;
1002		case 'V':
1003			cmd = TYPECMD_BIGV;
1004			break;
1005		case '?':
1006		default:
1007			error("unknown option: -%c", optopt);
1008		}
1009	}
1010	argc -= optind;
1011	argv += optind;
1012
1013	if (cmd != -1) {
1014		if (argc != 1)
1015			error("wrong number of arguments");
1016		return typecmd_impl(2, argv - 1, cmd);
1017	}
1018	if (argc != 0) {
1019		old = handler;
1020		handler = &loc;
1021		if (setjmp(handler->loc) == 0)
1022			shellexec(argv, environment(), path, 0);
1023		handler = old;
1024		if (exception == EXEXEC)
1025			exit(exerrno);
1026		exraise(exception);
1027	}
1028
1029	/*
1030	 * Do nothing successfully if no command was specified;
1031	 * ksh also does this.
1032	 */
1033	exit(0);
1034}
1035
1036
1037/*
1038 * The return command.
1039 */
1040
1041int
1042returncmd(int argc, char **argv)
1043{
1044	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1045
1046	if (funcnest) {
1047		evalskip = SKIPFUNC;
1048		skipcount = 1;
1049	} else {
1050		/* skip the rest of the file */
1051		evalskip = SKIPFILE;
1052		skipcount = 1;
1053	}
1054	return ret;
1055}
1056
1057
1058int
1059falsecmd(int argc __unused, char **argv __unused)
1060{
1061	return 1;
1062}
1063
1064
1065int
1066truecmd(int argc __unused, char **argv __unused)
1067{
1068	return 0;
1069}
1070
1071
1072int
1073execcmd(int argc, char **argv)
1074{
1075	if (argc > 1) {
1076		struct strlist *sp;
1077
1078		iflag = 0;		/* exit on error */
1079		mflag = 0;
1080		optschanged();
1081		for (sp = cmdenviron; sp ; sp = sp->next)
1082			setvareq(sp->text, VEXPORT|VSTACK);
1083		shellexec(argv + 1, environment(), pathval(), 0);
1084
1085	}
1086	return 0;
1087}
1088
1089
1090int
1091timescmd(int argc __unused, char **argv __unused)
1092{
1093	struct rusage ru;
1094	long shumins, shsmins, chumins, chsmins;
1095	double shusecs, shssecs, chusecs, chssecs;
1096
1097	if (getrusage(RUSAGE_SELF, &ru) < 0)
1098		return 1;
1099	shumins = ru.ru_utime.tv_sec / 60;
1100	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1101	shsmins = ru.ru_stime.tv_sec / 60;
1102	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1103	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1104		return 1;
1105	chumins = ru.ru_utime.tv_sec / 60;
1106	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1107	chsmins = ru.ru_stime.tv_sec / 60;
1108	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1109	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1110	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1111	return 0;
1112}
1113