/*
 * execute command tree
 */

#include "sh.h"
#include "c_test.h"
#include <ctype.h>
#include "ksh_stat.h"

/* Does ps4 get parameter substitutions done? */
#ifdef KSH
# define PS4_SUBSTITUTE(s)	substitute((s), 0)
#else
# define PS4_SUBSTITUTE(s)	(s)
#endif /* KSH */

static int	comexec	 ARGS((struct op *t, struct tbl *volatile tp, char **ap,
			      int volatile flags, volatile int *xerrok));

static void	scriptexec ARGS((struct op *tp, char **ap));
static int	call_builtin ARGS((struct tbl *tp, char **wp));
static int	iosetup ARGS((struct ioword *iop, struct tbl *tp));
static int	herein ARGS((const char *content, int sub));

extern int posh_builtin_builtin(int, char **, int);
extern int posh_builtin_command(int, char **, int);
extern int posh_builtin_exec(int, char **, int);

/*
 * handle systems that don't have F_SETFD
 */
#ifndef F_SETFD
# ifndef MAXFD
#   define  MAXFD 64
# endif
/* a bit field would be smaller, but this will work */
static char clexec_tab[MAXFD+1];
#endif

static struct block *blocktemp;

/*
 * we now use this function always.
 */
int
fd_clexec(fd)
    int fd;
{
#ifndef F_SETFD
	if (fd >= 0 && fd < sizeof(clexec_tab)) {
		clexec_tab[fd] = 1;
		return 0;
	}
	return -1;
#else
	return fcntl(fd, F_SETFD, 1);
#endif
}


/*
 * execute command tree
 */
int
execute(struct op * volatile t, volatile int flags, volatile int * volatile xerrok)
{
	int i;
	volatile int rv = 0, dummy = 0;
	int pv[2];
	char ** volatile ap;
	char *s, *cp;
	struct ioword **iowp;
	struct tbl *tp = NULL;

	if (t == NULL)
		return (0);

	/* Caller doesn't care if XERROK should propagate. */
	if (xerrok == NULL)
		xerrok = &dummy;

	/* Is this the end of a pipeline?  If so, we want to evaluate the
	 * command arguments
	bool_t eval_done = FALSE;
	if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
		eval_done = TRUE;
		tp = eval_execute_args(t, &ap);
	}
	 */
	if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
		return exchild(t, flags, xerrok, -1); /* run in sub-process */

	newenv(E_EXEC);
	if (trap)
		runtraps(0);

	if (t->type == TCOM) {
		/* Clear subst_exstat before argument expansion.  Used by
		 * null commands (see comexec() and c_eval()) and by c_set().
		 */
		subst_exstat = 0;

		current_lineno = t->lineno;	/* for $LINENO */

		/* POSIX says expand command words first, then redirections,
		 * and assignments last..
		 */
		ap = eval((const char **)t->args, t->evalflags | DOBLANK | DOGLOB | DOTILDE);
		if (Flag(FXTRACE) && ap[0]) {
			shf_fprintf(shl_out, "%s",
				PS4_SUBSTITUTE(str_val(global("PS4"))));
			for (i = 0; ap[i]; i++)
				shf_fprintf(shl_out, "%s%c", ap[i],
					ap[i + 1] ? ' ' : '\n');
			shf_flush(shl_out);
		}
		if (ap[0])
			tp = findcom(ap[0], FC_BI|FC_FUNC);
	}
#ifdef SILLY_FEATURES
	flags &= ~XTIME;
#endif /* SILLY_FEATURES */

	if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
		e->savefd = (short *) alloc(sizeofN(short, NUFILE), ATEMP);
		/* initialize to not redirected */
		memset(e->savefd, 0, sizeofN(short, NUFILE));
	}

	/* do redirection, to be restored in quitenv() */
	if (t->ioact != NULL)
		for (iowp = t->ioact; *iowp != NULL; iowp++) {
			if (iosetup(*iowp, tp) < 0) {
				exstat = rv = 1;
				/* Redirection failures for special commands
				 * cause (non-interactive) shell to exit.
				 */
				if (tp && tp->type == CSHELL
				    && (tp->flag & SPEC_BI))
					errorf(NULL);
				/* Deal with FERREXIT, quitenv(), etc. */
				goto Break;
			}
		}
	
	switch(t->type) {
	  case TCOM:
		rv = comexec(t, tp, ap, flags, xerrok);
		break;

	  case TPAREN:
		rv = execute(t->left, flags | XFORK, xerrok);
		break;

	  case TPIPE:
		flags |= XFORK;
		flags &= ~XEXEC;
		e->savefd[0] = savefd(0, 0);
		(void) ksh_dup2(e->savefd[0], 0, FALSE); /* stdin of first */
		e->savefd[1] = savefd(1, 0);
		while (t->type == TPIPE) {
			openpipe(pv);
			(void) ksh_dup2(pv[1], 1, FALSE); /* stdout of curr */
			/* Let exchild() close pv[0] in child
			 * (if this isn't done, commands like
			 *    (: ; cat /etc/termcap) | sleep 1
			 *  will hang forever).
			 */
			exchild(t->left, flags | XPIPEO | XCCLOSE,
			    NULL, pv[0]);
			(void) ksh_dup2(pv[0], 0, FALSE); /* stdin of next */
			closepipe(pv);
			flags |= XPIPEI;
			t = t->right;
		}
		restfd(1, e->savefd[1]); /* stdout of last */
		e->savefd[1] = 0; /* no need to re-restore this */
		/* Let exchild() close 0 in parent, after fork, before wait */
		i = exchild(t, flags | XPCLOSE, xerrok, 0);
		if (!(flags&XBGND) && !(flags&XXCOM))
			rv = i;
		break;

	case TLIST:
		while (t->type == TLIST) {
			execute(t->left, flags & XERROK, NULL);
			t = t->right;
		}
		rv = execute(t, flags & XERROK, xerrok);
		break;


	  case TASYNC:
		/* XXX non-optimal, I think - "(foo &)", forks for (),
		 * forks again for async...  parent should optimize
		 * this to "foo &"...
		 */
		rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK, xerrok);
		break;

	case TOR:
	case TAND:
		rv = execute(t->left, XERROK, xerrok);
		if ((rv == 0) == (t->type == TAND))
			rv = execute(t->right, XERROK, xerrok);
		flags |= XERROK;
		if (xerrok)
			*xerrok = 1;
		break;

	case TBANG:
		rv = !execute(t->right, XERROK, xerrok);
		flags |= XERROK;
		if (xerrok)
			*xerrok = 1;
		break;

