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