eval.c revision 216761
1/*-
2 * Copyright (c) 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/sh/eval.c 216761 2010-12-28 13:28:24Z jilles $");
40
41#include <paths.h>
42#include <signal.h>
43#include <stdlib.h>
44#include <unistd.h>
45#include <sys/resource.h>
46#include <sys/wait.h> /* For WIFSIGNALED(status) */
47#include <errno.h>
48
49/*
50 * Evaluate a command.
51 */
52
53#include "shell.h"
54#include "nodes.h"
55#include "syntax.h"
56#include "expand.h"
57#include "parser.h"
58#include "jobs.h"
59#include "eval.h"
60#include "builtins.h"
61#include "options.h"
62#include "exec.h"
63#include "redir.h"
64#include "input.h"
65#include "output.h"
66#include "trap.h"
67#include "var.h"
68#include "memalloc.h"
69#include "error.h"
70#include "show.h"
71#include "mystring.h"
72#ifndef NO_HISTORY
73#include "myhistedit.h"
74#endif
75
76
77int evalskip;			/* set if we are skipping commands */
78static int skipcount;		/* number of levels to skip */
79MKINIT int loopnest;		/* current loop nesting level */
80int funcnest;			/* depth of function calls */
81static int builtin_flags;	/* evalcommand flags for builtins */
82
83
84char *commandname;
85struct strlist *cmdenviron;
86int exitstatus;			/* exit status of last command */
87int oexitstatus;		/* saved exit status */
88
89
90static void evalloop(union node *, int);
91static void evalfor(union node *, int);
92static void evalcase(union node *, int);
93static void evalsubshell(union node *, int);
94static void evalredir(union node *, int);
95static void expredir(union node *);
96static void evalpipe(union node *);
97static void evalcommand(union node *, int, struct backcmd *);
98static void prehash(union node *);
99
100
101/*
102 * Called to reset things after an exception.
103 */
104
105#ifdef mkinit
106INCLUDE "eval.h"
107
108RESET {
109	evalskip = 0;
110	loopnest = 0;
111	funcnest = 0;
112}
113
114SHELLPROC {
115	exitstatus = 0;
116}
117#endif
118
119
120
121/*
122 * The eval command.
123 */
124
125int
126evalcmd(int argc, char **argv)
127{
128        char *p;
129        char *concat;
130        char **ap;
131
132        if (argc > 1) {
133                p = argv[1];
134                if (argc > 2) {
135                        STARTSTACKSTR(concat);
136                        ap = argv + 2;
137                        for (;;) {
138                                STPUTS(p, concat);
139                                if ((p = *ap++) == NULL)
140                                        break;
141                                STPUTC(' ', concat);
142                        }
143                        STPUTC('\0', concat);
144                        p = grabstackstr(concat);
145                }
146                evalstring(p, builtin_flags & EV_TESTED);
147        } else
148                exitstatus = 0;
149        return exitstatus;
150}
151
152
153/*
154 * Execute a command or commands contained in a string.
155 */
156
157void
158evalstring(char *s, int flags)
159{
160	union node *n;
161	struct stackmark smark;
162	int flags_exit;
163	int any;
164
165	flags_exit = flags & EV_EXIT;
166	flags &= ~EV_EXIT;
167	any = 0;
168	setstackmark(&smark);
169	setinputstring(s, 1);
170	while ((n = parsecmd(0)) != NEOF) {
171		if (n != NULL) {
172			if (flags_exit && preadateof())
173				evaltree(n, flags | EV_EXIT);
174			else
175				evaltree(n, flags);
176			any = 1;
177		}
178		popstackmark(&smark);
179	}
180	popfile();
181	popstackmark(&smark);
182	if (!any)
183		exitstatus = 0;
184	if (flags_exit)
185		exitshell(exitstatus);
186}
187
188
189/*
190 * Evaluate a parse tree.  The value is left in the global variable
191 * exitstatus.
192 */
193
194void
195evaltree(union node *n, int flags)
196{
197	int do_etest;
198	union node *next;
199
200	do_etest = 0;
201	if (n == NULL) {
202		TRACE(("evaltree(NULL) called\n"));
203		exitstatus = 0;
204		goto out;
205	}
206	do {
207		next = NULL;
208#ifndef NO_HISTORY
209		displayhist = 1;	/* show history substitutions done with fc */
210#endif
211		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
212		switch (n->type) {
213		case NSEMI:
214			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
215			if (evalskip)
216				goto out;
217			next = n->nbinary.ch2;
218			break;
219		case NAND:
220			evaltree(n->nbinary.ch1, EV_TESTED);
221			if (evalskip || exitstatus != 0) {
222				goto out;
223			}
224			next = n->nbinary.ch2;
225			break;
226		case NOR:
227			evaltree(n->nbinary.ch1, EV_TESTED);
228			if (evalskip || exitstatus == 0)
229				goto out;
230			next = n->nbinary.ch2;
231			break;
232		case NREDIR:
233			evalredir(n, flags);
234			break;
235		case NSUBSHELL:
236			evalsubshell(n, flags);
237			do_etest = !(flags & EV_TESTED);
238			break;
239		case NBACKGND:
240			evalsubshell(n, flags);
241			break;
242		case NIF: {
243			evaltree(n->nif.test, EV_TESTED);
244			if (evalskip)
245				goto out;
246			if (exitstatus == 0)
247				next = n->nif.ifpart;
248			else if (n->nif.elsepart)
249				next = n->nif.elsepart;
250			else
251				exitstatus = 0;
252			break;
253		}
254		case NWHILE:
255		case NUNTIL:
256			evalloop(n, flags & ~EV_EXIT);
257			break;
258		case NFOR:
259			evalfor(n, flags & ~EV_EXIT);
260			break;
261		case NCASE:
262			evalcase(n, flags);
263			break;
264		case NDEFUN:
265			defun(n->narg.text, n->narg.next);
266			exitstatus = 0;
267			break;
268		case NNOT:
269			evaltree(n->nnot.com, EV_TESTED);
270			exitstatus = !exitstatus;
271			break;
272
273		case NPIPE:
274			evalpipe(n);
275			do_etest = !(flags & EV_TESTED);
276			break;
277		case NCMD:
278			evalcommand(n, flags, (struct backcmd *)NULL);
279			do_etest = !(flags & EV_TESTED);
280			break;
281		default:
282			out1fmt("Node type = %d\n", n->type);
283			flushout(&output);
284			break;
285		}
286		n = next;
287	} while (n != NULL);
288out:
289	if (pendingsigs)
290		dotrap();
291	if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest))
292		exitshell(exitstatus);
293}
294
295
296static void
297evalloop(union node *n, int flags)
298{
299	int status;
300
301	loopnest++;
302	status = 0;
303	for (;;) {
304		evaltree(n->nbinary.ch1, EV_TESTED);
305		if (evalskip) {
306skipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
307				evalskip = 0;
308				continue;
309			}
310			if (evalskip == SKIPBREAK && --skipcount <= 0)
311				evalskip = 0;
312			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
313				status = exitstatus;
314			break;
315		}
316		if (n->type == NWHILE) {
317			if (exitstatus != 0)
318				break;
319		} else {
320			if (exitstatus == 0)
321				break;
322		}
323		evaltree(n->nbinary.ch2, flags);
324		status = exitstatus;
325		if (evalskip)
326			goto skipping;
327	}
328	loopnest--;
329	exitstatus = status;
330}
331
332
333
334static void
335evalfor(union node *n, int flags)
336{
337	struct arglist arglist;
338	union node *argp;
339	struct strlist *sp;
340	struct stackmark smark;
341
342	setstackmark(&smark);
343	arglist.lastp = &arglist.list;
344	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
345		oexitstatus = exitstatus;
346		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
347		if (evalskip)
348			goto out;
349	}
350	*arglist.lastp = NULL;
351
352	exitstatus = 0;
353	loopnest++;
354	for (sp = arglist.list ; sp ; sp = sp->next) {
355		setvar(n->nfor.var, sp->text, 0);
356		evaltree(n->nfor.body, flags);
357		if (evalskip) {
358			if (evalskip == SKIPCONT && --skipcount <= 0) {
359				evalskip = 0;
360				continue;
361			}
362			if (evalskip == SKIPBREAK && --skipcount <= 0)
363				evalskip = 0;
364			break;
365		}
366	}
367	loopnest--;
368out:
369	popstackmark(&smark);
370}
371
372
373
374static void
375evalcase(union node *n, int flags)
376{
377	union node *cp;
378	union node *patp;
379	struct arglist arglist;
380	struct stackmark smark;
381
382	setstackmark(&smark);
383	arglist.lastp = &arglist.list;
384	oexitstatus = exitstatus;
385	exitstatus = 0;
386	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
387	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
388		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
389			if (casematch(patp, arglist.list->text)) {
390				if (evalskip == 0) {
391					evaltree(cp->nclist.body, flags);
392				}
393				goto out;
394			}
395		}
396	}
397out:
398	popstackmark(&smark);
399}
400
401
402
403/*
404 * Kick off a subshell to evaluate a tree.
405 */
406
407static void
408evalsubshell(union node *n, int flags)
409{
410	struct job *jp;
411	int backgnd = (n->type == NBACKGND);
412
413	expredir(n->nredir.redirect);
414	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
415			forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
416		if (backgnd)
417			flags &=~ EV_TESTED;
418		redirect(n->nredir.redirect, 0);
419		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
420	} else if (! backgnd) {
421		INTOFF;
422		exitstatus = waitforjob(jp, (int *)NULL);
423		INTON;
424	}
425}
426
427
428/*
429 * Evaluate a redirected compound command.
430 */
431
432static void
433evalredir(union node *n, int flags)
434{
435	struct jmploc jmploc;
436	struct jmploc *savehandler;
437	volatile int in_redirect = 1;
438
439	expredir(n->nredir.redirect);
440	savehandler = handler;
441	if (setjmp(jmploc.loc)) {
442		int e;
443
444		handler = savehandler;
445		e = exception;
446		if (e == EXERROR || e == EXEXEC) {
447			popredir();
448			if (in_redirect) {
449				exitstatus = 2;
450				return;
451			}
452		}
453		longjmp(handler->loc, 1);
454	} else {
455		INTOFF;
456		handler = &jmploc;
457		redirect(n->nredir.redirect, REDIR_PUSH);
458		in_redirect = 0;
459		INTON;
460		evaltree(n->nredir.n, flags);
461	}
462	INTOFF;
463	handler = savehandler;
464	popredir();
465	INTON;
466}
467
468
469/*
470 * Compute the names of the files in a redirection list.
471 */
472
473static void
474expredir(union node *n)
475{
476	union node *redir;
477
478	for (redir = n ; redir ; redir = redir->nfile.next) {
479		struct arglist fn;
480		fn.lastp = &fn.list;
481		oexitstatus = exitstatus;
482		switch (redir->type) {
483		case NFROM:
484		case NTO:
485		case NFROMTO:
486		case NAPPEND:
487		case NCLOBBER:
488			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
489			redir->nfile.expfname = fn.list->text;
490			break;
491		case NFROMFD:
492		case NTOFD:
493			if (redir->ndup.vname) {
494				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
495				fixredir(redir, fn.list->text, 1);
496			}
497			break;
498		}
499	}
500}
501
502
503
504/*
505 * Evaluate a pipeline.  All the processes in the pipeline are children
506 * of the process creating the pipeline.  (This differs from some versions
507 * of the shell, which make the last process in a pipeline the parent
508 * of all the rest.)
509 */
510
511static void
512evalpipe(union node *n)
513{
514	struct job *jp;
515	struct nodelist *lp;
516	int pipelen;
517	int prevfd;
518	int pip[2];
519
520	TRACE(("evalpipe(%p) called\n", (void *)n));
521	pipelen = 0;
522	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
523		pipelen++;
524	INTOFF;
525	jp = makejob(n, pipelen);
526	prevfd = -1;
527	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
528		prehash(lp->n);
529		pip[1] = -1;
530		if (lp->next) {
531			if (pipe(pip) < 0) {
532				close(prevfd);
533				error("Pipe call failed: %s", strerror(errno));
534			}
535		}
536		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
537			INTON;
538			if (prevfd > 0) {
539				dup2(prevfd, 0);
540				close(prevfd);
541			}
542			if (pip[1] >= 0) {
543				if (!(prevfd >= 0 && pip[0] == 0))
544					close(pip[0]);
545				if (pip[1] != 1) {
546					dup2(pip[1], 1);
547					close(pip[1]);
548				}
549			}
550			evaltree(lp->n, EV_EXIT);
551		}
552		if (prevfd >= 0)
553			close(prevfd);
554		prevfd = pip[0];
555		close(pip[1]);
556	}
557	INTON;
558	if (n->npipe.backgnd == 0) {
559		INTOFF;
560		exitstatus = waitforjob(jp, (int *)NULL);
561		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
562		INTON;
563	}
564}
565
566
567
568/*
569 * Execute a command inside back quotes.  If it's a builtin command, we
570 * want to save its output in a block obtained from malloc.  Otherwise
571 * we fork off a subprocess and get the output of the command via a pipe.
572 * Should be called with interrupts off.
573 */
574
575void
576evalbackcmd(union node *n, struct backcmd *result)
577{
578	int pip[2];
579	struct job *jp;
580	struct stackmark smark;		/* unnecessary */
581	struct jmploc jmploc;
582	struct jmploc *savehandler;
583
584	setstackmark(&smark);
585	result->fd = -1;
586	result->buf = NULL;
587	result->nleft = 0;
588	result->jp = NULL;
589	if (n == NULL) {
590		exitstatus = 0;
591		goto out;
592	}
593	if (n->type == NCMD) {
594		exitstatus = oexitstatus;
595		savehandler = handler;
596		if (setjmp(jmploc.loc)) {
597			if (exception == EXERROR || exception == EXEXEC)
598				exitstatus = 2;
599			else if (exception != 0) {
600				handler = savehandler;
601				longjmp(handler->loc, 1);
602			}
603		} else {
604			handler = &jmploc;
605			evalcommand(n, EV_BACKCMD, result);
606		}
607		handler = savehandler;
608	} else {
609		exitstatus = 0;
610		if (pipe(pip) < 0)
611			error("Pipe call failed: %s", strerror(errno));
612		jp = makejob(n, 1);
613		if (forkshell(jp, n, FORK_NOJOB) == 0) {
614			FORCEINTON;
615			close(pip[0]);
616			if (pip[1] != 1) {
617				dup2(pip[1], 1);
618				close(pip[1]);
619			}
620			evaltree(n, EV_EXIT);
621		}
622		close(pip[1]);
623		result->fd = pip[0];
624		result->jp = jp;
625	}
626out:
627	popstackmark(&smark);
628	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
629		result->fd, result->buf, result->nleft, result->jp));
630}
631
632
633
634/*
635 * Execute a simple command.
636 */
637
638static void
639evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
640{
641	struct stackmark smark;
642	union node *argp;
643	struct arglist arglist;
644	struct arglist varlist;
645	char **argv;
646	int argc;
647	char **envp;
648	int varflag;
649	struct strlist *sp;
650	int mode;
651	int pip[2];
652	struct cmdentry cmdentry;
653	struct job *jp;
654	struct jmploc jmploc;
655	struct jmploc *savehandler;
656	char *savecmdname;
657	struct shparam saveparam;
658	struct localvar *savelocalvars;
659	struct parsefile *savetopfile;
660	volatile int e;
661	char *lastarg;
662	int realstatus;
663	int do_clearcmdentry;
664	const char *path = pathval();
665
666	/* First expand the arguments. */
667	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
668	setstackmark(&smark);
669	arglist.lastp = &arglist.list;
670	varlist.lastp = &varlist.list;
671	varflag = 1;
672	do_clearcmdentry = 0;
673	oexitstatus = exitstatus;
674	exitstatus = 0;
675	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
676		char *p = argp->narg.text;
677		if (varflag && is_name(*p)) {
678			do {
679				p++;
680			} while (is_in_name(*p));
681			if (*p == '=') {
682				expandarg(argp, &varlist, EXP_VARTILDE);
683				continue;
684			}
685		}
686		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
687		varflag = 0;
688	}
689	*arglist.lastp = NULL;
690	*varlist.lastp = NULL;
691	expredir(cmd->ncmd.redirect);
692	argc = 0;
693	for (sp = arglist.list ; sp ; sp = sp->next)
694		argc++;
695	argv = stalloc(sizeof (char *) * (argc + 1));
696
697	for (sp = arglist.list ; sp ; sp = sp->next) {
698		TRACE(("evalcommand arg: %s\n", sp->text));
699		*argv++ = sp->text;
700	}
701	*argv = NULL;
702	lastarg = NULL;
703	if (iflag && funcnest == 0 && argc > 0)
704		lastarg = argv[-1];
705	argv -= argc;
706
707	/* Print the command if xflag is set. */
708	if (xflag) {
709		char sep = 0;
710		const char *p;
711		out2str(ps4val());
712		for (sp = varlist.list ; sp ; sp = sp->next) {
713			if (sep != 0)
714				out2c(' ');
715			p = strchr(sp->text, '=');
716			if (p != NULL) {
717				p++;
718				outbin(sp->text, p - sp->text, out2);
719				out2qstr(p);
720			} else
721				out2qstr(sp->text);
722			sep = ' ';
723		}
724		for (sp = arglist.list ; sp ; sp = sp->next) {
725			if (sep != 0)
726				out2c(' ');
727			/* Disambiguate command looking like assignment. */
728			if (sp == arglist.list &&
729					strchr(sp->text, '=') != NULL &&
730					strchr(sp->text, '\'') == NULL) {
731				out2c('\'');
732				out2str(sp->text);
733				out2c('\'');
734			} else
735				out2qstr(sp->text);
736			sep = ' ';
737		}
738		out2c('\n');
739		flushout(&errout);
740	}
741
742	/* Now locate the command. */
743	if (argc == 0) {
744		/* Variable assignment(s) without command */
745		cmdentry.cmdtype = CMDBUILTIN;
746		cmdentry.u.index = BLTINCMD;
747		cmdentry.special = 0;
748	} else {
749		static const char PATH[] = "PATH=";
750		int cmd_flags = 0, bltinonly = 0;
751
752		/*
753		 * Modify the command lookup path, if a PATH= assignment
754		 * is present
755		 */
756		for (sp = varlist.list ; sp ; sp = sp->next)
757			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
758				path = sp->text + sizeof(PATH) - 1;
759				/*
760				 * On `PATH=... command`, we need to make
761				 * sure that the command isn't using the
762				 * non-updated hash table of the outer PATH
763				 * setting and we need to make sure that
764				 * the hash table isn't filled with items
765				 * from the temporary setting.
766				 *
767				 * It would be better to forbit using and
768				 * updating the table while this command
769				 * runs, by the command finding mechanism
770				 * is heavily integrated with hash handling,
771				 * so we just delete the hash before and after
772				 * the command runs. Partly deleting like
773				 * changepatch() does doesn't seem worth the
774				 * bookinging effort, since most such runs add
775				 * directories in front of the new PATH.
776				 */
777				clearcmdentry(0);
778				do_clearcmdentry = 1;
779			}
780
781		for (;;) {
782			if (bltinonly) {
783				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
784				if (cmdentry.u.index < 0) {
785					cmdentry.u.index = BLTINCMD;
786					argv--;
787					argc++;
788					break;
789				}
790			} else
791				find_command(argv[0], &cmdentry, cmd_flags, path);
792			/* implement the bltin and command builtins here */
793			if (cmdentry.cmdtype != CMDBUILTIN)
794				break;
795			if (cmdentry.u.index == BLTINCMD) {
796				if (argc == 1)
797					break;
798				argv++;
799				argc--;
800				bltinonly = 1;
801			} else if (cmdentry.u.index == COMMANDCMD) {
802				if (argc == 1)
803					break;
804				if (!strcmp(argv[1], "-p")) {
805					if (argc == 2)
806						break;
807					if (argv[2][0] == '-') {
808						if (strcmp(argv[2], "--"))
809							break;
810						if (argc == 3)
811							break;
812						argv += 3;
813						argc -= 3;
814					} else {
815						argv += 2;
816						argc -= 2;
817					}
818					path = _PATH_STDPATH;
819					clearcmdentry(0);
820					do_clearcmdentry = 1;
821				} else if (!strcmp(argv[1], "--")) {
822					if (argc == 2)
823						break;
824					argv += 2;
825					argc -= 2;
826				} else if (argv[1][0] == '-')
827					break;
828				else {
829					argv++;
830					argc--;
831				}
832				cmd_flags |= DO_NOFUNC;
833				bltinonly = 0;
834			} else
835				break;
836		}
837		/*
838		 * Special builtins lose their special properties when
839		 * called via 'command'.
840		 */
841		if (cmd_flags & DO_NOFUNC)
842			cmdentry.special = 0;
843	}
844
845	/* Fork off a child process if necessary. */
846	if (cmd->ncmd.backgnd
847	 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
848	    && ((flags & EV_EXIT) == 0 || have_traps()))
849	 || ((flags & EV_BACKCMD) != 0
850	    && (cmdentry.cmdtype != CMDBUILTIN
851		 || cmdentry.u.index == CDCMD
852		 || cmdentry.u.index == DOTCMD
853		 || cmdentry.u.index == EVALCMD))) {
854		jp = makejob(cmd, 1);
855		mode = cmd->ncmd.backgnd;
856		if (flags & EV_BACKCMD) {
857			mode = FORK_NOJOB;
858			if (pipe(pip) < 0)
859				error("Pipe call failed: %s", strerror(errno));
860		}
861		if (forkshell(jp, cmd, mode) != 0)
862			goto parent;	/* at end of routine */
863		if (flags & EV_BACKCMD) {
864			FORCEINTON;
865			close(pip[0]);
866			if (pip[1] != 1) {
867				dup2(pip[1], 1);
868				close(pip[1]);
869			}
870		}
871		flags |= EV_EXIT;
872	}
873
874	/* This is the child process if a fork occurred. */
875	/* Execute the command. */
876	if (cmdentry.cmdtype == CMDFUNCTION) {
877#ifdef DEBUG
878		trputs("Shell function:  ");  trargs(argv);
879#endif
880		saveparam = shellparam;
881		shellparam.malloc = 0;
882		shellparam.reset = 1;
883		shellparam.nparam = argc - 1;
884		shellparam.p = argv + 1;
885		shellparam.optnext = NULL;
886		INTOFF;
887		savelocalvars = localvars;
888		localvars = NULL;
889		reffunc(cmdentry.u.func);
890		savehandler = handler;
891		if (setjmp(jmploc.loc)) {
892			if (exception == EXSHELLPROC)
893				freeparam(&saveparam);
894			else {
895				freeparam(&shellparam);
896				shellparam = saveparam;
897				if (exception == EXERROR || exception == EXEXEC)
898					popredir();
899			}
900			unreffunc(cmdentry.u.func);
901			poplocalvars();
902			localvars = savelocalvars;
903			funcnest--;
904			handler = savehandler;
905			longjmp(handler->loc, 1);
906		}
907		handler = &jmploc;
908		funcnest++;
909		redirect(cmd->ncmd.redirect, REDIR_PUSH);
910		INTON;
911		for (sp = varlist.list ; sp ; sp = sp->next)
912			mklocal(sp->text);
913		exitstatus = oexitstatus;
914		if (flags & EV_TESTED)
915			evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
916		else
917			evaltree(getfuncnode(cmdentry.u.func), 0);
918		INTOFF;
919		unreffunc(cmdentry.u.func);
920		poplocalvars();
921		localvars = savelocalvars;
922		freeparam(&shellparam);
923		shellparam = saveparam;
924		handler = savehandler;
925		funcnest--;
926		popredir();
927		INTON;
928		if (evalskip == SKIPFUNC) {
929			evalskip = 0;
930			skipcount = 0;
931		}
932		if (flags & EV_EXIT)
933			exitshell(exitstatus);
934	} else if (cmdentry.cmdtype == CMDBUILTIN) {
935#ifdef DEBUG
936		trputs("builtin command:  ");  trargs(argv);
937#endif
938		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
939		if (flags == EV_BACKCMD) {
940			memout.nleft = 0;
941			memout.nextc = memout.buf;
942			memout.bufsize = 64;
943			mode |= REDIR_BACKQ;
944			cmdentry.special = 0;
945		}
946		savecmdname = commandname;
947		savetopfile = getcurrentfile();
948		cmdenviron = varlist.list;
949		e = -1;
950		savehandler = handler;
951		if (setjmp(jmploc.loc)) {
952			e = exception;
953			exitstatus = (e == EXINT)? SIGINT+128 : 2;
954			goto cmddone;
955		}
956		handler = &jmploc;
957		redirect(cmd->ncmd.redirect, mode);
958		/*
959		 * If there is no command word, redirection errors should
960		 * not be fatal but assignment errors should.
961		 */
962		if (argc == 0 && !(flags & EV_BACKCMD))
963			cmdentry.special = 1;
964		if (cmdentry.special)
965			listsetvar(cmdenviron);
966		if (argc > 0)
967			bltinsetlocale();
968		commandname = argv[0];
969		argptr = argv + 1;
970		nextopt_optptr = NULL;		/* initialize nextopt */
971		builtin_flags = flags;
972		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
973		flushall();
974cmddone:
975		if (argc > 0)
976			bltinunsetlocale();
977		cmdenviron = NULL;
978		out1 = &output;
979		out2 = &errout;
980		freestdout();
981		if (e != EXSHELLPROC) {
982			commandname = savecmdname;
983			if (flags & EV_EXIT) {
984				exitshell(exitstatus);
985			}
986		}
987		handler = savehandler;
988		if (flags == EV_BACKCMD) {
989			backcmd->buf = memout.buf;
990			backcmd->nleft = memout.nextc - memout.buf;
991			memout.buf = NULL;
992		}
993		if (cmdentry.u.index != EXECCMD &&
994				(e == -1 || e == EXERROR || e == EXEXEC))
995			popredir();
996		if (e != -1) {
997			if ((e != EXERROR && e != EXEXEC)
998			    || cmdentry.special)
999				exraise(e);
1000			popfilesupto(savetopfile);
1001			if (flags != EV_BACKCMD)
1002				FORCEINTON;
1003		}
1004	} else {
1005#ifdef DEBUG
1006		trputs("normal command:  ");  trargs(argv);
1007#endif
1008		redirect(cmd->ncmd.redirect, 0);
1009		for (sp = varlist.list ; sp ; sp = sp->next)
1010			setvareq(sp->text, VEXPORT|VSTACK);
1011		envp = environment();
1012		shellexec(argv, envp, path, cmdentry.u.index);
1013		/*NOTREACHED*/
1014	}
1015	goto out;
1016
1017parent:	/* parent process gets here (if we forked) */
1018	if (mode == FORK_FG) {	/* argument to fork */
1019		INTOFF;
1020		exitstatus = waitforjob(jp, &realstatus);
1021		INTON;
1022		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1023			evalskip = SKIPBREAK;
1024			skipcount = loopnest;
1025		}
1026	} else if (mode == FORK_NOJOB) {
1027		backcmd->fd = pip[0];
1028		close(pip[1]);
1029		backcmd->jp = jp;
1030	}
1031
1032out:
1033	if (lastarg)
1034		setvar("_", lastarg, 0);
1035	if (do_clearcmdentry)
1036		clearcmdentry(0);
1037	popstackmark(&smark);
1038}
1039
1040
1041
1042/*
1043 * Search for a command.  This is called before we fork so that the
1044 * location of the command will be available in the parent as well as
1045 * the child.  The check for "goodname" is an overly conservative
1046 * check that the name will not be subject to expansion.
1047 */
1048
1049static void
1050prehash(union node *n)
1051{
1052	struct cmdentry entry;
1053
1054	if (n && n->type == NCMD && n->ncmd.args)
1055		if (goodname(n->ncmd.args->narg.text))
1056			find_command(n->ncmd.args->narg.text, &entry, 0,
1057				     pathval());
1058}
1059
1060
1061
1062/*
1063 * Builtin commands.  Builtin commands whose functions are closely
1064 * tied to evaluation are implemented here.
1065 */
1066
1067/*
1068 * No command given, a bltin command with no arguments, or a bltin command
1069 * with an invalid name.
1070 */
1071
1072int
1073bltincmd(int argc, char **argv)
1074{
1075	if (argc > 1) {
1076		out2fmt_flush("%s: not found\n", argv[1]);
1077		return 127;
1078	}
1079	/*
1080	 * Preserve exitstatus of a previous possible redirection
1081	 * as POSIX mandates
1082	 */
1083	return exitstatus;
1084}
1085
1086
1087/*
1088 * Handle break and continue commands.  Break, continue, and return are
1089 * all handled by setting the evalskip flag.  The evaluation routines
1090 * above all check this flag, and if it is set they start skipping
1091 * commands rather than executing them.  The variable skipcount is
1092 * the number of loops to break/continue, or the number of function
1093 * levels to return.  (The latter is always 1.)  It should probably
1094 * be an error to break out of more loops than exist, but it isn't
1095 * in the standard shell so we don't make it one here.
1096 */
1097
1098int
1099breakcmd(int argc, char **argv)
1100{
1101	int n = argc > 1 ? number(argv[1]) : 1;
1102
1103	if (n > loopnest)
1104		n = loopnest;
1105	if (n > 0) {
1106		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1107		skipcount = n;
1108	}
1109	return 0;
1110}
1111
1112/*
1113 * The `command' command.
1114 */
1115int
1116commandcmd(int argc, char **argv)
1117{
1118	const char *path;
1119	int ch;
1120	int cmd = -1;
1121
1122	path = bltinlookup("PATH", 1);
1123
1124	optind = optreset = 1;
1125	opterr = 0;
1126	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1127		switch (ch) {
1128		case 'p':
1129			path = _PATH_STDPATH;
1130			break;
1131		case 'v':
1132			cmd = TYPECMD_SMALLV;
1133			break;
1134		case 'V':
1135			cmd = TYPECMD_BIGV;
1136			break;
1137		case '?':
1138		default:
1139			error("unknown option: -%c", optopt);
1140		}
1141	}
1142	argc -= optind;
1143	argv += optind;
1144
1145	if (cmd != -1) {
1146		if (argc != 1)
1147			error("wrong number of arguments");
1148		return typecmd_impl(2, argv - 1, cmd, path);
1149	}
1150	if (argc != 0)
1151		error("commandcmd bad call");
1152
1153	/*
1154	 * Do nothing successfully if no command was specified;
1155	 * ksh also does this.
1156	 */
1157	return 0;
1158}
1159
1160
1161/*
1162 * The return command.
1163 */
1164
1165int
1166returncmd(int argc, char **argv)
1167{
1168	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1169
1170	if (funcnest) {
1171		evalskip = SKIPFUNC;
1172		skipcount = 1;
1173	} else {
1174		/* skip the rest of the file */
1175		evalskip = SKIPFILE;
1176		skipcount = 1;
1177	}
1178	return ret;
1179}
1180
1181
1182int
1183falsecmd(int argc __unused, char **argv __unused)
1184{
1185	return 1;
1186}
1187
1188
1189int
1190truecmd(int argc __unused, char **argv __unused)
1191{
1192	return 0;
1193}
1194
1195
1196int
1197execcmd(int argc, char **argv)
1198{
1199	/*
1200	 * Because we have historically not supported any options,
1201	 * only treat "--" specially.
1202	 */
1203	if (argc > 1 && strcmp(argv[1], "--") == 0)
1204		argc--, argv++;
1205	if (argc > 1) {
1206		struct strlist *sp;
1207
1208		iflag = 0;		/* exit on error */
1209		mflag = 0;
1210		optschanged();
1211		for (sp = cmdenviron; sp ; sp = sp->next)
1212			setvareq(sp->text, VEXPORT|VSTACK);
1213		shellexec(argv + 1, environment(), pathval(), 0);
1214
1215	}
1216	return 0;
1217}
1218
1219
1220int
1221timescmd(int argc __unused, char **argv __unused)
1222{
1223	struct rusage ru;
1224	long shumins, shsmins, chumins, chsmins;
1225	double shusecs, shssecs, chusecs, chssecs;
1226
1227	if (getrusage(RUSAGE_SELF, &ru) < 0)
1228		return 1;
1229	shumins = ru.ru_utime.tv_sec / 60;
1230	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1231	shsmins = ru.ru_stime.tv_sec / 60;
1232	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1233	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1234		return 1;
1235	chumins = ru.ru_utime.tv_sec / 60;
1236	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1237	chsmins = ru.ru_stime.tv_sec / 60;
1238	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1239	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1240	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1241	return 0;
1242}
1243