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