#ifdef KSH
	  case TDBRACKET:
	    {
		Test_env te;

		te.flags = TEF_DBRACKET;
		te.pos.wp = t->args;
		te.isa = dbteste_isa;
		te.getopnd = dbteste_getopnd;
		te.eval = dbteste_eval;
		te.error = dbteste_error;

		rv = test_parse(&te);
		break;
	    }
#endif /* KSH */

	case TFOR:
#ifdef KSH
	  case TSELECT:
	    {
		volatile bool_t is_first = TRUE;
#endif /* KSH */
		ap = (t->vars != NULL) ?
			  eval((const char **)t->vars, DOBLANK|DOGLOB|DOTILDE)
			: e->loc->argv + 1;
		e->type = E_LOOP;
		while (1) {
			i = sigsetjmp(e->jbuf, 0);
			if (!i)
				break;
			if ((e->flags&EF_BRKCONT_PASS) ||
			    (i != LBREAK && i != LCONTIN)) {
				quitenv();
				unwind(i);
			} else if (i == LBREAK) {
				rv = 0;
				goto Break;
			}
		}
		rv = 0; /* in case of a continue */
		if (t->type == TFOR) {
			while (*ap != NULL) {
				setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
				rv = execute(t->left, flags & XERROK, xerrok);
			}
		}
#ifdef KSH
		else { /* TSELECT */
			for (;;) {
				if (!(cp = do_selectargs(ap, is_first))) {
					rv = 1;
					break;
				}
				is_first = FALSE;
				setstr(global(t->str), cp, KSH_UNWIND_ERROR);
				rv = execute(t->left, flags & XERROK, xerrok);
			}
		}
	    }
