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