Home | History | Annotate | Line # | Download | only in sh
eval.c revision 1.152
      1 /*	$NetBSD: eval.c,v 1.152 2017/09/29 17:53:57 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.152 2017/09/29 17:53:57 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 			out2str(expandstr(ps4val(), line_number));
    283 			out2str("using redirections:");
    284 			for (rn = n->nredir.redirect; rn; rn = rn->nfile.next)
    285 				(void) outredir(&errout, rn, ' ');
    286 			out2str(" do\n");
    287 			flushout(&errout);
    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 			out2str(expandstr(ps4val(), line_number));
    294 			out2str("done\n");
    295 			flushout(&errout);
    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 			out2str(expandstr(ps4val(), line_number));
    441 			out2str("for ");
    442 			out2str(n->nfor.var);
    443 			out2c('=');
    444 			out2shstr(sp->text);
    445 			out2c('\n');
    446 			flushout(&errout);
    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 		out2str(expandstr(ps4val(), line_number));
    527 		out2str("using redirections:");
    528 		for (rn = n->nredir.redirect; rn; rn = rn->nfile.next)
    529 			(void) outredir(&errout, rn, ' ');
    530 		out2str(" do subshell\n");
    531 		flushout(&errout);
    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 		out2str(expandstr(ps4val(), line_number));
    547 		out2str("done subshell\n");
    548 		flushout(&errout);
    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 static 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\n", cmd, flags));
    801 	setstackmark(&smark);
    802 	back_exitstatus = 0;
    803 
    804 	line_number = cmd->ncmd.lineno;
    805 
    806 	arglist.lastp = &arglist.list;
    807 	varflag = 1;
    808 	/* Expand arguments, ignoring the initial 'name=value' ones */
    809 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
    810 		char *p = argp->narg.text;
    811 
    812 		line_number = argp->narg.lineno;
    813 		if (varflag && is_name(*p)) {
    814 			do {
    815 				p++;
    816 			} while (is_in_name(*p));
    817 			if (*p == '=')
    818 				continue;
    819 		}
    820 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
    821 		varflag = 0;
    822 	}
    823 	*arglist.lastp = NULL;
    824 
    825 	expredir(cmd->ncmd.redirect);
    826 
    827 	/* Now do the initial 'name=value' ones we skipped above */
    828 	varlist.lastp = &varlist.list;
    829 	for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
    830 		char *p = argp->narg.text;
    831 
    832 		line_number = argp->narg.lineno;
    833 		if (!is_name(*p))
    834 			break;
    835 		do
    836 			p++;
    837 		while (is_in_name(*p));
    838 		if (*p != '=')
    839 			break;
    840 		expandarg(argp, &varlist, EXP_VARTILDE);
    841 	}
    842 	*varlist.lastp = NULL;
    843 
    844 	argc = 0;
    845 	for (sp = arglist.list ; sp ; sp = sp->next)
    846 		argc++;
    847 	argv = stalloc(sizeof (char *) * (argc + 1));
    848 
    849 	for (sp = arglist.list ; sp ; sp = sp->next) {
    850 		VTRACE(DBG_EVAL, ("evalcommand arg: %s\n", sp->text));
    851 		*argv++ = sp->text;
    852 	}
    853 	*argv = NULL;
    854 	lastarg = NULL;
    855 	if (iflag && funcnest == 0 && argc > 0)
    856 		lastarg = argv[-1];
    857 	argv -= argc;
    858 
    859 	/* Print the command if xflag is set. */
    860 	if (xflag) {
    861 		char sep = 0;
    862 		union node *rn;
    863 
    864 		out2str(expandstr(ps4val(), line_number));
    865 		for (sp = varlist.list ; sp ; sp = sp->next) {
    866 			char *p;
    867 
    868 			if (sep != 0)
    869 				outc(sep, &errout);
    870 
    871 			/*
    872 			 * The "var=" part should not be quoted, regardless
    873 			 * of the value, or it would not represent an
    874 			 * assignment, but rather a command
    875 			 */
    876 			p = strchr(sp->text, '=');
    877 			if (p != NULL) {
    878 				*p = '\0';	/*XXX*/
    879 				out2shstr(sp->text);
    880 				out2c('=');
    881 				*p++ = '=';	/*XXX*/
    882 			} else
    883 				p = sp->text;
    884 			out2shstr(p);
    885 			sep = ' ';
    886 		}
    887 		for (sp = arglist.list ; sp ; sp = sp->next) {
    888 			if (sep != 0)
    889 				outc(sep, &errout);
    890 			out2shstr(sp->text);
    891 			sep = ' ';
    892 		}
    893 		for (rn = cmd->ncmd.redirect; rn; rn = rn->nfile.next)
    894 			if (outredir(&errout, rn, sep))
    895 				sep = ' ';
    896 		outc('\n', &errout);
    897 		flushout(&errout);
    898 	}
    899 
    900 	/* Now locate the command. */
    901 	if (argc == 0) {
    902 		cmdentry.cmdtype = CMDSPLBLTIN;
    903 		cmdentry.u.bltin = bltincmd;
    904 	} else {
    905 		static const char PATH[] = "PATH=";
    906 		int cmd_flags = DO_ERR;
    907 
    908 		/*
    909 		 * Modify the command lookup path, if a PATH= assignment
    910 		 * is present
    911 		 */
    912 		for (sp = varlist.list; sp; sp = sp->next)
    913 			if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0)
    914 				path = sp->text + sizeof(PATH) - 1;
    915 
    916 		do {
    917 			int argsused, use_syspath;
    918 
    919 			find_command(argv[0], &cmdentry, cmd_flags, path);
    920 			if (cmdentry.cmdtype == CMDUNKNOWN) {
    921 				exitstatus = 127;
    922 				flushout(&errout);
    923 				goto out;
    924 			}
    925 
    926 			/* implement the 'command' builtin here */
    927 			if (cmdentry.cmdtype != CMDBUILTIN ||
    928 			    cmdentry.u.bltin != bltincmd)
    929 				break;
    930 			cmd_flags |= DO_NOFUNC;
    931 			argsused = parse_command_args(argc, argv, &use_syspath);
    932 			if (argsused == 0) {
    933 				/* use 'type' builting to display info */
    934 				cmdentry.u.bltin = typecmd;
    935 				break;
    936 			}
    937 			argc -= argsused;
    938 			argv += argsused;
    939 			if (use_syspath)
    940 				path = syspath() + 5;
    941 		} while (argc != 0);
    942 		if (cmdentry.cmdtype == CMDSPLBLTIN && cmd_flags & DO_NOFUNC)
    943 			/* posix mandates that 'command <splbltin>' act as if
    944 			   <splbltin> was a normal builtin */
    945 			cmdentry.cmdtype = CMDBUILTIN;
    946 	}
    947 
    948 	/* Fork off a child process if necessary. */
    949 	if (cmd->ncmd.backgnd || (trap[0] && (flags & EV_EXIT) != 0)
    950 	 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
    951 	 || ((flags & EV_BACKCMD) != 0
    952 	    && ((cmdentry.cmdtype != CMDBUILTIN && cmdentry.cmdtype != CMDSPLBLTIN)
    953 		 || cmdentry.u.bltin == dotcmd
    954 		 || cmdentry.u.bltin == evalcmd))) {
    955 		INTOFF;
    956 		jp = makejob(cmd, 1);
    957 		mode = cmd->ncmd.backgnd;
    958 		if (mode)
    959 			flags &= ~EV_MORE;
    960 		if (flags & EV_BACKCMD) {
    961 			mode = FORK_NOJOB;
    962 			if (sh_pipe(pip) < 0)
    963 				error("Pipe call failed");
    964 		}
    965 #ifdef DO_SHAREDVFORK
    966 		/* It is essential that if DO_SHAREDVFORK is defined that the
    967 		 * child's address space is actually shared with the parent as
    968 		 * we rely on this.
    969 		 */
    970 		if (usefork == 0 && cmdentry.cmdtype == CMDNORMAL) {
    971 			pid_t	pid;
    972 			int serrno;
    973 
    974 			savelocalvars = localvars;
    975 			localvars = NULL;
    976 			vforked = 1;
    977 	VFORK_BLOCK
    978 			switch (pid = vfork()) {
    979 			case -1:
    980 				serrno = errno;
    981 				VTRACE(DBG_EVAL, ("vfork() failed, errno=%d\n",
    982 				    serrno));
    983 				INTON;
    984 				error("Cannot vfork (%s)", strerror(serrno));
    985 				break;
    986 			case 0:
    987 				/* Make sure that exceptions only unwind to
    988 				 * after the vfork(2)
    989 				 */
    990 				SHELL_FORKED();
    991 				if (setjmp(jmploc.loc)) {
    992 					if (exception == EXSHELLPROC) {
    993 						/*
    994 						 * We can't progress with the
    995 						 * vfork, so, set vforked = 2
    996 						 * so the parent knows,
    997 						 * and _exit();
    998 						 */
    999 						vforked = 2;
   1000 						_exit(0);
   1001 					} else {
   1002 						_exit(exerrno);
   1003 					}
   1004 				}
   1005 				savehandler = handler;
   1006 				handler = &jmploc;
   1007 				listmklocal(varlist.list, VEXPORT | VNOFUNC);
   1008 				forkchild(jp, cmd, mode, vforked);
   1009 				break;
   1010 			default:
   1011 				VFORK_UNDO();
   1012 						/* restore from vfork(2) */
   1013 				handler = savehandler;
   1014 				poplocalvars();
   1015 				localvars = savelocalvars;
   1016 				if (vforked == 2) {
   1017 					vforked = 0;
   1018 
   1019 					(void)waitpid(pid, NULL, 0);
   1020 					/*
   1021 					 * We need to progress in a
   1022 					 * normal fork fashion
   1023 					 */
   1024 					goto normal_fork;
   1025 				}
   1026 				/*
   1027 				 * Here the child has left home,
   1028 				 * getting on with its life, so
   1029 				 * so must we...
   1030 				 */
   1031 				vforked = 0;
   1032 				forkparent(jp, cmd, mode, pid);
   1033 				goto parent;
   1034 			}
   1035 	VFORK_END
   1036 		} else {
   1037  normal_fork:
   1038 #endif
   1039 			if (forkshell(jp, cmd, mode) != 0)
   1040 				goto parent;	/* at end of routine */
   1041 			FORCEINTON;
   1042 #ifdef DO_SHAREDVFORK
   1043 		}
   1044 #endif
   1045 		if (flags & EV_BACKCMD) {
   1046 			if (!vforked) {
   1047 				FORCEINTON;
   1048 			}
   1049 			close(pip[0]);
   1050 			movefd(pip[1], 1);
   1051 		}
   1052 		flags |= EV_EXIT;
   1053 	}
   1054 
   1055 	/* This is the child process if a fork occurred. */
   1056 	/* Execute the command. */
   1057 	switch (cmdentry.cmdtype) {
   1058 	case CMDFUNCTION:
   1059 		VXTRACE(DBG_EVAL, ("Shell function%s:  ",vforked?" VF":""),
   1060 		    trargs(argv));
   1061 		redirect(cmd->ncmd.redirect, flags & EV_MORE ? REDIR_PUSH : 0);
   1062 		saveparam = shellparam;
   1063 		shellparam.malloc = 0;
   1064 		shellparam.reset = 1;
   1065 		shellparam.nparam = argc - 1;
   1066 		shellparam.p = argv + 1;
   1067 		shellparam.optnext = NULL;
   1068 		INTOFF;
   1069 		savelocalvars = localvars;
   1070 		localvars = NULL;
   1071 		INTON;
   1072 		if (setjmp(jmploc.loc)) {
   1073 			if (exception == EXSHELLPROC) {
   1074 				freeparam((volatile struct shparam *)
   1075 				    &saveparam);
   1076 			} else {
   1077 				freeparam(&shellparam);
   1078 				shellparam = saveparam;
   1079 			}
   1080 			poplocalvars();
   1081 			localvars = savelocalvars;
   1082 			funclinebase = savefuncline;
   1083 			funclineabs = savefuncabs;
   1084 			handler = savehandler;
   1085 			longjmp(handler->loc, 1);
   1086 		}
   1087 		savehandler = handler;
   1088 		handler = &jmploc;
   1089 		if (cmdentry.u.func) {
   1090 			if (cmdentry.lno_frel)
   1091 				funclinebase = cmdentry.lineno - 1;
   1092 			else
   1093 				funclinebase = 0;
   1094 			funclineabs = cmdentry.lineno;
   1095 
   1096 			VTRACE(DBG_EVAL,
   1097 			  ("function: node: %d '%s' # %d%s; funclinebase=%d\n",
   1098 			    cmdentry.u.func->type,
   1099 			    NODETYPENAME(cmdentry.u.func->type),
   1100 			    cmdentry.lineno, cmdentry.lno_frel?" (=1)":"",
   1101 			    funclinebase));
   1102 		}
   1103 		listmklocal(varlist.list, VEXPORT);
   1104 		/* stop shell blowing its stack */
   1105 		if (++funcnest > 1000)
   1106 			error("too many nested function calls");
   1107 		evaltree(cmdentry.u.func, flags & EV_TESTED);
   1108 		funcnest--;
   1109 		INTOFF;
   1110 		poplocalvars();
   1111 		localvars = savelocalvars;
   1112 		funclinebase = savefuncline;
   1113 		funclineabs = savefuncabs;
   1114 		freeparam(&shellparam);
   1115 		shellparam = saveparam;
   1116 		handler = savehandler;
   1117 		if (flags & EV_MORE)
   1118 			popredir();
   1119 		INTON;
   1120 		if (evalskip == SKIPFUNC) {
   1121 			evalskip = SKIPNONE;
   1122 			skipcount = 0;
   1123 		}
   1124 		if (flags & EV_EXIT)
   1125 			exitshell(exitstatus);
   1126 		break;
   1127 
   1128 	case CMDBUILTIN:
   1129 	case CMDSPLBLTIN:
   1130 		VXTRACE(DBG_EVAL, ("builtin command%s:  ",vforked?" VF":""), trargs(argv));
   1131 		mode = (cmdentry.u.bltin == execcmd) ? 0 : REDIR_PUSH;
   1132 		if (flags == EV_BACKCMD) {
   1133 			memout.nleft = 0;
   1134 			memout.nextc = memout.buf;
   1135 			memout.bufsize = 64;
   1136 			mode |= REDIR_BACKQ;
   1137 		}
   1138 		e = -1;
   1139 		savehandler = handler;
   1140 		savecmdname = commandname;
   1141 		handler = &jmploc;
   1142 		temp_path = 0;
   1143 		if (!setjmp(jmploc.loc)) {
   1144 			/*
   1145 			 * We need to ensure the command hash table isn't
   1146 			 * corrupted by temporary PATH assignments.
   1147 			 * However we must ensure the 'local' command works!
   1148 			 */
   1149 			if (path != pathval() && (cmdentry.u.bltin == hashcmd ||
   1150 			    cmdentry.u.bltin == typecmd)) {
   1151 				savelocalvars = localvars;
   1152 				localvars = 0;
   1153 				temp_path = 1;
   1154 				mklocal(path - 5 /* PATH= */, 0);
   1155 			}
   1156 			redirect(cmd->ncmd.redirect, mode);
   1157 
   1158 			/* exec is a special builtin, but needs this list... */
   1159 			cmdenviron = varlist.list;
   1160 			/* we must check 'readonly' flag for all builtins */
   1161 			listsetvar(varlist.list,
   1162 				cmdentry.cmdtype == CMDSPLBLTIN ? 0 : VNOSET);
   1163 			commandname = argv[0];
   1164 			/* initialize nextopt */
   1165 			argptr = argv + 1;
   1166 			optptr = NULL;
   1167 			/* and getopt */
   1168 			optreset = 1;
   1169 			optind = 1;
   1170 			builtin_flags = flags;
   1171 			exitstatus = cmdentry.u.bltin(argc, argv);
   1172 		} else {
   1173 			e = exception;
   1174 			exitstatus = e == EXINT ? SIGINT + 128 :
   1175 					e == EXEXEC ? exerrno : 2;
   1176 		}
   1177 		handler = savehandler;
   1178 		flushall();
   1179 		out1 = &output;
   1180 		out2 = &errout;
   1181 		freestdout();
   1182 		if (temp_path) {
   1183 			poplocalvars();
   1184 			localvars = savelocalvars;
   1185 		}
   1186 		cmdenviron = NULL;
   1187 		if (e != EXSHELLPROC) {
   1188 			commandname = savecmdname;
   1189 			if (flags & EV_EXIT)
   1190 				exitshell(exitstatus);
   1191 		}
   1192 		if (e != -1) {
   1193 			if ((e != EXERROR && e != EXEXEC)
   1194 			    || cmdentry.cmdtype == CMDSPLBLTIN)
   1195 				exraise(e);
   1196 			FORCEINTON;
   1197 		}
   1198 		if (cmdentry.u.bltin != execcmd)
   1199 			popredir();
   1200 		if (flags == EV_BACKCMD) {
   1201 			backcmd->buf = memout.buf;
   1202 			backcmd->nleft = memout.nextc - memout.buf;
   1203 			memout.buf = NULL;
   1204 		}
   1205 		break;
   1206 
   1207 	default:
   1208 		VXTRACE(DBG_EVAL, ("normal command%s:  ", vforked?" VF":""),
   1209 		    trargs(argv));
   1210 		redirect(cmd->ncmd.redirect,
   1211 		    (vforked ? REDIR_VFORK : 0) | REDIR_KEEP);
   1212 		if (!vforked)
   1213 			for (sp = varlist.list ; sp ; sp = sp->next)
   1214 				setvareq(sp->text, VEXPORT|VSTACK);
   1215 		envp = environment();
   1216 		shellexec(argv, envp, path, cmdentry.u.index, vforked);
   1217 		break;
   1218 	}
   1219 	goto out;
   1220 
   1221  parent:			/* parent process gets here (if we forked) */
   1222 
   1223 	exitstatus = 0;		/* if not altered just below */
   1224 	if (mode == FORK_FG) {	/* argument to fork */
   1225 		exitstatus = waitforjob(jp);
   1226 	} else if (mode == FORK_NOJOB) {
   1227 		backcmd->fd = pip[0];
   1228 		close(pip[1]);
   1229 		backcmd->jp = jp;
   1230 	}
   1231 	FORCEINTON;
   1232 
   1233  out:
   1234 	if (lastarg)
   1235 		/* implement $_ for whatever use that really is */
   1236 		(void) setvarsafe("_", lastarg, VNOERROR);
   1237 	popstackmark(&smark);
   1238 }
   1239 
   1240 
   1241 /*
   1242  * Search for a command.  This is called before we fork so that the
   1243  * location of the command will be available in the parent as well as
   1244  * the child.  The check for "goodname" is an overly conservative
   1245  * check that the name will not be subject to expansion.
   1246  */
   1247 
   1248 STATIC void
   1249 prehash(union node *n)
   1250 {
   1251 	struct cmdentry entry;
   1252 
   1253 	if (n && n->type == NCMD && n->ncmd.args)
   1254 		if (goodname(n->ncmd.args->narg.text))
   1255 			find_command(n->ncmd.args->narg.text, &entry, 0,
   1256 				     pathval());
   1257 }
   1258 
   1259 int
   1260 in_function(void)
   1261 {
   1262 	return funcnest;
   1263 }
   1264 
   1265 enum skipstate
   1266 current_skipstate(void)
   1267 {
   1268 	return evalskip;
   1269 }
   1270 
   1271 void
   1272 stop_skipping(void)
   1273 {
   1274 	evalskip = SKIPNONE;
   1275 	skipcount = 0;
   1276 }
   1277 
   1278 /*
   1279  * Builtin commands.  Builtin commands whose functions are closely
   1280  * tied to evaluation are implemented here.
   1281  */
   1282 
   1283 /*
   1284  * No command given.
   1285  */
   1286 
   1287 int
   1288 bltincmd(int argc, char **argv)
   1289 {
   1290 	/*
   1291 	 * Preserve exitstatus of a previous possible redirection
   1292 	 * as POSIX mandates
   1293 	 */
   1294 	return back_exitstatus;
   1295 }
   1296 
   1297 
   1298 /*
   1299  * Handle break and continue commands.  Break, continue, and return are
   1300  * all handled by setting the evalskip flag.  The evaluation routines
   1301  * above all check this flag, and if it is set they start skipping
   1302  * commands rather than executing them.  The variable skipcount is
   1303  * the number of loops to break/continue, or the number of function
   1304  * levels to return.  (The latter is always 1.)  It should probably
   1305  * be an error to break out of more loops than exist, but it isn't
   1306  * in the standard shell so we don't make it one here.
   1307  */
   1308 
   1309 int
   1310 breakcmd(int argc, char **argv)
   1311 {
   1312 	int n = argc > 1 ? number(argv[1]) : 1;
   1313 
   1314 	if (n <= 0)
   1315 		error("invalid count: %d", n);
   1316 	if (n > loopnest)
   1317 		n = loopnest;
   1318 	if (n > 0) {
   1319 		evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
   1320 		skipcount = n;
   1321 	}
   1322 	return 0;
   1323 }
   1324 
   1325 int
   1326 dotcmd(int argc, char **argv)
   1327 {
   1328 	exitstatus = 0;
   1329 
   1330 	if (argc >= 2) {		/* That's what SVR2 does */
   1331 		char *fullname;
   1332 		/*
   1333 		 * dot_funcnest needs to be 0 when not in a dotcmd, so it
   1334 		 * cannot be restored with (funcnest + 1).
   1335 		 */
   1336 		int dot_funcnest_old;
   1337 		struct stackmark smark;
   1338 
   1339 		setstackmark(&smark);
   1340 		fullname = find_dot_file(argv[1]);
   1341 		setinputfile(fullname, 1);
   1342 		commandname = fullname;
   1343 		dot_funcnest_old = dot_funcnest;
   1344 		dot_funcnest = funcnest + 1;
   1345 		cmdloop(0);
   1346 		dot_funcnest = dot_funcnest_old;
   1347 		popfile();
   1348 		popstackmark(&smark);
   1349 	}
   1350 	return exitstatus;
   1351 }
   1352 
   1353 /*
   1354  * Take commands from a file.  To be compatible we should do a path
   1355  * search for the file, which is necessary to find sub-commands.
   1356  */
   1357 
   1358 STATIC char *
   1359 find_dot_file(char *basename)
   1360 {
   1361 	char *fullname;
   1362 	const char *path = pathval();
   1363 	struct stat statb;
   1364 
   1365 	/* don't try this for absolute or relative paths */
   1366 	if (strchr(basename, '/')) {
   1367 		if (stat(basename, &statb) == 0) {
   1368 			if (S_ISDIR(statb.st_mode))
   1369 				error("%s: is a directory", basename);
   1370 			if (S_ISBLK(statb.st_mode))
   1371 				error("%s: is a block device", basename);
   1372 			return basename;
   1373 		}
   1374 	} else while ((fullname = padvance(&path, basename, 1)) != NULL) {
   1375 		if ((stat(fullname, &statb) == 0)) {
   1376 			/* weird format is to ease future code... */
   1377 			if (S_ISDIR(statb.st_mode) || S_ISBLK(statb.st_mode))
   1378 				;
   1379 #if notyet
   1380 			else if (unreadable()) {
   1381 				/*
   1382 				 * testing this via st_mode is ugly to get
   1383 				 * correct (and would ignore ACLs).
   1384 				 * better way is just to open the file.
   1385 				 * But doing that here would (currently)
   1386 				 * mean opening the file twice, which
   1387 				 * might not be safe.  So, defer this
   1388 				 * test until code is restructures so
   1389 				 * we can return a fd.   Then we also
   1390 				 * get to fix the mem leak just below...
   1391 				 */
   1392 			}
   1393 #endif
   1394 			else {
   1395 				/*
   1396 				 * Don't bother freeing here, since
   1397 				 * it will be freed by the caller.
   1398 				 * XXX no it won't - a bug for later.
   1399 				 */
   1400 				return fullname;
   1401 			}
   1402 		}
   1403 		stunalloc(fullname);
   1404 	}
   1405 
   1406 	/* not found in the PATH */
   1407 	error("%s: not found", basename);
   1408 	/* NOTREACHED */
   1409 }
   1410 
   1411 
   1412 
   1413 /*
   1414  * The return command.
   1415  *
   1416  * Quoth the POSIX standard:
   1417  *   The return utility shall cause the shell to stop executing the current
   1418  *   function or dot script. If the shell is not currently executing
   1419  *   a function or dot script, the results are unspecified.
   1420  *
   1421  * As for the unspecified part, there seems to be no de-facto standard: bash
   1422  * ignores the return with a warning, zsh ignores the return in interactive
   1423  * mode but seems to liken it to exit in a script.  (checked May 2014)
   1424  *
   1425  * We choose to silently ignore the return.  Older versions of this shell
   1426  * set evalskip to SKIPFILE causing the shell to (indirectly) exit.  This
   1427  * had at least the problem of circumventing the check for stopped jobs,
   1428  * which would occur for exit or ^D.
   1429  */
   1430 
   1431 int
   1432 returncmd(int argc, char **argv)
   1433 {
   1434 	int ret = argc > 1 ? number(argv[1]) : exitstatus;
   1435 
   1436 	if ((dot_funcnest == 0 && funcnest)
   1437 	    || (dot_funcnest > 0 && funcnest - (dot_funcnest - 1) > 0)) {
   1438 		evalskip = SKIPFUNC;
   1439 		skipcount = 1;
   1440 	} else if (dot_funcnest > 0) {
   1441 		evalskip = SKIPFILE;
   1442 		skipcount = 1;
   1443 	} else {
   1444 		/* XXX: should a warning be issued? */
   1445 		ret = 0;
   1446 	}
   1447 
   1448 	return ret;
   1449 }
   1450 
   1451 
   1452 int
   1453 falsecmd(int argc, char **argv)
   1454 {
   1455 	return 1;
   1456 }
   1457 
   1458 
   1459 int
   1460 truecmd(int argc, char **argv)
   1461 {
   1462 	return 0;
   1463 }
   1464 
   1465 
   1466 int
   1467 execcmd(int argc, char **argv)
   1468 {
   1469 	if (argc > 1) {
   1470 		struct strlist *sp;
   1471 
   1472 		iflag = 0;		/* exit on error */
   1473 		mflag = 0;
   1474 		optschanged();
   1475 		for (sp = cmdenviron; sp; sp = sp->next)
   1476 			setvareq(sp->text, VEXPORT|VSTACK);
   1477 		shellexec(argv + 1, environment(), pathval(), 0, 0);
   1478 	}
   1479 	return 0;
   1480 }
   1481 
   1482 static int
   1483 conv_time(clock_t ticks, char *seconds, size_t l)
   1484 {
   1485 	static clock_t tpm = 0;
   1486 	clock_t mins;
   1487 	int i;
   1488 
   1489 	if (!tpm)
   1490 		tpm = sysconf(_SC_CLK_TCK) * 60;
   1491 
   1492 	mins = ticks / tpm;
   1493 	snprintf(seconds, l, "%.4f", (ticks - mins * tpm) * 60.0 / tpm );
   1494 
   1495 	if (seconds[0] == '6' && seconds[1] == '0') {
   1496 		/* 59.99995 got rounded up... */
   1497 		mins++;
   1498 		strlcpy(seconds, "0.0", l);
   1499 		return mins;
   1500 	}
   1501 
   1502 	/* suppress trailing zeros */
   1503 	i = strlen(seconds) - 1;
   1504 	for (; seconds[i] == '0' && seconds[i - 1] != '.'; i--)
   1505 		seconds[i] = 0;
   1506 	return mins;
   1507 }
   1508 
   1509 int
   1510 timescmd(int argc, char **argv)
   1511 {
   1512 	struct tms tms;
   1513 	int u, s, cu, cs;
   1514 	char us[8], ss[8], cus[8], css[8];
   1515 
   1516 	nextopt("");
   1517 
   1518 	times(&tms);
   1519 
   1520 	u = conv_time(tms.tms_utime, us, sizeof(us));
   1521 	s = conv_time(tms.tms_stime, ss, sizeof(ss));
   1522 	cu = conv_time(tms.tms_cutime, cus, sizeof(cus));
   1523 	cs = conv_time(tms.tms_cstime, css, sizeof(css));
   1524 
   1525 	outfmt(out1, "%dm%ss %dm%ss\n%dm%ss %dm%ss\n",
   1526 		u, us, s, ss, cu, cus, cs, css);
   1527 
   1528 	return 0;
   1529 }
   1530