etc/services - sync with NetBSD-8
[minix.git] / bin / ksh / exec.c
blob93c1aa25726e15da24cbc614912e13d2d86f9b7a
1 /* $NetBSD: exec.c,v 1.15 2012/03/25 17:23:48 christos Exp $ */
3 /*
4 * execute command tree
5 */
6 #include <sys/cdefs.h>
8 #ifndef lint
9 __RCSID("$NetBSD: exec.c,v 1.15 2012/03/25 17:23:48 christos Exp $");
10 #endif
13 #include "sh.h"
14 #include "c_test.h"
15 #include <ctype.h>
16 #include "ksh_stat.h"
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 */
25 static int comexec ARGS((struct op *, struct tbl *volatile, char **,
26 int volatile));
27 static void scriptexec ARGS((struct op *, char **));
28 static int call_builtin ARGS((struct tbl *, char **));
29 static int iosetup ARGS((struct ioword *, struct tbl *));
30 static int herein ARGS((const char *, int));
31 #ifdef KSH
32 static char *do_selectargs ARGS((char **, bool_t));
33 #endif /* KSH */
34 #ifdef KSH
35 static int dbteste_isa ARGS((Test_env *, Test_meta));
36 static const char *dbteste_getopnd ARGS((Test_env *, Test_op, int));
37 static int dbteste_eval ARGS((Test_env *, Test_op, const char *,
38 const char *, int));
39 static void dbteste_error ARGS((Test_env *, int, const char *));
40 #endif /* KSH */
41 #ifdef OS2
42 static int search_access1 ARGS((const char *, int, int *));
43 #endif /* OS2 */
47 * handle systems that don't have F_SETFD
49 #ifndef F_SETFD
50 # ifndef MAXFD
51 # define MAXFD 64
52 # endif
53 /* a bit field would be smaller, but this will work */
54 static char clexec_tab[MAXFD+1];
55 #endif
58 * we now use this function always.
60 int
61 fd_clexec(fd)
62 int fd;
64 #ifndef F_SETFD
65 if (fd >= 0 && fd < sizeof(clexec_tab)) {
66 clexec_tab[fd] = 1;
67 return 0;
69 return -1;
70 #else
71 return fcntl(fd, F_SETFD, 1);
72 #endif
77 * execute command tree
79 int
80 execute(t, flags)
81 struct op * volatile t;
82 volatile int flags; /* if XEXEC don't fork */
84 int i;
85 volatile int rv = 0;
86 int pv[2];
87 char ** volatile ap;
88 char *s, *cp;
89 struct ioword **iowp;
90 struct tbl *tp = NULL;
92 if (t == NULL)
93 return 0;
95 /* Is this the end of a pipeline? If so, we want to evaluate the
96 * command arguments
97 bool_t eval_done = FALSE;
98 if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
99 eval_done = TRUE;
100 tp = eval_execute_args(t, &ap);
103 if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
104 return exchild(t, flags & ~XTIME, -1); /* run in sub-process */
106 newenv(E_EXEC);
107 if (trap)
108 runtraps(0);
110 if (t->type == TCOM) {
111 /* Clear subst_exstat before argument expansion. Used by
112 * null commands (see comexec() and c_eval()) and by c_set().
114 subst_exstat = 0;
116 current_lineno = t->lineno; /* for $LINENO */
118 /* POSIX says expand command words first, then redirections,
119 * and assignments last..
121 ap = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
122 if (flags & XTIME)
123 /* Allow option parsing (bizarre, but POSIX) */
124 timex_hook(t, &ap);
125 if (Flag(FXTRACE) && ap[0]) {
126 shf_fprintf(shl_out, "%s",
127 PS4_SUBSTITUTE(str_val(global("PS4"))));
128 for (i = 0; ap[i]; i++)
129 shf_fprintf(shl_out, "%s%s", ap[i],
130 ap[i + 1] ? space : newline);
131 shf_flush(shl_out);
133 if (ap[0])
134 tp = findcom(ap[0], FC_BI|FC_FUNC);
136 flags &= ~XTIME;
138 if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
139 e->savefd = (short *) alloc(sizeofN(short, NUFILE), ATEMP);
140 /* initialize to not redirected */
141 memset(e->savefd, 0, sizeofN(short, NUFILE));
144 /* do redirection, to be restored in quitenv() */
145 if (t->ioact != NULL)
146 for (iowp = t->ioact; *iowp != NULL; iowp++) {
147 if (iosetup(*iowp, tp) < 0) {
148 exstat = rv = 1;
149 /* Redirection failures for special commands
150 * cause (non-interactive) shell to exit.
152 if (tp && tp->type == CSHELL
153 && (tp->flag & SPEC_BI))
154 errorf("%s", null);
155 /* Deal with FERREXIT, quitenv(), etc. */
156 goto Break;
160 switch(t->type) {
161 case TCOM:
162 rv = comexec(t, tp, ap, flags);
163 break;
165 case TPAREN:
166 rv = execute(t->left, flags|XFORK);
167 break;
169 case TPIPE:
170 flags |= XFORK;
171 flags &= ~XEXEC;
172 e->savefd[0] = savefd(0, 0);
173 (void) ksh_dup2(e->savefd[0], 0, FALSE); /* stdin of first */
174 e->savefd[1] = savefd(1, 0);
175 while (t->type == TPIPE) {
176 openpipe(pv);
177 (void) ksh_dup2(pv[1], 1, FALSE); /* stdout of curr */
178 /* Let exchild() close pv[0] in child
179 * (if this isn't done, commands like
180 * (: ; cat /etc/termcap) | sleep 1
181 * will hang forever).
183 exchild(t->left, flags|XPIPEO|XCCLOSE, pv[0]);
184 (void) ksh_dup2(pv[0], 0, FALSE); /* stdin of next */
185 closepipe(pv);
186 flags |= XPIPEI;
187 t = t->right;
189 restfd(1, e->savefd[1]); /* stdout of last */
190 e->savefd[1] = 0; /* no need to re-restore this */
191 /* Let exchild() close 0 in parent, after fork, before wait */
192 i = exchild(t, flags|XPCLOSE, 0);
193 if (!(flags&XBGND) && !(flags&XXCOM))
194 rv = i;
195 break;
197 case TLIST:
198 while (t->type == TLIST) {
199 execute(t->left, flags & XERROK);
200 t = t->right;
202 rv = execute(t, flags & XERROK);
203 break;
205 #ifdef KSH
206 case TCOPROC:
208 # ifdef JOB_SIGS
209 sigset_t omask;
210 # endif /* JOB_SIGS */
212 # ifdef JOB_SIGS
213 /* Block sigchild as we are using things changed in the
214 * signal handler
216 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
217 e->type = E_ERRH;
218 i = ksh_sigsetjmp(e->jbuf, 0);
219 if (i) {
220 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
221 quitenv();
222 unwind(i);
223 /*NOTREACHED*/
225 # endif /* JOB_SIGS */
226 /* Already have a (live) co-process? */
227 if (coproc.job && coproc.write >= 0)
228 errorf("coprocess already exists");
230 /* Can we re-use the existing co-process pipe? */
231 coproc_cleanup(TRUE);
233 /* do this before opening pipes, in case these fail */
234 e->savefd[0] = savefd(0, 0);
235 e->savefd[1] = savefd(1, 0);
237 openpipe(pv);
238 if (pv[0] != 0) {
239 ksh_dup2(pv[0], 0, FALSE);
240 close(pv[0]);
242 coproc.write = pv[1];
243 coproc.job = (void *) 0;
245 if (coproc.readw >= 0)
246 ksh_dup2(coproc.readw, 1, FALSE);
247 else {
248 openpipe(pv);
249 coproc.read = pv[0];
250 ksh_dup2(pv[1], 1, FALSE);
251 coproc.readw = pv[1]; /* closed before first read */
252 coproc.njobs = 0;
253 /* create new coprocess id */
254 ++coproc.id;
256 # ifdef JOB_SIGS
257 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
258 e->type = E_EXEC; /* no more need for error handler */
259 # endif /* JOB_SIGS */
261 /* exchild() closes coproc.* in child after fork,
262 * will also increment coproc.njobs when the
263 * job is actually created.
265 flags &= ~XEXEC;
266 exchild(t->left, flags|XBGND|XFORK|XCOPROC|XCCLOSE,
267 coproc.readw);
268 break;
270 #endif /* KSH */
272 case TASYNC:
273 /* XXX non-optimal, I think - "(foo &)", forks for (),
274 * forks again for async... parent should optimize
275 * this to "foo &"...
277 rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK);
278 break;
280 case TOR:
281 case TAND:
282 rv = execute(t->left, XERROK);
283 if (t->right != NULL && (rv == 0) == (t->type == TAND))
284 rv = execute(t->right, flags & XERROK);
285 else
286 flags |= XERROK;
287 break;
289 case TBANG:
290 rv = !execute(t->right, XERROK);
291 break;
293 #ifdef KSH
294 case TDBRACKET:
296 Test_env te;
298 te.flags = TEF_DBRACKET;
299 te.pos.wp = t->args;
300 te.isa = dbteste_isa;
301 te.getopnd = dbteste_getopnd;
302 te.eval = dbteste_eval;
303 te.error = dbteste_error;
305 rv = test_parse(&te);
306 break;
308 #endif /* KSH */
310 case TFOR:
311 #ifdef KSH
312 case TSELECT:
314 volatile bool_t is_first = TRUE;
315 #endif /* KSH */
316 ap = (t->vars != NULL) ?
317 eval(t->vars, DOBLANK|DOGLOB|DOTILDE)
318 : e->loc->argv + 1;
319 e->type = E_LOOP;
320 while (1) {
321 i = ksh_sigsetjmp(e->jbuf, 0);
322 if (!i)
323 break;
324 if ((e->flags&EF_BRKCONT_PASS)
325 || (i != LBREAK && i != LCONTIN))
327 quitenv();
328 unwind(i);
329 } else if (i == LBREAK) {
330 rv = 0;
331 goto Break;
334 rv = 0; /* in case of a continue */
335 if (t->type == TFOR) {
336 while (*ap != NULL) {
337 setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
338 rv = execute(t->left, flags & XERROK);
341 #ifdef KSH
342 else { /* TSELECT */
343 for (;;) {
344 if (!(cp = do_selectargs(ap, is_first))) {
345 rv = 1;
346 break;
348 is_first = FALSE;
349 setstr(global(t->str), cp, KSH_UNWIND_ERROR);
350 rv = execute(t->left, flags & XERROK);
354 #endif /* KSH */
355 break;
357 case TWHILE:
358 case TUNTIL:
359 e->type = E_LOOP;
360 while (1) {
361 i = ksh_sigsetjmp(e->jbuf, 0);
362 if (!i)
363 break;
364 if ((e->flags&EF_BRKCONT_PASS)
365 || (i != LBREAK && i != LCONTIN))
367 quitenv();
368 unwind(i);
369 } else if (i == LBREAK) {
370 rv = 0;
371 goto Break;
374 rv = 0; /* in case of a continue */
375 while ((execute(t->left, XERROK) == 0) == (t->type == TWHILE))
376 rv = execute(t->right, flags & XERROK);
377 break;
379 case TIF:
380 case TELIF:
381 if (t->right == NULL)
382 break; /* should be error */
383 rv = execute(t->left, XERROK) == 0 ?
384 execute(t->right->left, flags & XERROK) :
385 execute(t->right->right, flags & XERROK);
386 break;
388 case TCASE:
389 cp = evalstr(t->str, DOTILDE);
390 for (t = t->left; t != NULL && t->type == TPAT; t = t->right)
391 for (ap = t->vars; *ap; ap++)
392 if ((s = evalstr(*ap, DOTILDE|DOPAT))
393 && gmatch(cp, s, FALSE))
394 goto Found;
395 break;
396 Found:
397 rv = execute(t->left, flags & XERROK);
398 break;
400 case TBRACE:
401 rv = execute(t->left, flags & XERROK);
402 break;
404 case TFUNCT:
405 rv = define(t->str, t);
406 break;
408 case TTIME:
409 /* Clear XEXEC so nested execute() call doesn't exit
410 * (allows "ls -l | time grep foo").
412 rv = timex(t, flags & ~XEXEC);
413 break;
415 case TEXEC: /* an eval'd TCOM */
416 s = t->args[0];
417 ap = makenv();
418 #ifndef F_SETFD
419 for (i = 0; i < sizeof(clexec_tab); i++)
420 if (clexec_tab[i]) {
421 close(i);
422 clexec_tab[i] = 0;
424 #endif
425 restoresigs();
426 cleanup_proc_env();
427 /* XINTACT bit is for OS2 */
428 ksh_execve(t->str, t->args, ap, (flags & XINTACT) ? 1 : 0);
429 if (errno == ENOEXEC)
430 scriptexec(t, ap);
431 else
432 errorf("%s: %s", s, strerror(errno));
434 Break:
435 exstat = rv;
437 quitenv(); /* restores IO */
438 if ((flags&XEXEC))
439 unwind(LEXIT); /* exit child */
440 if (rv != 0 && !(flags & XERROK)) {
441 if (Flag(FERREXIT))
442 unwind(LERROR);
443 trapsig(SIGERR_);
445 return rv;
449 * execute simple command
452 static int
453 comexec(t, tp, ap, flags)
454 struct op *t;
455 struct tbl *volatile tp;
456 register char **ap;
457 int volatile flags;
459 int i;
460 int leave = LLEAVE;
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;
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()?.
476 if (Flag(FTALKING) && *(lastp = ap)) {
477 while (*++lastp)
479 /* setstr() can't fail here */
480 setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
481 KSH_RETURN_ERROR);
483 #endif /* KSH */
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
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;
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;
517 /* Ugly dealing with options in two places (here and
518 * in c_command(), but such is life)
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;
535 fcflags |= FC_DEFPATH;
537 ap += builtin_opt.optind;
538 /* POSIX says special builtins lose their status
539 * if accessed using command.
541 keepasn_ok = 0;
542 if (!ap[0]) {
543 /* ensure command with no args exits with 0 */
544 subst_exstat = 0;
545 break;
547 } else
548 break;
549 tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
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;
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);
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);
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;
591 tp = findcom(cp, fcflags);
594 switch (tp->type) {
595 case CSHELL: /* shell built-in */
596 rv = call_builtin(tp, ap);
597 break;
599 case CFUNC: /* function call */
601 volatile int old_xflag;
602 volatile Tflag old_inuse;
603 const char *volatile old_kshname;
605 if (!(tp->flag & ISSET)) {
606 struct tbl *ftp;
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;
619 break;
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;
628 if (!(ftp = findfunc(cp, hash(cp), FALSE))
629 || !(ftp->flag & ISSET))
631 warningf(TRUE,
632 "%s: function not defined by %s",
633 cp, tp->u.fpath);
634 rv = 127;
635 break;
637 tp = ftp;
640 /* ksh functions set $0 to function name, POSIX functions leave
641 * $0 unchanged.
643 old_kshname = kshname;
644 if (tp->flag & FKSH)
645 kshname = ap[0];
646 else
647 ap[0] = (char *) __UNCONST(kshname);
648 e->loc->argv = ap;
649 for (i = 0; *ap++ != NULL; i++)
651 e->loc->argc = i - 1;
652 /* ksh-style functions handle getopts sanely,
653 * bourne/posix functions are insane...
655 if (tp->flag & FKSH) {
656 e->loc->flags |= BF_DOGETOPTS;
657 e->loc->getopts_state = user_opt;
658 getopts_reset(1);
661 old_xflag = Flag(FXTRACE);
662 Flag(FXTRACE) = tp->flag & TRACE ? TRUE : FALSE;
664 old_inuse = tp->flag & FINUSE;
665 tp->flag |= FINUSE;
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;
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.
681 if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
682 if (tp->flag & ALLOC) {
683 tp->flag &= ~ALLOC;
684 tfree(tp->val.t, tp->areap);
686 tp->flag = 0;
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);
704 break;
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.
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;
723 break;
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 */
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);
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;
749 leave = LEXIT;
750 Leave:
751 if (flags & XEXEC) {
752 exstat = rv;
753 unwind(leave);
755 return rv;
758 static void
759 scriptexec(tp, ap)
760 register struct op *tp;
761 register char **ap;
763 char *shellv;
765 shellv = str_val(global(EXECSHELL_STR));
766 if (shellv && *shellv)
767 shellv = search(shellv, path, X_OK, (int *) 0);
768 if (!shellv || !*shellv)
769 shellv = __UNCONST(EXECSHELL);
771 *tp->args-- = tp->str;
772 #ifdef SHARPBANG
774 char buf[LINE];
775 register char *cp;
776 register int fd, n;
778 buf[0] = '\0';
779 if ((fd = open(tp->str, O_RDONLY)) >= 0) {
780 if ((n = read(fd, buf, LINE - 1)) > 0)
781 buf[n] = '\0';
782 (void) close(fd);
784 if ((buf[0] == '#' && buf[1] == '!' && (cp = &buf[2]))
785 # ifdef OS2
786 || (strncmp(buf, "extproc", 7) == 0 && isspace((unsigned char)buf[7])
787 && (cp = &buf[7]))
788 # endif /* OS2 */
791 while (*cp && (*cp == ' ' || *cp == '\t'))
792 cp++;
793 if (*cp && *cp != '\n') {
794 char *a0 = cp, *a1 = (char *) 0;
795 # ifdef OS2
796 char *a2 = cp;
797 # endif /* OS2 */
799 while (*cp && *cp != '\n' && *cp != ' '
800 && *cp != '\t')
802 # ifdef OS2
803 /* Allow shell search without prepended path
804 * if shell with / in pathname cannot be found.
805 * Use / explicitly so \ can be used if explicit
806 * needs to be forced.
808 if (*cp == '/')
809 a2 = cp + 1;
810 # endif /* OS2 */
811 cp++;
813 if (*cp && *cp != '\n') {
814 *cp++ = '\0';
815 while (*cp
816 && (*cp == ' ' || *cp == '\t'))
817 cp++;
818 if (*cp && *cp != '\n') {
819 a1 = cp;
820 /* all one argument */
821 while (*cp && *cp != '\n')
822 cp++;
825 if (*cp == '\n') {
826 *cp = '\0';
827 if (a1)
828 *tp->args-- = a1;
829 # ifdef OS2
830 if (a0 != a2) {
831 char *tmp_a0 = str_nsave(a0,
832 strlen(a0) + 5, ATEMP);
833 if (search_access(tmp_a0, X_OK,
834 (int *) 0))
835 a0 = a2;
836 afree(tmp_a0, ATEMP);
838 # endif /* OS2 */
839 shellv = a0;
842 # ifdef OS2
843 } else {
844 /* Use ksh documented shell default if present
845 * else use OS2_SHELL which is assumed to need
846 * the /c option and '\' as dir separator.
848 char *p = shellv;
850 shellv = str_val(global("EXECSHELL"));
851 if (shellv && *shellv)
852 shellv = search(shellv, path, X_OK, (int *) 0);
853 if (!shellv || !*shellv) {
854 shellv = p;
855 *tp->args-- = "/c";
856 for (p = tp->str; *p; p++)
857 if (*p == '/')
858 *p = '\\';
860 # endif /* OS2 */
863 #endif /* SHARPBANG */
864 *tp->args = shellv;
866 ksh_execve(tp->args[0], tp->args, ap, 0);
868 /* report both the program that was run and the bogus shell */
869 errorf("%s: %s: %s", tp->str, shellv, strerror(errno));
873 shcomexec(wp)
874 register char **wp;
876 register struct tbl *tp;
878 tp = tsearch(&builtins, *wp, hash(*wp));
879 if (tp == NULL)
880 internal_errorf(1, "shcomexec: %s", *wp);
881 return call_builtin(tp, wp);
885 * Search function tables for a function. If create set, a table entry
886 * is created if none is found.
888 struct tbl *
889 findfunc(name, h, create)
890 const char *name;
891 unsigned int h;
892 int create;
894 struct block *l;
895 struct tbl *tp = (struct tbl *) 0;
897 for (l = e->loc; l; l = l->next) {
898 tp = tsearch(&l->funs, name, h);
899 if (tp)
900 break;
901 if (!l->next && create) {
902 tp = tenter(&l->funs, name, h);
903 tp->flag = DEFINED;
904 tp->type = CFUNC;
905 tp->val.t = (struct op *) 0;
906 break;
909 return tp;
913 * define function. Returns 1 if function is being undefined (t == 0) and
914 * function did not exist, returns 0 otherwise.
917 define(name, t)
918 const char *name;
919 struct op *t;
921 struct tbl *tp;
922 int was_set = 0;
924 while (1) {
925 tp = findfunc(name, hash(name), TRUE);
927 if (tp->flag & ISSET)
928 was_set = 1;
929 /* If this function is currently being executed, we zap this
930 * table entry so findfunc() won't see it
932 if (tp->flag & FINUSE) {
933 tp->name[0] = '\0';
934 tp->flag &= ~DEFINED; /* ensure it won't be found */
935 tp->flag |= FDELETE;
936 } else
937 break;
940 if (tp->flag & ALLOC) {
941 tp->flag &= ~(ISSET|ALLOC);
942 tfree(tp->val.t, tp->areap);
945 if (t == NULL) { /* undefine */
946 tdelete(tp);
947 return was_set ? 0 : 1;
950 tp->val.t = tcopy(t->left, tp->areap);
951 tp->flag |= (ISSET|ALLOC);
952 if (t->u.ksh_func)
953 tp->flag |= FKSH;
955 return 0;
959 * add builtin
961 void
962 builtin(name, func)
963 const char *name;
964 int (*func) ARGS((char **));
966 register struct tbl *tp;
967 Tflag flag;
969 /* see if any flags should be set for this builtin */
970 for (flag = 0; ; name++) {
971 if (*name == '=') /* command does variable assignment */
972 flag |= KEEPASN;
973 else if (*name == '*') /* POSIX special builtin */
974 flag |= SPEC_BI;
975 else if (*name == '+') /* POSIX regular builtin */
976 flag |= REG_BI;
977 else
978 break;
981 tp = tenter(&builtins, name, hash(name));
982 tp->flag = DEFINED | flag;
983 tp->type = CSHELL;
984 tp->val.f = func;
988 * find command
989 * either function, hashed command, or built-in (in that order)
991 struct tbl *
992 findcom(name, flags)
993 const char *name;
994 int flags; /* FC_* */
996 static struct tbl temp;
997 unsigned int h = hash(name);
998 struct tbl *tp = NULL, *tbi;
999 int insert = Flag(FTRACKALL); /* insert if not found */
1000 char *fpath; /* for function autoloading */
1001 char *npath;
1003 if (ksh_strchr_dirsep(name) != NULL) {
1004 insert = 0;
1005 /* prevent FPATH search below */
1006 flags &= ~FC_FUNC;
1007 goto Search;
1009 tbi = (flags & FC_BI) ? tsearch(&builtins, name, h) : NULL;
1010 /* POSIX says special builtins first, then functions, then
1011 * POSIX regular builtins, then search path...
1013 if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
1014 tp = tbi;
1015 if (!tp && (flags & FC_FUNC)) {
1016 tp = findfunc(name, h, FALSE);
1017 if (tp && !(tp->flag & ISSET)) {
1018 if ((fpath = str_val(global("FPATH"))) == null) {
1019 tp->u.fpath = (char *) 0;
1020 tp->u2.errno_ = 0;
1021 } else
1022 tp->u.fpath = search(name, fpath, R_OK,
1023 &tp->u2.errno_);
1026 if (!tp && (flags & FC_REGBI) && tbi && (tbi->flag & REG_BI))
1027 tp = tbi;
1028 /* todo: posix says non-special/non-regular builtins must
1029 * be triggered by some user-controllable means like a
1030 * special directory in PATH. Requires modifications to
1031 * the search() function. Tracked aliases should be
1032 * modified to allow tracking of builtin commands.
1033 * This should be under control of the FPOSIX flag.
1034 * If this is changed, also change c_whence...
1036 if (!tp && (flags & FC_UNREGBI) && tbi)
1037 tp = tbi;
1038 if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
1039 tp = tsearch(&taliases, name, h);
1040 if (tp && (tp->flag & ISSET) && eaccess(tp->val.s, X_OK) != 0) {
1041 if (tp->flag & ALLOC) {
1042 tp->flag &= ~ALLOC;
1043 afree(tp->val.s, APERM);
1045 tp->flag &= ~ISSET;
1049 Search:
1050 if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET)))
1051 && (flags & FC_PATH))
1053 if (!tp) {
1054 if (insert && !(flags & FC_DEFPATH)) {
1055 tp = tenter(&taliases, name, h);
1056 tp->type = CTALIAS;
1057 } else {
1058 tp = &temp;
1059 tp->type = CEXEC;
1061 tp->flag = DEFINED; /* make ~ISSET */
1063 npath = search(name, flags & FC_DEFPATH ? def_path : path,
1064 X_OK, &tp->u2.errno_);
1065 if (npath) {
1066 if (tp == &temp) {
1067 tp->val.s = npath;
1068 } else {
1069 tp->val.s = str_save(npath, APERM);
1070 afree(npath, ATEMP);
1072 tp->flag |= ISSET|ALLOC;
1073 } else if ((flags & FC_FUNC)
1074 && (fpath = str_val(global("FPATH"))) != null
1075 && (npath = search(name, fpath, R_OK,
1076 &tp->u2.errno_)) != (char *) 0)
1078 /* An undocumented feature of at&t ksh is that it
1079 * searches FPATH if a command is not found, even
1080 * if the command hasn't been set up as an autoloaded
1081 * function (ie, no typeset -uf).
1083 tp = &temp;
1084 tp->type = CFUNC;
1085 tp->flag = DEFINED; /* make ~ISSET */
1086 tp->u.fpath = npath;
1089 return tp;
1093 * flush executable commands with relative paths
1095 void
1096 flushcom(all)
1097 int all; /* just relative or all */
1099 struct tbl *tp;
1100 struct tstate ts;
1102 for (twalk(&ts, &taliases); (tp = tnext(&ts)) != NULL; )
1103 if ((tp->flag&ISSET) && (all || !ISDIRSEP(tp->val.s[0]))) {
1104 if (tp->flag&ALLOC) {
1105 tp->flag &= ~(ALLOC|ISSET);
1106 afree(tp->val.s, APERM);
1108 tp->flag &= ~ISSET;
1112 /* Check if path is something we want to find. Returns -1 for failure. */
1114 search_access(pathx, mode, errnop)
1115 const char *pathx;
1116 int mode;
1117 int *errnop; /* set if candidate found, but not suitable */
1119 #ifndef OS2
1120 int ret, err = 0;
1121 struct stat statb;
1123 if (stat(pathx, &statb) < 0)
1124 return -1;
1125 ret = eaccess(pathx, mode);
1126 if (ret < 0)
1127 err = errno; /* File exists, but we can't access it */
1128 else if (mode == X_OK
1129 && (!S_ISREG(statb.st_mode)
1130 /* This 'cause access() says root can execute everything */
1131 || !(statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))))
1133 ret = -1;
1134 err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
1136 if (err && errnop && !*errnop)
1137 *errnop = err;
1138 return ret;
1139 #else /* !OS2 */
1141 * NOTE: ASSUMES path can be modified and has enough room at the
1142 * end of the string for a suffix (ie, 4 extra characters).
1143 * Certain code knows this (eg, eval.c(globit()),
1144 * exec.c(search())).
1146 static char *xsuffixes[] = { ".ksh", ".exe", ".", ".sh", ".cmd",
1147 ".com", ".bat", (char *) 0
1149 static char *rsuffixes[] = { ".ksh", ".", ".sh", ".cmd", ".bat",
1150 (char *) 0
1152 int i;
1153 char *mpath = (char *) pathx;
1154 char *tp = mpath + strlen(mpath);
1155 char *p;
1156 char **sfx;
1158 /* If a suffix has been specified, check if it is one of the
1159 * suffixes that indicate the file is executable - if so, change
1160 * the access test to R_OK...
1161 * This code assumes OS/2 files can have only one suffix...
1163 if ((p = strrchr((p = ksh_strrchr_dirsep(mpath)) ? p : mpath, '.'))) {
1164 if (mode == X_OK)
1165 mode = R_OK;
1166 return search_access1(mpath, mode, errnop);
1168 /* Try appending the various suffixes. Different suffixes for
1169 * read and execute 'cause we don't want to read an executable...
1171 sfx = mode == R_OK ? rsuffixes : xsuffixes;
1172 for (i = 0; sfx[i]; i++) {
1173 strcpy(tp, p = sfx[i]);
1174 if (search_access1(mpath, R_OK, errnop) == 0)
1175 return 0;
1176 *tp = '\0';
1178 return -1;
1179 #endif /* !OS2 */
1182 #ifdef OS2
1183 static int
1184 search_access1(pathx, mode, errnop)
1185 const char *pathx;
1186 int mode;
1187 int *errnop; /* set if candidate found, but not suitable */
1189 int ret, err = 0;
1190 struct stat statb;
1192 if (stat(pathx, &statb) < 0)
1193 return -1;
1194 ret = eaccess(pathx, mode);
1195 if (ret < 0)
1196 err = errno; /* File exists, but we can't access it */
1197 else if (!S_ISREG(statb.st_mode)) {
1198 ret = -1;
1199 err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
1201 if (err && errnop && !*errnop)
1202 *errnop = err;
1203 return ret;
1205 #endif /* OS2 */
1208 * search for command with PATH
1210 char *
1211 search(name, pathx, mode, errnop)
1212 const char *name;
1213 const char *pathx;
1214 int mode; /* R_OK or X_OK */
1215 int *errnop; /* set if candidate found, but not suitable */
1217 const char *sp, *p;
1218 char *xp;
1219 XString xs;
1220 int namelen;
1222 if (errnop)
1223 *errnop = 0;
1224 #ifdef OS2
1225 /* Xinit() allocates 8 additional bytes, so appended suffixes won't
1226 * overflow the memory.
1228 namelen = strlen(name) + 1;
1229 Xinit(xs, xp, namelen, ATEMP);
1230 memcpy(Xstring(xs, xp), name, namelen);
1232 if (ksh_strchr_dirsep(name)) {
1233 if (search_access(Xstring(xs, xp), mode, errnop) >= 0)
1234 return Xstring(xs, xp); /* not Xclose() - see above */
1235 Xfree(xs, xp);
1236 return NULL;
1239 /* Look in current context always. (os2 style) */
1240 if (search_access(Xstring(xs, xp), mode, errnop) == 0)
1241 return Xstring(xs, xp); /* not Xclose() - xp may be wrong */
1242 #else /* OS2 */
1243 if (ksh_strchr_dirsep(name)) {
1244 if (search_access(name, mode, errnop) == 0)
1245 return (char *)__UNCONST(name);
1246 return NULL;
1249 namelen = strlen(name) + 1;
1250 Xinit(xs, xp, 128, ATEMP);
1251 #endif /* OS2 */
1253 sp = pathx;
1254 while (sp != NULL) {
1255 xp = Xstring(xs, xp);
1256 if (!(p = strchr(sp, PATHSEP)))
1257 p = sp + strlen(sp);
1258 if (p != sp) {
1259 XcheckN(xs, xp, p - sp);
1260 memcpy(xp, sp, p - sp);
1261 xp += p - sp;
1262 *xp++ = DIRSEP;
1264 sp = p;
1265 XcheckN(xs, xp, namelen);
1266 memcpy(xp, name, namelen);
1267 if (search_access(Xstring(xs, xp), mode, errnop) == 0)
1268 #ifdef OS2
1269 return Xstring(xs, xp); /* Not Xclose() - see above */
1270 #else /* OS2 */
1271 return Xclose(xs, xp + namelen);
1272 #endif /* OS2 */
1273 if (*sp++ == '\0')
1274 sp = NULL;
1276 Xfree(xs, xp);
1277 return NULL;
1280 static int
1281 call_builtin(tp, wp)
1282 struct tbl *tp;
1283 char **wp;
1285 int rv;
1287 builtin_argv0 = wp[0];
1288 builtin_flag = tp->flag;
1289 shf_reopen(1, SHF_WR, shl_stdout);
1290 shl_stdout_ok = 1;
1291 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1292 rv = (*tp->val.f)(wp);
1293 shf_flush(shl_stdout);
1294 shl_stdout_ok = 0;
1295 builtin_flag = 0;
1296 builtin_argv0 = (char *) 0;
1297 return rv;
1301 * set up redirection, saving old fd's in e->savefd
1303 static int
1304 iosetup(iop, tp)
1305 register struct ioword *iop;
1306 struct tbl *tp;
1308 register int u = -1;
1309 char *cp = iop->name;
1310 int iotype = iop->flag & IOTYPE;
1311 int do_open = 1, do_close = 0, UNINITIALIZED(flags);
1312 struct ioword iotmp;
1313 struct stat statb;
1315 if (iotype != IOHERE)
1316 cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1318 /* Used for tracing and error messages to print expanded cp */
1319 iotmp = *iop;
1320 iotmp.name = (iotype == IOHERE) ? (char *) 0 : cp;
1321 iotmp.flag |= IONAMEXP;
1323 if (Flag(FXTRACE))
1324 shellf("%s%s\n",
1325 PS4_SUBSTITUTE(str_val(global("PS4"))),
1326 snptreef((char *) 0, 32, "%R", &iotmp));
1328 switch (iotype) {
1329 case IOREAD:
1330 flags = O_RDONLY;
1331 break;
1333 case IOCAT:
1334 flags = O_WRONLY | O_APPEND | O_CREAT;
1335 break;
1337 case IOWRITE:
1338 flags = O_WRONLY | O_CREAT | O_TRUNC;
1339 /* The stat() is here to allow redirections to
1340 * things like /dev/null without error.
1342 if (Flag(FNOCLOBBER) && !(iop->flag & IOCLOB)
1343 && (stat(cp, &statb) < 0 || S_ISREG(statb.st_mode)))
1344 flags |= O_EXCL;
1345 break;
1347 case IORDWR:
1348 flags = O_RDWR | O_CREAT;
1349 break;
1351 case IOHERE:
1352 do_open = 0;
1353 /* herein() returns -2 if error has been printed */
1354 u = herein(iop->heredoc, iop->flag & IOEVAL);
1355 /* cp may have wrong name */
1356 break;
1358 case IODUP:
1360 const char *emsg;
1362 do_open = 0;
1363 if (*cp == '-' && !cp[1]) {
1364 u = 1009; /* prevent error return below */
1365 do_close = 1;
1366 } else if ((u = check_fd(cp,
1367 X_OK | ((iop->flag & IORDUP) ? R_OK : W_OK),
1368 &emsg)) < 0)
1370 warningf(TRUE, "%s: %s",
1371 snptreef((char *) 0, 32, "%R", &iotmp), emsg);
1372 return -1;
1374 if (u == iop->unit)
1375 return 0; /* "dup from" == "dup to" */
1376 break;
1379 if (do_open) {
1380 if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
1381 warningf(TRUE, "%s: restricted", cp);
1382 return -1;
1384 u = open(cp, flags, 0666);
1385 #ifdef OS2
1386 if (u < 0 && strcmp(cp, "/dev/null") == 0)
1387 u = open("nul", flags, 0666);
1388 #endif /* OS2 */
1390 if (u < 0) {
1391 /* herein() may already have printed message */
1392 if (u == -1)
1393 warningf(TRUE, "cannot %s %s: %s",
1394 iotype == IODUP ? "dup"
1395 : (iotype == IOREAD || iotype == IOHERE) ?
1396 "open" : "create", cp, strerror(errno));
1397 return -1;
1399 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1400 if (e->savefd[iop->unit] == 0) {
1401 /* If these are the same, it means unit was previously closed */
1402 if (u == iop->unit)
1403 e->savefd[iop->unit] = -1;
1404 else
1405 /* c_exec() assumes e->savefd[fd] set for any
1406 * redirections. Ask savefd() not to close iop->unit;
1407 * this allows error messages to be seen if iop->unit
1408 * is 2; also means we can't lose the fd (eg, both
1409 * dup2 below and dup2 in restfd() failing).
1411 e->savefd[iop->unit] = savefd(iop->unit, 1);
1414 if (do_close)
1415 close(iop->unit);
1416 else if (u != iop->unit) {
1417 if (ksh_dup2(u, iop->unit, TRUE) < 0) {
1418 warningf(TRUE,
1419 "could not finish (dup) redirection %s: %s",
1420 snptreef((char *) 0, 32, "%R", &iotmp),
1421 strerror(errno));
1422 if (iotype != IODUP)
1423 close(u);
1424 return -1;
1426 if (iotype != IODUP)
1427 close(u);
1428 #ifdef KSH
1429 /* Touching any co-process fd in an empty exec
1430 * causes the shell to close its copies
1432 else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1433 if (iop->flag & IORDUP) /* possible exec <&p */
1434 coproc_read_close(u);
1435 else /* possible exec >&p */
1436 coproc_write_close(u);
1438 #endif /* KSH */
1440 if (u == 2) /* Clear any write errors */
1441 shf_reopen(2, SHF_WR, shl_out);
1442 return 0;
1446 * open here document temp file.
1447 * if unquoted here, expand here temp file into second temp file.
1449 static int
1450 herein(content, sub)
1451 const char *content;
1452 int sub;
1454 volatile int fd = -1;
1455 struct source *s, *volatile osource;
1456 struct shf *volatile shf;
1457 struct temp *h;
1458 int i;
1460 /* ksh -c 'cat << EOF' can cause this... */
1461 if (content == (char *) 0) {
1462 warningf(TRUE, "here document missing");
1463 return -2; /* special to iosetup(): don't print error */
1466 /* Create temp file to hold content (done before newenv so temp
1467 * doesn't get removed too soon).
1469 h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1470 if (!(shf = h->shf) || (fd = open(h->name, O_RDONLY, 0)) < 0) {
1471 warningf(TRUE, "can't %s temporary file %s: %s",
1472 !shf ? "create" : "open",
1473 h->name, strerror(errno));
1474 if (shf)
1475 shf_close(shf);
1476 return -2 /* special to iosetup(): don't print error */;
1479 osource = source;
1480 newenv(E_ERRH);
1481 i = ksh_sigsetjmp(e->jbuf, 0);
1482 if (i) {
1483 source = osource;
1484 quitenv();
1485 shf_close(shf); /* after quitenv */
1486 close(fd);
1487 return -2; /* special to iosetup(): don't print error */
1489 if (sub) {
1490 /* Do substitutions on the content of heredoc */
1491 s = pushs(SSTRING, ATEMP);
1492 s->start = s->str = content;
1493 source = s;
1494 if (yylex(ONEWORD|HEREDOC) != LWORD)
1495 internal_errorf(1, "herein: yylex");
1496 source = osource;
1497 shf_puts(evalstr(yylval.cp, 0), shf);
1498 } else
1499 shf_puts(content, shf);
1501 quitenv();
1503 if (shf_close(shf) == EOF) {
1504 close(fd);
1505 warningf(TRUE, "error writing %s: %s", h->name,
1506 strerror(errno));
1507 return -2; /* special to iosetup(): don't print error */
1510 return fd;
1513 #ifdef KSH
1515 * ksh special - the select command processing section
1516 * print the args in column form - assuming that we can
1518 static char *
1519 do_selectargs(ap, print_menu)
1520 register char **ap;
1521 bool_t print_menu;
1523 static const char *const read_args[] = {
1524 "read", "-r", "REPLY", (char *) 0
1526 char *s;
1527 int i, argct;
1529 for (argct = 0; ap[argct]; argct++)
1531 while (1) {
1532 /* Menu is printed if
1533 * - this is the first time around the select loop
1534 * - the user enters a blank line
1535 * - the REPLY parameter is empty
1537 if (print_menu || !*str_val(global("REPLY")))
1538 pr_menu(ap);
1539 shellf("%s", str_val(global("PS3")));
1540 if (call_builtin(findcom("read", FC_BI),
1541 (char **) __UNCONST(read_args)))
1542 return (char *) 0;
1543 s = str_val(global("REPLY"));
1544 if (*s) {
1545 i = atoi(s);
1546 return (i >= 1 && i <= argct) ? ap[i - 1] : null;
1548 print_menu = 1;
1552 struct select_menu_info {
1553 char *const *args;
1554 int arg_width;
1555 int num_width;
1556 } info;
1558 static char *select_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
1560 /* format a single select menu item */
1561 static char *
1562 select_fmt_entry(arg, i, buf, buflen)
1563 void *arg;
1564 int i;
1565 char *buf;
1566 int buflen;
1568 struct select_menu_info *smi = (struct select_menu_info *) arg;
1570 shf_snprintf(buf, buflen, "%*d) %s",
1571 smi->num_width, i + 1, smi->args[i]);
1572 return buf;
1576 * print a select style menu
1579 pr_menu(ap)
1580 char *const *ap;
1582 struct select_menu_info smi;
1583 char *const *pp;
1584 int nwidth, dwidth;
1585 int i, n;
1587 /* Width/column calculations were done once and saved, but this
1588 * means select can't be used recursively so we re-calculate each
1589 * time (could save in a structure that is returned, but its probably
1590 * not worth the bother).
1594 * get dimensions of the list
1596 for (n = 0, nwidth = 0, pp = ap; *pp; n++, pp++) {
1597 i = strlen(*pp);
1598 nwidth = (i > nwidth) ? i : nwidth;
1601 * we will print an index of the form
1602 * %d)
1603 * in front of each entry
1604 * get the max width of this
1606 for (i = n, dwidth = 1; i >= 10; i /= 10)
1607 dwidth++;
1609 smi.args = ap;
1610 smi.arg_width = nwidth;
1611 smi.num_width = dwidth;
1612 print_columns(shl_out, n, select_fmt_entry, (void *) &smi,
1613 dwidth + nwidth + 2, 1);
1615 return n;
1618 /* XXX: horrible kludge to fit within the framework */
1620 static char *plain_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
1622 static char *
1623 plain_fmt_entry(arg, i, buf, buflen)
1624 void *arg;
1625 int i;
1626 char *buf;
1627 int buflen;
1629 shf_snprintf(buf, buflen, "%s", ((char *const *)arg)[i]);
1630 return buf;
1634 pr_list(ap)
1635 char *const *ap;
1637 char *const *pp;
1638 int nwidth;
1639 int i, n;
1641 for (n = 0, nwidth = 0, pp = ap; *pp; n++, pp++) {
1642 i = strlen(*pp);
1643 nwidth = (i > nwidth) ? i : nwidth;
1645 print_columns(shl_out, n, plain_fmt_entry, (void *)__UNCONST(ap),
1646 nwidth + 1, 0);
1648 return n;
1650 #endif /* KSH */
1651 #ifdef KSH
1654 * [[ ... ]] evaluation routines
1657 extern const char *const dbtest_tokens[];
1658 extern const char db_close[];
1660 /* Test if the current token is a whatever. Accepts the current token if
1661 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1662 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1664 static int
1665 dbteste_isa(te, meta)
1666 Test_env *te;
1667 Test_meta meta;
1669 int ret = 0;
1670 int uqword;
1671 char *p;
1673 if (!*te->pos.wp)
1674 return meta == TM_END;
1676 /* unquoted word? */
1677 for (p = *te->pos.wp; *p == CHAR; p += 2)
1679 uqword = *p == EOS;
1681 if (meta == TM_UNOP || meta == TM_BINOP) {
1682 if (uqword) {
1683 char buf[8]; /* longer than the longest operator */
1684 char *q = buf;
1685 for (p = *te->pos.wp; *p == CHAR
1686 && q < &buf[sizeof(buf) - 1];
1687 p += 2)
1688 *q++ = p[1];
1689 *q = '\0';
1690 ret = (int) test_isop(te, meta, buf);
1692 } else if (meta == TM_END)
1693 ret = 0;
1694 else
1695 ret = uqword
1696 && strcmp(*te->pos.wp, dbtest_tokens[(int) meta]) == 0;
1698 /* Accept the token? */
1699 if (ret)
1700 te->pos.wp++;
1702 return ret;
1705 static const char *
1706 dbteste_getopnd(te, op, do_eval)
1707 Test_env *te;
1708 Test_op op;
1709 int do_eval;
1711 char *s = *te->pos.wp;
1713 if (!s)
1714 return (char *) 0;
1716 te->pos.wp++;
1718 if (!do_eval)
1719 return null;
1721 if (op == TO_STEQL || op == TO_STNEQ)
1722 s = evalstr(s, DOTILDE | DOPAT);
1723 else
1724 s = evalstr(s, DOTILDE);
1726 return s;
1729 static int
1730 dbteste_eval(te, op, opnd1, opnd2, do_eval)
1731 Test_env *te;
1732 Test_op op;
1733 const char *opnd1;
1734 const char *opnd2;
1735 int do_eval;
1737 return test_eval(te, op, opnd1, opnd2, do_eval);
1740 static void
1741 dbteste_error(te, offset, msg)
1742 Test_env *te;
1743 int offset;
1744 const char *msg;
1746 te->flags |= TEF_ERROR;
1747 internal_errorf(0, "dbteste_error: %s (offset %d)", msg, offset);
1749 #endif /* KSH */