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