#endif /* KSH */
		break;

	case TWHILE:
	case TUNTIL:
		e->type = E_LOOP;
		while (1) {
			i = sigsetjmp(e->jbuf, 0);
			if (!i)
				break;
			if ((e->flags&EF_BRKCONT_PASS) ||
			    (i != LBREAK && i != LCONTIN)) {
				quitenv();
				unwind(i);
			} else if (i == LBREAK) {
				rv = 0;
				goto Break;
			}
		}
		rv = 0; /* in case of a continue */
		while ((execute(t->left, XERROK, NULL) == 0) ==
		    (t->type == TWHILE))
			rv = execute(t->right, flags & XERROK, xerrok);
		break;

	case TIF:
	case TELIF:
		if (t->right == NULL)
			break;	/* should be error */
		rv = execute(t->left, XERROK, NULL) == 0 ?
		    execute(t->right->left, flags & XERROK, xerrok) :
		    execute(t->right->right, flags & XERROK, xerrok);
		break;

	case TCASE:
		cp = evalstr(t->str, DOTILDE);
		for (t = t->left; t != NULL && t->type == TPAT; t = t->right)
		    for (ap = t->vars; *ap; ap++)
			if ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
			    gmatchx(cp, s, FALSE))
				goto Found;
		break;
 Found:
		rv = execute(t->left, flags & XERROK, xerrok);
		break;

	case TBRACE:
		rv = execute(t->left, flags & XERROK, xerrok);
		break;

	case TFUNCT:
		rv = define(t->str, t);
		break;


	case TEXEC:		/* an eval'd TCOM */
		s = t->args[0];
		ap = makenv();
		restoresigs();
		cleanup_proc_env();
		/* XINTACT bit is for OS2 */
		ksh_execve(t->str, t->args, ap, (flags & XINTACT) ? 1 : 0);
		if (errno == ENOEXEC)
			scriptexec(t, ap);
		else
			errorf("%s: %s", s, strerror(errno));
	}
 Break:
	exstat = rv;

	quitenv();		/* restores IO */
	if ((flags&XEXEC))
		unwind(LEXIT);	/* exit child */
	if (rv != 0 && !(flags & XERROK) &&
	    (xerrok == NULL || !*xerrok)) {
		if (Flag(FERREXIT))
			unwind(LERROR);
	}
	return (rv);
}

/*
 * execute simple command
 */

