xref: /netbsd-src/bin/sh/eval.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /*	$NetBSD: eval.c,v 1.180 2020/05/14 08:34:17 msaitoh 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.180 2020/05/14 08:34:17 msaitoh 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 <string.h>
49 #include <errno.h>
50 #include <limits.h>
51 #include <unistd.h>
52 #include <sys/fcntl.h>
53 #include <sys/stat.h>
54 #include <sys/times.h>
55 #include <sys/param.h>
56 #include <sys/types.h>
57 #include <sys/wait.h>
58 #include <sys/sysctl.h>
59 
60 /*
61  * Evaluate a command.
62  */
63 
64 #include "shell.h"
65 #include "nodes.h"
66 #include "syntax.h"
67 #include "expand.h"
68 #include "parser.h"
69 #include "jobs.h"
70 #include "eval.h"
71 #include "builtins.h"
72 #include "options.h"
73 #include "exec.h"
74 #include "redir.h"
75 #include "input.h"
76 #include "output.h"
77 #include "trap.h"
78 #include "var.h"
79 #include "memalloc.h"
80 #include "error.h"
81 #include "show.h"
82 #include "mystring.h"
83 #include "main.h"
84 #ifndef SMALL
85 #include "nodenames.h"
86 #include "myhistedit.h"
87 #endif
88 
89 
90 STATIC struct skipsave s_k_i_p;
91 #define	evalskip	(s_k_i_p.state)
92 #define	skipcount	(s_k_i_p.count)
93 
94 STATIC int loopnest;		/* current loop nesting level */
95 STATIC int funcnest;		/* depth of function calls */
96 STATIC int builtin_flags;	/* evalcommand flags for builtins */
97 /*
98  * Base function nesting level inside a dot command.  Set to 0 initially
99  * and to (funcnest + 1) before every dot command to enable
100  *   1) detection of being in a file sourced by a dot command and
101  *   2) counting of function nesting in that file for the implementation
102  *      of the return command.
103  * The value is reset to its previous value after the dot command.
104  */
105 STATIC int dot_funcnest;
106 
107 
108 const char *commandname;
109 struct strlist *cmdenviron;
110 int exitstatus;			/* exit status of last command */
111 int back_exitstatus;		/* exit status of backquoted command */
112 
113 
114 STATIC void evalloop(union node *, int);
115 STATIC void evalfor(union node *, int);
116 STATIC void evalcase(union node *, int);
117 STATIC void evalsubshell(union node *, int);
118 STATIC void expredir(union node *);
119 STATIC void evalredir(union node *, int);
120 STATIC void evalpipe(union node *);
121 STATIC void evalcommand(union node *, int, struct backcmd *);
122 STATIC void prehash(union node *);
123 
124 STATIC char *find_dot_file(char *);
125 
126 /*
127  * Called to reset things after an exception.
128  */
129 
130 #ifdef mkinit
131 INCLUDE "eval.h"
132 
133 RESET {
134 	reset_eval();
135 }
136 
137 SHELLPROC {
138 	exitstatus = 0;
139 }
140 #endif
141 
142 void
143 reset_eval(void)
144 {
145 	evalskip = SKIPNONE;
146 	dot_funcnest = 0;
147 	loopnest = 0;
148 	funcnest = 0;
149 }
150 
151 static int
152 sh_pipe(int fds[2])
153 {
154 	int nfd;
155 
156 	if (pipe(fds))
157 		return -1;
158 
159 	if (fds[0] < 3) {
160 		nfd = fcntl(fds[0], F_DUPFD, 3);
161 		if (nfd != -1) {
162 			close(fds[0]);
163 			fds[0] = nfd;
164 		}
165 	}
166 
167 	if (fds[1] < 3) {
168 		nfd = fcntl(fds[1], F_DUPFD, 3);
169 		if (nfd != -1) {
170 			close(fds[1]);
171 			fds[1] = nfd;
172 		}
173 	}
174 	return 0;
175 }
176 
177 
178 /*
179  * The eval commmand.
180  */
181 
182 int
183 evalcmd(int argc, char **argv)
184 {
185 	char *p;
186 	char *concat;
187 	char **ap;
188 
189 	if (argc > 1) {
190 		p = argv[1];
191 		if (argc > 2) {
192 			STARTSTACKSTR(concat);
193 			ap = argv + 2;
194 			for (;;) {
195 				while (*p)
196 					STPUTC(*p++, concat);
197 				if ((p = *ap++) == NULL)
198 					break;
199 				STPUTC(' ', concat);
200 			}
201 			STPUTC('\0', concat);
202 			p = grabstackstr(concat);
203 		}
204 		evalstring(p, builtin_flags & EV_TESTED);
205 	} else
206 		exitstatus = 0;
207 	return exitstatus;
208 }
209 
210 
211 /*
212  * Execute a command or commands contained in a string.
213  */
214 
215 void
216 evalstring(char *s, int flag)
217 {
218 	union node *n;
219 	struct stackmark smark;
220 	int last;
221 	int any;
222 
223 	last = flag & EV_EXIT;
224 	flag &= ~EV_EXIT;
225 
226 	setstackmark(&smark);
227 	setinputstring(s, 1, line_number);
228 
229 	any = 0;	/* to determine if exitstatus will have been set */
230 	while ((n = parsecmd(0)) != NEOF) {
231 		XTRACE(DBG_EVAL, ("evalstring: "), showtree(n));
232 		if (n && nflag == 0) {
233 			if (last && at_eof())
234 				evaltree(n, flag | EV_EXIT);
235 			else
236 				evaltree(n, flag);
237 			any = 1;
238 			if (evalskip)
239 				break;
240 		}
241 		rststackmark(&smark);
242 	}
243 	popfile();
244 	popstackmark(&smark);
245 	if (!any)
246 		exitstatus = 0;
247 	if (last)
248 		exraise(EXEXIT);
249 }
250 
251 
252 
253 /*
254  * Evaluate a parse tree.  The value is left in the global variable
255  * exitstatus.
256  */
257 
258 void
259 evaltree(union node *n, int flags)
260 {
261 	bool do_etest;
262 	int sflags = flags & ~EV_EXIT;
263 	union node *next;
264 	struct stackmark smark;
265 
266 	do_etest = false;
267 	if (n == NULL || nflag) {
268 		VTRACE(DBG_EVAL, ("evaltree(%s) called\n",
269 		    n == NULL ? "NULL" : "-n"));
270 		if (nflag == 0)
271 			exitstatus = 0;
272 		goto out2;
273 	}
274 
275 	setstackmark(&smark);
276 	do {
277 #ifndef SMALL
278 		displayhist = 1; /* show history substitutions done with fc */
279 #endif
280 		next = NULL;
281 		CTRACE(DBG_EVAL, ("pid %d, evaltree(%p: %s(%d), %#x) called\n",
282 		    getpid(), n, NODETYPENAME(n->type), n->type, flags));
283 		if (n->type != NCMD && traps_invalid)
284 			free_traps();
285 		switch (n->type) {
286 		case NSEMI:
287 			evaltree(n->nbinary.ch1, sflags);
288 			if (nflag || evalskip)
289 				goto out1;
290 			next = n->nbinary.ch2;
291 			break;
292 		case NAND:
293 			evaltree(n->nbinary.ch1, EV_TESTED);
294 			if (nflag || evalskip || exitstatus != 0)
295 				goto out1;
296 			next = n->nbinary.ch2;
297 			break;
298 		case NOR:
299 			evaltree(n->nbinary.ch1, EV_TESTED);
300 			if (nflag || evalskip || exitstatus == 0)
301 				goto out1;
302 			next = n->nbinary.ch2;
303 			break;
304 		case NREDIR:
305 			evalredir(n, flags);
306 			break;
307 		case NSUBSHELL:
308 			evalsubshell(n, flags);
309 			do_etest = !(flags & EV_TESTED);
310 			break;
311 		case NBACKGND:
312 			evalsubshell(n, flags);
313 			break;
314 		case NIF: {
315 			evaltree(n->nif.test, EV_TESTED);
316 			if (nflag || evalskip)
317 				goto out1;
318 			if (exitstatus == 0)
319 				next = n->nif.ifpart;
320 			else if (n->nif.elsepart)
321 				next = n->nif.elsepart;
322 			else
323 				exitstatus = 0;
324 			break;
325 		}
326 		case NWHILE:
327 		case NUNTIL:
328 			evalloop(n, sflags);
329 			break;
330 		case NFOR:
331 			evalfor(n, sflags);
332 			break;
333 		case NCASE:
334 			evalcase(n, sflags);
335 			break;
336 		case NDEFUN:
337 			CTRACE(DBG_EVAL, ("Defining fn %s @%d%s\n",
338 			    n->narg.text, n->narg.lineno,
339 			    fnline1 ? " LINENO=1" : ""));
340 			defun(n->narg.text, n->narg.next, n->narg.lineno);
341 			exitstatus = 0;
342 			break;
343 		case NNOT:
344 			evaltree(n->nnot.com, EV_TESTED);
345 			exitstatus = !exitstatus;
346 			break;
347 		case NDNOT:
348 			evaltree(n->nnot.com, EV_TESTED);
349 			if (exitstatus != 0)
350 				exitstatus = 1;
351 			break;
352 		case NPIPE:
353 			evalpipe(n);
354 			do_etest = !(flags & EV_TESTED);
355 			break;
356 		case NCMD:
357 			evalcommand(n, flags, NULL);
358 			do_etest = !(flags & EV_TESTED);
359 			break;
360 		default:
361 #ifdef NODETYPENAME
362 			out1fmt("Node type = %d(%s)\n",
363 				n->type, NODETYPENAME(n->type));
364 #else
365 			out1fmt("Node type = %d\n", n->type);
366 #endif
367 			flushout(&output);
368 			break;
369 		}
370 		n = next;
371 		rststackmark(&smark);
372 	} while(n != NULL);
373  out1:
374 	popstackmark(&smark);
375  out2:
376 	if (pendingsigs)
377 		dotrap();
378 	if (eflag && exitstatus != 0 && do_etest)
379 		exitshell(exitstatus);
380 	if (flags & EV_EXIT)
381 		exraise(EXEXIT);
382 }
383 
384 
385 STATIC void
386 evalloop(union node *n, int flags)
387 {
388 	int status;
389 
390 	loopnest++;
391 	status = 0;
392 
393 	CTRACE(DBG_EVAL,  ("evalloop %s:", NODETYPENAME(n->type)));
394 	VXTRACE(DBG_EVAL, (" "), showtree(n->nbinary.ch1));
395 	VXTRACE(DBG_EVAL, ("evalloop    do: "), showtree(n->nbinary.ch2));
396 	VTRACE(DBG_EVAL,  ("evalloop  done\n"));
397 	CTRACE(DBG_EVAL,  ("\n"));
398 
399 	for (;;) {
400 		evaltree(n->nbinary.ch1, EV_TESTED);
401 		if (nflag)
402 			break;
403 		if (evalskip) {
404  skipping:		if (evalskip == SKIPCONT && --skipcount <= 0) {
405 				evalskip = SKIPNONE;
406 				continue;
407 			}
408 			if (evalskip == SKIPBREAK && --skipcount <= 0)
409 				evalskip = SKIPNONE;
410 			if (evalskip == SKIPFUNC || evalskip == SKIPFILE)
411 				status = exitstatus;
412 			break;
413 		}
414 		if (n->type == NWHILE) {
415 			if (exitstatus != 0)
416 				break;
417 		} else {
418 			if (exitstatus == 0)
419 				break;
420 		}
421 		evaltree(n->nbinary.ch2, flags & EV_TESTED);
422 		status = exitstatus;
423 		if (evalskip)
424 			goto skipping;
425 	}
426 	loopnest--;
427 	exitstatus = status;
428 }
429 
430 
431 
432 STATIC void
433 evalfor(union node *n, int flags)
434 {
435 	struct arglist arglist;
436 	union node *argp;
437 	struct strlist *sp;
438 	struct stackmark smark;
439 	int status;
440 
441 	status = nflag ? exitstatus : 0;
442 
443 	setstackmark(&smark);
444 	arglist.lastp = &arglist.list;
445 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
446 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
447 		if (evalskip)
448 			goto out;
449 	}
450 	*arglist.lastp = NULL;
451 
452 	loopnest++;
453 	for (sp = arglist.list ; sp ; sp = sp->next) {
454 		if (xflag) {
455 			outxstr(expandstr(ps4val(), line_number));
456 			outxstr("for ");
457 			outxstr(n->nfor.var);
458 			outxc('=');
459 			outxshstr(sp->text);
460 			outxc('\n');
461 			flushout(outx);
462 		}
463 
464 		setvar(n->nfor.var, sp->text, 0);
465 		evaltree(n->nfor.body, flags & EV_TESTED);
466 		status = exitstatus;
467 		if (nflag)
468 			break;
469 		if (evalskip) {
470 			if (evalskip == SKIPCONT && --skipcount <= 0) {
471 				evalskip = SKIPNONE;
472 				continue;
473 			}
474 			if (evalskip == SKIPBREAK && --skipcount <= 0)
475 				evalskip = SKIPNONE;
476 			break;
477 		}
478 	}
479 	loopnest--;
480 	exitstatus = status;
481  out:
482 	popstackmark(&smark);
483 }
484 
485 
486 
487 STATIC void
488 evalcase(union node *n, int flags)
489 {
490 	union node *cp, *ncp;
491 	union node *patp;
492 	struct arglist arglist;
493 	struct stackmark smark;
494 	int status = 0;
495 
496 	setstackmark(&smark);
497 	arglist.lastp = &arglist.list;
498 	line_number = n->ncase.lineno;
499 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
500 	for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
501 		for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
502 			line_number = patp->narg.lineno;
503 			if (casematch(patp, arglist.list->text)) {
504 				while (cp != NULL && evalskip == 0 &&
505 				    nflag == 0) {
506 					if (cp->type == NCLISTCONT)
507 						ncp = cp->nclist.next;
508 					else
509 						ncp = NULL;
510 					line_number = cp->nclist.lineno;
511 					evaltree(cp->nclist.body, flags);
512 					status = exitstatus;
513 					cp = ncp;
514 				}
515 				goto out;
516 			}
517 		}
518 	}
519  out:
520 	exitstatus = status;
521 	popstackmark(&smark);
522 }
523 
524 
525 
526 /*
527  * Kick off a subshell to evaluate a tree.
528  */
529 
530 STATIC void
531 evalsubshell(union node *n, int flags)
532 {
533 	struct job *jp= NULL;
534 	int backgnd = (n->type == NBACKGND);
535 
536 	expredir(n->nredir.redirect);
537 	if (xflag && n->nredir.redirect) {
538 		union node *rn;
539 
540 		outxstr(expandstr(ps4val(), line_number));
541 		outxstr("using redirections:");
542 		for (rn = n->nredir.redirect; rn; rn = rn->nfile.next)
543 			(void) outredir(outx, rn, ' ');
544 		outxstr(" do subshell ("/*)*/);
545 		if (backgnd)
546 			outxstr(/*(*/") &");
547 		outxc('\n');
548 		flushout(outx);
549 	}
550 	INTOFF;
551 	if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
552 	    forkshell(jp = makejob(n, 1), n, backgnd?FORK_BG:FORK_FG) == 0) {
553 		if (backgnd)
554 			flags &=~ EV_TESTED;
555 		INTON;
556 		redirect(n->nredir.redirect, REDIR_KEEP);
557 		evaltree(n->nredir.n, flags | EV_EXIT);   /* never returns */
558 	} else if (backgnd)
559 		exitstatus = 0;
560 	else
561 		exitstatus = waitforjob(jp);
562 	INTON;
563 
564 	if (!backgnd && xflag && n->nredir.redirect) {
565 		outxstr(expandstr(ps4val(), line_number));
566 		outxstr(/*(*/") done subshell\n");
567 		flushout(outx);
568 	}
569 }
570 
571 
572 
573 /*
574  * Compute the names of the files in a redirection list.
575  */
576 
577 STATIC void
578 expredir(union node *n)
579 {
580 	union node *redir;
581 
582 	for (redir = n ; redir ; redir = redir->nfile.next) {
583 		struct arglist fn;
584 
585 		fn.lastp = &fn.list;
586 		switch (redir->type) {
587 		case NFROMTO:
588 		case NFROM:
589 		case NTO:
590 		case NCLOBBER:
591 		case NAPPEND:
592 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
593 			redir->nfile.expfname = fn.list->text;
594 			break;
595 		case NFROMFD:
596 		case NTOFD:
597 			if (redir->ndup.vname) {
598 				expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
599 				fixredir(redir, fn.list->text, 1);
600 			}
601 			break;
602 		}
603 	}
604 }
605 
606 /*
607  * Perform redirections for a compound command, and then do it (and restore)
608  */
609 STATIC void
610 evalredir(union node *n, int flags)
611 {
612 	struct jmploc jmploc;
613 	struct jmploc * const savehandler = handler;
614 	volatile int in_redirect = 1;
615 	const char * volatile PS4 = NULL;
616 
617 	expredir(n->nredir.redirect);
618 
619 	if (xflag && n->nredir.redirect) {
620 		union node *rn;
621 
622 		outxstr(PS4 = expandstr(ps4val(), line_number));
623 		outxstr("using redirections:");
624 		for (rn = n->nredir.redirect; rn != NULL; rn = rn->nfile.next)
625 			(void) outredir(outx, rn, ' ');
626 		outxstr(" do {\n");	/* } */
627 		flushout(outx);
628 	}
629 
630 	if (setjmp(jmploc.loc)) {
631 		int e;
632 
633 		handler = savehandler;
634 		e = exception;
635 		popredir();
636 		if (PS4 != NULL) {
637 			outxstr(PS4);
638 			/* { */ outxstr("} failed\n");
639 			flushout(outx);
640 		}
641 		if (e == EXERROR || e == EXEXEC) {
642 			if (in_redirect) {
643 				exitstatus = 2;
644 				return;
645 			}
646 		}
647 		longjmp(handler->loc, 1);
648 	} else {
649 		INTOFF;
650 		handler = &jmploc;
651 		redirect(n->nredir.redirect, REDIR_PUSH | REDIR_KEEP);
652 		in_redirect = 0;
653 		INTON;
654 		evaltree(n->nredir.n, flags);
655 	}
656 	INTOFF;
657 	handler = savehandler;
658 	popredir();
659 	INTON;
660 
661 	if (PS4 != NULL) {
662 		outxstr(PS4);
663 		/* { */ outxstr("} done\n");
664 		flushout(outx);
665 	}
666 }
667 
668 
669 /*
670  * Evaluate a pipeline.  All the processes in the pipeline are children
671  * of the process creating the pipeline.  (This differs from some versions
672  * of the shell, which make the last process in a pipeline the parent
673  * of all the rest.)
674  */
675 
676 STATIC void
677 evalpipe(union node *n)
678 {
679 	struct job *jp;
680 	struct nodelist *lp;
681 	int pipelen;
682 	int prevfd;
683 	int pip[2];
684 
685 	CTRACE(DBG_EVAL, ("evalpipe(%p) called\n", n));
686 	pipelen = 0;
687 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
688 		pipelen++;
689 	INTOFF;
690 	jp = makejob(n, pipelen);
691 	prevfd = -1;
692 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
693 		prehash(lp->n);
694 		pip[1] = -1;
695 		if (lp->next) {
696 			if (sh_pipe(pip) < 0) {
697 				if (prevfd >= 0)
698 					close(prevfd);
699 				error("Pipe call failed: %s", strerror(errno));
700 			}
701 		}
702 		if (forkshell(jp, lp->n,
703 		    n->npipe.backgnd ? FORK_BG : FORK_FG) == 0) {
704 			INTON;
705 			if (prevfd > 0)
706 				movefd(prevfd, 0);
707 			if (pip[1] >= 0) {
708 				close(pip[0]);
709 				movefd(pip[1], 1);
710 			}
711 			evaltree(lp->n, EV_EXIT);
712 		}
713 		if (prevfd >= 0)
714 			close(prevfd);
715 		prevfd = pip[0];
716 		close(pip[1]);
717 	}
718 	if (n->npipe.backgnd == 0) {
719 		exitstatus = waitforjob(jp);
720 		CTRACE(DBG_EVAL, ("evalpipe:  job done exit status %d\n",
721 		    exitstatus));
722 	} else
723 		exitstatus = 0;
724 	INTON;
725 }
726 
727 
728 
729 /*
730  * Execute a command inside back quotes.  If it's a builtin command, we
731  * want to save its output in a block obtained from malloc.  Otherwise
732  * we fork off a subprocess and get the output of the command via a pipe.
733  * Should be called with interrupts off.
734  */
735 
736 void
737 evalbackcmd(union node *n, struct backcmd *result)
738 {
739 	int pip[2];
740 	struct job *jp;
741 	struct stackmark smark;		/* unnecessary (because we fork) */
742 
743 	result->fd = -1;
744 	result->buf = NULL;
745 	result->nleft = 0;
746 	result->jp = NULL;
747 
748 	if (nflag || n == NULL)
749 		goto out;
750 
751 	setstackmark(&smark);
752 
753 #ifdef notyet
754 	/*
755 	 * For now we disable executing builtins in the same
756 	 * context as the shell, because we are not keeping
757 	 * enough state to recover from changes that are
758 	 * supposed only to affect subshells. eg. echo "`cd /`"
759 	 */
760 	if (n->type == NCMD) {
761 		exitstatus = oexitstatus;	/* XXX o... no longer exists */
762 		evalcommand(n, EV_BACKCMD, result);
763 	} else
764 #endif
765 	{
766 		INTOFF;
767 		if (sh_pipe(pip) < 0)
768 			error("Pipe call failed");
769 		jp = makejob(n, 1);
770 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
771 			FORCEINTON;
772 			close(pip[0]);
773 			movefd(pip[1], 1);
774 			evaltree(n, EV_EXIT);
775 			/* NOTREACHED */
776 		}
777 		close(pip[1]);
778 		result->fd = pip[0];
779 		result->jp = jp;
780 		INTON;
781 	}
782 	popstackmark(&smark);
783  out:
784 	CTRACE(DBG_EVAL, ("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
785 		result->fd, result->buf, result->nleft, result->jp));
786 }
787 
788 const char *
789 syspath(void)
790 {
791 	static char *sys_path = NULL;
792 	static int mib[] = {CTL_USER, USER_CS_PATH};
793 	static char def_path[] = "PATH=/usr/bin:/bin:/usr/sbin:/sbin";
794 	size_t len;
795 
796 	if (sys_path == NULL) {
797 		if (sysctl(mib, 2, 0, &len, 0, 0) != -1 &&
798 		    (sys_path = ckmalloc(len + 5)) != NULL &&
799 		    sysctl(mib, 2, sys_path + 5, &len, 0, 0) != -1) {
800 			memcpy(sys_path, "PATH=", 5);
801 		} else {
802 			ckfree(sys_path);
803 			/* something to keep things happy */
804 			sys_path = def_path;
805 		}
806 	}
807 	return sys_path;
808 }
809 
810 static int
811 parse_command_args(int argc, char **argv, int *use_syspath)
812 {
813 	int sv_argc = argc;
814 	char *cp, c;
815 
816 	*use_syspath = 0;
817 
818 	for (;;) {
819 		argv++;
820 		if (--argc == 0)
821 			break;
822 		cp = *argv;
823 		if (*cp++ != '-')
824 			break;
825 		if (*cp == '-' && cp[1] == 0) {
826 			argv++;
827 			argc--;
828 			break;
829 		}
830 		while ((c = *cp++)) {
831 			switch (c) {
832 			case 'p':
833 				*use_syspath = 1;
834 				break;
835 			default:
836 				/* run 'typecmd' for other options */
837 				return 0;
838 			}
839 		}
840 	}
841 	return sv_argc - argc;
842 }
843 
844 int vforked = 0;
845 
846 /*
847  * Execute a simple command.
848  */
849 
850 STATIC void
851 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd)
852 {
853 	struct stackmark smark;
854 	union node *argp;
855 	struct arglist arglist;
856 	struct arglist varlist;
857 	volatile int flags = flgs;
858 	char ** volatile argv;
859 	volatile int argc;
860 	char **envp;
861 	int varflag;
862 	struct strlist *sp;
863 	volatile int mode;
864 	int pip[2];
865 	struct cmdentry cmdentry;
866 	struct job * volatile jp;
867 	struct jmploc jmploc;
868 	struct jmploc *volatile savehandler = NULL;
869 	const char *volatile savecmdname;
870 	volatile struct shparam saveparam;
871 	struct localvar *volatile savelocalvars;
872 	struct parsefile *volatile savetopfile;
873 	volatile int e;
874 	char * volatile lastarg;
875 	const char * volatile path = pathval();
876 	volatile int temp_path;
877 	const int savefuncline = funclinebase;
878 	const int savefuncabs = funclineabs;
879 	volatile int cmd_flags = 0;
880 
881 	vforked = 0;
882 	/* First expand the arguments. */
883 	CTRACE(DBG_EVAL, ("evalcommand(%p, %d) called [%s]\n", cmd, flags,
884 	    cmd->ncmd.args ? cmd->ncmd.args->narg.text : ""));
885 	setstackmark(&smark);
886 	back_exitstatus = 0;
887 
888 	line_number = cmd->ncmd.lineno;
889 
890 	arglist.lastp = &arglist.list;
891 	varflag = 1;
892 	/* Expand arguments, ignoring the initial 'name=value' ones */
893 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
894 		if (varflag && isassignment(argp->narg.text))
895 			continue;
896 		varflag = 0;
897 		line_number = argp->narg.lineno;
898 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
899 	}
900 	*arglist.lastp = NULL;
901 
902 	expredir(cmd->ncmd.redirect);
903 
904 	/* Now do the initial 'name=value' ones we skipped above */
905 	varlist.lastp = &varlist.list;
906 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
907 		line_number = argp->narg.lineno;
908 		if (!isassignment(argp->narg.text))
909 			break;
910 		expandarg(argp, &varlist, EXP_VARTILDE);
911 	}
912 	*varlist.lastp = NULL;
913 
914 	argc = 0;
915 	for (sp = arglist.list ; sp ; sp = sp->next)
916 		argc++;
917 	argv = stalloc(sizeof (char *) * (argc + 1));
918 
919 	for (sp = arglist.list ; sp ; sp = sp->next) {
920 		VTRACE(DBG_EVAL, ("evalcommand arg: %s\n", sp->text));
921 		*argv++ = sp->text;
922 	}
923 	*argv = NULL;
924 	lastarg = NULL;
925 	if (iflag && funcnest == 0 && argc > 0)
926 		lastarg = argv[-1];
927 	argv -= argc;
928 
929 	/* Print the command if xflag is set. */
930 	if (xflag) {
931 		char sep = 0;
932 		union node *rn;
933 
934 		outxstr(expandstr(ps4val(), line_number));
935 		for (sp = varlist.list ; sp ; sp = sp->next) {
936 			char *p;
937 
938 			if (sep != 0)
939 				outxc(sep);
940 
941 			/*
942 			 * The "var=" part should not be quoted, regardless
943 			 * of the value, or it would not represent an
944 			 * assignment, but rather a command
945 			 */
946 			p = strchr(sp->text, '=');
947 			if (p != NULL) {
948 				*p = '\0';	/*XXX*/
949 				outxshstr(sp->text);
950 				outxc('=');
951 				*p++ = '=';	/*XXX*/
952 			} else
953 				p = sp->text;
954 			outxshstr(p);
955 			sep = ' ';
956 		}
957 		for (sp = arglist.list ; sp ; sp = sp->next) {
958 			if (sep != 0)
959 				outxc(sep);
960 			outxshstr(sp->text);
961 			sep = ' ';
962 		}
963 		for (rn = cmd->ncmd.redirect; rn; rn = rn->nfile.next)
964 			if (outredir(outx, rn, sep))
965 				sep = ' ';
966 		outxc('\n');
967 		flushout(outx);
968 	}
969 
970 	/* Now locate the command. */
971 	if (argc == 0) {
972 		/*
973 		 * the empty command begins as a normal builtin, and
974 		 * remains that way while redirects are processed, then
975 		 * will become special before we get to doing the
976 		 * var assigns.
977 		 */
978 		cmdentry.cmdtype = CMDBUILTIN;
979 		cmdentry.u.bltin = bltincmd;
980 		VTRACE(DBG_CMDS, ("No command name, assume \"comamnd\"\n"));
981 	} else {
982 		static const char PATH[] = "PATH=";
983 
984 		/*
985 		 * Modify the command lookup path, if a PATH= assignment
986 		 * is present
987 		 */
988 		for (sp = varlist.list; sp; sp = sp->next)
989 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0)
990 				path = sp->text + sizeof(PATH) - 1;
991 
992 		do {
993 			int argsused, use_syspath;
994 
995 			find_command(argv[0], &cmdentry, cmd_flags, path);
996 			VTRACE(DBG_CMDS, ("Command %s type %d\n", argv[0],
997 			    cmdentry.cmdtype));
998 #if 0
999 			/*
1000 			 * This short circuits all of the processing that
1001 			 * should be done (including processing the
1002 			 * redirects), so just don't ...
1003 			 *
1004 			 * (eventually this whole #if'd block will vanish)
1005 			 */
1006 			if (cmdentry.cmdtype == CMDUNKNOWN) {
1007 				exitstatus = 127;
1008 				flushout(&errout);
1009 				goto out;
1010 			}
1011 #endif
1012 
1013 			/* implement the 'command' builtin here */
1014 			if (cmdentry.cmdtype != CMDBUILTIN ||
1015 			    cmdentry.u.bltin != bltincmd)
1016 				break;
1017 			VTRACE(DBG_CMDS, ("Command \"command\"\n"));
1018 			cmd_flags |= DO_NOFUNC;
1019 			argsused = parse_command_args(argc, argv, &use_syspath);
1020 			if (argsused == 0) {
1021 				/* use 'type' builtin to display info */
1022 				VTRACE(DBG_CMDS,
1023 				    ("Command \"command\" -> \"type\"\n"));
1024 				cmdentry.u.bltin = typecmd;
1025 				break;
1026 			}
1027 			argc -= argsused;
1028 			argv += argsused;
1029 			if (use_syspath)
1030 				path = syspath() + 5;
1031 		} while (argc != 0);
1032 		if (cmdentry.cmdtype == CMDSPLBLTIN && cmd_flags & DO_NOFUNC)
1033 			/* posix mandates that 'command <splbltin>' act as if
1034 			   <splbltin> was a normal builtin */
1035 			cmdentry.cmdtype = CMDBUILTIN;
1036 	}
1037 
1038 	/*
1039 	 * When traps are invalid, we permit the following:
1040 	 *	trap
1041 	 *	command trap
1042 	 *	eval trap
1043 	 *	command eval trap
1044 	 *	eval command trap
1045 	 * without zapping the traps completely, in all other cases we do.
1046 	 *
1047 	 * The test here permits eval "anything" but when evalstring() comes
1048 	 * back here again, the "anything" will be validated.
1049 	 * This means we can actually do:
1050 	 *	eval eval eval command eval eval command trap
1051 	 * as long as we end up with just "trap"
1052 	 *
1053 	 * We permit "command" by allowing CMDBUILTIN as well as CMDSPLBLTIN
1054 	 *
1055 	 * trapcmd() takes care of doing free_traps() if it is needed there.
1056 	 */
1057 	if (traps_invalid &&
1058 	    ((cmdentry.cmdtype!=CMDSPLBLTIN && cmdentry.cmdtype!=CMDBUILTIN) ||
1059 	     (cmdentry.u.bltin != trapcmd && cmdentry.u.bltin != evalcmd)))
1060 		free_traps();
1061 
1062 	/* Fork off a child process if necessary. */
1063 	if (cmd->ncmd.backgnd
1064 	  || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
1065 	     && (have_traps() || (flags & EV_EXIT) == 0))
1066 #ifdef notyet			/* EV_BACKCMD is never set currently */
1067 			/* this will need more work if/when it gets used */
1068 	  || ((flags & EV_BACKCMD) != 0
1069 	     && (cmdentry.cmdtype != CMDBUILTIN
1070 	         && cmdentry.cmdtype != CMDSPLBLTIN)
1071 	       || cmdentry.u.bltin == dotcmd
1072 	       || cmdentry.u.bltin == evalcmd)
1073 #endif
1074 	 ) {
1075 		INTOFF;
1076 		jp = makejob(cmd, 1);
1077 		mode = cmd->ncmd.backgnd;
1078 		if (flags & EV_BACKCMD) {
1079 			mode = FORK_NOJOB;
1080 			if (sh_pipe(pip) < 0)
1081 				error("Pipe call failed");
1082 		}
1083 #ifdef DO_SHAREDVFORK
1084 		/* It is essential that if DO_SHAREDVFORK is defined that the
1085 		 * child's address space is actually shared with the parent as
1086 		 * we rely on this.
1087 		 */
1088 		if (usefork == 0 && cmdentry.cmdtype == CMDNORMAL &&
1089 		    (!cmd->ncmd.backgnd || cmd->ncmd.redirect == NULL)) {
1090 			pid_t	pid;
1091 			int serrno;
1092 
1093 			savelocalvars = localvars;
1094 			localvars = NULL;
1095 			vforked = 1;
1096 	VFORK_BLOCK
1097 			switch (pid = vfork()) {
1098 			case -1:
1099 				serrno = errno;
1100 				VTRACE(DBG_EVAL, ("vfork() failed, errno=%d\n",
1101 				    serrno));
1102 				INTON;
1103 				error("Cannot vfork (%s)", strerror(serrno));
1104 				break;
1105 			case 0:
1106 				/* Make sure that exceptions only unwind to
1107 				 * after the vfork(2)
1108 				 */
1109 				SHELL_FORKED();
1110 				if (setjmp(jmploc.loc)) {
1111 					if (exception == EXSHELLPROC) {
1112 						/*
1113 						 * We can't progress with the
1114 						 * vfork, so, set vforked = 2
1115 						 * so the parent knows,
1116 						 * and _exit();
1117 						 */
1118 						vforked = 2;
1119 						_exit(0);
1120 					} else {
1121 						_exit(exception == EXEXIT ?
1122 						    exitstatus : exerrno);
1123 					}
1124 				}
1125 				savehandler = handler;
1126 				handler = &jmploc;
1127 				listmklocal(varlist.list,
1128 				    VDOEXPORT | VEXPORT | VNOFUNC);
1129 				forkchild(jp, cmd, mode, vforked);
1130 				break;
1131 			default:
1132 				VFORK_UNDO();
1133 						/* restore from vfork(2) */
1134 				CTRACE(DBG_PROCS|DBG_CMDS,
1135 				    ("parent after vfork - vforked=%d\n",
1136 				      vforked));
1137 				handler = savehandler;
1138 				poplocalvars();
1139 				localvars = savelocalvars;
1140 				if (vforked == 2) {
1141 					vforked = 0;
1142 
1143 					(void)waitpid(pid, NULL, 0);
1144 					/*
1145 					 * We need to progress in a
1146 					 * normal fork fashion
1147 					 */
1148 					goto normal_fork;
1149 				}
1150 				/*
1151 				 * Here the child has left home,
1152 				 * getting on with its life, so
1153 				 * so must we...
1154 				 */
1155 				vforked = 0;
1156 				forkparent(jp, cmd, mode, pid);
1157 				goto parent;
1158 			}
1159 	VFORK_END
1160 		} else {
1161  normal_fork:
1162 #endif
1163 			if (forkshell(jp, cmd, mode) != 0)
1164 				goto parent;	/* at end of routine */
1165 			CTRACE(DBG_PROCS|DBG_CMDS, ("Child sets EV_EXIT\n"));
1166 			flags |= EV_EXIT;
1167 			FORCEINTON;
1168 #ifdef DO_SHAREDVFORK
1169 		}
1170 #endif
1171 		if (flags & EV_BACKCMD) {
1172 			if (!vforked) {
1173 				FORCEINTON;
1174 			}
1175 			close(pip[0]);
1176 			movefd(pip[1], 1);
1177 		}
1178 		flags |= EV_EXIT;
1179 	}
1180 
1181 	/* This is the child process if a fork occurred. */
1182 	/* Execute the command. */
1183 	switch (cmdentry.cmdtype) {
1184 		volatile int saved;
1185 
1186 	case CMDFUNCTION:
1187 		VXTRACE(DBG_EVAL, ("Shell function%s:  ",vforked?" VF":""),
1188 		    trargs(argv));
1189 		redirect(cmd->ncmd.redirect, saved =
1190 			!(flags & EV_EXIT) || have_traps() ? REDIR_PUSH : 0);
1191 		saveparam = shellparam;
1192 		shellparam.malloc = 0;
1193 		shellparam.reset = 1;
1194 		shellparam.nparam = argc - 1;
1195 		shellparam.p = argv + 1;
1196 		shellparam.optnext = NULL;
1197 		INTOFF;
1198 		savelocalvars = localvars;
1199 		localvars = NULL;
1200 		reffunc(cmdentry.u.func);
1201 		INTON;
1202 		if (setjmp(jmploc.loc)) {
1203 			if (exception == EXSHELLPROC) {
1204 				freeparam((volatile struct shparam *)
1205 				    &saveparam);
1206 			} else {
1207 				freeparam(&shellparam);
1208 				shellparam = saveparam;
1209 			}
1210 			if (saved)
1211 				popredir();
1212 			unreffunc(cmdentry.u.func);
1213 			poplocalvars();
1214 			localvars = savelocalvars;
1215 			funclinebase = savefuncline;
1216 			funclineabs = savefuncabs;
1217 			handler = savehandler;
1218 			longjmp(handler->loc, 1);
1219 		}
1220 		savehandler = handler;
1221 		handler = &jmploc;
1222 		if (cmdentry.u.func) {
1223 			if (cmdentry.lno_frel)
1224 				funclinebase = cmdentry.lineno - 1;
1225 			else
1226 				funclinebase = 0;
1227 			funclineabs = cmdentry.lineno;
1228 
1229 			VTRACE(DBG_EVAL,
1230 			  ("function: node: %d '%s' # %d%s; funclinebase=%d\n",
1231 			    getfuncnode(cmdentry.u.func)->type,
1232 			    NODETYPENAME(getfuncnode(cmdentry.u.func)->type),
1233 			    cmdentry.lineno, cmdentry.lno_frel?" (=1)":"",
1234 			    funclinebase));
1235 		}
1236 		listmklocal(varlist.list, VDOEXPORT | VEXPORT);
1237 		/* stop shell blowing its stack */
1238 		if (++funcnest > 1000)
1239 			error("too many nested function calls");
1240 		evaltree(getfuncnode(cmdentry.u.func),
1241 		    flags & (EV_TESTED|EV_EXIT));
1242 		funcnest--;
1243 		INTOFF;
1244 		unreffunc(cmdentry.u.func);
1245 		poplocalvars();
1246 		localvars = savelocalvars;
1247 		funclinebase = savefuncline;
1248 		funclineabs = savefuncabs;
1249 		freeparam(&shellparam);
1250 		shellparam = saveparam;
1251 		handler = savehandler;
1252 		if (saved)
1253 			popredir();
1254 		INTON;
1255 		if (evalskip == SKIPFUNC) {
1256 			evalskip = SKIPNONE;
1257 			skipcount = 0;
1258 		}
1259 		if (flags & EV_EXIT)
1260 			exitshell(exitstatus);
1261 		break;
1262 
1263 	case CMDSPLBLTIN:
1264 		VTRACE(DBG_EVAL, ("special "));
1265 	case CMDBUILTIN:
1266 		VXTRACE(DBG_EVAL, ("builtin command [%d]%s:  ", argc,
1267 		    vforked ? " VF" : ""), trargs(argv));
1268 		mode = (cmdentry.u.bltin == execcmd) ? 0 : REDIR_PUSH;
1269 		if (flags == EV_BACKCMD) {
1270 			memout.nleft = 0;
1271 			memout.nextc = memout.buf;
1272 			memout.bufsize = 64;
1273 			mode |= REDIR_BACKQ;
1274 		}
1275 		e = -1;
1276 		savecmdname = commandname;
1277 		savetopfile = getcurrentfile();
1278 		savehandler = handler;
1279 		temp_path = 0;
1280 		if (!setjmp(jmploc.loc)) {
1281 			handler = &jmploc;
1282 
1283 			/*
1284 			 * We need to ensure the command hash table isn't
1285 			 * corrupted by temporary PATH assignments.
1286 			 * However we must ensure the 'local' command works!
1287 			 */
1288 			if (path != pathval() && (cmdentry.u.bltin == hashcmd ||
1289 			    cmdentry.u.bltin == typecmd)) {
1290 				savelocalvars = localvars;
1291 				localvars = 0;
1292 				temp_path = 1;
1293 				mklocal(path - 5 /* PATH= */, 0);
1294 			}
1295 			redirect(cmd->ncmd.redirect, mode);
1296 
1297 			/*
1298 			 * the empty command is regarded as a normal
1299 			 * builtin for the purposes of redirects, but
1300 			 * is a special builtin for var assigns.
1301 			 * (unless we are the "command" command.)
1302 			 */
1303 			if (argc == 0 && !(cmd_flags & DO_NOFUNC))
1304 				cmdentry.cmdtype = CMDSPLBLTIN;
1305 
1306 			/* exec is a special builtin, but needs this list... */
1307 			cmdenviron = varlist.list;
1308 			/* we must check 'readonly' flag for all builtins */
1309 			listsetvar(varlist.list,
1310 				cmdentry.cmdtype == CMDSPLBLTIN ? 0 : VNOSET);
1311 			commandname = argv[0];
1312 			/* initialize nextopt */
1313 			argptr = argv + 1;
1314 			optptr = NULL;
1315 			/* and getopt */
1316 			optreset = 1;
1317 			optind = 1;
1318 			builtin_flags = flags;
1319 			exitstatus = cmdentry.u.bltin(argc, argv);
1320 		} else {
1321 			e = exception;
1322 			if (e == EXINT)
1323 				exitstatus = SIGINT + 128;
1324 			else if (e == EXEXEC)
1325 				exitstatus = exerrno;
1326 			else if (e != EXEXIT)
1327 				exitstatus = 2;
1328 		}
1329 		handler = savehandler;
1330 		flushall();
1331 		out1 = &output;
1332 		out2 = &errout;
1333 		freestdout();
1334 		if (temp_path) {
1335 			poplocalvars();
1336 			localvars = savelocalvars;
1337 		}
1338 		cmdenviron = NULL;
1339 		if (e != EXSHELLPROC) {
1340 			commandname = savecmdname;
1341 			if (flags & EV_EXIT)
1342 				exitshell(exitstatus);
1343 		}
1344 		if (e != -1) {
1345 			if ((e != EXERROR && e != EXEXEC)
1346 			    || cmdentry.cmdtype == CMDSPLBLTIN)
1347 				exraise(e);
1348 			popfilesupto(savetopfile);
1349 			FORCEINTON;
1350 		}
1351 		if (cmdentry.u.bltin != execcmd)
1352 			popredir();
1353 		if (flags == EV_BACKCMD) {
1354 			backcmd->buf = memout.buf;
1355 			backcmd->nleft = memout.nextc - memout.buf;
1356 			memout.buf = NULL;
1357 		}
1358 		break;
1359 
1360 	default:
1361 		VXTRACE(DBG_EVAL, ("normal command%s:  ", vforked?" VF":""),
1362 		    trargs(argv));
1363 		redirect(cmd->ncmd.redirect,
1364 		    (vforked ? REDIR_VFORK : 0) | REDIR_KEEP);
1365 		if (!vforked)
1366 			for (sp = varlist.list ; sp ; sp = sp->next)
1367 				setvareq(sp->text, VDOEXPORT|VEXPORT|VSTACK);
1368 		envp = environment();
1369 		shellexec(argv, envp, path, cmdentry.u.index, vforked);
1370 		break;
1371 	}
1372 	goto out;
1373 
1374  parent:			/* parent process gets here (if we forked) */
1375 
1376 	exitstatus = 0;		/* if not altered just below */
1377 	if (mode == FORK_FG) {	/* argument to fork */
1378 		exitstatus = waitforjob(jp);
1379 	} else if (mode == FORK_NOJOB) {
1380 		backcmd->fd = pip[0];
1381 		close(pip[1]);
1382 		backcmd->jp = jp;
1383 	}
1384 	FORCEINTON;
1385 
1386  out:
1387 	if (lastarg)
1388 		/* implement $_ for whatever use that really is */
1389 		(void) setvarsafe("_", lastarg, VNOERROR);
1390 	popstackmark(&smark);
1391 }
1392 
1393 
1394 /*
1395  * Search for a command.  This is called before we fork so that the
1396  * location of the command will be available in the parent as well as
1397  * the child.  The check for "goodname" is an overly conservative
1398  * check that the name will not be subject to expansion.
1399  */
1400 
1401 STATIC void
1402 prehash(union node *n)
1403 {
1404 	struct cmdentry entry;
1405 
1406 	if (n && n->type == NCMD && n->ncmd.args)
1407 		if (goodname(n->ncmd.args->narg.text))
1408 			find_command(n->ncmd.args->narg.text, &entry, 0,
1409 				     pathval());
1410 }
1411 
1412 int
1413 in_function(void)
1414 {
1415 	return funcnest;
1416 }
1417 
1418 enum skipstate
1419 current_skipstate(void)
1420 {
1421 	return evalskip;
1422 }
1423 
1424 void
1425 save_skipstate(struct skipsave *p)
1426 {
1427 	*p = s_k_i_p;
1428 }
1429 
1430 void
1431 restore_skipstate(const struct skipsave *p)
1432 {
1433 	s_k_i_p = *p;
1434 }
1435 
1436 void
1437 stop_skipping(void)
1438 {
1439 	evalskip = SKIPNONE;
1440 	skipcount = 0;
1441 }
1442 
1443 /*
1444  * Builtin commands.  Builtin commands whose functions are closely
1445  * tied to evaluation are implemented here.
1446  */
1447 
1448 /*
1449  * No command given.
1450  */
1451 
1452 int
1453 bltincmd(int argc, char **argv)
1454 {
1455 	/*
1456 	 * Preserve exitstatus of a previous possible redirection
1457 	 * as POSIX mandates
1458 	 */
1459 	return back_exitstatus;
1460 }
1461 
1462 
1463 /*
1464  * Handle break and continue commands.  Break, continue, and return are
1465  * all handled by setting the evalskip flag.  The evaluation routines
1466  * above all check this flag, and if it is set they start skipping
1467  * commands rather than executing them.  The variable skipcount is
1468  * the number of loops to break/continue, or the number of function
1469  * levels to return.  (The latter is always 1.)  It should probably
1470  * be an error to break out of more loops than exist, but it isn't
1471  * in the standard shell so we don't make it one here.
1472  */
1473 
1474 int
1475 breakcmd(int argc, char **argv)
1476 {
1477 	int n = argc > 1 ? number(argv[1]) : 1;
1478 
1479 	if (n <= 0)
1480 		error("invalid count: %d", n);
1481 	if (n > loopnest)
1482 		n = loopnest;
1483 	if (n > 0) {
1484 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1485 		skipcount = n;
1486 	}
1487 	return 0;
1488 }
1489 
1490 int
1491 dotcmd(int argc, char **argv)
1492 {
1493 	exitstatus = 0;
1494 
1495 	(void) nextopt(NULL);		/* ignore a leading "--" */
1496 
1497 	if (*argptr != NULL) {		/* That's what SVR2 does */
1498 		char *fullname;
1499 		/*
1500 		 * dot_funcnest needs to be 0 when not in a dotcmd, so it
1501 		 * cannot be restored with (funcnest + 1).
1502 		 */
1503 		int dot_funcnest_old;
1504 		struct stackmark smark;
1505 
1506 		setstackmark(&smark);
1507 		fullname = find_dot_file(*argptr);
1508 		setinputfile(fullname, 1);
1509 		commandname = fullname;
1510 		dot_funcnest_old = dot_funcnest;
1511 		dot_funcnest = funcnest + 1;
1512 		cmdloop(0);
1513 		dot_funcnest = dot_funcnest_old;
1514 		popfile();
1515 		popstackmark(&smark);
1516 	}
1517 	return exitstatus;
1518 }
1519 
1520 /*
1521  * allow dotfile function nesting to be manipulated
1522  * (for read_profile).  This allows profile files to
1523  * be treated as if they were used as '.' commands,
1524  * (approximately) and in particular, for "return" to work.
1525  */
1526 int
1527 set_dot_funcnest(int new)
1528 {
1529 	int rv = dot_funcnest;
1530 
1531 	if (new >= 0)
1532 		dot_funcnest = new;
1533 
1534 	return rv;
1535 }
1536 
1537 /*
1538  * Take commands from a file.  To be compatible we should do a path
1539  * search for the file, which is necessary to find sub-commands.
1540  */
1541 
1542 STATIC char *
1543 find_dot_file(char *basename)
1544 {
1545 	char *fullname;
1546 	const char *path = pathval();
1547 	struct stat statb;
1548 
1549 	/* don't try this for absolute or relative paths */
1550 	if (strchr(basename, '/')) {
1551 		if (stat(basename, &statb) == 0) {
1552 			if (S_ISDIR(statb.st_mode))
1553 				error("%s: is a directory", basename);
1554 			if (S_ISBLK(statb.st_mode))
1555 				error("%s: is a block device", basename);
1556 			return basename;
1557 		}
1558 	} else while ((fullname = padvance(&path, basename, 1)) != NULL) {
1559 		if ((stat(fullname, &statb) == 0)) {
1560 			/* weird format is to ease future code... */
1561 			if (S_ISDIR(statb.st_mode) || S_ISBLK(statb.st_mode))
1562 				;
1563 #if notyet
1564 			else if (unreadable()) {
1565 				/*
1566 				 * testing this via st_mode is ugly to get
1567 				 * correct (and would ignore ACLs).
1568 				 * better way is just to open the file.
1569 				 * But doing that here would (currently)
1570 				 * mean opening the file twice, which
1571 				 * might not be safe.  So, defer this
1572 				 * test until code is restructures so
1573 				 * we can return a fd.   Then we also
1574 				 * get to fix the mem leak just below...
1575 				 */
1576 			}
1577 #endif
1578 			else {
1579 				/*
1580 				 * Don't bother freeing here, since
1581 				 * it will be freed by the caller.
1582 				 * XXX no it won't - a bug for later.
1583 				 */
1584 				return fullname;
1585 			}
1586 		}
1587 		stunalloc(fullname);
1588 	}
1589 
1590 	/* not found in the PATH */
1591 	error("%s: not found", basename);
1592 	/* NOTREACHED */
1593 }
1594 
1595 
1596 
1597 /*
1598  * The return command.
1599  *
1600  * Quoth the POSIX standard:
1601  *   The return utility shall cause the shell to stop executing the current
1602  *   function or dot script. If the shell is not currently executing
1603  *   a function or dot script, the results are unspecified.
1604  *
1605  * As for the unspecified part, there seems to be no de-facto standard: bash
1606  * ignores the return with a warning, zsh ignores the return in interactive
1607  * mode but seems to liken it to exit in a script.  (checked May 2014)
1608  *
1609  * We choose to silently ignore the return.  Older versions of this shell
1610  * set evalskip to SKIPFILE causing the shell to (indirectly) exit.  This
1611  * had at least the problem of circumventing the check for stopped jobs,
1612  * which would occur for exit or ^D.
1613  */
1614 
1615 int
1616 returncmd(int argc, char **argv)
1617 {
1618 	int ret = argc > 1 ? number(argv[1]) : exitstatus;
1619 
1620 	if ((dot_funcnest == 0 && funcnest)
1621 	    || (dot_funcnest > 0 && funcnest - (dot_funcnest - 1) > 0)) {
1622 		evalskip = SKIPFUNC;
1623 		skipcount = 1;
1624 	} else if (dot_funcnest > 0) {
1625 		evalskip = SKIPFILE;
1626 		skipcount = 1;
1627 	} else {
1628 		/* XXX: should a warning be issued? */
1629 		ret = 0;
1630 	}
1631 
1632 	return ret;
1633 }
1634 
1635 
1636 int
1637 falsecmd(int argc, char **argv)
1638 {
1639 	return 1;
1640 }
1641 
1642 
1643 int
1644 truecmd(int argc, char **argv)
1645 {
1646 	return 0;
1647 }
1648 
1649 
1650 int
1651 execcmd(int argc, char **argv)
1652 {
1653 	(void) nextopt(NULL);		/* ignore a leading "--" */
1654 
1655 	if (*argptr) {
1656 		struct strlist *sp;
1657 
1658 		iflag = 0;		/* exit on error */
1659 		mflag = 0;
1660 		optschanged();
1661 		for (sp = cmdenviron; sp; sp = sp->next)
1662 			setvareq(sp->text, VDOEXPORT|VEXPORT|VSTACK);
1663 		shellexec(argptr, environment(), pathval(), 0, 0);
1664 	}
1665 	return 0;
1666 }
1667 
1668 static int
1669 conv_time(clock_t ticks, char *seconds, size_t l)
1670 {
1671 	static clock_t tpm = 0;
1672 	clock_t mins;
1673 	int i;
1674 
1675 	if (!tpm)
1676 		tpm = sysconf(_SC_CLK_TCK) * 60;
1677 
1678 	mins = ticks / tpm;
1679 	snprintf(seconds, l, "%.4f", (ticks - mins * tpm) * 60.0 / tpm );
1680 
1681 	if (seconds[0] == '6' && seconds[1] == '0') {
1682 		/* 59.99995 got rounded up... */
1683 		mins++;
1684 		strlcpy(seconds, "0.0", l);
1685 		return mins;
1686 	}
1687 
1688 	/* suppress trailing zeros */
1689 	i = strlen(seconds) - 1;
1690 	for (; seconds[i] == '0' && seconds[i - 1] != '.'; i--)
1691 		seconds[i] = 0;
1692 	return mins;
1693 }
1694 
1695 int
1696 timescmd(int argc, char **argv)
1697 {
1698 	struct tms tms;
1699 	int u, s, cu, cs;
1700 	char us[8], ss[8], cus[8], css[8];
1701 
1702 	nextopt("");
1703 
1704 	times(&tms);
1705 
1706 	u = conv_time(tms.tms_utime, us, sizeof(us));
1707 	s = conv_time(tms.tms_stime, ss, sizeof(ss));
1708 	cu = conv_time(tms.tms_cutime, cus, sizeof(cus));
1709 	cs = conv_time(tms.tms_cstime, css, sizeof(css));
1710 
1711 	outfmt(out1, "%dm%ss %dm%ss\n%dm%ss %dm%ss\n",
1712 		u, us, s, ss, cu, cus, cs, css);
1713 
1714 	return 0;
1715 }
1716