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