static int
comexec(struct op *t, struct tbl *volatile tp, char **ap, int volatile flags, volatile int *xerrok)
{
	int i;
	int rv = 0;
	char *cp;
	static struct op texec; /* Must be static (XXX but why?) */
	int type_flags;
	int keepasn_ok;
	int fcflags = FC_BI|FC_FUNC|FC_PATH;

	/* Deal with the shell builtins builtin, exec and command since
	 * they can be followed by other commands.  This must be done before
	 * we know if we should create a local block, which must be done
	 * before we can do a path search (in case the assignments change
	 * PATH).
	 * Odd cases:
	 *	FOO=bar exec >/dev/null		FOO is kept but not exported
	 *	FOO=bar exec foobar		FOO is exported
	 *	FOO=bar command exec >/dev/null	FOO is neither kept nor exported
	 *	FOO=bar command			FOO is neither kept nor exported
	 *	PATH=... foobar			use new PATH in foobar search
	 */
	keepasn_ok = 1;
	while (tp && tp->type == CSHELL) {
		fcflags = FC_BI|FC_FUNC|FC_PATH;/* undo effects of command */
		if (tp->val.f == posh_builtin_builtin) {
			if ((cp = *++ap) == NULL) {
				tp = NULL;
				break;
			}
			tp = findcom(cp, FC_BI);
			if (tp == NULL)
				errorf("builtin: %s: not a builtin", cp);
			continue;
		} else if (tp->val.f == posh_builtin_exec) {
			if (ap[1] == NULL)
				break;
			ap++;
			flags |= XEXEC;
		} else if (tp->val.f == posh_builtin_command) {
			int optc, noargc = 0, saw_p = 0;
			char **arg;

			/* Ugly dealing with options in two places (here and
			 * in posh_builtin_command(), but such is life)
			 */

	arg = ap;

	while (*arg++)
		++noargc;

	/* We need to set optind to 0 or else +p won't work */
	optind = 0;

	while ((optc = getopt(noargc, ap, "+p")) != -1) {
		switch (optc) {
		case 'p':
			saw_p = 1;
			break;
		default:
			return 1;
		}
	}
			/* don't look for functions */
			fcflags = FC_BI|FC_PATH;
			if (saw_p) {
				fcflags |= FC_DEFPATH;
			}
			ap += optind;
			/* POSIX says special builtins lose their status
			 * if accessed using command.
			 */
			keepasn_ok = 0;
			if (!ap[0]) {
				/* ensure command with no args exits with 0 */
				subst_exstat = 0;
				break;
			}
		} else
			break;
		tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
	}
	if (keepasn_ok && (!ap[0] || (tp && (tp->flag & KEEPASN))))
		type_flags = 0;
	else {
		/* create new variable/function block */
		newblock();

		type_flags = LOCAL|LOCAL_COPY|EXPORT;

	}
	if (Flag(FEXPORT))
		type_flags |= EXPORT;
	for (i = 0; t->vars[i]; i++) {
		cp = evalstr(t->vars[i], DOASNTILDE);
		if (Flag(FXTRACE)) {
			if (i == 0)
				shf_fprintf(shl_out, "%s",
					PS4_SUBSTITUTE(str_val(global("PS4"))));
			shf_fprintf(shl_out, "%s%c", cp,
				t->vars[i + 1] ? ' ' : '\n');
			if (!t->vars[i + 1])
				shf_flush(shl_out);
		}
		typeset(cp, type_flags, 0, 0, 0);
	}

	if ((cp = *ap) == NULL) {
		rv = subst_exstat;
		goto Leave;
	} else if (!tp) {
		tp = findcom(cp, fcflags);
	}

	switch (tp->type) {
	case CSHELL:			/* shell built-in */
		rv = call_builtin(tp, ap);
		break;

	  case CFUNC:			/* function call */
	  {
/*		volatile int old_xflag; */
		volatile Tflag old_inuse;
		const char *volatile old_kshname;

		if (!(tp->flag & ISSET)) {
			struct tbl *ftp;

			if (!tp->u.fpath) {
				if (tp->u2.errno_) {
					warningf(TRUE,
				"%s: can't find function definition file - %s",
						cp, strerror(tp->u2.errno_));
					rv = 126;
				} else {
					warningf(TRUE,
				"%s: can't find function definition file", cp);
					rv = 127;
				}
				break;
			}
			if (include(tp->u.fpath, 0, NULL, 0) < 0) {
				warningf(TRUE,
			    "%s: can't open function definition file %s - %s",
					cp, tp->u.fpath, strerror(errno));
				rv = 127;
				break;
			}
			if (!(ftp = findfunc(cp, FALSE))
			    || !(ftp->flag & ISSET))
			{
				warningf(TRUE,
					"%s: function not defined by %s",
					cp, tp->u.fpath);
				rv = 127;
				break;
			}
			tp = ftp;
		}

		/* ksh functions set $0 to function name, POSIX functions leave
		 * $0 unchanged.
		 */
		old_kshname = poshname;
		ap[0] = (char *) poshname;
		e->loc->argv = ap;
		for (i = 0; *ap++ != NULL; i++)
			;
		e->loc->argc = i - 1;
		/* ksh-style functions handle getopts sanely,
		 * bourne/posix functions are insane...
		 */

/*		old_xflag = Flag(FXTRACE);
 		Flag(FXTRACE) = tp->flag & TRACE ? TRUE : FALSE; */

		old_inuse = tp->flag & FINUSE;
		tp->flag |= FINUSE;

		e->type = E_FUNC;
		i = sigsetjmp(e->jbuf, 0);
		if (i == 0) {
			/* seems odd to pass XERROK here, but AT&T ksh does */
			exstat = execute(tp->val.t, flags & XERROK, xerrok);
			i = LRETURN;
		}
		poshname = old_kshname;
/*		Flag(FXTRACE) = old_xflag; */
		tp->flag = (tp->flag & ~FINUSE) | old_inuse;
		/* Were we deleted while executing? If so, free the execution
		 * tree. todo: Unfortunately, the table entry is never re-used
		 * until the lookup table is expanded.
		 */
		if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
			if (tp->flag & ALLOC) {
				tp->flag &= ~ALLOC;
				tfree(tp->val.t, tp->areap);
			}
			tp->flag = 0;
		}
		switch (i) {
		case LRETURN:
		case LERROR:
			rv = exstat;
			break;
		case LINTR:
		case LEXIT:
		case LLEAVE:
		case LSHELL:
			quitenv();
			unwind(i);
			/*NOTREACHED*/
		default:
			quitenv();
			internal_errorf(1, "CFUNC %d", i);
		}
		break;
	}

	case CEXEC:		/* executable command */
	case CTALIAS:		/* tracked alias */
		if (!(tp->flag&ISSET)) {
			/* errno_ will be set if the named command was found
			 * but could not be executed (permissions, no execute
			 * bit, directory, etc). Print out a (hopefully)
			 * useful error message and set the exit status to 126.
			 */
			if (tp->u2.errno_) {
				warningf(TRUE, "%s: cannot execute - %s", cp,
					strerror(tp->u2.errno_));
				rv = 126;	/* POSIX */
			} else {
				warningf(TRUE, "%s: not found", cp);
				rv = 127;
			}
			break;
		}

#ifdef KSH
		/* set $_ to program's full path */
		/* setstr() can't fail here */
		setstr(typeset("_", LOCAL|EXPORT, 0, INTEGER, 0),
		    tp->val.s, KSH_RETURN_ERROR);
#endif /* KSH */

		if (flags&XEXEC) {
			j_exit();
			if (!(flags&XBGND)) {
				setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
				setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
			}
		}

		/* to fork we set up a TEXEC node and call execute */
		texec.type = TEXEC;
		texec.left = t;	/* for tprint */
		texec.str = tp->val.s;
		texec.args = ap;
		rv = exchild(&texec, flags, xerrok, -1);
		break;
	}
 Leave:
	if (flags & XEXEC) {
		exstat = rv;
		unwind(LLEAVE);
	}
	return (rv);
}

