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