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