static void
scriptexec(struct op *tp, char **ap)
{
	char *shell;

	shell = str_val(global(EXECSHELL_STR));
	if (shell && *shell)
		shell = search(shell, path, X_OK, (int *) 0);
	if (!shell || !*shell)
		shell = EXECSHELL;

	*tp->args-- = tp->str;
#ifdef	SHARPBANG
	{
		char buf[LINE];
		register char *cp;
		register int fd, n;

		buf[0] = '\0';
		if ((fd = open(tp->str, O_RDONLY)) >= 0) {
			if ((n = read(fd, buf, LINE - 1)) > 0)
				buf[n] = '\0';
			(void) close(fd);
		}
		if ((buf[0] == '#' && buf[1] == '!' && (cp = &buf[2]))
		    )
		{
			while (*cp && (*cp == ' ' || *cp == '\t'))
				cp++;
			if (*cp && *cp != '\n') {
				char *a0 = cp, *a1 = (char *) 0;

				while (*cp && *cp != '\n' && *cp != ' '
				       && *cp != '\t')
				{
					cp++;
				}
				if (*cp && *cp != '\n') {
					*cp++ = '\0';
					while (*cp
					       && (*cp == ' ' || *cp == '\t'))
						cp++;
					if (*cp && *cp != '\n') {
						a1 = cp;
						/* all one argument */
						while (*cp && *cp != '\n')
							cp++;
					}
				}
				if (*cp == '\n') {
					*cp = '\0';
					if (a1)
						*tp->args-- = a1;
					shell = a0;
				}
			}
		}
	}
#endif	/* SHARPBANG */
	*tp->args = shell;

	ksh_execve(tp->args[0], tp->args, ap, 0);

	/* report both the program that was run and the bogus shell */
	errorf("%s: %s: %s", tp->str, shell, strerror(errno));
}

int
shcomexec(char **wp)
{
	struct tbl *tp;

	tp = transitional_tsearch(&builtins.root, *wp);
	if (tp == NULL)
		internal_errorf(1, "shcomexec: %s", *wp);
	return call_builtin(tp, wp);
}

/*
 * Search function tables for a function.  If create set, a table entry
 * is created if none is found.
 */
struct tbl *
findfunc(const char *name, int create)
{
	struct block *l;
	struct tbl *tp = (struct tbl *) 0;

	for (l = e->loc; l; l = l->next) {
		tp = transitional_tsearch(&l->funs.root, name);
		if (tp)
			break;
		if (!l->next && create) {
			tp = transitional_tenter(&l->funs.root, name, APERM);
			tp->flag = DEFINED;
			tp->type = CFUNC;
			tp->val.t = (struct op *) 0;
			break;
		}
	}
	blocktemp = l;
	return tp;
}

/*
 * define function.  Returns 1 if function is being undefined (t == 0) and
 * function did not exist, returns 0 otherwise.
 */
