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