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