int
define(const char *name, struct op *t)
{
	struct tbl *tp;
	int was_set = 0;

	while (1) {
		tp = findfunc(name, TRUE);

		if (tp->flag & ISSET)
			was_set = 1;
		/* If this function is currently being executed, we zap this
		 * table entry so findfunc() won't see it
		 */
		if (tp->flag & FINUSE) {
			tp->name[0] = '\0';
			tp->flag &= ~DEFINED; /* ensure it won't be found */
			tp->flag |= FDELETE;
		} else
			break;
	}

	if (tp->flag & ALLOC) {
		tp->flag &= ~(ISSET|ALLOC);
		tfree(tp->val.t, tp->areap);
	}

	if (t == NULL) {		/* undefine */
		transitional_tdelete(&blocktemp->vars.root, tp);
		return was_set ? 0 : 1;
	}

	tp->val.t = tcopy(t->left, tp->areap);
	tp->flag |= (ISSET|ALLOC);

	return (0);
}

/*
 * add builtin
 */
void
builtin(const char *name, int (*func) (int, char **, int), int flags)
{
	struct tbl *tp;

	/* see if any flags should be set for this builtin */

	tp = transitional_tenter(&builtins.root, name, APERM);
	tp->flag = DEFINED | flags;
	tp->type = CSHELL;
	tp->val.f = func;
}

/*
 * find command
 * either function, hashed command, or built-in (in that order)
 */
struct tbl *
findcom(const char *name, int flags)
{
	static struct tbl temp;
	struct tbl *tp = NULL, *tbi;
	char *fpath;			/* for function autoloading */
	char *npath;

	if (ksh_strchr_dirsep(name) != NULL) {
		/* prevent FPATH search below */
		flags &= ~FC_FUNC;
		goto Search;
	}
	tbi = (flags & FC_BI) ? transitional_tsearch(&builtins.root, name) : NULL;
	/* POSIX says special builtins first, then functions, then
	 * POSIX regular builtins, then search path...
	 */
	if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
		tp = tbi;
	if (!tp && (flags & FC_FUNC)) {
		tp = findfunc(name, FALSE);
		if (tp && !(tp->flag & ISSET)) {
			if ((fpath = str_val(global("FPATH"))) == null) {
				tp->u.fpath = NULL;
				tp->u2.errno_ = 0;
			} else
				tp->u.fpath = search(name, fpath, R_OK,
					&tp->u2.errno_);
		}
	}
	if (!tp && (flags & FC_REGBI) && tbi && (tbi->flag & REG_BI))
		tp = tbi;
	/* todo: posix says non-special/non-regular builtins must
	 * be triggered by some user-controllable means like a
	 * special directory in PATH.  Requires modifications to
	 * the search() function.  Tracked aliases should be
	 * modified to allow tracking of builtin commands.
	 * This should be under control of the FPOSIX flag.
	 * If this is changed, also change c_whence...
	 */
	if (!tp && (flags & FC_UNREGBI) && tbi)
		tp = tbi;

 Search:
	if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
	    (flags & FC_PATH)) {
		if (!tp) {
				tp = &temp;
				tp->type = CEXEC;
			tp->flag = DEFINED;	/* make ~ISSET */
		}
		npath = search(name, flags & FC_DEFPATH ? def_path : path,
				X_OK, &tp->u2.errno_);
		if (npath) {
			tp->val.s = tp == &temp ? npath : str_save(npath, APERM);
			tp->flag |= ISSET|ALLOC;
		} else if ((flags & FC_FUNC)
			   && (fpath = str_val(global("FPATH"))) != null
			   && (npath = search(name, fpath, R_OK,
					      &tp->u2.errno_)) != (char *) 0)
		{
			/* An undocumented feature of at&t ksh is that it
			 * searches FPATH if a command is not found, even
			 * if the command hasn't been set up as an autoloaded
			 * function (ie, no typeset -uf).
			 */
			tp = &temp;
			tp->type = CFUNC;
			tp->flag = DEFINED; /* make ~ISSET */
			tp->u.fpath = npath;
		}
	}
	return (tp);
}

