Home | History | Annotate | Line # | Download | only in sh
eval.c revision 1.53
      1 /*	$NetBSD: eval.c,v 1.53 2000/05/13 21:11:45 elric 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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 #if 0
     42 static char sccsid[] = "@(#)eval.c	8.9 (Berkeley) 6/8/95";
     43 #else
     44 __RCSID("$NetBSD: eval.c,v 1.53 2000/05/13 21:11:45 elric Exp $");
     45 #endif
     46 #endif /* not lint */
     47 
     48 #include <errno.h>
     49 #include <fcntl.h>
     50 #include <paths.h>
     51 #include <signal.h>
     52 #include <unistd.h>
     53 
     54 #include <sys/types.h>
     55 #include <sys/wait.h>
     56 
     57 /*
     58  * Evaluate a command.
     59  */
     60 
     61 #include "main.h"
     62 #include "shell.h"
     63 #include "nodes.h"
     64 #include "syntax.h"
     65 #include "expand.h"
     66 #include "parser.h"
     67 #include "jobs.h"
     68 #include "eval.h"
     69 #include "builtins.h"
     70 #include "options.h"
     71 #include "exec.h"
     72 #include "redir.h"
     73 #include "input.h"
     74 #include "output.h"
     75 #include "trap.h"
     76 #include "var.h"
     77 #include "memalloc.h"
     78 #include "error.h"
     79 #include "show.h"
     80 #include "mystring.h"
     81 #ifndef SMALL
     82 #include "myhistedit.h"
     83 #endif
     84 
     85 
     86 /* flags in argument to evaltree */
     87 #define EV_EXIT 01		/* exit after evaluating tree */
     88 #define EV_TESTED 02		/* exit status is checked; ignore -e flag */
     89 #define EV_BACKCMD 04		/* command executing within back quotes */
     90 
     91 MKINIT int evalskip;		/* set if we are skipping commands */
     92 STATIC int skipcount;		/* number of levels to skip */
     93 MKINIT int loopnest;		/* current loop nesting level */
     94 int funcnest;			/* depth of function calls */
     95 
     96 
     97 char *commandname;
     98 struct strlist *cmdenviron;
     99 int exitstatus;			/* exit status of last command */
    100 int oexitstatus;		/* saved exit status */
    101 
    102 
    103 STATIC void evalloop __P((union node *, int));
    104 STATIC void evalfor __P((union node *, int));
    105 STATIC void evalcase __P((union node *, int));
    106 STATIC void evalsubshell __P((union node *, int));
    107 STATIC void expredir __P((union node *));
    108 STATIC void evalpipe __P((union node *));
    109 STATIC void evalcommand __P((union node *, int, struct backcmd *));
    110 STATIC void prehash __P((union node *));
    111 
    112 
    113 /*
    114  * Called to reset things after an exception.
    115  */
    116 
    117 #ifdef mkinit
    118 INCLUDE "eval.h"
    119 
    120 RESET {
    121 	evalskip = 0;
    122 	loopnest = 0;
    123 	funcnest = 0;
    124 }
    125 
    126 SHELLPROC {
    127 	exitstatus = 0;
    128 }
    129 #endif
    130 
    131 
    132 
    133 /*
    134  * The eval commmand.
    135  */
    136 
    137 int
    138 evalcmd(argc, argv)
    139 	int argc;
    140 	char **argv;
    141 {
    142         char *p;
    143         char *concat;
    144         char **ap;
    145 
    146         if (argc > 1) {
    147                 p = argv[1];
    148                 if (argc > 2) {
    149                         STARTSTACKSTR(concat);
    150                         ap = argv + 2;
    151                         for (;;) {
    152                                 while (*p)
    153                                         STPUTC(*p++, concat);
    154                                 if ((p = *ap++) == NULL)
    155                                         break;
    156                                 STPUTC(' ', concat);
    157                         }
    158                         STPUTC('\0', concat);
    159                         p = grabstackstr(concat);
    160                 }
    161                 evalstring(p, EV_TESTED);
    162         }
    163         return exitstatus;
    164 }
    165 
    166 
    167 /*
    168  * Execute a command or commands contained in a string.
    169  */
    170 
    171 void
    172 evalstring(s, flag)
    173 	char *s;
    174 	int flag;
    175 	{
    176 	union node *n;
    177 	struct stackmark smark;
    178 
    179 	setstackmark(&smark);
    180 	setinputstring(s, 1);
    181 	while ((n = parsecmd(0)) != NEOF) {
    182 		evaltree(n, flag);
    183 		popstackmark(&smark);
    184 	}
    185 	popfile();
    186 	popstackmark(&smark);
    187 }
    188 
    189 
    190 
    191 /*
    192  * Evaluate a parse tree.  The value is left in the global variable
    193  * exitstatus.
    194  */
    195 
    196 void
    197 evaltree(n, flags)
    198 	union node *n;
    199 	int flags;
    200 {
    201 	if (n == NULL) {
    202 		TRACE(("evaltree(NULL) called\n"));
    203 		exitstatus = 0;
    204 		goto out;
    205 	}
    206 #ifndef SMALL
    207 	displayhist = 1;	/* show history substitutions done with fc */
    208 #endif
    209 	TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
    210 	switch (n->type) {
    211 	case NSEMI:
    212 		evaltree(n->nbinary.ch1, flags & EV_TESTED);
    213 		if (evalskip)
    214 			goto out;
    215 		evaltree(n->nbinary.ch2, flags);
    216 		break;
    217 	case NAND:
    218 		evaltree(n->nbinary.ch1, EV_TESTED);
    219 		if (evalskip || exitstatus != 0) {
    220 			/* don't bomb out on "set -e; false && true" */
    221 			flags |= EV_TESTED;
    222 			goto out;
    223 		}
    224 		evaltree(n->nbinary.ch2, flags | EV_TESTED);
    225 		break;
    226 	case NOR:
    227 		evaltree(n->nbinary.ch1, EV_TESTED);
    228 		if (evalskip || exitstatus == 0)
    229 			goto out;
    230 		evaltree(n->nbinary.ch2, flags | EV_TESTED);
    231 		break;
    232 	case NREDIR:
    233 		expredir(n->nredir.redirect);
    234 		redirect(n->nredir.redirect, REDIR_PUSH);
    235 		evaltree(n->nredir.n, flags);
    236 		popredir();
    237 		break;
    238 	case NSUBSHELL:
    239 		evalsubshell(n, flags);
    240 		break;
    241 	case NBACKGND:
    242 		evalsubshell(n, flags);
    243 		break;
    244 	case NIF: {
    245 		evaltree(n->nif.test, EV_TESTED);
    246 		if (evalskip)
    247 			goto out;
    248 		if (exitstatus == 0)
    249 			evaltree(n->nif.ifpart, flags);
    250 		else if (n->nif.elsepart)
    251 			evaltree(n->nif.elsepart, flags);
    252 		else
    253 			exitstatus = 0;
    254 		break;
    255 	}
    256 	case NWHILE:
    257 	case NUNTIL:
    258 		evalloop(n, flags);
    259 		break;
    260 	case NFOR:
    261 		evalfor(n, flags);
    262 		break;
    263 	case NCASE:
    264 		evalcase(n, flags);
    265 		break;
    266 	case NDEFUN:
    267 		defun(n->narg.text, n->narg.next);
    268 		exitstatus = 0;
    269 		break;
    270 	case NNOT:
    271 		evaltree(n->nnot.com, EV_TESTED);
    272 		exitstatus = !exitstatus;
    273 		break;
    274 
    275 	case NPIPE:
    276 		evalpipe(n);
    277 		break;
    278 	case NCMD:
    279 		evalcommand(n, flags, (struct backcmd *)NULL);
    280 		break;
    281 	default:
    282 		out1fmt("Node type = %d\n", n->type);
    283 		flushout(&output);
    284 		break;
    285 	}
    286 out:
    287 	if (pendingsigs)
    288 		dotrap();
    289 	if ((flags & EV_EXIT) || (eflag && exitstatus && !(flags & EV_TESTED)))
    290 		exitshell(exitstatus);
    291 }
    292 
    293 
    294 STATIC void
    295 evalloop(n, flags)
    296 	union node *n;
    297 	int flags;
    298 {
    299 	int status;
    300 
    301 	loopnest++;
    302 	status = 0;
    303 	for (;;) {
    304 		evaltree(n->nbinary.ch1, EV_TESTED);
    305 		if (evalskip) {
    306 skipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
    307 				evalskip = 0;
    308 				continue;
    309 			}
    310 			if (evalskip == SKIPBREAK && --skipcount <= 0)
    311 				evalskip = 0;
    312 			break;
    313 		}
    314 		if (n->type == NWHILE) {
    315 			if (exitstatus != 0)
    316 				break;
    317 		} else {
    318 			if (exitstatus == 0)
    319 				break;
    320 		}
    321 		evaltree(n->nbinary.ch2, flags & EV_TESTED);
    322 		status = exitstatus;
    323 		if (evalskip)
    324 			goto skipping;
    325 	}
    326 	loopnest--;
    327 	exitstatus = status;
    328 }
    329 
    330 
    331 
    332 STATIC void
    333 evalfor(n, flags)
    334     union node *n;
    335     int flags;
    336 {
    337 	struct arglist arglist;
    338 	union node *argp;
    339 	struct strlist *sp;
    340 	struct stackmark smark;
    341 
    342 	setstackmark(&smark);
    343 	arglist.lastp = &arglist.list;
    344 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
    345 		oexitstatus = exitstatus;
    346 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
    347 		if (evalskip)
    348 			goto out;
    349 	}
    350 	*arglist.lastp = NULL;
    351 
    352 	exitstatus = 0;
    353 	loopnest++;
    354 	for (sp = arglist.list ; sp ; sp = sp->next) {
    355 		setvar(n->nfor.var, sp->text, 0);
    356 		evaltree(n->nfor.body, flags & EV_TESTED);
    357 		if (evalskip) {
    358 			if (evalskip == SKIPCONT && --skipcount <= 0) {
    359 				evalskip = 0;
    360 				continue;
    361 			}
    362 			if (evalskip == SKIPBREAK && --skipcount <= 0)
    363 				evalskip = 0;
    364 			break;
    365 		}
    366 	}
    367 	loopnest--;
    368 out:
    369 	popstackmark(&smark);
    370 }
    371 
    372 
    373 
    374 STATIC void
    375 evalcase(n, flags)
    376 	union node *n;
    377 	int flags;
    378 {
    379 	union node *cp;
    380 	union node *patp;
    381 	struct arglist arglist;
    382 	struct stackmark smark;
    383 
    384 	setstackmark(&smark);
    385 	arglist.lastp = &arglist.list;
    386 	oexitstatus = exitstatus;
    387 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
    388 	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
    389 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
    390 			if (casematch(patp, arglist.list->text)) {
    391 				if (evalskip == 0) {
    392 					evaltree(cp->nclist.body, flags);
    393 				}
    394 				goto out;
    395 			}
    396 		}
    397 	}
    398 out:
    399 	popstackmark(&smark);
    400 }
    401 
    402 
    403 
    404 /*
    405  * Kick off a subshell to evaluate a tree.
    406  */
    407 
    408 STATIC void
    409 evalsubshell(n, flags)
    410 	union node *n;
    411 	int flags;
    412 {
    413 	struct job *jp;
    414 	int backgnd = (n->type == NBACKGND);
    415 
    416 	expredir(n->nredir.redirect);
    417 	jp = makejob(n, 1);
    418 	if (forkshell(jp, n, backgnd) == 0) {
    419 		if (backgnd)
    420 			flags &=~ EV_TESTED;
    421 		redirect(n->nredir.redirect, 0);
    422 		evaltree(n->nredir.n, flags | EV_EXIT);	/* never returns */
    423 	}
    424 	if (! backgnd) {
    425 		INTOFF;
    426 		exitstatus = waitforjob(jp);
    427 		INTON;
    428 	}
    429 }
    430 
    431 
    432 
    433 /*
    434  * Compute the names of the files in a redirection list.
    435  */
    436 
    437 STATIC void
    438 expredir(n)
    439 	union node *n;
    440 {
    441 	union node *redir;
    442 
    443 	for (redir = n ; redir ; redir = redir->nfile.next) {
    444 		struct arglist fn;
    445 		fn.lastp = &fn.list;
    446 		oexitstatus = exitstatus;
    447 		switch (redir->type) {
    448 		case NFROMTO:
    449 		case NFROM:
    450 		case NTO:
    451 		case NAPPEND:
    452 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
    453 			redir->nfile.expfname = fn.list->text;
    454 			break;
    455 		case NFROMFD:
    456 		case NTOFD:
    457 			if (redir->ndup.vname) {
    458 				expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
    459 				fixredir(redir, fn.list->text, 1);
    460 			}
    461 			break;
    462 		}
    463 	}
    464 }
    465 
    466 
    467 
    468 /*
    469  * Evaluate a pipeline.  All the processes in the pipeline are children
    470  * of the process creating the pipeline.  (This differs from some versions
    471  * of the shell, which make the last process in a pipeline the parent
    472  * of all the rest.)
    473  */
    474 
    475 STATIC void
    476 evalpipe(n)
    477 	union node *n;
    478 {
    479 	struct job *jp;
    480 	struct nodelist *lp;
    481 	int pipelen;
    482 	int prevfd;
    483 	int pip[2];
    484 
    485 	TRACE(("evalpipe(0x%lx) called\n", (long)n));
    486 	pipelen = 0;
    487 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
    488 		pipelen++;
    489 	INTOFF;
    490 	jp = makejob(n, pipelen);
    491 	prevfd = -1;
    492 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
    493 		prehash(lp->n);
    494 		pip[1] = -1;
    495 		if (lp->next) {
    496 			if (pipe(pip) < 0) {
    497 				close(prevfd);
    498 				error("Pipe call failed");
    499 			}
    500 		}
    501 		if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
    502 			INTON;
    503 			if (prevfd > 0) {
    504 				close(0);
    505 				copyfd(prevfd, 0);
    506 				close(prevfd);
    507 			}
    508 			if (pip[1] >= 0) {
    509 				close(pip[0]);
    510 				if (pip[1] != 1) {
    511 					close(1);
    512 					copyfd(pip[1], 1);
    513 					close(pip[1]);
    514 				}
    515 			}
    516 			evaltree(lp->n, EV_EXIT);
    517 		}
    518 		if (prevfd >= 0)
    519 			close(prevfd);
    520 		prevfd = pip[0];
    521 		close(pip[1]);
    522 	}
    523 	INTON;
    524 	if (n->npipe.backgnd == 0) {
    525 		INTOFF;
    526 		exitstatus = waitforjob(jp);
    527 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
    528 		INTON;
    529 	}
    530 }
    531 
    532 
    533 
    534 /*
    535  * Execute a command inside back quotes.  If it's a builtin command, we
    536  * want to save its output in a block obtained from malloc.  Otherwise
    537  * we fork off a subprocess and get the output of the command via a pipe.
    538  * Should be called with interrupts off.
    539  */
    540 
    541 void
    542 evalbackcmd(n, result)
    543 	union node *n;
    544 	struct backcmd *result;
    545 {
    546 	int pip[2];
    547 	struct job *jp;
    548 	struct stackmark smark;		/* unnecessary */
    549 
    550 	setstackmark(&smark);
    551 	result->fd = -1;
    552 	result->buf = NULL;
    553 	result->nleft = 0;
    554 	result->jp = NULL;
    555 	if (n == NULL) {
    556 		exitstatus = 0;
    557 		goto out;
    558 	}
    559 #ifdef notyet
    560 	/*
    561 	 * For now we disable executing builtins in the same
    562 	 * context as the shell, because we are not keeping
    563 	 * enough state to recover from changes that are
    564 	 * supposed only to affect subshells. eg. echo "`cd /`"
    565 	 */
    566 	if (n->type == NCMD) {
    567 		exitstatus = oexitstatus;
    568 		evalcommand(n, EV_BACKCMD, result);
    569 	} else
    570 #endif
    571 	{
    572 		exitstatus = 0;
    573 		if (pipe(pip) < 0)
    574 			error("Pipe call failed");
    575 		jp = makejob(n, 1);
    576 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
    577 			FORCEINTON;
    578 			close(pip[0]);
    579 			if (pip[1] != 1) {
    580 				close(1);
    581 				copyfd(pip[1], 1);
    582 				close(pip[1]);
    583 			}
    584 			eflag = 0;
    585 			evaltree(n, EV_EXIT);
    586 		}
    587 		close(pip[1]);
    588 		result->fd = pip[0];
    589 		result->jp = jp;
    590 	}
    591 out:
    592 	popstackmark(&smark);
    593 	TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
    594 		result->fd, result->buf, result->nleft, result->jp));
    595 }
    596 
    597 
    598 int vforked = 0;
    599 
    600 /*
    601  * Execute a simple command.
    602  */
    603 
    604 STATIC void
    605 evalcommand(cmd, flags, backcmd)
    606 	union node *cmd;
    607 	int flags;
    608 	struct backcmd *backcmd;
    609 {
    610 	struct stackmark smark;
    611 	union node *argp;
    612 	struct arglist arglist;
    613 	struct arglist varlist;
    614 	char **argv;
    615 	int argc;
    616 	char **envp;
    617 	int varflag;
    618 	struct strlist *sp;
    619 	int mode;
    620 	int pip[2];
    621 	struct cmdentry cmdentry;
    622 	struct job *jp;
    623 	struct jmploc jmploc;
    624 	struct jmploc *volatile savehandler;
    625 	char *volatile savecmdname;
    626 	volatile struct shparam saveparam;
    627 	struct localvar *volatile savelocalvars;
    628 	volatile int e;
    629 	char *lastarg;
    630 #if __GNUC__
    631 	/* Avoid longjmp clobbering */
    632 	(void) &argv;
    633 	(void) &argc;
    634 	(void) &lastarg;
    635 	(void) &flags;
    636 #endif
    637 
    638 	vforked = 0;
    639 	/* First expand the arguments. */
    640 	TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
    641 	setstackmark(&smark);
    642 	arglist.lastp = &arglist.list;
    643 	varlist.lastp = &varlist.list;
    644 	varflag = 1;
    645 	oexitstatus = exitstatus;
    646 	exitstatus = 0;
    647 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
    648 		char *p = argp->narg.text;
    649 		if (varflag && is_name(*p)) {
    650 			do {
    651 				p++;
    652 			} while (is_in_name(*p));
    653 			if (*p == '=') {
    654 				expandarg(argp, &varlist, EXP_VARTILDE);
    655 				continue;
    656 			}
    657 		}
    658 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
    659 		varflag = 0;
    660 	}
    661 	*arglist.lastp = NULL;
    662 	*varlist.lastp = NULL;
    663 	expredir(cmd->ncmd.redirect);
    664 	argc = 0;
    665 	for (sp = arglist.list ; sp ; sp = sp->next)
    666 		argc++;
    667 	argv = stalloc(sizeof (char *) * (argc + 1));
    668 
    669 	for (sp = arglist.list ; sp ; sp = sp->next) {
    670 		TRACE(("evalcommand arg: %s\n", sp->text));
    671 		*argv++ = sp->text;
    672 	}
    673 	*argv = NULL;
    674 	lastarg = NULL;
    675 	if (iflag && funcnest == 0 && argc > 0)
    676 		lastarg = argv[-1];
    677 	argv -= argc;
    678 
    679 	/* Print the command if xflag is set. */
    680 	if (xflag) {
    681 		outc('+', &errout);
    682 		for (sp = varlist.list ; sp ; sp = sp->next) {
    683 			outc(' ', &errout);
    684 			out2str(sp->text);
    685 		}
    686 		for (sp = arglist.list ; sp ; sp = sp->next) {
    687 			outc(' ', &errout);
    688 			out2str(sp->text);
    689 		}
    690 		outc('\n', &errout);
    691 		flushout(&errout);
    692 	}
    693 
    694 	/* Now locate the command. */
    695 	if (argc == 0) {
    696 		cmdentry.cmdtype = CMDBUILTIN;
    697 		cmdentry.u.index = BLTINCMD;
    698 	} else {
    699 		static const char PATH[] = "PATH=";
    700 		const char *path = pathval();
    701 
    702 		/*
    703 		 * Modify the command lookup path, if a PATH= assignment
    704 		 * is present
    705 		 */
    706 		for (sp = varlist.list ; sp ; sp = sp->next)
    707 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0)
    708 				path = sp->text + sizeof(PATH) - 1;
    709 
    710 		find_command(argv[0], &cmdentry, DO_ERR, path);
    711 		if (cmdentry.cmdtype == CMDUNKNOWN) {	/* command not found */
    712 			exitstatus = 127;
    713 			flushout(&errout);
    714 			return;
    715 		}
    716 		/* implement the bltin builtin here */
    717 		if (cmdentry.cmdtype == CMDBUILTIN && cmdentry.u.index == BLTINCMD) {
    718 			for (;;) {
    719 				argv++;
    720 				if (--argc == 0)
    721 					break;
    722 				if ((cmdentry.u.index = find_builtin(*argv)) < 0) {
    723 					outfmt(&errout, "%s: not found\n", *argv);
    724 					exitstatus = 127;
    725 					flushout(&errout);
    726 					return;
    727 				}
    728 				if (cmdentry.u.index != BLTINCMD)
    729 					break;
    730 			}
    731 		}
    732 	}
    733 
    734 	/* Fork off a child process if necessary. */
    735 	if (cmd->ncmd.backgnd
    736 	 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
    737 	 || ((flags & EV_BACKCMD) != 0
    738 	    && (cmdentry.cmdtype != CMDBUILTIN
    739 		 || cmdentry.u.index == DOTCMD
    740 		 || cmdentry.u.index == EVALCMD))) {
    741 		jp = makejob(cmd, 1);
    742 		mode = cmd->ncmd.backgnd;
    743 		if (flags & EV_BACKCMD) {
    744 			mode = FORK_NOJOB;
    745 			if (pipe(pip) < 0)
    746 				error("Pipe call failed");
    747 		}
    748 #ifdef DO_SHAREDVFORK
    749 		/* It is essential that if DO_SHAREDVFORK is defined that the
    750 		 * child's address space is actually shared with the parent as
    751 		 * we rely on this.
    752 		 */
    753 		if (cmdentry.cmdtype == CMDNORMAL) {
    754 			pid_t	pid;
    755 
    756 			INTOFF;
    757 			vforked = 1;
    758 			switch (pid = vfork()) {
    759 			case -1:
    760 				TRACE(("Vfork failed, errno=%d", errno));
    761 				INTON;
    762 				error("Cannot vfork");
    763 				break;
    764 			case 0:
    765 				/* Make sure that exceptions only unwind to
    766 				 * after the vfork(2)
    767 				 */
    768 				if (setjmp(jmploc.loc)) {
    769 					if (exception == EXSHELLPROC) {
    770 						/* We can't progress with the vfork,
    771 						 * so, set vforked = 2 so the parent
    772 						 * knows, and _exit();
    773 						 */
    774 						vforked = 2;
    775 						_exit(0);
    776 					} else {
    777 						_exit(exerrno);
    778 					}
    779 				}
    780 				savehandler = handler;
    781 				handler = &jmploc;
    782 				forkchild(jp, cmd, mode, vforked);
    783 				break;
    784 			default:
    785 				handler = savehandler;	/* restore from vfork(2) */
    786 				if (vforked == 2) {
    787 					vforked = 0;
    788 					waitpid(pid, NULL, 0);
    789 					/* We need to progress in a normal fork fashion */
    790 					goto normal_fork;
    791 				}
    792 				vforked = 0;
    793 				forkparent(jp, cmd, mode, pid);
    794 				goto parent;
    795 			}
    796 		} else {
    797 normal_fork:
    798 #endif
    799 			if (forkshell(jp, cmd, mode) != 0)
    800 				goto parent;	/* at end of routine */
    801 #ifdef DO_SHAREDVFORK
    802 		}
    803 #endif
    804 		if (flags & EV_BACKCMD) {
    805 			FORCEINTON;
    806 			close(pip[0]);
    807 			if (pip[1] != 1) {
    808 				close(1);
    809 				copyfd(pip[1], 1);
    810 				close(pip[1]);
    811 			}
    812 		}
    813 		flags |= EV_EXIT;
    814 	}
    815 
    816 	/* This is the child process if a fork occurred. */
    817 	/* Execute the command. */
    818 	if (cmdentry.cmdtype == CMDFUNCTION) {
    819 #ifdef DEBUG
    820 		trputs("Shell function:  ");  trargs(argv);
    821 #endif
    822 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
    823 		saveparam = shellparam;
    824 		shellparam.malloc = 0;
    825 		shellparam.reset = 1;
    826 		shellparam.nparam = argc - 1;
    827 		shellparam.p = argv + 1;
    828 		shellparam.optnext = NULL;
    829 		INTOFF;
    830 		savelocalvars = localvars;
    831 		localvars = NULL;
    832 		INTON;
    833 		if (setjmp(jmploc.loc)) {
    834 			if (exception == EXSHELLPROC) {
    835 				freeparam((volatile struct shparam *)
    836 				    &saveparam);
    837 			} else {
    838 				freeparam(&shellparam);
    839 				shellparam = saveparam;
    840 			}
    841 			poplocalvars();
    842 			localvars = savelocalvars;
    843 			handler = savehandler;
    844 			longjmp(handler->loc, 1);
    845 		}
    846 		savehandler = handler;
    847 		handler = &jmploc;
    848 		for (sp = varlist.list ; sp ; sp = sp->next)
    849 			mklocal(sp->text);
    850 		funcnest++;
    851 		evaltree(cmdentry.u.func, flags & EV_TESTED);
    852 		funcnest--;
    853 		INTOFF;
    854 		poplocalvars();
    855 		localvars = savelocalvars;
    856 		freeparam(&shellparam);
    857 		shellparam = saveparam;
    858 		handler = savehandler;
    859 		popredir();
    860 		INTON;
    861 		if (evalskip == SKIPFUNC) {
    862 			evalskip = 0;
    863 			skipcount = 0;
    864 		}
    865 		if (flags & EV_EXIT)
    866 			exitshell(exitstatus);
    867 	} else if (cmdentry.cmdtype == CMDBUILTIN) {
    868 #ifdef DEBUG
    869 		trputs("builtin command:  ");  trargs(argv);
    870 #endif
    871 		mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
    872 		if (flags == EV_BACKCMD) {
    873 			memout.nleft = 0;
    874 			memout.nextc = memout.buf;
    875 			memout.bufsize = 64;
    876 			mode |= REDIR_BACKQ;
    877 		}
    878 		redirect(cmd->ncmd.redirect, mode);
    879 		savecmdname = commandname;
    880 		cmdenviron = varlist.list;
    881 		e = -1;
    882 		if (setjmp(jmploc.loc)) {
    883 			e = exception;
    884 			exitstatus = (e == EXINT)? SIGINT+128 : 2;
    885 			goto cmddone;
    886 		}
    887 		savehandler = handler;
    888 		handler = &jmploc;
    889 		commandname = argv[0];
    890 		argptr = argv + 1;
    891 		optptr = NULL;			/* initialize nextopt */
    892 		exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
    893 		flushall();
    894 cmddone:
    895 		out1 = &output;
    896 		out2 = &errout;
    897 		freestdout();
    898 		cmdenviron = NULL;
    899 		if (e != EXSHELLPROC) {
    900 			commandname = savecmdname;
    901 			if (flags & EV_EXIT)
    902 				exitshell(exitstatus);
    903 		}
    904 		handler = savehandler;
    905 		if (e != -1) {
    906 			if ((e != EXERROR && e != EXEXEC)
    907 			   || cmdentry.u.index == BLTINCMD
    908 			   || cmdentry.u.index == DOTCMD
    909 			   || cmdentry.u.index == EVALCMD
    910 #ifndef SMALL
    911 			   || cmdentry.u.index == HISTCMD
    912 #endif
    913 			   || cmdentry.u.index == EXECCMD)
    914 				exraise(e);
    915 			FORCEINTON;
    916 		}
    917 		if (cmdentry.u.index != EXECCMD)
    918 			popredir();
    919 		if (flags == EV_BACKCMD) {
    920 			backcmd->buf = memout.buf;
    921 			backcmd->nleft = memout.nextc - memout.buf;
    922 			memout.buf = NULL;
    923 		}
    924 	} else {
    925 #ifdef DEBUG
    926 		trputs("normal command:  ");  trargs(argv);
    927 #endif
    928 		clearredir(vforked?REDIR_VFORK:0);
    929 		redirect(cmd->ncmd.redirect, vforked?REDIR_VFORK:0);
    930 		for (sp = varlist.list ; sp ; sp = sp->next)
    931 			setvareq(sp->text, VEXPORT|VSTACK);
    932 		envp = environment();
    933 		shellexec(argv, envp, pathval(), cmdentry.u.index, vforked);
    934 	}
    935 	goto out;
    936 
    937 parent:	/* parent process gets here (if we forked) */
    938 	if (mode == 0) {	/* argument to fork */
    939 		INTOFF;
    940 		exitstatus = waitforjob(jp);
    941 		INTON;
    942 	} else if (mode == 2) {
    943 		backcmd->fd = pip[0];
    944 		close(pip[1]);
    945 		backcmd->jp = jp;
    946 	}
    947 
    948 out:
    949 	if (lastarg)
    950 		setvar("_", lastarg, 0);
    951 	popstackmark(&smark);
    952 
    953 	if (eflag && exitstatus && !(flags & EV_TESTED))
    954 	    exitshell(exitstatus);
    955 }
    956 
    957 
    958 /*
    959  * Search for a command.  This is called before we fork so that the
    960  * location of the command will be available in the parent as well as
    961  * the child.  The check for "goodname" is an overly conservative
    962  * check that the name will not be subject to expansion.
    963  */
    964 
    965 STATIC void
    966 prehash(n)
    967 	union node *n;
    968 {
    969 	struct cmdentry entry;
    970 
    971 	if (n->type == NCMD && n->ncmd.args)
    972 		if (goodname(n->ncmd.args->narg.text))
    973 			find_command(n->ncmd.args->narg.text, &entry, 0,
    974 				     pathval());
    975 }
    976 
    977 
    978 
    979 /*
    980  * Builtin commands.  Builtin commands whose functions are closely
    981  * tied to evaluation are implemented here.
    982  */
    983 
    984 /*
    985  * No command given, or a bltin command with no arguments.  Set the
    986  * specified variables.
    987  */
    988 
    989 int
    990 bltincmd(argc, argv)
    991 	int argc;
    992 	char **argv;
    993 {
    994 	listsetvar(cmdenviron);
    995 	/*
    996 	 * Preserve exitstatus of a previous possible redirection
    997 	 * as POSIX mandates
    998 	 */
    999 	return exitstatus;
   1000 }
   1001 
   1002 
   1003 /*
   1004  * Handle break and continue commands.  Break, continue, and return are
   1005  * all handled by setting the evalskip flag.  The evaluation routines
   1006  * above all check this flag, and if it is set they start skipping
   1007  * commands rather than executing them.  The variable skipcount is
   1008  * the number of loops to break/continue, or the number of function
   1009  * levels to return.  (The latter is always 1.)  It should probably
   1010  * be an error to break out of more loops than exist, but it isn't
   1011  * in the standard shell so we don't make it one here.
   1012  */
   1013 
   1014 int
   1015 breakcmd(argc, argv)
   1016 	int argc;
   1017 	char **argv;
   1018 {
   1019 	int n = argc > 1 ? number(argv[1]) : 1;
   1020 
   1021 	if (n > loopnest)
   1022 		n = loopnest;
   1023 	if (n > 0) {
   1024 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
   1025 		skipcount = n;
   1026 	}
   1027 	return 0;
   1028 }
   1029 
   1030 
   1031 /*
   1032  * The return command.
   1033  */
   1034 
   1035 int
   1036 returncmd(argc, argv)
   1037 	int argc;
   1038 	char **argv;
   1039 {
   1040 	int ret = argc > 1 ? number(argv[1]) : oexitstatus;
   1041 
   1042 	if (funcnest) {
   1043 		evalskip = SKIPFUNC;
   1044 		skipcount = 1;
   1045 		return ret;
   1046 	}
   1047 	else {
   1048 		/* Do what ksh does; skip the rest of the file */
   1049 		evalskip = SKIPFILE;
   1050 		skipcount = 1;
   1051 		return ret;
   1052 	}
   1053 }
   1054 
   1055 
   1056 int
   1057 falsecmd(argc, argv)
   1058 	int argc;
   1059 	char **argv;
   1060 {
   1061 	return 1;
   1062 }
   1063 
   1064 
   1065 int
   1066 truecmd(argc, argv)
   1067 	int argc;
   1068 	char **argv;
   1069 {
   1070 	return 0;
   1071 }
   1072 
   1073 
   1074 int
   1075 execcmd(argc, argv)
   1076 	int argc;
   1077 	char **argv;
   1078 {
   1079 	if (argc > 1) {
   1080 		struct strlist *sp;
   1081 
   1082 		iflag = 0;		/* exit on error */
   1083 		mflag = 0;
   1084 		optschanged();
   1085 		for (sp = cmdenviron; sp ; sp = sp->next)
   1086 			setvareq(sp->text, VEXPORT|VSTACK);
   1087 		shellexec(argv + 1, environment(), pathval(), 0, 0);
   1088 	}
   1089 	return 0;
   1090 }
   1091