xref: /dragonfly/bin/sh/eval.c (revision 088f2cdc)
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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)eval.c	8.9 (Berkeley) 6/8/95
37  * $FreeBSD: src/bin/sh/eval.c,v 1.105 2011/05/21 22:03:06 jilles Exp $
38  */
39 
40 #include <sys/time.h>
41 #include <sys/resource.h>
42 #include <sys/wait.h> /* For WIFSIGNALED(status) */
43 
44 #include <errno.h>
45 #include <paths.h>
46 #include <signal.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 
50 /*
51  * Evaluate a command.
52  */
53 
54 #include "shell.h"
55 #include "nodes.h"
56 #include "syntax.h"
57 #include "expand.h"
58 #include "parser.h"
59 #include "jobs.h"
60 #include "eval.h"
61 #include "builtins.h"
62 #include "options.h"
63 #include "exec.h"
64 #include "redir.h"
65 #include "input.h"
66 #include "output.h"
67 #include "trap.h"
68 #include "var.h"
69 #include "memalloc.h"
70 #include "error.h"
71 #include "show.h"
72 #include "mystring.h"
73 #ifndef NO_HISTORY
74 #include "myhistedit.h"
75 #endif
76 
77 
78 int evalskip;			/* set if we are skipping commands */
79 static int skipcount;		/* number of levels to skip */
80 MKINIT int loopnest;		/* current loop nesting level */
81 int funcnest;			/* depth of function calls */
82 static int builtin_flags;	/* evalcommand flags for builtins */
83 
84 
85 const char *commandname;
86 struct strlist *cmdenviron;
87 int exitstatus;			/* exit status of last command */
88 int oexitstatus;		/* saved exit status */
89 
90 
91 static void evalloop(union node *, int);
92 static void evalfor(union node *, int);
93 static void evalcase(union node *, int);
94 static void evalsubshell(union node *, int);
95 static void evalredir(union node *, int);
96 static void expredir(union node *);
97 static void evalpipe(union node *);
98 static int is_valid_fast_cmdsubst(union node *n);
99 static void evalcommand(union node *, int, struct backcmd *);
100 static void prehash(union node *);
101 
102 
103 /*
104  * Called to reset things after an exception.
105  */
106 
107 #ifdef mkinit
108 INCLUDE "eval.h"
109 
110 RESET {
111 	evalskip = 0;
112 	loopnest = 0;
113 	funcnest = 0;
114 }
115 #endif
116 
117 
118 
119 /*
120  * The eval command.
121  */
122 
123 int
124 evalcmd(int argc, char **argv)
125 {
126         char *p;
127         char *concat;
128         char **ap;
129 
130         if (argc > 1) {
131                 p = argv[1];
132                 if (argc > 2) {
133                         STARTSTACKSTR(concat);
134                         ap = argv + 2;
135                         for (;;) {
136                                 STPUTS(p, concat);
137                                 if ((p = *ap++) == NULL)
138                                         break;
139                                 STPUTC(' ', concat);
140                         }
141                         STPUTC('\0', concat);
142                         p = grabstackstr(concat);
143                 }
144                 evalstring(p, builtin_flags & EV_TESTED);
145         } else
146                 exitstatus = 0;
147         return exitstatus;
148 }
149 
150 
151 /*
152  * Execute a command or commands contained in a string.
153  */
154 
155 void
156 evalstring(char *s, int flags)
157 {
158 	union node *n;
159 	struct stackmark smark;
160 	int flags_exit;
161 	int any;
162 
163 	flags_exit = flags & EV_EXIT;
164 	flags &= ~EV_EXIT;
165 	any = 0;
166 	setstackmark(&smark);
167 	setinputstring(s, 1);
168 	while ((n = parsecmd(0)) != NEOF) {
169 		if (n != NULL) {
170 			if (flags_exit && preadateof())
171 				evaltree(n, flags | EV_EXIT);
172 			else
173 				evaltree(n, flags);
174 			any = 1;
175 		}
176 		popstackmark(&smark);
177 	}
178 	popfile();
179 	popstackmark(&smark);
180 	if (!any)
181 		exitstatus = 0;
182 	if (flags_exit)
183 		exraise(EXEXIT);
184 }
185 
186 
187 /*
188  * Evaluate a parse tree.  The value is left in the global variable
189  * exitstatus.
190  */
191 
192 void
193 evaltree(union node *n, int flags)
194 {
195 	int do_etest;
196 	union node *next;
197 
198 	do_etest = 0;
199 	if (n == NULL) {
200 		TRACE(("evaltree(NULL) called\n"));
201 		exitstatus = 0;
202 		goto out;
203 	}
204 	do {
205 		next = NULL;
206 #ifndef NO_HISTORY
207 		displayhist = 1;	/* show history substitutions done with fc */
208 #endif
209 		TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
210 		switch (n->type) {
211 		case NSEMI:
212 			evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
213 			if (evalskip)
214 				goto out;
215 			next = n->nbinary.ch2;
216 			break;
217 		case NAND:
218 			evaltree(n->nbinary.ch1, EV_TESTED);
219 			if (evalskip || exitstatus != 0) {
220 				goto out;
221 			}
222 			next = n->nbinary.ch2;
223 			break;
224 		case NOR:
225 			evaltree(n->nbinary.ch1, EV_TESTED);
226 			if (evalskip || exitstatus == 0)
227 				goto out;
228 			next = n->nbinary.ch2;
229 			break;
230 		case NREDIR:
231 			evalredir(n, flags);
232 			break;
233 		case NSUBSHELL:
234 			evalsubshell(n, flags);
235 			do_etest = !(flags & EV_TESTED);
236 			break;
237 		case NBACKGND:
238 			evalsubshell(n, flags);
239 			break;
240 		case NIF: {
241 			evaltree(n->nif.test, EV_TESTED);
242 			if (evalskip)
243 				goto out;
244 			if (exitstatus == 0)
245 				next = n->nif.ifpart;
246 			else if (n->nif.elsepart)
247 				next = n->nif.elsepart;
248 			else
249 				exitstatus = 0;
250 			break;
251 		}
252 		case NWHILE:
253 		case NUNTIL:
254 			evalloop(n, flags & ~EV_EXIT);
255 			break;
256 		case NFOR:
257 			evalfor(n, flags & ~EV_EXIT);
258 			break;
259 		case NCASE:
260 			evalcase(n, flags);
261 			break;
262 		case NDEFUN:
263 			defun(n->narg.text, n->narg.next);
264 			exitstatus = 0;
265 			break;
266 		case NNOT:
267 			evaltree(n->nnot.com, EV_TESTED);
268 			exitstatus = !exitstatus;
269 			break;
270 
271 		case NPIPE:
272 			evalpipe(n);
273 			do_etest = !(flags & EV_TESTED);
274 			break;
275 		case NCMD:
276 			evalcommand(n, flags, NULL);
277 			do_etest = !(flags & EV_TESTED);
278 			break;
279 		default:
280 			out1fmt("Node type = %d\n", n->type);
281 			flushout(&output);
282 			break;
283 		}
284 		n = next;
285 	} while (n != NULL);
286 out:
287 	if (pendingsigs)
288 		dotrap();
289 	if (eflag && exitstatus != 0 && do_etest)
290 		exitshell(exitstatus);
291 	if (flags & EV_EXIT)
292 		exraise(EXEXIT);
293 }
294 
295 
296 static void
297 evalloop(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) {
306 skipping:	  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 
334 static void
335 evalfor(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--;
368 out:
369 	popstackmark(&smark);
370 }
371 
372 
373 
374 static void
375 evalcase(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 	}
397 out:
398 	popstackmark(&smark);
399 }
400 
401 
402 
403 /*
404  * Kick off a subshell to evaluate a tree.
405  */
406 
407 static void
408 evalsubshell(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, NULL);
423 		INTON;
424 	} else
425 		exitstatus = 0;
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 		popredir();
448 		if (e == EXERROR || e == EXEXEC) {
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 				if (prevfd >= 0)
534 					close(prevfd);
535 				error("Pipe call failed: %s", strerror(errno));
536 			}
537 		}
538 		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
539 			INTON;
540 			if (prevfd > 0) {
541 				dup2(prevfd, 0);
542 				close(prevfd);
543 			}
544 			if (pip[1] >= 0) {
545 				if (!(prevfd >= 0 && pip[0] == 0))
546 					close(pip[0]);
547 				if (pip[1] != 1) {
548 					dup2(pip[1], 1);
549 					close(pip[1]);
550 				}
551 			}
552 			evaltree(lp->n, EV_EXIT);
553 		}
554 		if (prevfd >= 0)
555 			close(prevfd);
556 		prevfd = pip[0];
557 		if (pip[1] != -1)
558 			close(pip[1]);
559 	}
560 	INTON;
561 	if (n->npipe.backgnd == 0) {
562 		INTOFF;
563 		exitstatus = waitforjob(jp, NULL);
564 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
565 		INTON;
566 	} else
567 		exitstatus = 0;
568 }
569 
570 
571 
572 static int
573 is_valid_fast_cmdsubst(union node *n)
574 {
575 	union node *argp;
576 
577 	if (n->type != NCMD)
578 		return 0;
579 	for (argp = n->ncmd.args ; argp ; argp = argp->narg.next)
580 		if (expandhassideeffects(argp->narg.text))
581 			return 0;
582 	return 1;
583 }
584 
585 /*
586  * Execute a command inside back quotes.  If it's a builtin command, we
587  * want to save its output in a block obtained from malloc.  Otherwise
588  * we fork off a subprocess and get the output of the command via a pipe.
589  * Should be called with interrupts off.
590  */
591 
592 void
593 evalbackcmd(union node *n, struct backcmd *result)
594 {
595 	int pip[2];
596 	struct job *jp;
597 	struct stackmark smark;		/* unnecessary */
598 	struct jmploc jmploc;
599 	struct jmploc *savehandler;
600 
601 	setstackmark(&smark);
602 	result->fd = -1;
603 	result->buf = NULL;
604 	result->nleft = 0;
605 	result->jp = NULL;
606 	if (n == NULL) {
607 		exitstatus = 0;
608 		goto out;
609 	}
610 	if (is_valid_fast_cmdsubst(n)) {
611 		exitstatus = oexitstatus;
612 		savehandler = handler;
613 		if (setjmp(jmploc.loc)) {
614 			if (exception == EXERROR || exception == EXEXEC)
615 				exitstatus = 2;
616 			else if (exception != 0) {
617 				handler = savehandler;
618 				longjmp(handler->loc, 1);
619 			}
620 		} else {
621 			handler = &jmploc;
622 			evalcommand(n, EV_BACKCMD, result);
623 		}
624 		handler = savehandler;
625 	} else {
626 		exitstatus = 0;
627 		if (pipe(pip) < 0)
628 			error("Pipe call failed: %s", strerror(errno));
629 		jp = makejob(n, 1);
630 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
631 			FORCEINTON;
632 			close(pip[0]);
633 			if (pip[1] != 1) {
634 				dup2(pip[1], 1);
635 				close(pip[1]);
636 			}
637 			evaltree(n, EV_EXIT);
638 		}
639 		close(pip[1]);
640 		result->fd = pip[0];
641 		result->jp = jp;
642 	}
643 out:
644 	popstackmark(&smark);
645 	TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
646 		result->fd, result->buf, result->nleft, result->jp));
647 }
648 
649 /*
650  * Check if a builtin can safely be executed in the same process,
651  * even though it should be in a subshell (command substitution).
652  * Note that jobid, jobs, times and trap can show information not
653  * available in a child process; this is deliberate.
654  * The arguments should already have been expanded.
655  */
656 static int
657 safe_builtin(int idx, int argc, char **argv)
658 {
659 	if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD ||
660 	    idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD ||
661 	    idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD ||
662 	    idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD ||
663 	    idx == TYPECMD)
664 		return (1);
665 	if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
666 	    idx == UMASKCMD)
667 		return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
668 	if (idx == SETCMD)
669 		return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
670 		    argv[1][0] == '+') && argv[1][1] == 'o' &&
671 		    argv[1][2] == '\0'));
672 	return (0);
673 }
674 
675 /*
676  * Execute a simple command.
677  * Note: This may or may not return if (flags & EV_EXIT).
678  */
679 
680 static void
681 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd)
682 {
683 	struct stackmark smark;
684 	union node *argp;
685 	struct arglist arglist;
686 	struct arglist varlist;
687 	volatile int flags = flgs;
688 	char **volatile argv;
689 	volatile int argc;
690 	char **envp;
691 	int varflag;
692 	struct strlist *sp;
693 	int mode;
694 	int pip[2];
695 	struct cmdentry cmdentry;
696 	struct job *volatile jp;
697 	struct jmploc jmploc;
698 	struct jmploc *savehandler;
699 	const char *savecmdname;
700 	struct shparam saveparam;
701 	struct localvar *savelocalvars;
702 	struct parsefile *savetopfile;
703 	volatile int e;
704 	char *volatile lastarg;
705 	int realstatus;
706 	volatile int do_clearcmdentry;
707 	const char *path = pathval();
708 
709 	/* First expand the arguments. */
710 	TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
711 	setstackmark(&smark);
712 	arglist.lastp = &arglist.list;
713 	varlist.lastp = &varlist.list;
714 	varflag = 1;
715 	jp = NULL;
716 	do_clearcmdentry = 0;
717 	oexitstatus = exitstatus;
718 	exitstatus = 0;
719 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
720 		if (varflag && isassignment(argp->narg.text)) {
721 			expandarg(argp, &varlist, EXP_VARTILDE);
722 			continue;
723 		}
724 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
725 		varflag = 0;
726 	}
727 	*arglist.lastp = NULL;
728 	*varlist.lastp = NULL;
729 	expredir(cmd->ncmd.redirect);
730 	argc = 0;
731 	for (sp = arglist.list ; sp ; sp = sp->next)
732 		argc++;
733 	/* Add one slot at the beginning for tryexec(). */
734 	argv = stalloc(sizeof (char *) * (argc + 2));
735 	argv++;
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();
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();
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 			freeparam(&shellparam);
931 			shellparam = saveparam;
932 			popredir();
933 			unreffunc(cmdentry.u.func);
934 			poplocalvars();
935 			localvars = savelocalvars;
936 			funcnest--;
937 			handler = savehandler;
938 			longjmp(handler->loc, 1);
939 		}
940 		handler = &jmploc;
941 		funcnest++;
942 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
943 		INTON;
944 		for (sp = varlist.list ; sp ; sp = sp->next)
945 			mklocal(sp->text);
946 		exitstatus = oexitstatus;
947 		evaltree(getfuncnode(cmdentry.u.func),
948 		    flags & (EV_TESTED | EV_EXIT));
949 		INTOFF;
950 		unreffunc(cmdentry.u.func);
951 		poplocalvars();
952 		localvars = savelocalvars;
953 		freeparam(&shellparam);
954 		shellparam = saveparam;
955 		handler = savehandler;
956 		funcnest--;
957 		popredir();
958 		INTON;
959 		if (evalskip == SKIPFUNC) {
960 			evalskip = 0;
961 			skipcount = 0;
962 		}
963 		if (jp)
964 			exitshell(exitstatus);
965 	} else if (cmdentry.cmdtype == CMDBUILTIN) {
966 #ifdef DEBUG
967 		trputs("builtin command:  ");  trargs(argv);
968 #endif
969 		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
970 		if (flags == EV_BACKCMD) {
971 			memout.nleft = 0;
972 			memout.nextc = memout.buf;
973 			memout.bufsize = 64;
974 			mode |= REDIR_BACKQ;
975 			cmdentry.special = 0;
976 		}
977 		savecmdname = commandname;
978 		savetopfile = getcurrentfile();
979 		cmdenviron = varlist.list;
980 		e = -1;
981 		savehandler = handler;
982 		if (setjmp(jmploc.loc)) {
983 			e = exception;
984 			if (e == EXINT)
985 				exitstatus = SIGINT+128;
986 			else if (e != EXEXIT)
987 				exitstatus = 2;
988 			goto cmddone;
989 		}
990 		handler = &jmploc;
991 		redirect(cmd->ncmd.redirect, mode);
992 		/*
993 		 * If there is no command word, redirection errors should
994 		 * not be fatal but assignment errors should.
995 		 */
996 		if (argc == 0 && !(flags & EV_BACKCMD))
997 			cmdentry.special = 1;
998 		listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
999 		if (argc > 0)
1000 			bltinsetlocale();
1001 		commandname = argv[0];
1002 		argptr = argv + 1;
1003 		nextopt_optptr = NULL;		/* initialize nextopt */
1004 		builtin_flags = flags;
1005 		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
1006 		flushall();
1007 cmddone:
1008 		if (argc > 0)
1009 			bltinunsetlocale();
1010 		cmdenviron = NULL;
1011 		out1 = &output;
1012 		out2 = &errout;
1013 		freestdout();
1014 		handler = savehandler;
1015 		commandname = savecmdname;
1016 		if (jp)
1017 			exitshell(exitstatus);
1018 		if (flags == EV_BACKCMD) {
1019 			backcmd->buf = memout.buf;
1020 			backcmd->nleft = memout.nextc - memout.buf;
1021 			memout.buf = NULL;
1022 		}
1023 		if (cmdentry.u.index != EXECCMD)
1024 			popredir();
1025 		if (e != -1) {
1026 			if ((e != EXERROR && e != EXEXEC)
1027 			    || cmdentry.special)
1028 				exraise(e);
1029 			popfilesupto(savetopfile);
1030 			if (flags != EV_BACKCMD)
1031 				FORCEINTON;
1032 		}
1033 	} else {
1034 #ifdef DEBUG
1035 		trputs("normal command:  ");  trargs(argv);
1036 #endif
1037 		redirect(cmd->ncmd.redirect, 0);
1038 		for (sp = varlist.list ; sp ; sp = sp->next)
1039 			setvareq(sp->text, VEXPORT|VSTACK);
1040 		envp = environment();
1041 		shellexec(argv, envp, path, cmdentry.u.index);
1042 		/*NOTREACHED*/
1043 	}
1044 	goto out;
1045 
1046 parent:	/* parent process gets here (if we forked) */
1047 	if (mode == FORK_FG) {	/* argument to fork */
1048 		INTOFF;
1049 		exitstatus = waitforjob(jp, &realstatus);
1050 		INTON;
1051 		if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) {
1052 			evalskip = SKIPBREAK;
1053 			skipcount = loopnest;
1054 		}
1055 	} else if (mode == FORK_NOJOB) {
1056 		backcmd->fd = pip[0];
1057 		close(pip[1]);
1058 		backcmd->jp = jp;
1059 	} else
1060 		exitstatus = 0;
1061 
1062 out:
1063 	if (lastarg)
1064 		setvar("_", lastarg, 0);
1065 	if (do_clearcmdentry)
1066 		clearcmdentry();
1067 	popstackmark(&smark);
1068 }
1069 
1070 
1071 
1072 /*
1073  * Search for a command.  This is called before we fork so that the
1074  * location of the command will be available in the parent as well as
1075  * the child.  The check for "goodname" is an overly conservative
1076  * check that the name will not be subject to expansion.
1077  */
1078 
1079 static void
1080 prehash(union node *n)
1081 {
1082 	struct cmdentry entry;
1083 
1084 	if (n && n->type == NCMD && n->ncmd.args)
1085 		if (goodname(n->ncmd.args->narg.text))
1086 			find_command(n->ncmd.args->narg.text, &entry, 0,
1087 				     pathval());
1088 }
1089 
1090 
1091 
1092 /*
1093  * Builtin commands.  Builtin commands whose functions are closely
1094  * tied to evaluation are implemented here.
1095  */
1096 
1097 /*
1098  * No command given, a bltin command with no arguments, or a bltin command
1099  * with an invalid name.
1100  */
1101 
1102 int
1103 bltincmd(int argc, char **argv)
1104 {
1105 	if (argc > 1) {
1106 		out2fmt_flush("%s: not found\n", argv[1]);
1107 		return 127;
1108 	}
1109 	/*
1110 	 * Preserve exitstatus of a previous possible redirection
1111 	 * as POSIX mandates
1112 	 */
1113 	return exitstatus;
1114 }
1115 
1116 
1117 /*
1118  * Handle break and continue commands.  Break, continue, and return are
1119  * all handled by setting the evalskip flag.  The evaluation routines
1120  * above all check this flag, and if it is set they start skipping
1121  * commands rather than executing them.  The variable skipcount is
1122  * the number of loops to break/continue, or the number of function
1123  * levels to return.  (The latter is always 1.)  It should probably
1124  * be an error to break out of more loops than exist, but it isn't
1125  * in the standard shell so we don't make it one here.
1126  */
1127 
1128 int
1129 breakcmd(int argc, char **argv)
1130 {
1131 	int n = argc > 1 ? number(argv[1]) : 1;
1132 
1133 	if (n > loopnest)
1134 		n = loopnest;
1135 	if (n > 0) {
1136 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1137 		skipcount = n;
1138 	}
1139 	return 0;
1140 }
1141 
1142 /*
1143  * The `command' command.
1144  */
1145 int
1146 commandcmd(int argc, char **argv)
1147 {
1148 	const char *path;
1149 	int ch;
1150 	int cmd = -1;
1151 
1152 	path = bltinlookup("PATH", 1);
1153 
1154 	optind = optreset = 1;
1155 	opterr = 0;
1156 	while ((ch = getopt(argc, argv, "pvV")) != -1) {
1157 		switch (ch) {
1158 		case 'p':
1159 			path = _PATH_STDPATH;
1160 			break;
1161 		case 'v':
1162 			cmd = TYPECMD_SMALLV;
1163 			break;
1164 		case 'V':
1165 			cmd = TYPECMD_BIGV;
1166 			break;
1167 		case '?':
1168 		default:
1169 			error("unknown option: -%c", optopt);
1170 		}
1171 	}
1172 	argc -= optind;
1173 	argv += optind;
1174 
1175 	if (cmd != -1) {
1176 		if (argc != 1)
1177 			error("wrong number of arguments");
1178 		return typecmd_impl(2, argv - 1, cmd, path);
1179 	}
1180 	if (argc != 0)
1181 		error("commandcmd bad call");
1182 
1183 	/*
1184 	 * Do nothing successfully if no command was specified;
1185 	 * ksh also does this.
1186 	 */
1187 	return(0);
1188 }
1189 
1190 
1191 /*
1192  * The return command.
1193  */
1194 
1195 int
1196 returncmd(int argc, char **argv)
1197 {
1198 	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
1199 
1200 	if (funcnest) {
1201 		evalskip = SKIPFUNC;
1202 		skipcount = 1;
1203 	} else {
1204 		/* skip the rest of the file */
1205 		evalskip = SKIPFILE;
1206 		skipcount = 1;
1207 	}
1208 	return ret;
1209 }
1210 
1211 
1212 int
1213 falsecmd(int argc __unused, char **argv __unused)
1214 {
1215 	return 1;
1216 }
1217 
1218 
1219 int
1220 truecmd(int argc __unused, char **argv __unused)
1221 {
1222 	return 0;
1223 }
1224 
1225 
1226 int
1227 execcmd(int argc, char **argv)
1228 {
1229 	/*
1230 	 * Because we have historically not supported any options,
1231 	 * only treat "--" specially.
1232 	 */
1233 	if (argc > 1 && strcmp(argv[1], "--") == 0)
1234 		argc--, argv++;
1235 	if (argc > 1) {
1236 		struct strlist *sp;
1237 
1238 		iflag = 0;		/* exit on error */
1239 		mflag = 0;
1240 		optschanged();
1241 		for (sp = cmdenviron; sp ; sp = sp->next)
1242 			setvareq(sp->text, VEXPORT|VSTACK);
1243 		shellexec(argv + 1, environment(), pathval(), 0);
1244 
1245 	}
1246 	return 0;
1247 }
1248 
1249 
1250 int
1251 timescmd(int argc __unused, char **argv __unused)
1252 {
1253 	struct rusage ru;
1254 	long shumins, shsmins, chumins, chsmins;
1255 	double shusecs, shssecs, chusecs, chssecs;
1256 
1257 	if (getrusage(RUSAGE_SELF, &ru) < 0)
1258 		return 1;
1259 	shumins = ru.ru_utime.tv_sec / 60;
1260 	shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1261 	shsmins = ru.ru_stime.tv_sec / 60;
1262 	shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1263 	if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
1264 		return 1;
1265 	chumins = ru.ru_utime.tv_sec / 60;
1266 	chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
1267 	chsmins = ru.ru_stime.tv_sec / 60;
1268 	chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
1269 	out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
1270 	    shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
1271 	return 0;
1272 }
1273