/* Check if path is something we want to find.  Returns -1 for failure. */
int
search_access(path, mode, errnop)
	const char *path;
	int mode;
	int *errnop;		/* set if candidate found, but not suitable */
{
	int ret, err = 0;
	struct stat statb;

	if (stat(path, &statb) < 0)
		return -1;
	ret = eaccess(path, mode);
	if (ret < 0)
		err = errno; /* File exists, but we can't access it */
	else if (mode == X_OK
		 && (!S_ISREG(statb.st_mode)
		     /* This 'cause access() says root can execute everything */
		     || !(statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))))
	{
		ret = -1;
		err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
	}
	if (err && errnop && !*errnop)
		*errnop = err;
	return (ret);
}

/*
 * search for command with PATH
 */
char *
search(name, path, mode, errnop)
	const char *name;
	const char *path;
	int mode;		/* R_OK or X_OK */
	int *errnop;		/* set if candidate found, but not suitable */
{
	const char *sp, *p;
	char *xp;
	XString xs;
	int namelen;

	if (errnop)
		*errnop = 0;
	if (ksh_strchr_dirsep(name)) {
		if (search_access(name, mode, errnop) == 0)
			return (char *)(name);
		return (NULL);
	}

	namelen = strlen(name) + 1;
	Xinit(xs, xp, 128, ATEMP);

	sp = path;
	while (sp != NULL) {
		xp = Xstring(xs, xp);
		if (!(p = strchr(sp, PATHSEP)))
			p = sp + strlen(sp);
		if (p != sp) {
			XcheckN(xs, xp, p - sp);
			memcpy(xp, sp, p - sp);
			xp += p - sp;
			*xp++ = DIRSEP;
		}
		sp = p;
		XcheckN(xs, xp, namelen);
		memcpy(xp, name, namelen);
		if (search_access(Xstring(xs, xp), mode, errnop) == 0)
			return Xclose(xs, xp + namelen);
		if (*sp++ == '\0')
			sp = NULL;
	}
	Xfree(xs, xp);
	return (NULL);
}

static int
call_builtin(struct tbl *tp, char **wp)
{
	int rv, noargc;
	char **arg;

	builtin_argv0 = wp[0];
	builtin_flag = tp->flag;
	shf_reopen(1, SHF_WR, shl_stdout);
	shl_stdout_ok = 1;

	optind = 1;
	noargc = 0;
	arg = wp;
	while(*arg++)
		++noargc;

	rv = (*tp->val.f)(noargc, wp, builtin_flag);
	shf_flush(shl_stdout);
	shl_stdout_ok = 0;
	builtin_flag = 0;
	builtin_argv0 = NULL;
	return (rv);
}

/*
 * set up redirection, saving old fd's in e->savefd
 */
