Home | History | Annotate | Line # | Download | only in ksh
exec.c revision 1.10
      1 /*	$NetBSD: exec.c,v 1.10 2005/04/19 20:14:29 rillig Exp $	*/
      2 
      3 /*
      4  * execute command tree
      5  */
      6 #include <sys/cdefs.h>
      7 
      8 #ifndef lint
      9 __RCSID("$NetBSD: exec.c,v 1.10 2005/04/19 20:14:29 rillig Exp $");
     10 #endif
     11 
     12 
     13 #include "sh.h"
     14 #include "c_test.h"
     15 #include <ctype.h>
     16 #include "ksh_stat.h"
     17 
     18 /* Does ps4 get parameter substitutions done? */
     19 #ifdef KSH
     20 # define PS4_SUBSTITUTE(s)	substitute((s), 0)
     21 #else
     22 # define PS4_SUBSTITUTE(s)	(s)
     23 #endif /* KSH */
     24 
     25 static int	comexec	 ARGS((struct op *t, struct tbl *volatile tp, char **ap,
     26 			      int volatile flags));
     27 static void	scriptexec ARGS((struct op *tp, char **ap));
     28 static int	call_builtin ARGS((struct tbl *tp, char **wp));
     29 static int	iosetup ARGS((struct ioword *iop, struct tbl *tp));
     30 static int	herein ARGS((const char *content, int sub));
     31 #ifdef KSH
     32 static char 	*do_selectargs ARGS((char **ap, bool_t print_menu));
     33 #endif /* KSH */
     34 #ifdef KSH
     35 static int	dbteste_isa ARGS((Test_env *te, Test_meta meta));
     36 static const char *dbteste_getopnd ARGS((Test_env *te, Test_op op,
     37 					 int do_eval));
     38 static int	dbteste_eval ARGS((Test_env *te, Test_op op, const char *opnd1,
     39 				const char *opnd2, int do_eval));
     40 static void	dbteste_error ARGS((Test_env *te, int offset, const char *msg));
     41 #endif /* KSH */
     42 #ifdef OS2
     43 static int	search_access1 ARGS((const char *path, int mode, int *errnop));
     44 #endif /* OS2 */
     45 
     46 
     47 /*
     48  * handle systems that don't have F_SETFD
     49  */
     50 #ifndef F_SETFD
     51 # ifndef MAXFD
     52 #   define  MAXFD 64
     53 # endif
     54 /* a bit field would be smaller, but this will work */
     55 static char clexec_tab[MAXFD+1];
     56 #endif
     57 
     58 /*
     59  * we now use this function always.
     60  */
     61 int
     62 fd_clexec(fd)
     63     int fd;
     64 {
     65 #ifndef F_SETFD
     66 	if (fd >= 0 && fd < sizeof(clexec_tab)) {
     67 		clexec_tab[fd] = 1;
     68 		return 0;
     69 	}
     70 	return -1;
     71 #else
     72 	return fcntl(fd, F_SETFD, 1);
     73 #endif
     74 }
     75 
     76 
     77 /*
     78  * execute command tree
     79  */
     80 int
     81 execute(t, flags)
     82 	struct op * volatile t;
     83 	volatile int flags;	/* if XEXEC don't fork */
     84 {
     85 	int i;
     86 	volatile int rv = 0;
     87 	int pv[2];
     88 	char ** volatile ap;
     89 	char *s, *cp;
     90 	struct ioword **iowp;
     91 	struct tbl *tp = NULL;
     92 
     93 	if (t == NULL)
     94 		return 0;
     95 
     96 	/* Is this the end of a pipeline?  If so, we want to evaluate the
     97 	 * command arguments
     98 	bool_t eval_done = FALSE;
     99 	if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
    100 		eval_done = TRUE;
    101 		tp = eval_execute_args(t, &ap);
    102 	}
    103 	 */
    104 	if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
    105 		return exchild(t, flags & ~XTIME, -1); /* run in sub-process */
    106 
    107 	newenv(E_EXEC);
    108 	if (trap)
    109 		runtraps(0);
    110 
    111 	if (t->type == TCOM) {
    112 		/* Clear subst_exstat before argument expansion.  Used by
    113 		 * null commands (see comexec() and c_eval()) and by c_set().
    114 		 */
    115 		subst_exstat = 0;
    116 
    117 		current_lineno = t->lineno;	/* for $LINENO */
    118 
    119 		/* POSIX says expand command words first, then redirections,
    120 		 * and assignments last..
    121 		 */
    122 		ap = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
    123 		if (flags & XTIME)
    124 			/* Allow option parsing (bizarre, but POSIX) */
    125 			timex_hook(t, &ap);
    126 		if (Flag(FXTRACE) && ap[0]) {
    127 			shf_fprintf(shl_out, "%s",
    128 				PS4_SUBSTITUTE(str_val(global("PS4"))));
    129 			for (i = 0; ap[i]; i++)
    130 				shf_fprintf(shl_out, "%s%s", ap[i],
    131 					ap[i + 1] ? space : newline);
    132 			shf_flush(shl_out);
    133 		}
    134 		if (ap[0])
    135 			tp = findcom(ap[0], FC_BI|FC_FUNC);
    136 	}
    137 	flags &= ~XTIME;
    138 
    139 	if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
    140 		e->savefd = (short *) alloc(sizeofN(short, NUFILE), ATEMP);
    141 		/* initialize to not redirected */
    142 		memset(e->savefd, 0, sizeofN(short, NUFILE));
    143 	}
    144 
    145 	/* do redirection, to be restored in quitenv() */
    146 	if (t->ioact != NULL)
    147 		for (iowp = t->ioact; *iowp != NULL; iowp++) {
    148 			if (iosetup(*iowp, tp) < 0) {
    149 				exstat = rv = 1;
    150 				/* Redirection failures for special commands
    151 				 * cause (non-interactive) shell to exit.
    152 				 */
    153 				if (tp && tp->type == CSHELL
    154 				    && (tp->flag & SPEC_BI))
    155 					errorf(null);
    156 				/* Deal with FERREXIT, quitenv(), etc. */
    157 				goto Break;
    158 			}
    159 		}
    160 
    161 	switch(t->type) {
    162 	  case TCOM:
    163 		rv = comexec(t, tp, ap, flags);
    164 		break;
    165 
    166 	  case TPAREN:
    167 		rv = execute(t->left, flags|XFORK);
    168 		break;
    169 
    170 	  case TPIPE:
    171 		flags |= XFORK;
    172 		flags &= ~XEXEC;
    173 		e->savefd[0] = savefd(0, 0);
    174 		(void) ksh_dup2(e->savefd[0], 0, FALSE); /* stdin of first */
    175 		e->savefd[1] = savefd(1, 0);
    176 		while (t->type == TPIPE) {
    177 			openpipe(pv);
    178 			(void) ksh_dup2(pv[1], 1, FALSE); /* stdout of curr */
    179 			/* Let exchild() close pv[0] in child
    180 			 * (if this isn't done, commands like
    181 			 *    (: ; cat /etc/termcap) | sleep 1
    182 			 *  will hang forever).
    183 			 */
    184 			exchild(t->left, flags|XPIPEO|XCCLOSE, pv[0]);
    185 			(void) ksh_dup2(pv[0], 0, FALSE); /* stdin of next */
    186 			closepipe(pv);
    187 			flags |= XPIPEI;
    188 			t = t->right;
    189 		}
    190 		restfd(1, e->savefd[1]); /* stdout of last */
    191 		e->savefd[1] = 0; /* no need to re-restore this */
    192 		/* Let exchild() close 0 in parent, after fork, before wait */
    193 		i = exchild(t, flags|XPCLOSE, 0);
    194 		if (!(flags&XBGND) && !(flags&XXCOM))
    195 			rv = i;
    196 		break;
    197 
    198 	  case TLIST:
    199 		while (t->type == TLIST) {
    200 			execute(t->left, flags & XERROK);
    201 			t = t->right;
    202 		}
    203 		rv = execute(t, flags & XERROK);
    204 		break;
    205 
    206 #ifdef KSH
    207 	  case TCOPROC:
    208 	  {
    209 # ifdef JOB_SIGS
    210 		sigset_t	omask;
    211 # endif /* JOB_SIGS */
    212 
    213 # ifdef JOB_SIGS
    214 		/* Block sigchild as we are using things changed in the
    215 		 * signal handler
    216 		 */
    217 		sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
    218 		e->type = E_ERRH;
    219 		i = ksh_sigsetjmp(e->jbuf, 0);
    220 		if (i) {
    221 			sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
    222 			quitenv();
    223 			unwind(i);
    224 			/*NOTREACHED*/
    225 		}
    226 # endif /* JOB_SIGS */
    227 		/* Already have a (live) co-process? */
    228 		if (coproc.job && coproc.write >= 0)
    229 			errorf("coprocess already exists");
    230 
    231 		/* Can we re-use the existing co-process pipe? */
    232 		coproc_cleanup(TRUE);
    233 
    234 		/* do this before opening pipes, in case these fail */
    235 		e->savefd[0] = savefd(0, 0);
    236 		e->savefd[1] = savefd(1, 0);
    237 
    238 		openpipe(pv);
    239 		if (pv[0] != 0) {
    240 			ksh_dup2(pv[0], 0, FALSE);
    241 			close(pv[0]);
    242 		}
    243 		coproc.write = pv[1];
    244 		coproc.job = (void *) 0;
    245 
    246 		if (coproc.readw >= 0)
    247 			ksh_dup2(coproc.readw, 1, FALSE);
    248 		else {
    249 			openpipe(pv);
    250 			coproc.read = pv[0];
    251 			ksh_dup2(pv[1], 1, FALSE);
    252 			coproc.readw = pv[1];	 /* closed before first read */
    253 			coproc.njobs = 0;
    254 			/* create new coprocess id */
    255 			++coproc.id;
    256 		}
    257 # ifdef JOB_SIGS
    258 		sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
    259 		e->type = E_EXEC; /* no more need for error handler */
    260 # endif /* JOB_SIGS */
    261 
    262 		/* exchild() closes coproc.* in child after fork,
    263 		 * will also increment coproc.njobs when the
    264 		 * job is actually created.
    265 		 */
    266 		flags &= ~XEXEC;
    267 		exchild(t->left, flags|XBGND|XFORK|XCOPROC|XCCLOSE,
    268 			coproc.readw);
    269 		break;
    270 	  }
    271 #endif /* KSH */
    272 
    273 	  case TASYNC:
    274 		/* XXX non-optimal, I think - "(foo &)", forks for (),
    275 		 * forks again for async...  parent should optimize
    276 		 * this to "foo &"...
    277 		 */
    278 		rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK);
    279 		break;
    280 
    281 	  case TOR:
    282 	  case TAND:
    283 		rv = execute(t->left, XERROK);
    284 		if (t->right != NULL && (rv == 0) == (t->type == TAND))
    285 			rv = execute(t->right, flags & XERROK);
    286 		else
    287 			flags |= XERROK;
    288 		break;
    289 
    290 	  case TBANG:
    291 		rv = !execute(t->right, XERROK);
    292 		break;
    293 
    294 #ifdef KSH
    295 	  case TDBRACKET:
    296 	    {
    297 		Test_env te;
    298 
    299 		te.flags = TEF_DBRACKET;
    300 		te.pos.wp = t->args;
    301 		te.isa = dbteste_isa;
    302 		te.getopnd = dbteste_getopnd;
    303 		te.eval = dbteste_eval;
    304 		te.error = dbteste_error;
    305 
    306 		rv = test_parse(&te);
    307 		break;
    308 	    }
    309 #endif /* KSH */
    310 
    311 	  case TFOR:
    312 #ifdef KSH
    313 	  case TSELECT:
    314 	    {
    315 		volatile bool_t is_first = TRUE;
    316 #endif /* KSH */
    317 		ap = (t->vars != NULL) ?
    318 			  eval(t->vars, DOBLANK|DOGLOB|DOTILDE)
    319 			: e->loc->argv + 1;
    320 		e->type = E_LOOP;
    321 		while (1) {
    322 			i = ksh_sigsetjmp(e->jbuf, 0);
    323 			if (!i)
    324 				break;
    325 			if ((e->flags&EF_BRKCONT_PASS)
    326 			    || (i != LBREAK && i != LCONTIN))
    327 			{
    328 				quitenv();
    329 				unwind(i);
    330 			} else if (i == LBREAK) {
    331 				rv = 0;
    332 				goto Break;
    333 			}
    334 		}
    335 		rv = 0; /* in case of a continue */
    336 		if (t->type == TFOR) {
    337 			while (*ap != NULL) {
    338 				setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
    339 				rv = execute(t->left, flags & XERROK);
    340 			}
    341 		}
    342 #ifdef KSH
    343 		else { /* TSELECT */
    344 			for (;;) {
    345 				if (!(cp = do_selectargs(ap, is_first))) {
    346 					rv = 1;
    347 					break;
    348 				}
    349 				is_first = FALSE;
    350 				setstr(global(t->str), cp, KSH_UNWIND_ERROR);
    351 				rv = execute(t->left, flags & XERROK);
    352 			}
    353 		}
    354 	    }
    355 #endif /* KSH */
    356 		break;
    357 
    358 	  case TWHILE:
    359 	  case TUNTIL:
    360 		e->type = E_LOOP;
    361 		while (1) {
    362 			i = ksh_sigsetjmp(e->jbuf, 0);
    363 			if (!i)
    364 				break;
    365 			if ((e->flags&EF_BRKCONT_PASS)
    366 			    || (i != LBREAK && i != LCONTIN))
    367 			{
    368 				quitenv();
    369 				unwind(i);
    370 			} else if (i == LBREAK) {
    371 				rv = 0;
    372 				goto Break;
    373 			}
    374 		}
    375 		rv = 0; /* in case of a continue */
    376 		while ((execute(t->left, XERROK) == 0) == (t->type == TWHILE))
    377 			rv = execute(t->right, flags & XERROK);
    378 		break;
    379 
    380 	  case TIF:
    381 	  case TELIF:
    382 		if (t->right == NULL)
    383 			break;	/* should be error */
    384 		rv = execute(t->left, XERROK) == 0 ?
    385 			execute(t->right->left, flags & XERROK) :
    386 			execute(t->right->right, flags & XERROK);
    387 		break;
    388 
    389 	  case TCASE:
    390 		cp = evalstr(t->str, DOTILDE);
    391 		for (t = t->left; t != NULL && t->type == TPAT; t = t->right)
    392 		    for (ap = t->vars; *ap; ap++)
    393 			if ((s = evalstr(*ap, DOTILDE|DOPAT))
    394 			    && gmatch(cp, s, FALSE))
    395 				goto Found;
    396 		break;
    397 	  Found:
    398 		rv = execute(t->left, flags & XERROK);
    399 		break;
    400 
    401 	  case TBRACE:
    402 		rv = execute(t->left, flags & XERROK);
    403 		break;
    404 
    405 	  case TFUNCT:
    406 		rv = define(t->str, t);
    407 		break;
    408 
    409 	  case TTIME:
    410 		/* Clear XEXEC so nested execute() call doesn't exit
    411 		 * (allows "ls -l | time grep foo").
    412 		 */
    413 		rv = timex(t, flags & ~XEXEC);
    414 		break;
    415 
    416 	  case TEXEC:		/* an eval'd TCOM */
    417 		s = t->args[0];
    418 		ap = makenv();
    419 #ifndef F_SETFD
    420 		for (i = 0; i < sizeof(clexec_tab); i++)
    421 			if (clexec_tab[i]) {
    422 				close(i);
    423 				clexec_tab[i] = 0;
    424 			}
    425 #endif
    426 		restoresigs();
    427 		cleanup_proc_env();
    428 		/* XINTACT bit is for OS2 */
    429 		ksh_execve(t->str, t->args, ap, (flags & XINTACT) ? 1 : 0);
    430 		if (errno == ENOEXEC)
    431 			scriptexec(t, ap);
    432 		else
    433 			errorf("%s: %s", s, strerror(errno));
    434 	}
    435     Break:
    436 	exstat = rv;
    437 
    438 	quitenv();		/* restores IO */
    439 	if ((flags&XEXEC))
    440 		unwind(LEXIT);	/* exit child */
    441 	if (rv != 0 && !(flags & XERROK)) {
    442 		if (Flag(FERREXIT))
    443 			unwind(LERROR);
    444 		trapsig(SIGERR_);
    445 	}
    446 	return rv;
    447 }
    448 
    449 /*
    450  * execute simple command
    451  */
    452 
    453 static int
    454 comexec(t, tp, ap, flags)
    455 	struct op *t;
    456 	struct tbl *volatile tp;
    457 	register char **ap;
    458 	int volatile flags;
    459 {
    460 	int i;
    461 	volatile int rv = 0;
    462 	register char *cp;
    463 	register char **lastp;
    464 	static struct op texec; /* Must be static (XXX but why?) */
    465 	int type_flags;
    466 	int keepasn_ok;
    467 	int fcflags = FC_BI|FC_FUNC|FC_PATH;
    468 	int bourne_function_call = 0;
    469 
    470 #ifdef KSH
    471 	/* snag the last argument for $_ XXX not the same as at&t ksh,
    472 	 * which only seems to set $_ after a newline (but not in
    473 	 * functions/dot scripts, but in interactive and script) -
    474 	 * perhaps save last arg here and set it in shell()?.
    475 	 */
    476 	if (Flag(FTALKING) && *(lastp = ap)) {
    477 		while (*++lastp)
    478 			;
    479 		/* setstr() can't fail here */
    480 		setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
    481 		       KSH_RETURN_ERROR);
    482 	}
    483 #endif /* KSH */
    484 
    485 	/* Deal with the shell builtins builtin, exec and command since
    486 	 * they can be followed by other commands.  This must be done before
    487 	 * we know if we should create a local block, which must be done
    488 	 * before we can do a path search (in case the assignments change
    489 	 * PATH).
    490 	 * Odd cases:
    491 	 *   FOO=bar exec > /dev/null		FOO is kept but not exported
    492 	 *   FOO=bar exec foobar		FOO is exported
    493 	 *   FOO=bar command exec > /dev/null	FOO is neither kept nor exported
    494 	 *   FOO=bar command			FOO is neither kept nor exported
    495 	 *   PATH=... foobar			use new PATH in foobar search
    496 	 */
    497 	keepasn_ok = 1;
    498 	while (tp && tp->type == CSHELL) {
    499 		fcflags = FC_BI|FC_FUNC|FC_PATH;/* undo effects of command */
    500 		if (tp->val.f == c_builtin) {
    501 			if ((cp = *++ap) == NULL) {
    502 				tp = NULL;
    503 				break;
    504 			}
    505 			tp = findcom(cp, FC_BI);
    506 			if (tp == NULL)
    507 				errorf("builtin: %s: not a builtin", cp);
    508 			continue;
    509 		} else if (tp->val.f == c_exec) {
    510 			if (ap[1] == NULL)
    511 				break;
    512 			ap++;
    513 			flags |= XEXEC;
    514 		} else if (tp->val.f == c_command) {
    515 			int optc, saw_p = 0;
    516 
    517 			/* Ugly dealing with options in two places (here and
    518 			 * in c_command(), but such is life)
    519 			 */
    520 			ksh_getopt_reset(&builtin_opt, 0);
    521 			while ((optc = ksh_getopt(ap, &builtin_opt, ":p"))
    522 									== 'p')
    523 				saw_p = 1;
    524 			if (optc != EOF)
    525 				break;	/* command -vV or something */
    526 			/* don't look for functions */
    527 			fcflags = FC_BI|FC_PATH;
    528 			if (saw_p) {
    529 				if (Flag(FRESTRICTED)) {
    530 					warningf(TRUE,
    531 						"command -p: restricted");
    532 					rv = 1;
    533 					goto Leave;
    534 				}
    535 				fcflags |= FC_DEFPATH;
    536 			}
    537 			ap += builtin_opt.optind;
    538 			/* POSIX says special builtins lose their status
    539 			 * if accessed using command.
    540 			 */
    541 			keepasn_ok = 0;
    542 			if (!ap[0]) {
    543 				/* ensure command with no args exits with 0 */
    544 				subst_exstat = 0;
    545 				break;
    546 			}
    547 		} else
    548 			break;
    549 		tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
    550 	}
    551 	if (keepasn_ok && (!ap[0] || (tp && (tp->flag & KEEPASN))))
    552 		type_flags = 0;
    553 	else {
    554 		/* create new variable/function block */
    555 		newblock();
    556 		/* ksh functions don't keep assignments, POSIX functions do. */
    557 		if (keepasn_ok && tp && tp->type == CFUNC
    558 		    && !(tp->flag & FKSH)) {
    559 			bourne_function_call = 1;
    560 			type_flags = 0;
    561 		} else
    562 			type_flags = LOCAL|LOCAL_COPY|EXPORT;
    563 	}
    564 	if (Flag(FEXPORT))
    565 		type_flags |= EXPORT;
    566 	for (i = 0; t->vars[i]; i++) {
    567 		cp = evalstr(t->vars[i], DOASNTILDE);
    568 		if (Flag(FXTRACE)) {
    569 			if (i == 0)
    570 				shf_fprintf(shl_out, "%s",
    571 					PS4_SUBSTITUTE(str_val(global("PS4"))));
    572 			shf_fprintf(shl_out, "%s%s", cp,
    573 				t->vars[i + 1] ? space : newline);
    574 			if (!t->vars[i + 1])
    575 				shf_flush(shl_out);
    576 		}
    577 		typeset(cp, type_flags, 0, 0, 0);
    578 		if (bourne_function_call && !(type_flags & EXPORT))
    579 			typeset(cp, LOCAL|LOCAL_COPY|EXPORT, 0, 0, 0);
    580 	}
    581 
    582 	if ((cp = *ap) == NULL) {
    583 		rv = subst_exstat;
    584 		goto Leave;
    585 	} else if (!tp) {
    586 		if (Flag(FRESTRICTED) && ksh_strchr_dirsep(cp)) {
    587 			warningf(TRUE, "%s: restricted", cp);
    588 			rv = 1;
    589 			goto Leave;
    590 		}
    591 		tp = findcom(cp, fcflags);
    592 	}
    593 
    594 	switch (tp->type) {
    595 	  case CSHELL:			/* shell built-in */
    596 		rv = call_builtin(tp, ap);
    597 		break;
    598 
    599 	  case CFUNC:			/* function call */
    600 	  {
    601 		volatile int old_xflag;
    602 		volatile Tflag old_inuse;
    603 		const char *volatile old_kshname;
    604 
    605 		if (!(tp->flag & ISSET)) {
    606 			struct tbl *ftp;
    607 
    608 			if (!tp->u.fpath) {
    609 				if (tp->u2.errno_) {
    610 					warningf(TRUE,
    611 				"%s: can't find function definition file - %s",
    612 						cp, strerror(tp->u2.errno_));
    613 					rv = 126;
    614 				} else {
    615 					warningf(TRUE,
    616 				"%s: can't find function definition file", cp);
    617 					rv = 127;
    618 				}
    619 				break;
    620 			}
    621 			if (include(tp->u.fpath, 0, (char **) 0, 0) < 0) {
    622 				warningf(TRUE,
    623 			    "%s: can't open function definition file %s - %s",
    624 					cp, tp->u.fpath, strerror(errno));
    625 				rv = 127;
    626 				break;
    627 			}
    628 			if (!(ftp = findfunc(cp, hash(cp), FALSE))
    629 			    || !(ftp->flag & ISSET))
    630 			{
    631 				warningf(TRUE,
    632 					"%s: function not defined by %s",
    633 					cp, tp->u.fpath);
    634 				rv = 127;
    635 				break;
    636 			}
    637 			tp = ftp;
    638 		}
    639 
    640 		/* ksh functions set $0 to function name, POSIX functions leave
    641 		 * $0 unchanged.
    642 		 */
    643 		old_kshname = kshname;
    644 		if (tp->flag & FKSH)
    645 			kshname = ap[0];
    646 		else
    647 			ap[0] = (char *) kshname;
    648 		e->loc->argv = ap;
    649 		for (i = 0; *ap++ != NULL; i++)
    650 			;
    651 		e->loc->argc = i - 1;
    652 		/* ksh-style functions handle getopts sanely,
    653 		 * bourne/posix functions are insane...
    654 		 */
    655 		if (tp->flag & FKSH) {
    656 			e->loc->flags |= BF_DOGETOPTS;
    657 			e->loc->getopts_state = user_opt;
    658 			getopts_reset(1);
    659 		}
    660 
    661 		old_xflag = Flag(FXTRACE);
    662 		Flag(FXTRACE) = tp->flag & TRACE ? TRUE : FALSE;
    663 
    664 		old_inuse = tp->flag & FINUSE;
    665 		tp->flag |= FINUSE;
    666 
    667 		e->type = E_FUNC;
    668 		i = ksh_sigsetjmp(e->jbuf, 0);
    669 		if (i == 0) {
    670 			/* seems odd to pass XERROK here, but at&t ksh does */
    671 			exstat = execute(tp->val.t, flags & XERROK);
    672 			i = LRETURN;
    673 		}
    674 		kshname = old_kshname;
    675 		Flag(FXTRACE) = old_xflag;
    676 		tp->flag = (tp->flag & ~FINUSE) | old_inuse;
    677 		/* Were we deleted while executing?  If so, free the execution
    678 		 * tree.  todo: Unfortunately, the table entry is never re-used
    679 		 * until the lookup table is expanded.
    680 		 */
    681 		if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
    682 			if (tp->flag & ALLOC) {
    683 				tp->flag &= ~ALLOC;
    684 				tfree(tp->val.t, tp->areap);
    685 			}
    686 			tp->flag = 0;
    687 		}
    688 		switch (i) {
    689 		  case LRETURN:
    690 		  case LERROR:
    691 			rv = exstat;
    692 			break;
    693 		  case LINTR:
    694 		  case LEXIT:
    695 		  case LLEAVE:
    696 		  case LSHELL:
    697 			quitenv();
    698 			unwind(i);
    699 			/*NOTREACHED*/
    700 		  default:
    701 			quitenv();
    702 			internal_errorf(1, "CFUNC %d", i);
    703 		}
    704 		break;
    705 	  }
    706 
    707 	  case CEXEC:		/* executable command */
    708 	  case CTALIAS:		/* tracked alias */
    709 		if (!(tp->flag&ISSET)) {
    710 			/* errno_ will be set if the named command was found
    711 			 * but could not be executed (permissions, no execute
    712 			 * bit, directory, etc).  Print out a (hopefully)
    713 			 * useful error message and set the exit status to 126.
    714 			 */
    715 			if (tp->u2.errno_) {
    716 				warningf(TRUE, "%s: cannot execute - %s", cp,
    717 					strerror(tp->u2.errno_));
    718 				rv = 126;	/* POSIX */
    719 			} else {
    720 				warningf(TRUE, "%s: not found", cp);
    721 				rv = 127;
    722 			}
    723 			break;
    724 		}
    725 
    726 #ifdef KSH
    727 		/* set $_ to program's full path */
    728 		/* setstr() can't fail here */
    729 		setstr(typeset("_", LOCAL|EXPORT, 0, INTEGER, 0),
    730 		       tp->val.s, KSH_RETURN_ERROR);
    731 #endif /* KSH */
    732 
    733 		if (flags&XEXEC) {
    734 			j_exit();
    735 			if (!(flags&XBGND) || Flag(FMONITOR)) {
    736 				setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
    737 				setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
    738 			}
    739 		}
    740 
    741 		/* to fork we set up a TEXEC node and call execute */
    742 		texec.type = TEXEC;
    743 		texec.left = t;	/* for tprint */
    744 		texec.str = tp->val.s;
    745 		texec.args = ap;
    746 		rv = exchild(&texec, flags, -1);
    747 		break;
    748 	}
    749   Leave:
    750 	if (flags & XEXEC) {
    751 		exstat = rv;
    752 		unwind(LLEAVE);
    753 	}
    754 	return rv;
    755 }
    756 
    757 static void
    758 scriptexec(tp, ap)
    759 	register struct op *tp;
    760 	register char **ap;
    761 {
    762 	char *shell;
    763 
    764 	shell = str_val(global(EXECSHELL_STR));
    765 	if (shell && *shell)
    766 		shell = search(shell, path, X_OK, (int *) 0);
    767 	if (!shell || !*shell)
    768 		shell = EXECSHELL;
    769 
    770 	*tp->args-- = tp->str;
    771 #ifdef	SHARPBANG
    772 	{
    773 		char buf[LINE];
    774 		register char *cp;
    775 		register int fd, n;
    776 
    777 		buf[0] = '\0';
    778 		if ((fd = open(tp->str, O_RDONLY)) >= 0) {
    779 			if ((n = read(fd, buf, LINE - 1)) > 0)
    780 				buf[n] = '\0';
    781 			(void) close(fd);
    782 		}
    783 		if ((buf[0] == '#' && buf[1] == '!' && (cp = &buf[2]))
    784 # ifdef OS2
    785 		    || (strncmp(buf, "extproc", 7) == 0 && isspace((unsigned char)buf[7])
    786 			&& (cp = &buf[7]))
    787 # endif /* OS2 */
    788 		    )
    789 		{
    790 			while (*cp && (*cp == ' ' || *cp == '\t'))
    791 				cp++;
    792 			if (*cp && *cp != '\n') {
    793 				char *a0 = cp, *a1 = (char *) 0;
    794 # ifdef OS2
    795 				char *a2 = cp;
    796 # endif /* OS2 */
    797 
    798 				while (*cp && *cp != '\n' && *cp != ' '
    799 				       && *cp != '\t')
    800 				{
    801 # ifdef OS2
    802 			/* Allow shell search without prepended path
    803 			 * if shell with / in pathname cannot be found.
    804 			 * Use / explicitly so \ can be used if explicit
    805 			 * needs to be forced.
    806 			 */
    807 					if (*cp == '/')
    808 						a2 = cp + 1;
    809 # endif /* OS2 */
    810 					cp++;
    811 				}
    812 				if (*cp && *cp != '\n') {
    813 					*cp++ = '\0';
    814 					while (*cp
    815 					       && (*cp == ' ' || *cp == '\t'))
    816 						cp++;
    817 					if (*cp && *cp != '\n') {
    818 						a1 = cp;
    819 						/* all one argument */
    820 						while (*cp && *cp != '\n')
    821 							cp++;
    822 					}
    823 				}
    824 				if (*cp == '\n') {
    825 					*cp = '\0';
    826 					if (a1)
    827 						*tp->args-- = a1;
    828 # ifdef OS2
    829 					if (a0 != a2) {
    830 						char *tmp_a0 = str_nsave(a0,
    831 							strlen(a0) + 5, ATEMP);
    832 						if (search_access(tmp_a0, X_OK,
    833 								(int *) 0))
    834 							a0 = a2;
    835 						afree(tmp_a0, ATEMP);
    836 					}
    837 # endif /* OS2 */
    838 					shell = a0;
    839 				}
    840 			}
    841 # ifdef OS2
    842 		} else {
    843 		        /* Use ksh documented shell default if present
    844 			 * else use OS2_SHELL which is assumed to need
    845 			 * the /c option and '\' as dir separator.
    846 			 */
    847 		         char *p = shell;
    848 
    849 			 shell = str_val(global("EXECSHELL"));
    850 			 if (shell && *shell)
    851 				 shell = search(shell, path, X_OK, (int *) 0);
    852 			 if (!shell || !*shell) {
    853 				 shell = p;
    854 				 *tp->args-- = "/c";
    855 				 for (p = tp->str; *p; p++)
    856 					 if (*p == '/')
    857 						 *p = '\\';
    858 			 }
    859 # endif /* OS2 */
    860 		}
    861 	}
    862 #endif	/* SHARPBANG */
    863 	*tp->args = shell;
    864 
    865 	ksh_execve(tp->args[0], tp->args, ap, 0);
    866 
    867 	/* report both the program that was run and the bogus shell */
    868 	errorf("%s: %s: %s", tp->str, shell, strerror(errno));
    869 }
    870 
    871 int
    872 shcomexec(wp)
    873 	register char **wp;
    874 {
    875 	register struct tbl *tp;
    876 
    877 	tp = tsearch(&builtins, *wp, hash(*wp));
    878 	if (tp == NULL)
    879 		internal_errorf(1, "shcomexec: %s", *wp);
    880 	return call_builtin(tp, wp);
    881 }
    882 
    883 /*
    884  * Search function tables for a function.  If create set, a table entry
    885  * is created if none is found.
    886  */
    887 struct tbl *
    888 findfunc(name, h, create)
    889 	const char *name;
    890 	unsigned int h;
    891 	int create;
    892 {
    893 	struct block *l;
    894 	struct tbl *tp = (struct tbl *) 0;
    895 
    896 	for (l = e->loc; l; l = l->next) {
    897 		tp = tsearch(&l->funs, name, h);
    898 		if (tp)
    899 			break;
    900 		if (!l->next && create) {
    901 			tp = tenter(&l->funs, name, h);
    902 			tp->flag = DEFINED;
    903 			tp->type = CFUNC;
    904 			tp->val.t = (struct op *) 0;
    905 			break;
    906 		}
    907 	}
    908 	return tp;
    909 }
    910 
    911 /*
    912  * define function.  Returns 1 if function is being undefined (t == 0) and
    913  * function did not exist, returns 0 otherwise.
    914  */
    915 int
    916 define(name, t)
    917 	const char *name;
    918 	struct op *t;
    919 {
    920 	struct tbl *tp;
    921 	int was_set = 0;
    922 
    923 	while (1) {
    924 		tp = findfunc(name, hash(name), TRUE);
    925 
    926 		if (tp->flag & ISSET)
    927 			was_set = 1;
    928 		/* If this function is currently being executed, we zap this
    929 		 * table entry so findfunc() won't see it
    930 		 */
    931 		if (tp->flag & FINUSE) {
    932 			tp->name[0] = '\0';
    933 			tp->flag &= ~DEFINED; /* ensure it won't be found */
    934 			tp->flag |= FDELETE;
    935 		} else
    936 			break;
    937 	}
    938 
    939 	if (tp->flag & ALLOC) {
    940 		tp->flag &= ~(ISSET|ALLOC);
    941 		tfree(tp->val.t, tp->areap);
    942 	}
    943 
    944 	if (t == NULL) {		/* undefine */
    945 		tdelete(tp);
    946 		return was_set ? 0 : 1;
    947 	}
    948 
    949 	tp->val.t = tcopy(t->left, tp->areap);
    950 	tp->flag |= (ISSET|ALLOC);
    951 	if (t->u.ksh_func)
    952 		tp->flag |= FKSH;
    953 
    954 	return 0;
    955 }
    956 
    957 /*
    958  * add builtin
    959  */
    960 void
    961 builtin(name, func)
    962 	const char *name;
    963 	int (*func) ARGS((char **));
    964 {
    965 	register struct tbl *tp;
    966 	Tflag flag;
    967 
    968 	/* see if any flags should be set for this builtin */
    969 	for (flag = 0; ; name++) {
    970 		if (*name == '=')	/* command does variable assignment */
    971 			flag |= KEEPASN;
    972 		else if (*name == '*')	/* POSIX special builtin */
    973 			flag |= SPEC_BI;
    974 		else if (*name == '+')	/* POSIX regular builtin */
    975 			flag |= REG_BI;
    976 		else
    977 			break;
    978 	}
    979 
    980 	tp = tenter(&builtins, name, hash(name));
    981 	tp->flag = DEFINED | flag;
    982 	tp->type = CSHELL;
    983 	tp->val.f = func;
    984 }
    985 
    986 /*
    987  * find command
    988  * either function, hashed command, or built-in (in that order)
    989  */
    990 struct tbl *
    991 findcom(name, flags)
    992 	const char *name;
    993 	int	flags;		/* FC_* */
    994 {
    995 	static struct tbl temp;
    996 	unsigned int h = hash(name);
    997 	struct tbl *tp = NULL, *tbi;
    998 	int insert = Flag(FTRACKALL);	/* insert if not found */
    999 	char *fpath;			/* for function autoloading */
   1000 	char *npath;
   1001 
   1002 	if (ksh_strchr_dirsep(name) != NULL) {
   1003 		insert = 0;
   1004 		/* prevent FPATH search below */
   1005 		flags &= ~FC_FUNC;
   1006 		goto Search;
   1007 	}
   1008 	tbi = (flags & FC_BI) ? tsearch(&builtins, name, h) : NULL;
   1009 	/* POSIX says special builtins first, then functions, then
   1010 	 * POSIX regular builtins, then search path...
   1011 	 */
   1012 	if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
   1013 		tp = tbi;
   1014 	if (!tp && (flags & FC_FUNC)) {
   1015 		tp = findfunc(name, h, FALSE);
   1016 		if (tp && !(tp->flag & ISSET)) {
   1017 			if ((fpath = str_val(global("FPATH"))) == null) {
   1018 				tp->u.fpath = (char *) 0;
   1019 				tp->u2.errno_ = 0;
   1020 			} else
   1021 				tp->u.fpath = search(name, fpath, R_OK,
   1022 					&tp->u2.errno_);
   1023 		}
   1024 	}
   1025 	if (!tp && (flags & FC_REGBI) && tbi && (tbi->flag & REG_BI))
   1026 		tp = tbi;
   1027 	/* todo: posix says non-special/non-regular builtins must
   1028 	 * be triggered by some user-controllable means like a
   1029 	 * special directory in PATH.  Requires modifications to
   1030 	 * the search() function.  Tracked aliases should be
   1031 	 * modified to allow tracking of builtin commands.
   1032 	 * This should be under control of the FPOSIX flag.
   1033 	 * If this is changed, also change c_whence...
   1034 	 */
   1035 	if (!tp && (flags & FC_UNREGBI) && tbi)
   1036 		tp = tbi;
   1037 	if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
   1038 		tp = tsearch(&taliases, name, h);
   1039 		if (tp && (tp->flag & ISSET) && eaccess(tp->val.s, X_OK) != 0) {
   1040 			if (tp->flag & ALLOC) {
   1041 				tp->flag &= ~ALLOC;
   1042 				afree(tp->val.s, APERM);
   1043 			}
   1044 			tp->flag &= ~ISSET;
   1045 		}
   1046 	}
   1047 
   1048   Search:
   1049 	if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET)))
   1050 	    && (flags & FC_PATH))
   1051 	{
   1052 		if (!tp) {
   1053 			if (insert && !(flags & FC_DEFPATH)) {
   1054 				tp = tenter(&taliases, name, h);
   1055 				tp->type = CTALIAS;
   1056 			} else {
   1057 				tp = &temp;
   1058 				tp->type = CEXEC;
   1059 			}
   1060 			tp->flag = DEFINED;	/* make ~ISSET */
   1061 		}
   1062 		npath = search(name, flags & FC_DEFPATH ? def_path : path,
   1063 				X_OK, &tp->u2.errno_);
   1064 		if (npath) {
   1065 			tp->val.s = tp == &temp ? npath : str_save(npath, APERM);
   1066 			tp->flag |= ISSET|ALLOC;
   1067 		} else if ((flags & FC_FUNC)
   1068 			   && (fpath = str_val(global("FPATH"))) != null
   1069 			   && (npath = search(name, fpath, R_OK,
   1070 					      &tp->u2.errno_)) != (char *) 0)
   1071 		{
   1072 			/* An undocumented feature of at&t ksh is that it
   1073 			 * searches FPATH if a command is not found, even
   1074 			 * if the command hasn't been set up as an autoloaded
   1075 			 * function (ie, no typeset -uf).
   1076 			 */
   1077 			tp = &temp;
   1078 			tp->type = CFUNC;
   1079 			tp->flag = DEFINED; /* make ~ISSET */
   1080 			tp->u.fpath = npath;
   1081 		}
   1082 	}
   1083 	return tp;
   1084 }
   1085 
   1086 /*
   1087  * flush executable commands with relative paths
   1088  */
   1089 void
   1090 flushcom(all)
   1091 	int all;		/* just relative or all */
   1092 {
   1093 	struct tbl *tp;
   1094 	struct tstate ts;
   1095 
   1096 	for (twalk(&ts, &taliases); (tp = tnext(&ts)) != NULL; )
   1097 		if ((tp->flag&ISSET) && (all || !ISDIRSEP(tp->val.s[0]))) {
   1098 			if (tp->flag&ALLOC) {
   1099 				tp->flag &= ~(ALLOC|ISSET);
   1100 				afree(tp->val.s, APERM);
   1101 			}
   1102 			tp->flag &= ~ISSET;
   1103 		}
   1104 }
   1105 
   1106 /* Check if path is something we want to find.  Returns -1 for failure. */
   1107 int
   1108 search_access(path, mode, errnop)
   1109 	const char *path;
   1110 	int mode;
   1111 	int *errnop;		/* set if candidate found, but not suitable */
   1112 {
   1113 #ifndef OS2
   1114 	int ret, err = 0;
   1115 	struct stat statb;
   1116 
   1117 	if (stat(path, &statb) < 0)
   1118 		return -1;
   1119 	ret = eaccess(path, mode);
   1120 	if (ret < 0)
   1121 		err = errno; /* File exists, but we can't access it */
   1122 	else if (mode == X_OK
   1123 		 && (!S_ISREG(statb.st_mode)
   1124 		     /* This 'cause access() says root can execute everything */
   1125 		     || !(statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))))
   1126 	{
   1127 		ret = -1;
   1128 		err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
   1129 	}
   1130 	if (err && errnop && !*errnop)
   1131 		*errnop = err;
   1132 	return ret;
   1133 #else /* !OS2 */
   1134 	/*
   1135 	 * NOTE: ASSUMES path can be modified and has enough room at the
   1136 	 *       end of the string for a suffix (ie, 4 extra characters).
   1137 	 *	 Certain code knows this (eg, eval.c(globit()),
   1138 	 *	 exec.c(search())).
   1139 	 */
   1140 	static char *xsuffixes[] = { ".ksh", ".exe", ".", ".sh", ".cmd",
   1141 				     ".com", ".bat", (char *) 0
   1142 				   };
   1143 	static char *rsuffixes[] = { ".ksh", ".", ".sh", ".cmd", ".bat",
   1144 				      (char *) 0
   1145 				   };
   1146 	int i;
   1147 	char *mpath = (char *) path;
   1148 	char *tp = mpath + strlen(mpath);
   1149 	char *p;
   1150 	char **sfx;
   1151 
   1152 	/* If a suffix has been specified, check if it is one of the
   1153 	 * suffixes that indicate the file is executable - if so, change
   1154 	 * the access test to R_OK...
   1155 	 * This code assumes OS/2 files can have only one suffix...
   1156 	 */
   1157 	if ((p = strrchr((p = ksh_strrchr_dirsep(mpath)) ? p : mpath, '.'))) {
   1158 		if (mode == X_OK)
   1159 			mode = R_OK;
   1160 		return search_access1(mpath, mode, errnop);
   1161 	}
   1162 	/* Try appending the various suffixes.  Different suffixes for
   1163 	 * read and execute 'cause we don't want to read an executable...
   1164 	 */
   1165 	sfx = mode == R_OK ? rsuffixes : xsuffixes;
   1166 	for (i = 0; sfx[i]; i++) {
   1167 		strcpy(tp, p = sfx[i]);
   1168 		if (search_access1(mpath, R_OK, errnop) == 0)
   1169 			return 0;
   1170 		*tp = '\0';
   1171 	}
   1172 	return -1;
   1173 #endif /* !OS2 */
   1174 }
   1175 
   1176 #ifdef OS2
   1177 static int
   1178 search_access1(path, mode, errnop)
   1179 	const char *path;
   1180 	int mode;
   1181 	int *errnop;		/* set if candidate found, but not suitable */
   1182 {
   1183 	int ret, err = 0;
   1184 	struct stat statb;
   1185 
   1186 	if (stat(path, &statb) < 0)
   1187 		return -1;
   1188 	ret = eaccess(path, mode);
   1189 	if (ret < 0)
   1190 		err = errno; /* File exists, but we can't access it */
   1191 	else if (!S_ISREG(statb.st_mode)) {
   1192 		ret = -1;
   1193 		err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
   1194 	}
   1195 	if (err && errnop && !*errnop)
   1196 		*errnop = err;
   1197 	return ret;
   1198 }
   1199 #endif /* OS2 */
   1200 
   1201 /*
   1202  * search for command with PATH
   1203  */
   1204 char *
   1205 search(name, path, mode, errnop)
   1206 	const char *name;
   1207 	const char *path;
   1208 	int mode;		/* R_OK or X_OK */
   1209 	int *errnop;		/* set if candidate found, but not suitable */
   1210 {
   1211 	const char *sp, *p;
   1212 	char *xp;
   1213 	XString xs;
   1214 	int namelen;
   1215 
   1216 	if (errnop)
   1217 		*errnop = 0;
   1218 #ifdef OS2
   1219 	/* Xinit() allocates 8 additional bytes, so appended suffixes won't
   1220 	 * overflow the memory.
   1221 	 */
   1222 	namelen = strlen(name) + 1;
   1223 	Xinit(xs, xp, namelen, ATEMP);
   1224 	memcpy(Xstring(xs, xp), name, namelen);
   1225 
   1226  	if (ksh_strchr_dirsep(name)) {
   1227 		if (search_access(Xstring(xs, xp), mode, errnop) >= 0)
   1228 			return Xstring(xs, xp); /* not Xclose() - see above */
   1229 		Xfree(xs, xp);
   1230 		return NULL;
   1231 	}
   1232 
   1233 	/* Look in current context always. (os2 style) */
   1234 	if (search_access(Xstring(xs, xp), mode, errnop) == 0)
   1235 		return Xstring(xs, xp); /* not Xclose() - xp may be wrong */
   1236 #else /* OS2 */
   1237 	if (ksh_strchr_dirsep(name)) {
   1238 		if (search_access(name, mode, errnop) == 0)
   1239 			return (char *) name;
   1240 		return NULL;
   1241 	}
   1242 
   1243 	namelen = strlen(name) + 1;
   1244 	Xinit(xs, xp, 128, ATEMP);
   1245 #endif /* OS2 */
   1246 
   1247 	sp = path;
   1248 	while (sp != NULL) {
   1249 		xp = Xstring(xs, xp);
   1250 		if (!(p = strchr(sp, PATHSEP)))
   1251 			p = sp + strlen(sp);
   1252 		if (p != sp) {
   1253 			XcheckN(xs, xp, p - sp);
   1254 			memcpy(xp, sp, p - sp);
   1255 			xp += p - sp;
   1256 			*xp++ = DIRSEP;
   1257 		}
   1258 		sp = p;
   1259 		XcheckN(xs, xp, namelen);
   1260 		memcpy(xp, name, namelen);
   1261  		if (search_access(Xstring(xs, xp), mode, errnop) == 0)
   1262 #ifdef OS2
   1263  			return Xstring(xs, xp); /* Not Xclose() - see above */
   1264 #else /* OS2 */
   1265 			return Xclose(xs, xp + namelen);
   1266 #endif /* OS2 */
   1267 		if (*sp++ == '\0')
   1268 			sp = NULL;
   1269 	}
   1270 	Xfree(xs, xp);
   1271 	return NULL;
   1272 }
   1273 
   1274 static int
   1275 call_builtin(tp, wp)
   1276 	struct tbl *tp;
   1277 	char **wp;
   1278 {
   1279 	int rv;
   1280 
   1281 	builtin_argv0 = wp[0];
   1282 	builtin_flag = tp->flag;
   1283 	shf_reopen(1, SHF_WR, shl_stdout);
   1284 	shl_stdout_ok = 1;
   1285 	ksh_getopt_reset(&builtin_opt, GF_ERROR);
   1286 	rv = (*tp->val.f)(wp);
   1287 	shf_flush(shl_stdout);
   1288 	shl_stdout_ok = 0;
   1289 	builtin_flag = 0;
   1290 	builtin_argv0 = (char *) 0;
   1291 	return rv;
   1292 }
   1293 
   1294 /*
   1295  * set up redirection, saving old fd's in e->savefd
   1296  */
   1297 static int
   1298 iosetup(iop, tp)
   1299 	register struct ioword *iop;
   1300 	struct tbl *tp;
   1301 {
   1302 	register int u = -1;
   1303 	char *cp = iop->name;
   1304 	int iotype = iop->flag & IOTYPE;
   1305 	int do_open = 1, do_close = 0, UNINITIALIZED(flags);
   1306 	struct ioword iotmp;
   1307 	struct stat statb;
   1308 
   1309 	if (iotype != IOHERE)
   1310 		cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
   1311 
   1312 	/* Used for tracing and error messages to print expanded cp */
   1313 	iotmp = *iop;
   1314 	iotmp.name = (iotype == IOHERE) ? (char *) 0 : cp;
   1315 	iotmp.flag |= IONAMEXP;
   1316 
   1317 	if (Flag(FXTRACE))
   1318 		shellf("%s%s\n",
   1319 			PS4_SUBSTITUTE(str_val(global("PS4"))),
   1320 			snptreef((char *) 0, 32, "%R", &iotmp));
   1321 
   1322 	switch (iotype) {
   1323 	  case IOREAD:
   1324 		flags = O_RDONLY;
   1325 		break;
   1326 
   1327 	  case IOCAT:
   1328 		flags = O_WRONLY | O_APPEND | O_CREAT;
   1329 		break;
   1330 
   1331 	  case IOWRITE:
   1332 		flags = O_WRONLY | O_CREAT | O_TRUNC;
   1333 		/* The stat() is here to allow redirections to
   1334 		 * things like /dev/null without error.
   1335 		 */
   1336 		if (Flag(FNOCLOBBER) && !(iop->flag & IOCLOB)
   1337 		    && (stat(cp, &statb) < 0 || S_ISREG(statb.st_mode)))
   1338 			flags |= O_EXCL;
   1339 		break;
   1340 
   1341 	  case IORDWR:
   1342 		flags = O_RDWR | O_CREAT;
   1343 		break;
   1344 
   1345 	  case IOHERE:
   1346 		do_open = 0;
   1347 		/* herein() returns -2 if error has been printed */
   1348 		u = herein(iop->heredoc, iop->flag & IOEVAL);
   1349 		/* cp may have wrong name */
   1350 		break;
   1351 
   1352 	  case IODUP:
   1353 	  {
   1354 		const char *emsg;
   1355 
   1356 		do_open = 0;
   1357 		if (*cp == '-' && !cp[1]) {
   1358 			u = 1009;	 /* prevent error return below */
   1359 			do_close = 1;
   1360 		} else if ((u = check_fd(cp,
   1361 				X_OK | ((iop->flag & IORDUP) ? R_OK : W_OK),
   1362 				&emsg)) < 0)
   1363 		{
   1364 			warningf(TRUE, "%s: %s",
   1365 				snptreef((char *) 0, 32, "%R", &iotmp), emsg);
   1366 			return -1;
   1367 		}
   1368 		if (u == iop->unit)
   1369 			return 0;		/* "dup from" == "dup to" */
   1370 		break;
   1371 	  }
   1372 	}
   1373 	if (do_open) {
   1374 		if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
   1375 			warningf(TRUE, "%s: restricted", cp);
   1376 			return -1;
   1377 		}
   1378 		u = open(cp, flags, 0666);
   1379 #ifdef OS2
   1380 		if (u < 0 && strcmp(cp, "/dev/null") == 0)
   1381 			u = open("nul", flags, 0666);
   1382 #endif /* OS2 */
   1383 	}
   1384 	if (u < 0) {
   1385 		/* herein() may already have printed message */
   1386 		if (u == -1)
   1387 			warningf(TRUE, "cannot %s %s: %s",
   1388 			       iotype == IODUP ? "dup"
   1389 				: (iotype == IOREAD || iotype == IOHERE) ?
   1390 				    "open" : "create", cp, strerror(errno));
   1391 		return -1;
   1392 	}
   1393 	/* Do not save if it has already been redirected (i.e. "cat >x >y"). */
   1394 	if (e->savefd[iop->unit] == 0) {
   1395 		/* If these are the same, it means unit was previously closed */
   1396 		if (u == iop->unit)
   1397 			e->savefd[iop->unit] = -1;
   1398 		else
   1399 			/* c_exec() assumes e->savefd[fd] set for any
   1400 			 * redirections.  Ask savefd() not to close iop->unit;
   1401 			 * this allows error messages to be seen if iop->unit
   1402 			 * is 2; also means we can't lose the fd (eg, both
   1403 			 * dup2 below and dup2 in restfd() failing).
   1404 			 */
   1405 			e->savefd[iop->unit] = savefd(iop->unit, 1);
   1406 	}
   1407 
   1408 	if (do_close)
   1409 		close(iop->unit);
   1410 	else if (u != iop->unit) {
   1411 		if (ksh_dup2(u, iop->unit, TRUE) < 0) {
   1412 			warningf(TRUE,
   1413 				"could not finish (dup) redirection %s: %s",
   1414 				snptreef((char *) 0, 32, "%R", &iotmp),
   1415 				strerror(errno));
   1416 			if (iotype != IODUP)
   1417 				close(u);
   1418 			return -1;
   1419 		}
   1420 		if (iotype != IODUP)
   1421 			close(u);
   1422 #ifdef KSH
   1423 		/* Touching any co-process fd in an empty exec
   1424 		 * causes the shell to close its copies
   1425 		 */
   1426 		else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
   1427 			if (iop->flag & IORDUP)	/* possible exec <&p */
   1428 				coproc_read_close(u);
   1429 			else			/* possible exec >&p */
   1430 				coproc_write_close(u);
   1431 		}
   1432 #endif /* KSH */
   1433 	}
   1434 	if (u == 2) /* Clear any write errors */
   1435 		shf_reopen(2, SHF_WR, shl_out);
   1436 	return 0;
   1437 }
   1438 
   1439 /*
   1440  * open here document temp file.
   1441  * if unquoted here, expand here temp file into second temp file.
   1442  */
   1443 static int
   1444 herein(content, sub)
   1445 	const char *content;
   1446 	int sub;
   1447 {
   1448 	volatile int fd = -1;
   1449 	struct source *s, *volatile osource;
   1450 	struct shf *volatile shf;
   1451 	struct temp *h;
   1452 	int i;
   1453 
   1454 	/* ksh -c 'cat << EOF' can cause this... */
   1455 	if (content == (char *) 0) {
   1456 		warningf(TRUE, "here document missing");
   1457 		return -2; /* special to iosetup(): don't print error */
   1458 	}
   1459 
   1460 	/* Create temp file to hold content (done before newenv so temp
   1461 	 * doesn't get removed too soon).
   1462 	 */
   1463 	h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
   1464 	if (!(shf = h->shf) || (fd = open(h->name, O_RDONLY, 0)) < 0) {
   1465 		warningf(TRUE, "can't %s temporary file %s: %s",
   1466 			!shf ? "create" : "open",
   1467 			h->name, strerror(errno));
   1468 		if (shf)
   1469 			shf_close(shf);
   1470 		return -2 /* special to iosetup(): don't print error */;
   1471 	}
   1472 
   1473 	osource = source;
   1474 	newenv(E_ERRH);
   1475 	i = ksh_sigsetjmp(e->jbuf, 0);
   1476 	if (i) {
   1477 		source = osource;
   1478 		quitenv();
   1479 		shf_close(shf);	/* after quitenv */
   1480 		close(fd);
   1481 		return -2; /* special to iosetup(): don't print error */
   1482 	}
   1483 	if (sub) {
   1484 		/* Do substitutions on the content of heredoc */
   1485 		s = pushs(SSTRING, ATEMP);
   1486 		s->start = s->str = content;
   1487 		source = s;
   1488 		if (yylex(ONEWORD) != LWORD)
   1489 			internal_errorf(1, "herein: yylex");
   1490 		source = osource;
   1491 		shf_puts(evalstr(yylval.cp, 0), shf);
   1492 	} else
   1493 		shf_puts(content, shf);
   1494 
   1495 	quitenv();
   1496 
   1497 	if (shf_close(shf) == EOF) {
   1498 		close(fd);
   1499 		warningf(TRUE, "error writing %s: %s", h->name,
   1500 			strerror(errno));
   1501 		return -2; /* special to iosetup(): don't print error */
   1502 	}
   1503 
   1504 	return fd;
   1505 }
   1506 
   1507 #ifdef KSH
   1508 /*
   1509  *	ksh special - the select command processing section
   1510  *	print the args in column form - assuming that we can
   1511  */
   1512 static char *
   1513 do_selectargs(ap, print_menu)
   1514 	register char **ap;
   1515 	bool_t print_menu;
   1516 {
   1517 	static const char *const read_args[] = {
   1518 					"read", "-r", "REPLY", (char *) 0
   1519 				    };
   1520 	char *s;
   1521 	int i, argct;
   1522 
   1523 	for (argct = 0; ap[argct]; argct++)
   1524 		;
   1525 	while (1) {
   1526 		/* Menu is printed if
   1527 		 *	- this is the first time around the select loop
   1528 		 *	- the user enters a blank line
   1529 		 *	- the REPLY parameter is empty
   1530 		 */
   1531 		if (print_menu || !*str_val(global("REPLY")))
   1532 			pr_menu(ap);
   1533 		shellf("%s", str_val(global("PS3")));
   1534 		if (call_builtin(findcom("read", FC_BI), (char **) read_args))
   1535 			return (char *) 0;
   1536 		s = str_val(global("REPLY"));
   1537 		if (*s) {
   1538 			i = atoi(s);
   1539 			return (i >= 1 && i <= argct) ? ap[i - 1] : null;
   1540 		}
   1541 		print_menu = 1;
   1542 	}
   1543 }
   1544 
   1545 struct select_menu_info {
   1546 	char	*const *args;
   1547 	int	arg_width;
   1548 	int	num_width;
   1549 } info;
   1550 
   1551 static char *select_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
   1552 
   1553 /* format a single select menu item */
   1554 static char *
   1555 select_fmt_entry(arg, i, buf, buflen)
   1556 	void *arg;
   1557 	int i;
   1558 	char *buf;
   1559 	int buflen;
   1560 {
   1561 	struct select_menu_info *smi = (struct select_menu_info *) arg;
   1562 
   1563 	shf_snprintf(buf, buflen, "%*d) %s",
   1564 		smi->num_width, i + 1, smi->args[i]);
   1565 	return buf;
   1566 }
   1567 
   1568 /*
   1569  *	print a select style menu
   1570  */
   1571 int
   1572 pr_menu(ap)
   1573 	char *const *ap;
   1574 {
   1575 	struct select_menu_info smi;
   1576 	char *const *pp;
   1577 	int nwidth, dwidth;
   1578 	int i, n;
   1579 
   1580 	/* Width/column calculations were done once and saved, but this
   1581 	 * means select can't be used recursively so we re-calculate each
   1582 	 * time (could save in a structure that is returned, but its probably
   1583 	 * not worth the bother).
   1584 	 */
   1585 
   1586 	/*
   1587 	 * get dimensions of the list
   1588 	 */
   1589 	for (n = 0, nwidth = 0, pp = ap; *pp; n++, pp++) {
   1590 		i = strlen(*pp);
   1591 		nwidth = (i > nwidth) ? i : nwidth;
   1592 	}
   1593 	/*
   1594 	 * we will print an index of the form
   1595 	 *	%d)
   1596 	 * in front of each entry
   1597 	 * get the max width of this
   1598 	 */
   1599 	for (i = n, dwidth = 1; i >= 10; i /= 10)
   1600 		dwidth++;
   1601 
   1602 	smi.args = ap;
   1603 	smi.arg_width = nwidth;
   1604 	smi.num_width = dwidth;
   1605 	print_columns(shl_out, n, select_fmt_entry, (void *) &smi,
   1606 		dwidth + nwidth + 2, 1);
   1607 
   1608 	return n;
   1609 }
   1610 
   1611 /* XXX: horrible kludge to fit within the framework */
   1612 
   1613 static char *plain_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
   1614 
   1615 static char *
   1616 plain_fmt_entry(arg, i, buf, buflen)
   1617 	void *arg;
   1618 	int i;
   1619 	char *buf;
   1620 	int buflen;
   1621 {
   1622 	shf_snprintf(buf, buflen, "%s", ((char *const *)arg)[i]);
   1623 	return buf;
   1624 }
   1625 
   1626 int
   1627 pr_list(ap)
   1628 	char *const *ap;
   1629 {
   1630 	char *const *pp;
   1631 	int nwidth;
   1632 	int i, n;
   1633 
   1634 	for (n = 0, nwidth = 0, pp = ap; *pp; n++, pp++) {
   1635 		i = strlen(*pp);
   1636 		nwidth = (i > nwidth) ? i : nwidth;
   1637 	}
   1638 	print_columns(shl_out, n, plain_fmt_entry, (void *) ap, nwidth + 1, 0);
   1639 
   1640 	return n;
   1641 }
   1642 #endif /* KSH */
   1643 #ifdef KSH
   1644 
   1645 /*
   1646  *	[[ ... ]] evaluation routines
   1647  */
   1648 
   1649 extern const char *const dbtest_tokens[];
   1650 extern const char db_close[];
   1651 
   1652 /* Test if the current token is a whatever.  Accepts the current token if
   1653  * it is.  Returns 0 if it is not, non-zero if it is (in the case of
   1654  * TM_UNOP and TM_BINOP, the returned value is a Test_op).
   1655  */
   1656 static int
   1657 dbteste_isa(te, meta)
   1658 	Test_env *te;
   1659 	Test_meta meta;
   1660 {
   1661 	int ret = 0;
   1662 	int uqword;
   1663 	char *p;
   1664 
   1665 	if (!*te->pos.wp)
   1666 		return meta == TM_END;
   1667 
   1668 	/* unquoted word? */
   1669 	for (p = *te->pos.wp; *p == CHAR; p += 2)
   1670 		;
   1671 	uqword = *p == EOS;
   1672 
   1673 	if (meta == TM_UNOP || meta == TM_BINOP) {
   1674 		if (uqword) {
   1675 			char buf[8];	/* longer than the longest operator */
   1676 			char *q = buf;
   1677 			for (p = *te->pos.wp; *p == CHAR
   1678 					      && q < &buf[sizeof(buf) - 1];
   1679 					      p += 2)
   1680 				*q++ = p[1];
   1681 			*q = '\0';
   1682 			ret = (int) test_isop(te, meta, buf);
   1683 		}
   1684 	} else if (meta == TM_END)
   1685 		ret = 0;
   1686 	else
   1687 		ret = uqword
   1688 			&& strcmp(*te->pos.wp, dbtest_tokens[(int) meta]) == 0;
   1689 
   1690 	/* Accept the token? */
   1691 	if (ret)
   1692 		te->pos.wp++;
   1693 
   1694 	return ret;
   1695 }
   1696 
   1697 static const char *
   1698 dbteste_getopnd(te, op, do_eval)
   1699 	Test_env *te;
   1700 	Test_op op;
   1701 	int do_eval;
   1702 {
   1703 	char *s = *te->pos.wp;
   1704 
   1705 	if (!s)
   1706 		return (char *) 0;
   1707 
   1708 	te->pos.wp++;
   1709 
   1710 	if (!do_eval)
   1711 		return null;
   1712 
   1713 	if (op == TO_STEQL || op == TO_STNEQ)
   1714 		s = evalstr(s, DOTILDE | DOPAT);
   1715 	else
   1716 		s = evalstr(s, DOTILDE);
   1717 
   1718 	return s;
   1719 }
   1720 
   1721 static int
   1722 dbteste_eval(te, op, opnd1, opnd2, do_eval)
   1723 	Test_env *te;
   1724 	Test_op op;
   1725 	const char *opnd1;
   1726 	const char *opnd2;
   1727 	int do_eval;
   1728 {
   1729 	return test_eval(te, op, opnd1, opnd2, do_eval);
   1730 }
   1731 
   1732 static void
   1733 dbteste_error(te, offset, msg)
   1734 	Test_env *te;
   1735 	int offset;
   1736 	const char *msg;
   1737 {
   1738 	te->flags |= TEF_ERROR;
   1739 	internal_errorf(0, "dbteste_error: %s (offset %d)", msg, offset);
   1740 }
   1741 #endif /* KSH */
   1742