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