static int
iosetup(struct ioword *iop, struct tbl UNUSED(*tp))
{
	int u = -1;
	char *cp = iop->name;
	int iotype = iop->flag & IOTYPE;
	int do_open = 1, do_close = 0, flags = 0;
	struct ioword iotmp;
	struct stat statb;

	if (iotype != IOHERE)
		cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));

	/* Used for tracing and error messages to print expanded cp */
	iotmp = *iop;
	iotmp.name = (iotype == IOHERE) ? NULL : cp;
	iotmp.flag |= IONAMEXP;

	if (Flag(FXTRACE))
		shellf("%s%s\n",
			PS4_SUBSTITUTE(str_val(global("PS4"))),
			snptreef((char *) 0, 32, "%R", &iotmp));

	switch (iotype) {
	case IOREAD:
		flags = O_RDONLY;
		break;

	case IOCAT:
		flags = O_WRONLY | O_APPEND | O_CREAT;
		break;

	case IOWRITE:
		flags = O_WRONLY | O_CREAT | O_TRUNC;
		/* The stat() is here to allow redirections to
		 * things like /dev/null without error.
		 */
		if (Flag(FNOCLOBBER) && !(iop->flag & IOCLOB) &&
		    (stat(cp, &statb) < 0 || S_ISREG(statb.st_mode)))
			flags |= O_EXCL;
		break;

	case IORDWR:
		flags = O_RDWR | O_CREAT;
		break;

	case IOHERE:
		do_open = 0;
		/* herein() returns -2 if error has been printed */
		u = herein(iop->heredoc, iop->flag & IOEVAL);
		/* cp may have wrong name */
		break;

	case IODUP: {
		const char *emsg;

		do_open = 0;
		if (*cp == '-' && !cp[1]) {
			u = 1009;	 /* prevent error return below */
			do_close = 1;
		} else if ((u = check_fd(cp,
		    X_OK | ((iop->flag & IORDUP) ? R_OK : W_OK),
		    &emsg)) < 0) {
			warningf(TRUE, "%s: %s",
			    snptreef(NULL, 32, "%R", &iotmp), emsg);
			return (-1);
		}
		if (u == iop->unit)
			return (0);		/* "dup from" == "dup to" */
		break;
	  }
	}
	if (do_open) {
		u = open(cp, flags, 0666);
	}
	if (u < 0) {
		/* herein() may already have printed message */
		if (u == -1) {
			u = errno;
			warningf(TRUE, "cannot %s %s: %s",
			    iotype == IODUP ? "dup" :
			    (iotype == IOREAD || iotype == IOHERE) ?
			    "open" : "create", cp, strerror(u));
		}
		return (-1);
	}
	/* Do not save if it has already been redirected (i.e. "cat >x >y"). */
	if (e->savefd[iop->unit] == 0) {
		/* If these are the same, it means unit was previously closed */
		if (u == iop->unit)
			e->savefd[iop->unit] = -1;
		else
			/* c_exec() assumes e->savefd[fd] set for any
			 * redirections. Ask savefd() not to close iop->unit;
			 * this allows error messages to be seen if iop->unit
			 * is 2; also means we can't lose the fd (eg, both
			 * dup2 below and dup2 in restfd() failing).
			 */
			e->savefd[iop->unit] = savefd(iop->unit, 1);
	}

	if (do_close)
		close(iop->unit);
	else if (u != iop->unit) {
		if (ksh_dup2(u, iop->unit, TRUE) < 0) {
			int ev;

			ev = errno;
			warningf(TRUE,
			    "could not finish (dup) redirection %s: %s",
			    snptreef(NULL, 32, "%R", &iotmp),
			    strerror(ev));
			if (iotype != IODUP)
				close(u);
			return (-1);
		}
		if (iotype != IODUP)
			close(u);
#ifdef KSH
		/* Touching any co-process fd in an empty exec
		 * causes the shell to close its copies
		 */
		else if (tp && tp->type == CSHELL && tp->val.f == posh_builtin_exec) {
			if (iop->flag & IORDUP)	/* possible exec <&p */
				coproc_read_close(u);
			else			/* possible exec >&p */
				coproc_write_close(u);
		}
#endif /* KSH */
	}
	if (u == 2) /* Clear any write errors */
		shf_reopen(2, SHF_WR, shl_out);
	return (0);
}

/*
 * open here document temp file.
 * if unquoted here, expand here temp file into second temp file.
 */
static int
herein(const char *content, int sub)
{
	volatile int fd = -1;
	struct source *s, *volatile osource;
	struct shf *volatile shf;
	struct temp *h;
	int i;

	/* ksh -c 'cat << EOF' can cause this... */
	if (content == NULL) {
		warningf(TRUE, "here document missing");
		return (-2); /* special to iosetup(): don't print error */
	}

	/* Create temp file to hold content (done before newenv so temp
	 * doesn't get removed too soon).
	 */
	h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
	if (!(shf = h->shf) || (fd = open(h->name, O_RDONLY, 0)) < 0) {
		warningf(TRUE, "can't %s temporary file %s: %s",
			!shf ? "create" : "open",
			h->name, strerror(errno));
		if (shf)
			shf_close(shf);
		return (-2) /* special to iosetup(): don't print error */;
	}

	osource = source;
	newenv(E_ERRH);
	i = sigsetjmp(e->jbuf, 0);
	if (i) {
		source = osource;
		quitenv();
		shf_close(shf);	/* after quitenv */
		close(fd);
		return (-2); /* special to iosetup(): don't print error */
	}
	if (sub) {
		/* Do substitutions on the content of heredoc */
		s = pushs(SSTRING, ATEMP);
		s->start = s->str = content;
		source = s;
		if (yylex(ONEWORD|HEREDOC) != LWORD)
			internal_errorf(1, "herein: yylex");
		source = osource;
		shf_puts(evalstr(yylval.cp, 0), shf);
	} else
		shf_puts(content, shf);

	quitenv();

	if (shf_close(shf) == EOF) {
		close(fd);
		warningf(TRUE, "error writing %s: %s", h->name,
			strerror(errno));
		return (-2); /* special to iosetup(): don't print error */
	}

	return (fd);
}
