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