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