eval.c revision 215783
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 215783 2010-11-23 22:17:39Z 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
582	setstackmark(&smark);
583	result->fd = -1;
584	result->buf = NULL;
585	result->nleft = 0;
586	result->jp = NULL;
587	if (n == NULL) {
588		exitstatus = 0;
589		goto out;
590	}
591	if (n->type == NCMD) {
592		exitstatus = oexitstatus;
593		evalcommand(n, EV_BACKCMD, result);
594	} else {
595		exitstatus = 0;
596		if (pipe(pip) < 0)
597			error("Pipe call failed: %s", strerror(errno));
598		jp = makejob(n, 1);
599		if (forkshell(jp, n, FORK_NOJOB) == 0) {
600			FORCEINTON;
601			close(pip[0]);
602			if (pip[1] != 1) {
603				dup2(pip[1], 1);
604				close(pip[1]);
605			}
606			evaltree(n, EV_EXIT);
607		}
608		close(pip[1]);
609		result->fd = pip[0];
610		result->jp = jp;
611	}
612out:
613	popstackmark(&smark);
614	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
615		result->fd, result->buf, result->nleft, result->jp));
616}
617
618
619
620/*
621 * Execute a simple command.
622 */
623
624static void
625evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
626{
627	struct stackmark smark;
628	union node *argp;
629	struct arglist arglist;
630	struct arglist varlist;
631	char **argv;
632	int argc;
633	char **envp;
634	int varflag;
635	struct strlist *sp;
636	int mode;
637	int pip[2];
638	struct cmdentry cmdentry;
639	struct job *jp;
640	struct jmploc jmploc;
641	struct jmploc *savehandler;
642	char *savecmdname;
643	struct shparam saveparam;
644	struct localvar *savelocalvars;
645	struct parsefile *savetopfile;
646	volatile int e;
647	char *lastarg;
648	int realstatus;
649	int do_clearcmdentry;
650	const char *path = pathval();
651
652	/* First expand the arguments. */
653	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
654	setstackmark(&smark);
655	arglist.lastp = &arglist.list;
656	varlist.lastp = &varlist.list;
657	varflag = 1;
658	do_clearcmdentry = 0;
659	oexitstatus = exitstatus;
660	exitstatus = 0;
661	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
662		char *p = argp->narg.text;
663		if (varflag && is_name(*p)) {
664			do {
665				p++;
666			} while (is_in_name(*p));
667			if (*p == '=') {
668				expandarg(argp, &varlist, EXP_VARTILDE);
669				continue;
670			}
671		}
672		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
673		varflag = 0;
674	}
675	*arglist.lastp = NULL;
676	*varlist.lastp = NULL;
677	expredir(cmd->ncmd.redirect);
678	argc = 0;
679	for (sp = arglist.list ; sp ; sp = sp->next)
680		argc++;
681	argv = stalloc(sizeof (char *) * (argc + 1));
682
683	for (sp = arglist.list ; sp ; sp = sp->next) {
684		TRACE(("evalcommand arg: %s\n", sp->text));
685		*argv++ = sp->text;
686	}
687	*argv = NULL;
688	lastarg = NULL;
689	if (iflag && funcnest == 0 && argc > 0)
690		lastarg = argv[-1];
691	argv -= argc;
692
693	/* Print the command if xflag is set. */
694	if (xflag) {
695		char sep = 0;
696		const char *p;
697		out2str(ps4val());
698		for (sp = varlist.list ; sp ; sp = sp->next) {
699			if (sep != 0)
700				out2c(' ');
701			p = strchr(sp->text, '=');
702			if (p != NULL) {
703				p++;
704				outbin(sp->text, p - sp->text, out2);
705				out2qstr(p);
706			} else
707				out2qstr(sp->text);
708			sep = ' ';
709		}
710		for (sp = arglist.list ; sp ; sp = sp->next) {
711			if (sep != 0)
712				out2c(' ');
713			/* Disambiguate command looking like assignment. */
714			if (sp == arglist.list &&
715					strchr(sp->text, '=') != NULL &&
716					strchr(sp->text, '\'') == NULL) {
717				out2c('\'');
718				out2str(sp->text);
719				out2c('\'');
720			} else
721				out2qstr(sp->text);
722			sep = ' ';
723		}
724		out2c('\n');
725		flushout(&errout);
726	}
727
728	/* Now locate the command. */
729	if (argc == 0) {
730		/* Variable assignment(s) without command */
731		cmdentry.cmdtype = CMDBUILTIN;
732		cmdentry.u.index = BLTINCMD;
733		cmdentry.special = 0;
734	} else {
735		static const char PATH[] = "PATH=";
736		int cmd_flags = 0, bltinonly = 0;
737
738		/*
739		 * Modify the command lookup path, if a PATH= assignment
740		 * is present
741		 */
742		for (sp = varlist.list ; sp ; sp = sp->next)
743			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) {
744				path = sp->text + sizeof(PATH) - 1;
745				/*
746				 * On `PATH=... command`, we need to make
747				 * sure that the command isn't using the
748				 * non-updated hash table of the outer PATH
749				 * setting and we need to make sure that
750				 * the hash table isn't filled with items
751				 * from the temporary setting.
752				 *
753				 * It would be better to forbit using and
754				 * updating the table while this command
755				 * runs, by the command finding mechanism
756				 * is heavily integrated with hash handling,
757				 * so we just delete the hash before and after
758				 * the command runs. Partly deleting like
759				 * changepatch() does doesn't seem worth the
760				 * bookinging effort, since most such runs add
761				 * directories in front of the new PATH.
762				 */
763				clearcmdentry(0);
764				do_clearcmdentry = 1;
765			}
766
767		for (;;) {
768			if (bltinonly) {
769				cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
770				if (cmdentry.u.index < 0) {
771					cmdentry.u.index = BLTINCMD;
772					argv--;
773					argc++;
774					break;
775				}
776			} else
777				find_command(argv[0], &cmdentry, cmd_flags, path);
778			/* implement the bltin and command builtins here */
779			if (cmdentry.cmdtype != CMDBUILTIN)
780				break;
781			if (cmdentry.u.index == BLTINCMD) {
782				if (argc == 1)
783					break;
784				argv++;
785				argc--;
786				bltinonly = 1;
787			} else if (cmdentry.u.index == COMMANDCMD) {
788				if (argc == 1)
789					break;
790				if (!strcmp(argv[1], "-p")) {
791					if (argc == 2)
792						break;
793					if (argv[2][0] == '-') {
794						if (strcmp(argv[2], "--"))
795							break;
796						if (argc == 3)
797							break;
798						argv += 3;
799						argc -= 3;
800					} else {
801						argv += 2;
802						argc -= 2;
803					}
804					path = _PATH_STDPATH;
805					clearcmdentry(0);
806					do_clearcmdentry = 1;
807				} else if (!strcmp(argv[1], "--")) {
808					if (argc == 2)
809						break;
810					argv += 2;
811					argc -= 2;
812				} else if (argv[1][0] == '-')
813					break;
814				else {
815					argv++;
816					argc--;
817				}
818				cmd_flags |= DO_NOFUNC;
819				bltinonly = 0;
820			} else
821				break;
822		}
823		/*
824		 * Special builtins lose their special properties when
825		 * called via 'command'.
826		 */
827		if (cmd_flags & DO_NOFUNC)
828			cmdentry.special = 0;
829	}
830
831	/* Fork off a child process if necessary. */
832	if (cmd->ncmd.backgnd
833	 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
834	    && ((flags & EV_EXIT) == 0 || have_traps()))
835	 || ((flags & EV_BACKCMD) != 0
836	    && (cmdentry.cmdtype != CMDBUILTIN
837		 || cmdentry.u.index == CDCMD
838		 || cmdentry.u.index == DOTCMD
839		 || cmdentry.u.index == EVALCMD))) {
840		jp = makejob(cmd, 1);
841		mode = cmd->ncmd.backgnd;
842		if (flags & EV_BACKCMD) {
843			mode = FORK_NOJOB;
844			if (pipe(pip) < 0)
845				error("Pipe call failed: %s", strerror(errno));
846		}
847		if (forkshell(jp, cmd, mode) != 0)
848			goto parent;	/* at end of routine */
849		if (flags & EV_BACKCMD) {
850			FORCEINTON;
851			close(pip[0]);
852			if (pip[1] != 1) {
853				dup2(pip[1], 1);
854				close(pip[1]);
855			}
856		}
857		flags |= EV_EXIT;
858	}
859
860	/* This is the child process if a fork occurred. */
861	/* Execute the command. */
862	if (cmdentry.cmdtype == CMDFUNCTION) {
863#ifdef DEBUG
864		trputs("Shell function:  ");  trargs(argv);
865#endif
866		saveparam = shellparam;
867		shellparam.malloc = 0;
868		shellparam.reset = 1;
869		shellparam.nparam = argc - 1;
870		shellparam.p = argv + 1;
871		shellparam.optnext = NULL;
872		INTOFF;
873		savelocalvars = localvars;
874		localvars = NULL;
875		reffunc(cmdentry.u.func);
876		savehandler = handler;
877		if (setjmp(jmploc.loc)) {
878			if (exception == EXSHELLPROC)
879				freeparam(&saveparam);
880			else {
881				freeparam(&shellparam);
882				shellparam = saveparam;
883				if (exception == EXERROR || exception == EXEXEC)
884					popredir();
885			}
886			unreffunc(cmdentry.u.func);
887			poplocalvars();
888			localvars = savelocalvars;
889			funcnest--;
890			handler = savehandler;
891			longjmp(handler->loc, 1);
892		}
893		handler = &jmploc;
894		funcnest++;
895		redirect(cmd->ncmd.redirect, REDIR_PUSH);
896		INTON;
897		for (sp = varlist.list ; sp ; sp = sp->next)
898			mklocal(sp->text);
899		exitstatus = oexitstatus;
900		if (flags & EV_TESTED)
901			evaltree(getfuncnode(cmdentry.u.func), EV_TESTED);
902		else
903			evaltree(getfuncnode(cmdentry.u.func), 0);
904		INTOFF;
905		unreffunc(cmdentry.u.func);
906		poplocalvars();
907		localvars = savelocalvars;
908		freeparam(&shellparam);
909		shellparam = saveparam;
910		handler = savehandler;
911		funcnest--;
912		popredir();
913		INTON;
914		if (evalskip == SKIPFUNC) {
915			evalskip = 0;
916			skipcount = 0;
917		}
918		if (flags & EV_EXIT)
919			exitshell(exitstatus);
920	} else if (cmdentry.cmdtype == CMDBUILTIN) {
921#ifdef DEBUG
922		trputs("builtin command:  ");  trargs(argv);
923#endif
924		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
925		if (flags == EV_BACKCMD) {
926			memout.nleft = 0;
927			memout.nextc = memout.buf;
928			memout.bufsize = 64;
929			mode |= REDIR_BACKQ;
930			cmdentry.special = 0;
931		}
932		savecmdname = commandname;
933		savetopfile = getcurrentfile();
934		cmdenviron = varlist.list;
935		e = -1;
936		savehandler = handler;
937		if (setjmp(jmploc.loc)) {
938			e = exception;
939			exitstatus = (e == EXINT)? SIGINT+128 : 2;
940			goto cmddone;
941		}
942		handler = &jmploc;
943		redirect(cmd->ncmd.redirect, mode);
944		/*
945		 * If there is no command word, redirection errors should
946		 * not be fatal but assignment errors should.
947		 */
948		if (argc == 0 && !(flags & EV_BACKCMD))
949			cmdentry.special = 1;
950		if (cmdentry.special)
951			listsetvar(cmdenviron);
952		if (argc > 0)
953			bltinsetlocale();
954		commandname = argv[0];
955		argptr = argv + 1;
956		nextopt_optptr = NULL;		/* initialize nextopt */
957		builtin_flags = flags;
958		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
959		flushall();
960cmddone:
961		if (argc > 0)
962			bltinunsetlocale();
963		cmdenviron = NULL;
964		out1 = &output;
965		out2 = &errout;
966		freestdout();
967		if (e != EXSHELLPROC) {
968			commandname = savecmdname;
969			if (flags & EV_EXIT) {
970				exitshell(exitstatus);
971			}
972		}
973		handler = savehandler;
974		if (flags == EV_BACKCMD) {
975			backcmd->buf = memout.buf;
976			backcmd->nleft = memout.nextc - memout.buf;
977			memout.buf = NULL;
978		}
979		if (cmdentry.u.index != EXECCMD &&
980				(e == -1 || e == EXERROR || e == EXEXEC))
981			popredir();
982		if (e != -1) {
983			if ((e != EXERROR && e != EXEXEC)
984			    || cmdentry.special)
985				exraise(e);
986			popfilesupto(savetopfile);
987			if (flags != EV_BACKCMD)
988				FORCEINTON;
989		}
990	} else {
991#ifdef DEBUG
992		trputs("normal command:  ");  trargs(argv);
993#endif
994		redirect(cmd->ncmd.redirect, 0);
995		for (sp = varlist.list ; sp ; sp = sp->next)
996			setvareq(sp->text, VEXPORT|VSTACK);
997		envp = environment();
998		shellexec(argv, envp, path, cmdentry.u.index);
999		/*NOTREACHED*/
1000	}
1001	goto out;
1002
1003parent:	/* parent process gets here (if we forked) */
1004	if (mode == FORK_FG) {	/* argument to fork */
1005		INTOFF;
1006		exitstatus = waitforjob(jp, &realstatus);
1007		INTON;
1008		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1009			evalskip = SKIPBREAK;
1010			skipcount = loopnest;
1011		}
1012	} else if (mode == FORK_NOJOB) {
1013		backcmd->fd = pip[0];
1014		close(pip[1]);
1015		backcmd->jp = jp;
1016	}
1017
1018out:
1019	if (lastarg)
1020		setvar("_", lastarg, 0);
1021	if (do_clearcmdentry)
1022		clearcmdentry(0);
1023	popstackmark(&smark);
1024}
1025
1026
1027
1028/*
1029 * Search for a command.  This is called before we fork so that the
1030 * location of the command will be available in the parent as well as
1031 * the child.  The check for "goodname" is an overly conservative
1032 * check that the name will not be subject to expansion.
1033 */
1034
1035static void
1036prehash(union node *n)
1037{
1038	struct cmdentry entry;
1039
1040	if (n && n->type == NCMD && n->ncmd.args)
1041		if (goodname(n->ncmd.args->narg.text))
1042			find_command(n->ncmd.args->narg.text, &entry, 0,
1043				     pathval());
1044}
1045
1046
1047
1048/*
1049 * Builtin commands.  Builtin commands whose functions are closely
1050 * tied to evaluation are implemented here.
1051 */
1052
1053/*
1054 * No command given, a bltin command with no arguments, or a bltin command
1055 * with an invalid name.
1056 */
1057
1058int
1059bltincmd(int argc, char **argv)
1060{
1061	if (argc > 1) {
1062		out2fmt_flush("%s: not found\n", argv[1]);
1063		return 127;
1064	}
1065	/*
1066	 * Preserve exitstatus of a previous possible redirection
1067	 * as POSIX mandates
1068	 */
1069	return exitstatus;
1070}
1071
1072
1073/*
1074 * Handle break and continue commands.  Break, continue, and return are
1075 * all handled by setting the evalskip flag.  The evaluation routines
1076 * above all check this flag, and if it is set they start skipping
1077 * commands rather than executing them.  The variable skipcount is
1078 * the number of loops to break/continue, or the number of function
1079 * levels to return.  (The latter is always 1.)  It should probably
1080 * be an error to break out of more loops than exist, but it isn't
1081 * in the standard shell so we don't make it one here.
1082 */
1083
1084int
1085breakcmd(int argc, char **argv)
1086{
1087	int n = argc > 1 ? number(argv[1]) : 1;
1088
1089	if (n > loopnest)
1090		n = loopnest;
1091	if (n > 0) {
1092		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1093		skipcount = n;
1094	}
1095	return 0;
1096}
1097
1098/*
1099 * The `command' command.
1100 */
1101int
1102commandcmd(int argc, char **argv)
1103{
1104	const char *path;
1105	int ch;
1106	int cmd = -1;
1107
1108	path = bltinlookup("PATH", 1);
1109
1110	optind = optreset = 1;
1111	opterr = 0;
1112	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1113		switch (ch) {
1114		case 'p':
1115			path = _PATH_STDPATH;
1116			break;
1117		case 'v':
1118			cmd = TYPECMD_SMALLV;
1119			break;
1120		case 'V':
1121			cmd = TYPECMD_BIGV;
1122			break;
1123		case '?':
1124		default:
1125			error("unknown option: -%c", optopt);
1126		}
1127	}
1128	argc -= optind;
1129	argv += optind;
1130
1131	if (cmd != -1) {
1132		if (argc != 1)
1133			error("wrong number of arguments");
1134		return typecmd_impl(2, argv - 1, cmd, path);
1135	}
1136	if (argc != 0)
1137		error("commandcmd bad call");
1138
1139	/*
1140	 * Do nothing successfully if no command was specified;
1141	 * ksh also does this.
1142	 */
1143	return 0;
1144}
1145
1146
1147/*
1148 * The return command.
1149 */
1150
1151int
1152returncmd(int argc, char **argv)
1153{
1154	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1155
1156	if (funcnest) {
1157		evalskip = SKIPFUNC;
1158		skipcount = 1;
1159	} else {
1160		/* skip the rest of the file */
1161		evalskip = SKIPFILE;
1162		skipcount = 1;
1163	}
1164	return ret;
1165}
1166
1167
1168int
1169falsecmd(int argc __unused, char **argv __unused)
1170{
1171	return 1;
1172}
1173
1174
1175int
1176truecmd(int argc __unused, char **argv __unused)
1177{
1178	return 0;
1179}
1180
1181
1182int
1183execcmd(int argc, char **argv)
1184{
1185	/*
1186	 * Because we have historically not supported any options,
1187	 * only treat "--" specially.
1188	 */
1189	if (argc > 1 && strcmp(argv[1], "--") == 0)
1190		argc--, argv++;
1191	if (argc > 1) {
1192		struct strlist *sp;
1193
1194		iflag = 0;		/* exit on error */
1195		mflag = 0;
1196		optschanged();
1197		for (sp = cmdenviron; sp ; sp = sp->next)
1198			setvareq(sp->text, VEXPORT|VSTACK);
1199		shellexec(argv + 1, environment(), pathval(), 0);
1200
1201	}
1202	return 0;
1203}
1204
1205
1206int
1207timescmd(int argc __unused, char **argv __unused)
1208{
1209	struct rusage ru;
1210	long shumins, shsmins, chumins, chsmins;
1211	double shusecs, shssecs, chusecs, chssecs;
1212
1213	if (getrusage(RUSAGE_SELF, &ru) < 0)
1214		return 1;
1215	shumins = ru.ru_utime.tv_sec / 60;
1216	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1217	shsmins = ru.ru_stime.tv_sec / 60;
1218	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1219	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1220		return 1;
1221	chumins = ru.ru_utime.tv_sec / 60;
1222	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1223	chsmins = ru.ru_stime.tv_sec / 60;
1224	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1225	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1226	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1227	return 0;
1228}
1229