Home | History | Annotate | Line # | Download | only in sh
eval.c revision 1.91
      1 /*	$NetBSD: eval.c,v 1.91 2008/05/24 19:06:43 tron 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.91 2008/05/24 19:06:43 tron 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 <unistd.h>
     49 #include <sys/fcntl.h>
     50 #include <sys/times.h>
     51 #include <sys/param.h>
     52 #include <sys/types.h>
     53 #include <sys/wait.h>
     54 #include <sys/sysctl.h>
     55 
     56 /*
     57  * Evaluate a command.
     58  */
     59 
     60 #include "shell.h"
     61 #include "nodes.h"
     62 #include "syntax.h"
     63 #include "expand.h"
     64 #include "parser.h"
     65 #include "jobs.h"
     66 #include "eval.h"
     67 #include "builtins.h"
     68 #include "options.h"
     69 #include "exec.h"
     70 #include "redir.h"
     71 #include "input.h"
     72 #include "output.h"
     73 #include "trap.h"
     74 #include "var.h"
     75 #include "memalloc.h"
     76 #include "error.h"
     77 #include "show.h"
     78 #include "mystring.h"
     79 #include "main.h"
     80 #ifndef SMALL
     81 #include "myhistedit.h"
     82 #endif
     83 
     84 
     85 /* flags in argument to evaltree */
     86 #define EV_EXIT 01		/* exit after evaluating tree */
     87 #define EV_TESTED 02		/* exit status is checked; ignore -e flag */
     88 #define EV_BACKCMD 04		/* command executing within back quotes */
     89 
     90 int evalskip;			/* set if we are skipping commands */
     91 STATIC int skipcount;		/* number of levels to skip */
     92 MKINIT int loopnest;		/* current loop nesting level */
     93 int funcnest;			/* depth of function calls */
     94 
     95 
     96 const char *commandname;
     97 struct strlist *cmdenviron;
     98 int exitstatus;			/* exit status of last command */
     99 int back_exitstatus;		/* exit status of backquoted command */
    100 
    101 
    102 STATIC void evalloop(union node *, int);
    103 STATIC void evalfor(union node *, int);
    104 STATIC void evalcase(union node *, int);
    105 STATIC void evalsubshell(union node *, int);
    106 STATIC void expredir(union node *);
    107 STATIC void evalpipe(union node *);
    108 STATIC void evalcommand(union node *, int, struct backcmd *);
    109 STATIC void prehash(union node *);
    110 
    111 
    112 /*
    113  * Called to reset things after an exception.
    114  */
    115 
    116 #ifdef mkinit
    117 INCLUDE "eval.h"
    118 
    119 RESET {
    120 	evalskip = 0;
    121 	loopnest = 0;
    122 	funcnest = 0;
    123 }
    124 
    125 SHELLPROC {
    126 	exitstatus = 0;
    127 }
    128 #endif
    129 
    130 static int
    131 sh_pipe(int fds[2])
    132 {
    133 	int nfd;
    134 
    135 	if (pipe(fds))
    136 		return -1;
    137 
    138 	if (fds[0] < 3) {
    139 		nfd = fcntl(fds[0], F_DUPFD, 3);
    140 		if (nfd != -1) {
    141 			close(fds[0]);
    142 			fds[0] = nfd;
    143 		}
    144 	}
    145 
    146 	if (fds[1] < 3) {
    147 		nfd = fcntl(fds[1], F_DUPFD, 3);
    148 		if (nfd != -1) {
    149 			close(fds[1]);
    150 			fds[1] = nfd;
    151 		}
    152 	}
    153 	return 0;
    154 }
    155 
    156 
    157 /*
    158  * The eval commmand.
    159  */
    160 
    161 int
    162 evalcmd(int argc, char **argv)
    163 {
    164         char *p;
    165         char *concat;
    166         char **ap;
    167 
    168         if (argc > 1) {
    169                 p = argv[1];
    170                 if (argc > 2) {
    171                         STARTSTACKSTR(concat);
    172                         ap = argv + 2;
    173                         for (;;) {
    174                                 while (*p)
    175                                         STPUTC(*p++, concat);
    176                                 if ((p = *ap++) == NULL)
    177                                         break;
    178                                 STPUTC(' ', concat);
    179                         }
    180                         STPUTC('\0', concat);
    181                         p = grabstackstr(concat);
    182                 }
    183                 evalstring(p, EV_TESTED);
    184         }
    185         return exitstatus;
    186 }
    187 
    188 
    189 /*
    190  * Execute a command or commands contained in a string.
    191  */
    192 
    193 void
    194 evalstring(char *s, int flag)
    195 {
    196 	union node *n;
    197 	struct stackmark smark;
    198 
    199 	setstackmark(&smark);
    200 	setinputstring(s, 1);
    201 
    202 	while ((n = parsecmd(0)) != NEOF) {
    203 		evaltree(n, flag);
    204 		popstackmark(&smark);
    205 	}
    206 	popfile();
    207 	popstackmark(&smark);
    208 }
    209 
    210 
    211 
    212 /*
    213  * Evaluate a parse tree.  The value is left in the global variable
    214  * exitstatus.
    215  */
    216 
    217 void
    218 evaltree(union node *n, int flags)
    219 {
    220 	bool do_etest;
    221 
    222 	do_etest = false;
    223 	if (n == NULL) {
    224 		TRACE(("evaltree(NULL) called\n"));
    225 		exitstatus = 0;
    226 		goto out;
    227 	}
    228 #ifndef SMALL
    229 	displayhist = 1;	/* show history substitutions done with fc */
    230 #endif
    231 	TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
    232 	    getpid(), n, n->type, flags));
    233 	switch (n->type) {
    234 	case NSEMI:
    235 		do_etest = !(flags & EV_TESTED);
    236 		evaltree(n->nbinary.ch1, flags & EV_TESTED);
    237 		if (evalskip)
    238 			goto out;
    239 		evaltree(n->nbinary.ch2, flags);
    240 		break;
    241 	case NAND:
    242 		evaltree(n->nbinary.ch1, EV_TESTED);
    243 		if (evalskip || exitstatus != 0)
    244 			goto out;
    245 		evaltree(n->nbinary.ch2, flags);
    246 		break;
    247 	case NOR:
    248 		evaltree(n->nbinary.ch1, EV_TESTED);
    249 		if (evalskip || exitstatus == 0)
    250 			goto out;
    251 		evaltree(n->nbinary.ch2, flags);
    252 		break;
    253 	case NREDIR:
    254 		expredir(n->nredir.redirect);
    255 		redirect(n->nredir.redirect, REDIR_PUSH);
    256 		evaltree(n->nredir.n, flags);
    257 		popredir();
    258 		break;
    259 	case NSUBSHELL:
    260 		evalsubshell(n, flags);
    261 		do_etest = !(flags & EV_TESTED);
    262 		break;
    263 	case NBACKGND:
    264 		evalsubshell(n, flags);
    265 		break;
    266 	case NIF: {
    267 		evaltree(n->nif.test, EV_TESTED);
    268 		if (evalskip)
    269 			goto out;
    270 		if (exitstatus == 0)
    271 			evaltree(n->nif.ifpart, flags);
    272 		else if (n->nif.elsepart)
    273 			evaltree(n->nif.elsepart, flags);
    274 		else
    275 			exitstatus = 0;
    276 		break;
    277 	}
    278 	case NWHILE:
    279 	case NUNTIL:
    280 		evalloop(n, flags);
    281 		break;
    282 	case NFOR:
    283 		evalfor(n, flags);
    284 		break;
    285 	case NCASE:
    286 		evalcase(n, flags);
    287 		break;
    288 	case NDEFUN:
    289 		defun(n->narg.text, n->narg.next);
    290 		exitstatus = 0;
    291 		break;
    292 	case NNOT:
    293 		evaltree(n->nnot.com, EV_TESTED);
    294 		exitstatus = !exitstatus;
    295 		do_etest = !(flags & EV_TESTED);
    296 		break;
    297 	case NPIPE:
    298 		evalpipe(n);
    299 		do_etest = !(flags & EV_TESTED);
    300 		break;
    301 	case NCMD:
    302 		evalcommand(n, flags, (struct backcmd *)NULL);
    303 		do_etest = !(flags & EV_TESTED);
    304 		break;
    305 	default:
    306 		out1fmt("Node type = %d\n", n->type);
    307 		flushout(&output);
    308 		break;
    309 	}
    310 out:
    311 	if (pendingsigs)
    312 		dotrap();
    313 	if ((flags & EV_EXIT) != 0 || (eflag && exitstatus != 0 && do_etest))
    314 		exitshell(exitstatus);
    315 }
    316 
    317 
    318 STATIC void
    319 evalloop(union node *n, int flags)
    320 {
    321 	int status;
    322 
    323 	loopnest++;
    324 	status = 0;
    325 	for (;;) {
    326 		evaltree(n->nbinary.ch1, EV_TESTED);
    327 		if (evalskip) {
    328 skipping:	  if (evalskip == SKIPCONT && --skipcount <= 0) {
    329 				evalskip = 0;
    330 				continue;
    331 			}
    332 			if (evalskip == SKIPBREAK && --skipcount <= 0)
    333 				evalskip = 0;
    334 			break;
    335 		}
    336 		if (n->type == NWHILE) {
    337 			if (exitstatus != 0)
    338 				break;
    339 		} else {
    340 			if (exitstatus == 0)
    341 				break;
    342 		}
    343 		evaltree(n->nbinary.ch2, flags & EV_TESTED);
    344 		status = exitstatus;
    345 		if (evalskip)
    346 			goto skipping;
    347 	}
    348 	loopnest--;
    349 	exitstatus = status;
    350 }
    351 
    352 
    353 
    354 STATIC void
    355 evalfor(union node *n, int flags)
    356 {
    357 	struct arglist arglist;
    358 	union node *argp;
    359 	struct strlist *sp;
    360 	struct stackmark smark;
    361 	int status = 0;
    362 
    363 	setstackmark(&smark);
    364 	arglist.lastp = &arglist.list;
    365 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
    366 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
    367 		if (evalskip)
    368 			goto out;
    369 	}
    370 	*arglist.lastp = NULL;
    371 
    372 	loopnest++;
    373 	for (sp = arglist.list ; sp ; sp = sp->next) {
    374 		setvar(n->nfor.var, sp->text, 0);
    375 		evaltree(n->nfor.body, flags & EV_TESTED);
    376 		status = exitstatus;
    377 		if (evalskip) {
    378 			if (evalskip == SKIPCONT && --skipcount <= 0) {
    379 				evalskip = 0;
    380 				continue;
    381 			}
    382 			if (evalskip == SKIPBREAK && --skipcount <= 0)
    383 				evalskip = 0;
    384 			break;
    385 		}
    386 	}
    387 	loopnest--;
    388 	exitstatus = status;
    389 out:
    390 	popstackmark(&smark);
    391 }
    392 
    393 
    394 
    395 STATIC void
    396 evalcase(union node *n, int flags)
    397 {
    398 	union node *cp;
    399 	union node *patp;
    400 	struct arglist arglist;
    401 	struct stackmark smark;
    402 	int status = 0;
    403 
    404 	setstackmark(&smark);
    405 	arglist.lastp = &arglist.list;
    406 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
    407 	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
    408 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
    409 			if (casematch(patp, arglist.list->text)) {
    410 				if (evalskip == 0) {
    411 					evaltree(cp->nclist.body, flags);
    412 					status = exitstatus;
    413 				}
    414 				goto out;
    415 			}
    416 		}
    417 	}
    418 out:
    419 	exitstatus = status;
    420 	popstackmark(&smark);
    421 }
    422 
    423 
    424 
    425 /*
    426  * Kick off a subshell to evaluate a tree.
    427  */
    428 
    429 STATIC void
    430 evalsubshell(union node *n, int flags)
    431 {
    432 	struct job *jp;
    433 	int backgnd = (n->type == NBACKGND);
    434 
    435 	expredir(n->nredir.redirect);
    436 	INTOFF;
    437 	jp = makejob(n, 1);
    438 	if (forkshell(jp, n, backgnd ? FORK_BG : FORK_FG) == 0) {
    439 		INTON;
    440 		if (backgnd)
    441 			flags &=~ EV_TESTED;
    442 		redirect(n->nredir.redirect, 0);
    443 		/* never returns */
    444 		evaltree(n->nredir.n, flags | EV_EXIT);
    445 	}
    446 	if (! backgnd)
    447 		exitstatus = waitforjob(jp);
    448 	INTON;
    449 }
    450 
    451 
    452 
    453 /*
    454  * Compute the names of the files in a redirection list.
    455  */
    456 
    457 STATIC void
    458 expredir(union node *n)
    459 {
    460 	union node *redir;
    461 
    462 	for (redir = n ; redir ; redir = redir->nfile.next) {
    463 		struct arglist fn;
    464 		fn.lastp = &fn.list;
    465 		switch (redir->type) {
    466 		case NFROMTO:
    467 		case NFROM:
    468 		case NTO:
    469 		case NCLOBBER:
    470 		case NAPPEND:
    471 			expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
    472 			redir->nfile.expfname = fn.list->text;
    473 			break;
    474 		case NFROMFD:
    475 		case NTOFD:
    476 			if (redir->ndup.vname) {
    477 				expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
    478 				fixredir(redir, fn.list->text, 1);
    479 			}
    480 			break;
    481 		}
    482 	}
    483 }
    484 
    485 
    486 
    487 /*
    488  * Evaluate a pipeline.  All the processes in the pipeline are children
    489  * of the process creating the pipeline.  (This differs from some versions
    490  * of the shell, which make the last process in a pipeline the parent
    491  * of all the rest.)
    492  */
    493 
    494 STATIC void
    495 evalpipe(union node *n)
    496 {
    497 	struct job *jp;
    498 	struct nodelist *lp;
    499 	int pipelen;
    500 	int prevfd;
    501 	int pip[2];
    502 
    503 	TRACE(("evalpipe(0x%lx) called\n", (long)n));
    504 	pipelen = 0;
    505 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
    506 		pipelen++;
    507 	INTOFF;
    508 	jp = makejob(n, pipelen);
    509 	prevfd = -1;
    510 	for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
    511 		prehash(lp->n);
    512 		pip[1] = -1;
    513 		if (lp->next) {
    514 			if (sh_pipe(pip) < 0) {
    515 				if (prevfd >= 0)
    516 					close(prevfd);
    517 				error("Pipe call failed");
    518 			}
    519 		}
    520 		if (forkshell(jp, lp->n, n->npipe.backgnd ? FORK_BG : FORK_FG) == 0) {
    521 			INTON;
    522 			if (prevfd > 0) {
    523 				close(0);
    524 				copyfd(prevfd, 0);
    525 				close(prevfd);
    526 			}
    527 			if (pip[1] >= 0) {
    528 				close(pip[0]);
    529 				if (pip[1] != 1) {
    530 					close(1);
    531 					copyfd(pip[1], 1);
    532 					close(pip[1]);
    533 				}
    534 			}
    535 			evaltree(lp->n, EV_EXIT);
    536 		}
    537 		if (prevfd >= 0)
    538 			close(prevfd);
    539 		prevfd = pip[0];
    540 		close(pip[1]);
    541 	}
    542 	if (n->npipe.backgnd == 0) {
    543 		exitstatus = waitforjob(jp);
    544 		TRACE(("evalpipe:  job done exit status %d\n", exitstatus));
    545 	}
    546 	INTON;
    547 }
    548 
    549 
    550 
    551 /*
    552  * Execute a command inside back quotes.  If it's a builtin command, we
    553  * want to save its output in a block obtained from malloc.  Otherwise
    554  * we fork off a subprocess and get the output of the command via a pipe.
    555  * Should be called with interrupts off.
    556  */
    557 
    558 void
    559 evalbackcmd(union node *n, struct backcmd *result)
    560 {
    561 	int pip[2];
    562 	struct job *jp;
    563 	struct stackmark smark;		/* unnecessary */
    564 
    565 	setstackmark(&smark);
    566 	result->fd = -1;
    567 	result->buf = NULL;
    568 	result->nleft = 0;
    569 	result->jp = NULL;
    570 	if (n == NULL) {
    571 		goto out;
    572 	}
    573 #ifdef notyet
    574 	/*
    575 	 * For now we disable executing builtins in the same
    576 	 * context as the shell, because we are not keeping
    577 	 * enough state to recover from changes that are
    578 	 * supposed only to affect subshells. eg. echo "`cd /`"
    579 	 */
    580 	if (n->type == NCMD) {
    581 		exitstatus = oexitstatus;
    582 		evalcommand(n, EV_BACKCMD, result);
    583 	} else
    584 #endif
    585 	{
    586 		INTOFF;
    587 		if (sh_pipe(pip) < 0)
    588 			error("Pipe call failed");
    589 		jp = makejob(n, 1);
    590 		if (forkshell(jp, n, FORK_NOJOB) == 0) {
    591 			FORCEINTON;
    592 			close(pip[0]);
    593 			if (pip[1] != 1) {
    594 				close(1);
    595 				copyfd(pip[1], 1);
    596 				close(pip[1]);
    597 			}
    598 			eflag = 0;
    599 			evaltree(n, EV_EXIT);
    600 			/* NOTREACHED */
    601 		}
    602 		close(pip[1]);
    603 		result->fd = pip[0];
    604 		result->jp = jp;
    605 		INTON;
    606 	}
    607 out:
    608 	popstackmark(&smark);
    609 	TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
    610 		result->fd, result->buf, result->nleft, result->jp));
    611 }
    612 
    613 static const char *
    614 syspath(void)
    615 {
    616 	static char *sys_path = NULL;
    617 	static int mib[] = {CTL_USER, USER_CS_PATH};
    618 	static char def_path[] = "PATH=/usr/bin:/bin:/usr/sbin:/sbin";
    619 	size_t len;
    620 
    621 	if (sys_path == NULL) {
    622 		if (sysctl(mib, 2, 0, &len, 0, 0) != -1 &&
    623 		    (sys_path = ckmalloc(len + 5)) != NULL &&
    624 		    sysctl(mib, 2, sys_path + 5, &len, 0, 0) != -1) {
    625 			memcpy(sys_path, "PATH=", 5);
    626 		} else {
    627 			ckfree(sys_path);
    628 			/* something to keep things happy */
    629 			sys_path = def_path;
    630 		}
    631 	}
    632 	return sys_path;
    633 }
    634 
    635 static int
    636 parse_command_args(int argc, char **argv, int *use_syspath)
    637 {
    638 	int sv_argc = argc;
    639 	char *cp, c;
    640 
    641 	*use_syspath = 0;
    642 
    643 	for (;;) {
    644 		argv++;
    645 		if (--argc == 0)
    646 			break;
    647 		cp = *argv;
    648 		if (*cp++ != '-')
    649 			break;
    650 		if (*cp == '-' && cp[1] == 0) {
    651 			argv++;
    652 			argc--;
    653 			break;
    654 		}
    655 		while ((c = *cp++)) {
    656 			switch (c) {
    657 			case 'p':
    658 				*use_syspath = 1;
    659 				break;
    660 			default:
    661 				/* run 'typecmd' for other options */
    662 				return 0;
    663 			}
    664 		}
    665 	}
    666 	return sv_argc - argc;
    667 }
    668 
    669 int vforked = 0;
    670 
    671 /*
    672  * Execute a simple command.
    673  */
    674 
    675 STATIC void
    676 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd)
    677 {
    678 	struct stackmark smark;
    679 	union node *argp;
    680 	struct arglist arglist;
    681 	struct arglist varlist;
    682 	volatile int flags = flgs;
    683 	char ** volatile argv;
    684 	volatile int argc;
    685 	char **envp;
    686 	int varflag;
    687 	struct strlist *sp;
    688 	volatile int mode;
    689 	int pip[2];
    690 	struct cmdentry cmdentry;
    691 	struct job * volatile jp;
    692 	struct jmploc jmploc;
    693 	struct jmploc *volatile savehandler = NULL;
    694 	const char *volatile savecmdname;
    695 	volatile struct shparam saveparam;
    696 	struct localvar *volatile savelocalvars;
    697 	volatile int e;
    698 	char * volatile lastarg;
    699 	const char * volatile path = pathval();
    700 	volatile int temp_path;
    701 
    702 	vforked = 0;
    703 	/* First expand the arguments. */
    704 	TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
    705 	setstackmark(&smark);
    706 	back_exitstatus = 0;
    707 
    708 	arglist.lastp = &arglist.list;
    709 	varflag = 1;
    710 	/* Expand arguments, ignoring the initial 'name=value' ones */
    711 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
    712 		char *p = argp->narg.text;
    713 		if (varflag && is_name(*p)) {
    714 			do {
    715 				p++;
    716 			} while (is_in_name(*p));
    717 			if (*p == '=')
    718 				continue;
    719 		}
    720 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
    721 		varflag = 0;
    722 	}
    723 	*arglist.lastp = NULL;
    724 
    725 	expredir(cmd->ncmd.redirect);
    726 
    727 	/* Now do the initial 'name=value' ones we skipped above */
    728 	varlist.lastp = &varlist.list;
    729 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
    730 		char *p = argp->narg.text;
    731 		if (!is_name(*p))
    732 			break;
    733 		do
    734 			p++;
    735 		while (is_in_name(*p));
    736 		if (*p != '=')
    737 			break;
    738 		expandarg(argp, &varlist, EXP_VARTILDE);
    739 	}
    740 	*varlist.lastp = NULL;
    741 
    742 	argc = 0;
    743 	for (sp = arglist.list ; sp ; sp = sp->next)
    744 		argc++;
    745 	argv = stalloc(sizeof (char *) * (argc + 1));
    746 
    747 	for (sp = arglist.list ; sp ; sp = sp->next) {
    748 		TRACE(("evalcommand arg: %s\n", sp->text));
    749 		*argv++ = sp->text;
    750 	}
    751 	*argv = NULL;
    752 	lastarg = NULL;
    753 	if (iflag && funcnest == 0 && argc > 0)
    754 		lastarg = argv[-1];
    755 	argv -= argc;
    756 
    757 	/* Print the command if xflag is set. */
    758 	if (xflag) {
    759 		char sep = 0;
    760 		out2str(ps4val());
    761 		for (sp = varlist.list ; sp ; sp = sp->next) {
    762 			if (sep != 0)
    763 				outc(sep, &errout);
    764 			out2str(sp->text);
    765 			sep = ' ';
    766 		}
    767 		for (sp = arglist.list ; sp ; sp = sp->next) {
    768 			if (sep != 0)
    769 				outc(sep, &errout);
    770 			out2str(sp->text);
    771 			sep = ' ';
    772 		}
    773 		outc('\n', &errout);
    774 		flushout(&errout);
    775 	}
    776 
    777 	/* Now locate the command. */
    778 	if (argc == 0) {
    779 		cmdentry.cmdtype = CMDSPLBLTIN;
    780 		cmdentry.u.bltin = bltincmd;
    781 	} else {
    782 		static const char PATH[] = "PATH=";
    783 		int cmd_flags = DO_ERR;
    784 
    785 		/*
    786 		 * Modify the command lookup path, if a PATH= assignment
    787 		 * is present
    788 		 */
    789 		for (sp = varlist.list; sp; sp = sp->next)
    790 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0)
    791 				path = sp->text + sizeof(PATH) - 1;
    792 
    793 		do {
    794 			int argsused, use_syspath;
    795 			find_command(argv[0], &cmdentry, cmd_flags, path);
    796 			if (cmdentry.cmdtype == CMDUNKNOWN) {
    797 				exitstatus = 127;
    798 				flushout(&errout);
    799 				goto out;
    800 			}
    801 
    802 			/* implement the 'command' builtin here */
    803 			if (cmdentry.cmdtype != CMDBUILTIN ||
    804 			    cmdentry.u.bltin != bltincmd)
    805 				break;
    806 			cmd_flags |= DO_NOFUNC;
    807 			argsused = parse_command_args(argc, argv, &use_syspath);
    808 			if (argsused == 0) {
    809 				/* use 'type' builting to display info */
    810 				cmdentry.u.bltin = typecmd;
    811 				break;
    812 			}
    813 			argc -= argsused;
    814 			argv += argsused;
    815 			if (use_syspath)
    816 				path = syspath() + 5;
    817 		} while (argc != 0);
    818 		if (cmdentry.cmdtype == CMDSPLBLTIN && cmd_flags & DO_NOFUNC)
    819 			/* posix mandates that 'command <splbltin>' act as if
    820 			   <splbltin> was a normal builtin */
    821 			cmdentry.cmdtype = CMDBUILTIN;
    822 	}
    823 
    824 	/* Fork off a child process if necessary. */
    825 	if (cmd->ncmd.backgnd
    826 	 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
    827 	 || ((flags & EV_BACKCMD) != 0
    828 	    && ((cmdentry.cmdtype != CMDBUILTIN && cmdentry.cmdtype != CMDSPLBLTIN)
    829 		 || cmdentry.u.bltin == dotcmd
    830 		 || cmdentry.u.bltin == evalcmd))) {
    831 		INTOFF;
    832 		jp = makejob(cmd, 1);
    833 		mode = cmd->ncmd.backgnd;
    834 		if (flags & EV_BACKCMD) {
    835 			mode = FORK_NOJOB;
    836 			if (sh_pipe(pip) < 0)
    837 				error("Pipe call failed");
    838 		}
    839 #ifdef DO_SHAREDVFORK
    840 		/* It is essential that if DO_SHAREDVFORK is defined that the
    841 		 * child's address space is actually shared with the parent as
    842 		 * we rely on this.
    843 		 */
    844 		if (cmdentry.cmdtype == CMDNORMAL) {
    845 			pid_t	pid;
    846 
    847 			savelocalvars = localvars;
    848 			localvars = NULL;
    849 			vforked = 1;
    850 			switch (pid = vfork()) {
    851 			case -1:
    852 				TRACE(("Vfork failed, errno=%d\n", errno));
    853 				INTON;
    854 				error("Cannot vfork");
    855 				break;
    856 			case 0:
    857 				/* Make sure that exceptions only unwind to
    858 				 * after the vfork(2)
    859 				 */
    860 				if (setjmp(jmploc.loc)) {
    861 					if (exception == EXSHELLPROC) {
    862 						/* We can't progress with the vfork,
    863 						 * so, set vforked = 2 so the parent
    864 						 * knows, and _exit();
    865 						 */
    866 						vforked = 2;
    867 						_exit(0);
    868 					} else {
    869 						_exit(exerrno);
    870 					}
    871 				}
    872 				savehandler = handler;
    873 				handler = &jmploc;
    874 				listmklocal(varlist.list, VEXPORT | VNOFUNC);
    875 				forkchild(jp, cmd, mode, vforked);
    876 				break;
    877 			default:
    878 				handler = savehandler;	/* restore from vfork(2) */
    879 				poplocalvars();
    880 				localvars = savelocalvars;
    881 				if (vforked == 2) {
    882 					vforked = 0;
    883 
    884 					(void)waitpid(pid, NULL, 0);
    885 					/* We need to progress in a normal fork fashion */
    886 					goto normal_fork;
    887 				}
    888 				vforked = 0;
    889 				forkparent(jp, cmd, mode, pid);
    890 				goto parent;
    891 			}
    892 		} else {
    893 normal_fork:
    894 #endif
    895 			if (forkshell(jp, cmd, mode) != 0)
    896 				goto parent;	/* at end of routine */
    897 			FORCEINTON;
    898 #ifdef DO_SHAREDVFORK
    899 		}
    900 #endif
    901 		if (flags & EV_BACKCMD) {
    902 			if (!vforked) {
    903 				FORCEINTON;
    904 			}
    905 			close(pip[0]);
    906 			if (pip[1] != 1) {
    907 				close(1);
    908 				copyfd(pip[1], 1);
    909 				close(pip[1]);
    910 			}
    911 		}
    912 		flags |= EV_EXIT;
    913 	}
    914 
    915 	/* This is the child process if a fork occurred. */
    916 	/* Execute the command. */
    917 	switch (cmdentry.cmdtype) {
    918 	case CMDFUNCTION:
    919 #ifdef DEBUG
    920 		trputs("Shell function:  ");  trargs(argv);
    921 #endif
    922 		redirect(cmd->ncmd.redirect, REDIR_PUSH);
    923 		saveparam = shellparam;
    924 		shellparam.malloc = 0;
    925 		shellparam.reset = 1;
    926 		shellparam.nparam = argc - 1;
    927 		shellparam.p = argv + 1;
    928 		shellparam.optnext = NULL;
    929 		INTOFF;
    930 		savelocalvars = localvars;
    931 		localvars = NULL;
    932 		INTON;
    933 		if (setjmp(jmploc.loc)) {
    934 			if (exception == EXSHELLPROC) {
    935 				freeparam((volatile struct shparam *)
    936 				    &saveparam);
    937 			} else {
    938 				freeparam(&shellparam);
    939 				shellparam = saveparam;
    940 			}
    941 			poplocalvars();
    942 			localvars = savelocalvars;
    943 			handler = savehandler;
    944 			longjmp(handler->loc, 1);
    945 		}
    946 		savehandler = handler;
    947 		handler = &jmploc;
    948 		listmklocal(varlist.list, 0);
    949 		/* stop shell blowing its stack */
    950 		if (++funcnest > 1000)
    951 			error("too many nested function calls");
    952 		evaltree(cmdentry.u.func, flags & EV_TESTED);
    953 		funcnest--;
    954 		INTOFF;
    955 		poplocalvars();
    956 		localvars = savelocalvars;
    957 		freeparam(&shellparam);
    958 		shellparam = saveparam;
    959 		handler = savehandler;
    960 		popredir();
    961 		INTON;
    962 		if (evalskip == SKIPFUNC) {
    963 			evalskip = 0;
    964 			skipcount = 0;
    965 		}
    966 		if (flags & EV_EXIT)
    967 			exitshell(exitstatus);
    968 		break;
    969 
    970 	case CMDBUILTIN:
    971 	case CMDSPLBLTIN:
    972 #ifdef DEBUG
    973 		trputs("builtin command:  ");  trargs(argv);
    974 #endif
    975 		mode = (cmdentry.u.bltin == execcmd) ? 0 : REDIR_PUSH;
    976 		if (flags == EV_BACKCMD) {
    977 			memout.nleft = 0;
    978 			memout.nextc = memout.buf;
    979 			memout.bufsize = 64;
    980 			mode |= REDIR_BACKQ;
    981 		}
    982 		e = -1;
    983 		savehandler = handler;
    984 		savecmdname = commandname;
    985 		handler = &jmploc;
    986 		if (!setjmp(jmploc.loc)) {
    987 			/* We need to ensure the command hash table isn't
    988 			 * corruped by temporary PATH assignments.
    989 			 * However we must ensure the 'local' command works!
    990 			 */
    991 			if (path != pathval() && (cmdentry.u.bltin == hashcmd ||
    992 			    cmdentry.u.bltin == typecmd)) {
    993 				savelocalvars = localvars;
    994 				localvars = 0;
    995 				mklocal(path - 5 /* PATH= */, 0);
    996 				temp_path = 1;
    997 			} else
    998 				temp_path = 0;
    999 			redirect(cmd->ncmd.redirect, mode);
   1000 
   1001 			/* exec is a special builtin, but needs this list... */
   1002 			cmdenviron = varlist.list;
   1003 			/* we must check 'readonly' flag for all builtins */
   1004 			listsetvar(varlist.list,
   1005 				cmdentry.cmdtype == CMDSPLBLTIN ? 0 : VNOSET);
   1006 			commandname = argv[0];
   1007 			/* initialize nextopt */
   1008 			argptr = argv + 1;
   1009 			optptr = NULL;
   1010 			/* and getopt */
   1011 			optreset = 1;
   1012 			optind = 1;
   1013 			exitstatus = cmdentry.u.bltin(argc, argv);
   1014 		} else {
   1015 			e = exception;
   1016 			exitstatus = e == EXINT ? SIGINT + 128 :
   1017 					e == EXEXEC ? exerrno : 2;
   1018 		}
   1019 		handler = savehandler;
   1020 		flushall();
   1021 		out1 = &output;
   1022 		out2 = &errout;
   1023 		freestdout();
   1024 		if (temp_path) {
   1025 			poplocalvars();
   1026 			localvars = savelocalvars;
   1027 		}
   1028 		cmdenviron = NULL;
   1029 		if (e != EXSHELLPROC) {
   1030 			commandname = savecmdname;
   1031 			if (flags & EV_EXIT)
   1032 				exitshell(exitstatus);
   1033 		}
   1034 		if (e != -1) {
   1035 			if ((e != EXERROR && e != EXEXEC)
   1036 			    || cmdentry.cmdtype == CMDSPLBLTIN)
   1037 				exraise(e);
   1038 			FORCEINTON;
   1039 		}
   1040 		if (cmdentry.u.bltin != execcmd)
   1041 			popredir();
   1042 		if (flags == EV_BACKCMD) {
   1043 			backcmd->buf = memout.buf;
   1044 			backcmd->nleft = memout.nextc - memout.buf;
   1045 			memout.buf = NULL;
   1046 		}
   1047 		break;
   1048 
   1049 	default:
   1050 #ifdef DEBUG
   1051 		trputs("normal command:  ");  trargs(argv);
   1052 #endif
   1053 		clearredir(vforked);
   1054 		redirect(cmd->ncmd.redirect, vforked ? REDIR_VFORK : 0);
   1055 		if (!vforked)
   1056 			for (sp = varlist.list ; sp ; sp = sp->next)
   1057 				setvareq(sp->text, VEXPORT|VSTACK);
   1058 		envp = environment();
   1059 		shellexec(argv, envp, path, cmdentry.u.index, vforked);
   1060 		break;
   1061 	}
   1062 	goto out;
   1063 
   1064 parent:	/* parent process gets here (if we forked) */
   1065 	if (mode == FORK_FG) {	/* argument to fork */
   1066 		exitstatus = waitforjob(jp);
   1067 	} else if (mode == FORK_NOJOB) {
   1068 		backcmd->fd = pip[0];
   1069 		close(pip[1]);
   1070 		backcmd->jp = jp;
   1071 	}
   1072 	FORCEINTON;
   1073 
   1074 out:
   1075 	if (lastarg)
   1076 		/* dsl: I think this is intended to be used to support
   1077 		 * '_' in 'vi' command mode during line editing...
   1078 		 * However I implemented that within libedit itself.
   1079 		 */
   1080 		setvar("_", lastarg, 0);
   1081 	popstackmark(&smark);
   1082 }
   1083 
   1084 
   1085 /*
   1086  * Search for a command.  This is called before we fork so that the
   1087  * location of the command will be available in the parent as well as
   1088  * the child.  The check for "goodname" is an overly conservative
   1089  * check that the name will not be subject to expansion.
   1090  */
   1091 
   1092 STATIC void
   1093 prehash(union node *n)
   1094 {
   1095 	struct cmdentry entry;
   1096 
   1097 	if (n && n->type == NCMD && n->ncmd.args)
   1098 		if (goodname(n->ncmd.args->narg.text))
   1099 			find_command(n->ncmd.args->narg.text, &entry, 0,
   1100 				     pathval());
   1101 }
   1102 
   1103 
   1104 
   1105 /*
   1106  * Builtin commands.  Builtin commands whose functions are closely
   1107  * tied to evaluation are implemented here.
   1108  */
   1109 
   1110 /*
   1111  * No command given.
   1112  */
   1113 
   1114 int
   1115 bltincmd(int argc, char **argv)
   1116 {
   1117 	/*
   1118 	 * Preserve exitstatus of a previous possible redirection
   1119 	 * as POSIX mandates
   1120 	 */
   1121 	return back_exitstatus;
   1122 }
   1123 
   1124 
   1125 /*
   1126  * Handle break and continue commands.  Break, continue, and return are
   1127  * all handled by setting the evalskip flag.  The evaluation routines
   1128  * above all check this flag, and if it is set they start skipping
   1129  * commands rather than executing them.  The variable skipcount is
   1130  * the number of loops to break/continue, or the number of function
   1131  * levels to return.  (The latter is always 1.)  It should probably
   1132  * be an error to break out of more loops than exist, but it isn't
   1133  * in the standard shell so we don't make it one here.
   1134  */
   1135 
   1136 int
   1137 breakcmd(int argc, char **argv)
   1138 {
   1139 	int n = argc > 1 ? number(argv[1]) : 1;
   1140 
   1141 	if (n > loopnest)
   1142 		n = loopnest;
   1143 	if (n > 0) {
   1144 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
   1145 		skipcount = n;
   1146 	}
   1147 	return 0;
   1148 }
   1149 
   1150 
   1151 /*
   1152  * The return command.
   1153  */
   1154 
   1155 int
   1156 returncmd(int argc, char **argv)
   1157 {
   1158 	int ret = argc > 1 ? number(argv[1]) : exitstatus;
   1159 
   1160 	if (funcnest) {
   1161 		evalskip = SKIPFUNC;
   1162 		skipcount = 1;
   1163 		return ret;
   1164 	}
   1165 	else {
   1166 		/* Do what ksh does; skip the rest of the file */
   1167 		evalskip = SKIPFILE;
   1168 		skipcount = 1;
   1169 		return ret;
   1170 	}
   1171 }
   1172 
   1173 
   1174 int
   1175 falsecmd(int argc, char **argv)
   1176 {
   1177 	return 1;
   1178 }
   1179 
   1180 
   1181 int
   1182 truecmd(int argc, char **argv)
   1183 {
   1184 	return 0;
   1185 }
   1186 
   1187 
   1188 int
   1189 execcmd(int argc, char **argv)
   1190 {
   1191 	if (argc > 1) {
   1192 		struct strlist *sp;
   1193 
   1194 		iflag = 0;		/* exit on error */
   1195 		mflag = 0;
   1196 		optschanged();
   1197 		for (sp = cmdenviron; sp; sp = sp->next)
   1198 			setvareq(sp->text, VEXPORT|VSTACK);
   1199 		shellexec(argv + 1, environment(), pathval(), 0, 0);
   1200 	}
   1201 	return 0;
   1202 }
   1203 
   1204 static int
   1205 conv_time(clock_t ticks, char *seconds, size_t l)
   1206 {
   1207 	static clock_t tpm = 0;
   1208 	clock_t mins;
   1209 	int i;
   1210 
   1211 	if (!tpm)
   1212 		tpm = sysconf(_SC_CLK_TCK) * 60;
   1213 
   1214 	mins = ticks / tpm;
   1215 	snprintf(seconds, l, "%.4f", (ticks - mins * tpm) * 60.0 / tpm );
   1216 
   1217 	if (seconds[0] == '6' && seconds[1] == '0') {
   1218 		/* 59.99995 got rounded up... */
   1219 		mins++;
   1220 		strlcpy(seconds, "0.0", l);
   1221 		return mins;
   1222 	}
   1223 
   1224 	/* suppress trailing zeros */
   1225 	i = strlen(seconds) - 1;
   1226 	for (; seconds[i] == '0' && seconds[i - 1] != '.'; i--)
   1227 		seconds[i] = 0;
   1228 	return mins;
   1229 }
   1230 
   1231 int
   1232 timescmd(int argc, char **argv)
   1233 {
   1234 	struct tms tms;
   1235 	int u, s, cu, cs;
   1236 	char us[8], ss[8], cus[8], css[8];
   1237 
   1238 	nextopt("");
   1239 
   1240 	times(&tms);
   1241 
   1242 	u = conv_time(tms.tms_utime, us, sizeof(us));
   1243 	s = conv_time(tms.tms_stime, ss, sizeof(ss));
   1244 	cu = conv_time(tms.tms_cutime, cus, sizeof(cus));
   1245 	cs = conv_time(tms.tms_cstime, css, sizeof(css));
   1246 
   1247 	outfmt(out1, "%dm%ss %dm%ss\n%dm%ss %dm%ss\n",
   1248 		u, us, s, ss, cu, cus, cs, css);
   1249 
   1250 	return 0;
   1251 }
   1252