1 /* $NetBSD: exec.c,v 1.12 2005/09/11 22:16:00 christos Exp $ */
9 __RCSID("$NetBSD: exec.c,v 1.12 2005/09/11 22:16:00 christos Exp $");
18 /* Does ps4 get parameter substitutions done? */
20 # define PS4_SUBSTITUTE(s) substitute((s), 0)
22 # define PS4_SUBSTITUTE(s) (s)
25 static int comexec
ARGS((struct op
*, struct tbl
*volatile, char **,
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));
32 static char *do_selectargs
ARGS((char **, bool_t
));
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 *,
39 static void dbteste_error
ARGS((Test_env
*, int, const char *));
42 static int search_access1
ARGS((const char *, int, int *));
47 * handle systems that don't have F_SETFD
53 /* a bit field would be smaller, but this will work */
54 static char clexec_tab
[MAXFD
+1];
58 * we now use this function always.
65 if (fd
>= 0 && fd
< sizeof(clexec_tab
)) {
71 return fcntl(fd
, F_SETFD
, 1);
77 * execute command tree
81 struct op
* volatile t
;
82 volatile int flags
; /* if XEXEC don't fork */
90 struct tbl
*tp
= NULL
;
95 /* Is this the end of a pipeline? If so, we want to evaluate the
97 bool_t eval_done = FALSE;
98 if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
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 */
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().
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
);
123 /* Allow option parsing (bizarre, but POSIX) */
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
);
134 tp
= findcom(ap
[0], FC_BI
|FC_FUNC
);
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) {
149 /* Redirection failures for special commands
150 * cause (non-interactive) shell to exit.
152 if (tp
&& tp
->type
== CSHELL
153 && (tp
->flag
& SPEC_BI
))
155 /* Deal with FERREXIT, quitenv(), etc. */
162 rv
= comexec(t
, tp
, ap
, flags
);
166 rv
= execute(t
->left
, flags
|XFORK
);
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
) {
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 */
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
))
198 while (t
->type
== TLIST
) {
199 execute(t
->left
, flags
& XERROK
);
202 rv
= execute(t
, flags
& XERROK
);
210 # endif /* JOB_SIGS */
213 /* Block sigchild as we are using things changed in the
216 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
218 i
= ksh_sigsetjmp(e
->jbuf
, 0);
220 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
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);
239 ksh_dup2(pv
[0], 0, FALSE
);
242 coproc
.write
= pv
[1];
243 coproc
.job
= (void *) 0;
245 if (coproc
.readw
>= 0)
246 ksh_dup2(coproc
.readw
, 1, FALSE
);
250 ksh_dup2(pv
[1], 1, FALSE
);
251 coproc
.readw
= pv
[1]; /* closed before first read */
253 /* create new coprocess id */
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.
266 exchild(t
->left
, flags
|XBGND
|XFORK
|XCOPROC
|XCCLOSE
,
273 /* XXX non-optimal, I think - "(foo &)", forks for (),
274 * forks again for async... parent should optimize
277 rv
= execute(t
->left
, (flags
&~XEXEC
)|XBGND
|XFORK
);
282 rv
= execute(t
->left
, XERROK
);
283 if (t
->right
!= NULL
&& (rv
== 0) == (t
->type
== TAND
))
284 rv
= execute(t
->right
, flags
& XERROK
);
290 rv
= !execute(t
->right
, XERROK
);
298 te
.flags
= TEF_DBRACKET
;
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
);
314 volatile bool_t is_first
= TRUE
;
316 ap
= (t
->vars
!= NULL
) ?
317 eval(t
->vars
, DOBLANK
|DOGLOB
|DOTILDE
)
321 i
= ksh_sigsetjmp(e
->jbuf
, 0);
324 if ((e
->flags
&EF_BRKCONT_PASS
)
325 || (i
!= LBREAK
&& i
!= LCONTIN
))
329 } else if (i
== LBREAK
) {
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
);
344 if (!(cp
= do_selectargs(ap
, is_first
))) {
349 setstr(global(t
->str
), cp
, KSH_UNWIND_ERROR
);
350 rv
= execute(t
->left
, flags
& XERROK
);
361 i
= ksh_sigsetjmp(e
->jbuf
, 0);
364 if ((e
->flags
&EF_BRKCONT_PASS
)
365 || (i
!= LBREAK
&& i
!= LCONTIN
))
369 } else if (i
== LBREAK
) {
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
);
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
);
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
))
397 rv
= execute(t
->left
, flags
& XERROK
);
401 rv
= execute(t
->left
, flags
& XERROK
);
405 rv
= define(t
->str
, t
);
409 /* Clear XEXEC so nested execute() call doesn't exit
410 * (allows "ls -l | time grep foo").
412 rv
= timex(t
, flags
& ~XEXEC
);
415 case TEXEC
: /* an eval'd TCOM */
419 for (i
= 0; i
< sizeof(clexec_tab
); i
++)
427 /* XINTACT bit is for OS2 */
428 ksh_execve(t
->str
, t
->args
, ap
, (flags
& XINTACT
) ? 1 : 0);
429 if (errno
== ENOEXEC
)
432 errorf("%s: %s", s
, strerror(errno
));
437 quitenv(); /* restores IO */
439 unwind(LEXIT
); /* exit child */
440 if (rv
!= 0 && !(flags
& XERROK
)) {
449 * execute simple command
453 comexec(t
, tp
, ap
, flags
)
455 struct tbl
*volatile tp
;
462 register char **lastp
;
463 static struct op texec
; /* Must be static (XXX but why?) */
466 int fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;
467 int bourne_function_call
= 0;
470 /* snag the last argument for $_ XXX not the same as at&t ksh,
471 * which only seems to set $_ after a newline (but not in
472 * functions/dot scripts, but in interactive and script) -
473 * perhaps save last arg here and set it in shell()?.
475 if (Flag(FTALKING
) && *(lastp
= ap
)) {
478 /* setstr() can't fail here */
479 setstr(typeset("_", LOCAL
, 0, INTEGER
, 0), *--lastp
,
484 /* Deal with the shell builtins builtin, exec and command since
485 * they can be followed by other commands. This must be done before
486 * we know if we should create a local block, which must be done
487 * before we can do a path search (in case the assignments change
490 * FOO=bar exec > /dev/null FOO is kept but not exported
491 * FOO=bar exec foobar FOO is exported
492 * FOO=bar command exec > /dev/null FOO is neither kept nor exported
493 * FOO=bar command FOO is neither kept nor exported
494 * PATH=... foobar use new PATH in foobar search
497 while (tp
&& tp
->type
== CSHELL
) {
498 fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;/* undo effects of command */
499 if (tp
->val
.f
== c_builtin
) {
500 if ((cp
= *++ap
) == NULL
) {
504 tp
= findcom(cp
, FC_BI
);
506 errorf("builtin: %s: not a builtin", cp
);
508 } else if (tp
->val
.f
== c_exec
) {
513 } else if (tp
->val
.f
== c_command
) {
516 /* Ugly dealing with options in two places (here and
517 * in c_command(), but such is life)
519 ksh_getopt_reset(&builtin_opt
, 0);
520 while ((optc
= ksh_getopt(ap
, &builtin_opt
, ":p"))
524 break; /* command -vV or something */
525 /* don't look for functions */
526 fcflags
= FC_BI
|FC_PATH
;
528 if (Flag(FRESTRICTED
)) {
530 "command -p: restricted");
534 fcflags
|= FC_DEFPATH
;
536 ap
+= builtin_opt
.optind
;
537 /* POSIX says special builtins lose their status
538 * if accessed using command.
542 /* ensure command with no args exits with 0 */
548 tp
= findcom(ap
[0], fcflags
& (FC_BI
|FC_FUNC
));
550 if (keepasn_ok
&& (!ap
[0] || (tp
&& (tp
->flag
& KEEPASN
))))
553 /* create new variable/function block */
555 /* ksh functions don't keep assignments, POSIX functions do. */
556 if (keepasn_ok
&& tp
&& tp
->type
== CFUNC
557 && !(tp
->flag
& FKSH
)) {
558 bourne_function_call
= 1;
561 type_flags
= LOCAL
|LOCAL_COPY
|EXPORT
;
564 type_flags
|= EXPORT
;
565 for (i
= 0; t
->vars
[i
]; i
++) {
566 cp
= evalstr(t
->vars
[i
], DOASNTILDE
);
569 shf_fprintf(shl_out
, "%s",
570 PS4_SUBSTITUTE(str_val(global("PS4"))));
571 shf_fprintf(shl_out
, "%s%s", cp
,
572 t
->vars
[i
+ 1] ? space
: newline
);
576 typeset(cp
, type_flags
, 0, 0, 0);
577 if (bourne_function_call
&& !(type_flags
& EXPORT
))
578 typeset(cp
, LOCAL
|LOCAL_COPY
|EXPORT
, 0, 0, 0);
581 if ((cp
= *ap
) == NULL
) {
585 if (Flag(FRESTRICTED
) && ksh_strchr_dirsep(cp
)) {
586 warningf(TRUE
, "%s: restricted", cp
);
590 tp
= findcom(cp
, fcflags
);
594 case CSHELL
: /* shell built-in */
595 rv
= call_builtin(tp
, ap
);
598 case CFUNC
: /* function call */
600 volatile int old_xflag
;
601 volatile Tflag old_inuse
;
602 const char *volatile old_kshname
;
604 if (!(tp
->flag
& ISSET
)) {
610 "%s: can't find function definition file - %s",
611 cp
, strerror(tp
->u2
.errno_
));
615 "%s: can't find function definition file", cp
);
620 if (include(tp
->u
.fpath
, 0, (char **) 0, 0) < 0) {
622 "%s: can't open function definition file %s - %s",
623 cp
, tp
->u
.fpath
, strerror(errno
));
627 if (!(ftp
= findfunc(cp
, hash(cp
), FALSE
))
628 || !(ftp
->flag
& ISSET
))
631 "%s: function not defined by %s",
639 /* ksh functions set $0 to function name, POSIX functions leave
642 old_kshname
= kshname
;
646 ap
[0] = (char *) __UNCONST(kshname
);
648 for (i
= 0; *ap
++ != NULL
; i
++)
650 e
->loc
->argc
= i
- 1;
651 /* ksh-style functions handle getopts sanely,
652 * bourne/posix functions are insane...
654 if (tp
->flag
& FKSH
) {
655 e
->loc
->flags
|= BF_DOGETOPTS
;
656 e
->loc
->getopts_state
= user_opt
;
660 old_xflag
= Flag(FXTRACE
);
661 Flag(FXTRACE
) = tp
->flag
& TRACE
? TRUE
: FALSE
;
663 old_inuse
= tp
->flag
& FINUSE
;
667 i
= ksh_sigsetjmp(e
->jbuf
, 0);
669 /* seems odd to pass XERROK here, but at&t ksh does */
670 exstat
= execute(tp
->val
.t
, flags
& XERROK
);
673 kshname
= old_kshname
;
674 Flag(FXTRACE
) = old_xflag
;
675 tp
->flag
= (tp
->flag
& ~FINUSE
) | old_inuse
;
676 /* Were we deleted while executing? If so, free the execution
677 * tree. todo: Unfortunately, the table entry is never re-used
678 * until the lookup table is expanded.
680 if ((tp
->flag
& (FDELETE
|FINUSE
)) == FDELETE
) {
681 if (tp
->flag
& ALLOC
) {
683 tfree(tp
->val
.t
, tp
->areap
);
701 internal_errorf(1, "CFUNC %d", i
);
706 case CEXEC
: /* executable command */
707 case CTALIAS
: /* tracked alias */
708 if (!(tp
->flag
&ISSET
)) {
709 /* errno_ will be set if the named command was found
710 * but could not be executed (permissions, no execute
711 * bit, directory, etc). Print out a (hopefully)
712 * useful error message and set the exit status to 126.
715 warningf(TRUE
, "%s: cannot execute - %s", cp
,
716 strerror(tp
->u2
.errno_
));
717 rv
= 126; /* POSIX */
719 warningf(TRUE
, "%s: not found", cp
);
726 /* set $_ to program's full path */
727 /* setstr() can't fail here */
728 setstr(typeset("_", LOCAL
|EXPORT
, 0, INTEGER
, 0),
729 tp
->val
.s
, KSH_RETURN_ERROR
);
734 if (!(flags
&XBGND
) || Flag(FMONITOR
)) {
735 setexecsig(&sigtraps
[SIGINT
], SS_RESTORE_ORIG
);
736 setexecsig(&sigtraps
[SIGQUIT
], SS_RESTORE_ORIG
);
740 /* to fork we set up a TEXEC node and call execute */
742 texec
.left
= t
; /* for tprint */
743 texec
.str
= tp
->val
.s
;
745 rv
= exchild(&texec
, flags
, -1);
758 register struct op
*tp
;
763 shellv
= str_val(global(EXECSHELL_STR
));
764 if (shellv
&& *shellv
)
765 shellv
= search(shellv
, path
, X_OK
, (int *) 0);
766 if (!shellv
|| !*shellv
)
767 shellv
= __UNCONST(EXECSHELL
);
769 *tp
->args
-- = tp
->str
;
777 if ((fd
= open(tp
->str
, O_RDONLY
)) >= 0) {
778 if ((n
= read(fd
, buf
, LINE
- 1)) > 0)
782 if ((buf
[0] == '#' && buf
[1] == '!' && (cp
= &buf
[2]))
784 || (strncmp(buf
, "extproc", 7) == 0 && isspace((unsigned char)buf
[7])
789 while (*cp
&& (*cp
== ' ' || *cp
== '\t'))
791 if (*cp
&& *cp
!= '\n') {
792 char *a0
= cp
, *a1
= (char *) 0;
797 while (*cp
&& *cp
!= '\n' && *cp
!= ' '
801 /* Allow shell search without prepended path
802 * if shell with / in pathname cannot be found.
803 * Use / explicitly so \ can be used if explicit
804 * needs to be forced.
811 if (*cp
&& *cp
!= '\n') {
814 && (*cp
== ' ' || *cp
== '\t'))
816 if (*cp
&& *cp
!= '\n') {
818 /* all one argument */
819 while (*cp
&& *cp
!= '\n')
829 char *tmp_a0
= str_nsave(a0
,
830 strlen(a0
) + 5, ATEMP
);
831 if (search_access(tmp_a0
, X_OK
,
834 afree(tmp_a0
, ATEMP
);
842 /* Use ksh documented shell default if present
843 * else use OS2_SHELL which is assumed to need
844 * the /c option and '\' as dir separator.
848 shellv
= str_val(global("EXECSHELL"));
849 if (shellv
&& *shellv
)
850 shellv
= search(shellv
, path
, X_OK
, (int *) 0);
851 if (!shellv
|| !*shellv
) {
854 for (p
= tp
->str
; *p
; p
++)
861 #endif /* SHARPBANG */
864 ksh_execve(tp
->args
[0], tp
->args
, ap
, 0);
866 /* report both the program that was run and the bogus shell */
867 errorf("%s: %s: %s", tp
->str
, shellv
, strerror(errno
));
874 register struct tbl
*tp
;
876 tp
= tsearch(&builtins
, *wp
, hash(*wp
));
878 internal_errorf(1, "shcomexec: %s", *wp
);
879 return call_builtin(tp
, wp
);
883 * Search function tables for a function. If create set, a table entry
884 * is created if none is found.
887 findfunc(name
, h
, create
)
893 struct tbl
*tp
= (struct tbl
*) 0;
895 for (l
= e
->loc
; l
; l
= l
->next
) {
896 tp
= tsearch(&l
->funs
, name
, h
);
899 if (!l
->next
&& create
) {
900 tp
= tenter(&l
->funs
, name
, h
);
903 tp
->val
.t
= (struct op
*) 0;
911 * define function. Returns 1 if function is being undefined (t == 0) and
912 * function did not exist, returns 0 otherwise.
923 tp
= findfunc(name
, hash(name
), TRUE
);
925 if (tp
->flag
& ISSET
)
927 /* If this function is currently being executed, we zap this
928 * table entry so findfunc() won't see it
930 if (tp
->flag
& FINUSE
) {
932 tp
->flag
&= ~DEFINED
; /* ensure it won't be found */
938 if (tp
->flag
& ALLOC
) {
939 tp
->flag
&= ~(ISSET
|ALLOC
);
940 tfree(tp
->val
.t
, tp
->areap
);
943 if (t
== NULL
) { /* undefine */
945 return was_set
? 0 : 1;
948 tp
->val
.t
= tcopy(t
->left
, tp
->areap
);
949 tp
->flag
|= (ISSET
|ALLOC
);
962 int (*func
) ARGS((char **));
964 register struct tbl
*tp
;
967 /* see if any flags should be set for this builtin */
968 for (flag
= 0; ; name
++) {
969 if (*name
== '=') /* command does variable assignment */
971 else if (*name
== '*') /* POSIX special builtin */
973 else if (*name
== '+') /* POSIX regular builtin */
979 tp
= tenter(&builtins
, name
, hash(name
));
980 tp
->flag
= DEFINED
| flag
;
987 * either function, hashed command, or built-in (in that order)
992 int flags
; /* FC_* */
994 static struct tbl temp
;
995 unsigned int h
= hash(name
);
996 struct tbl
*tp
= NULL
, *tbi
;
997 int insert
= Flag(FTRACKALL
); /* insert if not found */
998 char *fpath
; /* for function autoloading */
1001 if (ksh_strchr_dirsep(name
) != NULL
) {
1003 /* prevent FPATH search below */
1007 tbi
= (flags
& FC_BI
) ? tsearch(&builtins
, name
, h
) : NULL
;
1008 /* POSIX says special builtins first, then functions, then
1009 * POSIX regular builtins, then search path...
1011 if ((flags
& FC_SPECBI
) && tbi
&& (tbi
->flag
& SPEC_BI
))
1013 if (!tp
&& (flags
& FC_FUNC
)) {
1014 tp
= findfunc(name
, h
, FALSE
);
1015 if (tp
&& !(tp
->flag
& ISSET
)) {
1016 if ((fpath
= str_val(global("FPATH"))) == null
) {
1017 tp
->u
.fpath
= (char *) 0;
1020 tp
->u
.fpath
= search(name
, fpath
, R_OK
,
1024 if (!tp
&& (flags
& FC_REGBI
) && tbi
&& (tbi
->flag
& REG_BI
))
1026 /* todo: posix says non-special/non-regular builtins must
1027 * be triggered by some user-controllable means like a
1028 * special directory in PATH. Requires modifications to
1029 * the search() function. Tracked aliases should be
1030 * modified to allow tracking of builtin commands.
1031 * This should be under control of the FPOSIX flag.
1032 * If this is changed, also change c_whence...
1034 if (!tp
&& (flags
& FC_UNREGBI
) && tbi
)
1036 if (!tp
&& (flags
& FC_PATH
) && !(flags
& FC_DEFPATH
)) {
1037 tp
= tsearch(&taliases
, name
, h
);
1038 if (tp
&& (tp
->flag
& ISSET
) && eaccess(tp
->val
.s
, X_OK
) != 0) {
1039 if (tp
->flag
& ALLOC
) {
1041 afree(tp
->val
.s
, APERM
);
1048 if ((!tp
|| (tp
->type
== CTALIAS
&& !(tp
->flag
&ISSET
)))
1049 && (flags
& FC_PATH
))
1052 if (insert
&& !(flags
& FC_DEFPATH
)) {
1053 tp
= tenter(&taliases
, name
, h
);
1059 tp
->flag
= DEFINED
; /* make ~ISSET */
1061 npath
= search(name
, flags
& FC_DEFPATH
? def_path
: path
,
1062 X_OK
, &tp
->u2
.errno_
);
1067 tp
->val
.s
= str_save(npath
, APERM
);
1068 afree(npath
, ATEMP
);
1070 tp
->flag
|= ISSET
|ALLOC
;
1071 } else if ((flags
& FC_FUNC
)
1072 && (fpath
= str_val(global("FPATH"))) != null
1073 && (npath
= search(name
, fpath
, R_OK
,
1074 &tp
->u2
.errno_
)) != (char *) 0)
1076 /* An undocumented feature of at&t ksh is that it
1077 * searches FPATH if a command is not found, even
1078 * if the command hasn't been set up as an autoloaded
1079 * function (ie, no typeset -uf).
1083 tp
->flag
= DEFINED
; /* make ~ISSET */
1084 tp
->u
.fpath
= npath
;
1091 * flush executable commands with relative paths
1095 int all
; /* just relative or all */
1100 for (twalk(&ts
, &taliases
); (tp
= tnext(&ts
)) != NULL
; )
1101 if ((tp
->flag
&ISSET
) && (all
|| !ISDIRSEP(tp
->val
.s
[0]))) {
1102 if (tp
->flag
&ALLOC
) {
1103 tp
->flag
&= ~(ALLOC
|ISSET
);
1104 afree(tp
->val
.s
, APERM
);
1110 /* Check if path is something we want to find. Returns -1 for failure. */
1112 search_access(pathx
, mode
, errnop
)
1115 int *errnop
; /* set if candidate found, but not suitable */
1121 if (stat(pathx
, &statb
) < 0)
1123 ret
= eaccess(pathx
, mode
);
1125 err
= errno
; /* File exists, but we can't access it */
1126 else if (mode
== X_OK
1127 && (!S_ISREG(statb
.st_mode
)
1128 /* This 'cause access() says root can execute everything */
1129 || !(statb
.st_mode
& (S_IXUSR
|S_IXGRP
|S_IXOTH
))))
1132 err
= S_ISDIR(statb
.st_mode
) ? EISDIR
: EACCES
;
1134 if (err
&& errnop
&& !*errnop
)
1139 * NOTE: ASSUMES path can be modified and has enough room at the
1140 * end of the string for a suffix (ie, 4 extra characters).
1141 * Certain code knows this (eg, eval.c(globit()),
1142 * exec.c(search())).
1144 static char *xsuffixes
[] = { ".ksh", ".exe", ".", ".sh", ".cmd",
1145 ".com", ".bat", (char *) 0
1147 static char *rsuffixes
[] = { ".ksh", ".", ".sh", ".cmd", ".bat",
1151 char *mpath
= (char *) pathx
;
1152 char *tp
= mpath
+ strlen(mpath
);
1156 /* If a suffix has been specified, check if it is one of the
1157 * suffixes that indicate the file is executable - if so, change
1158 * the access test to R_OK...
1159 * This code assumes OS/2 files can have only one suffix...
1161 if ((p
= strrchr((p
= ksh_strrchr_dirsep(mpath
)) ? p
: mpath
, '.'))) {
1164 return search_access1(mpath
, mode
, errnop
);
1166 /* Try appending the various suffixes. Different suffixes for
1167 * read and execute 'cause we don't want to read an executable...
1169 sfx
= mode
== R_OK
? rsuffixes
: xsuffixes
;
1170 for (i
= 0; sfx
[i
]; i
++) {
1171 strcpy(tp
, p
= sfx
[i
]);
1172 if (search_access1(mpath
, R_OK
, errnop
) == 0)
1182 search_access1(pathx
, mode
, errnop
)
1185 int *errnop
; /* set if candidate found, but not suitable */
1190 if (stat(pathx
, &statb
) < 0)
1192 ret
= eaccess(pathx
, mode
);
1194 err
= errno
; /* File exists, but we can't access it */
1195 else if (!S_ISREG(statb
.st_mode
)) {
1197 err
= S_ISDIR(statb
.st_mode
) ? EISDIR
: EACCES
;
1199 if (err
&& errnop
&& !*errnop
)
1206 * search for command with PATH
1209 search(name
, pathx
, mode
, errnop
)
1212 int mode
; /* R_OK or X_OK */
1213 int *errnop
; /* set if candidate found, but not suitable */
1223 /* Xinit() allocates 8 additional bytes, so appended suffixes won't
1224 * overflow the memory.
1226 namelen
= strlen(name
) + 1;
1227 Xinit(xs
, xp
, namelen
, ATEMP
);
1228 memcpy(Xstring(xs
, xp
), name
, namelen
);
1230 if (ksh_strchr_dirsep(name
)) {
1231 if (search_access(Xstring(xs
, xp
), mode
, errnop
) >= 0)
1232 return Xstring(xs
, xp
); /* not Xclose() - see above */
1237 /* Look in current context always. (os2 style) */
1238 if (search_access(Xstring(xs
, xp
), mode
, errnop
) == 0)
1239 return Xstring(xs
, xp
); /* not Xclose() - xp may be wrong */
1241 if (ksh_strchr_dirsep(name
)) {
1242 if (search_access(name
, mode
, errnop
) == 0)
1243 return (char *)__UNCONST(name
);
1247 namelen
= strlen(name
) + 1;
1248 Xinit(xs
, xp
, 128, ATEMP
);
1252 while (sp
!= NULL
) {
1253 xp
= Xstring(xs
, xp
);
1254 if (!(p
= strchr(sp
, PATHSEP
)))
1255 p
= sp
+ strlen(sp
);
1257 XcheckN(xs
, xp
, p
- sp
);
1258 memcpy(xp
, sp
, p
- sp
);
1263 XcheckN(xs
, xp
, namelen
);
1264 memcpy(xp
, name
, namelen
);
1265 if (search_access(Xstring(xs
, xp
), mode
, errnop
) == 0)
1267 return Xstring(xs
, xp
); /* Not Xclose() - see above */
1269 return Xclose(xs
, xp
+ namelen
);
1279 call_builtin(tp
, wp
)
1285 builtin_argv0
= wp
[0];
1286 builtin_flag
= tp
->flag
;
1287 shf_reopen(1, SHF_WR
, shl_stdout
);
1289 ksh_getopt_reset(&builtin_opt
, GF_ERROR
);
1290 rv
= (*tp
->val
.f
)(wp
);
1291 shf_flush(shl_stdout
);
1294 builtin_argv0
= (char *) 0;
1299 * set up redirection, saving old fd's in e->savefd
1303 register struct ioword
*iop
;
1306 register int u
= -1;
1307 char *cp
= iop
->name
;
1308 int iotype
= iop
->flag
& IOTYPE
;
1309 int do_open
= 1, do_close
= 0, UNINITIALIZED(flags
);
1310 struct ioword iotmp
;
1313 if (iotype
!= IOHERE
)
1314 cp
= evalonestr(cp
, DOTILDE
|(Flag(FTALKING_I
) ? DOGLOB
: 0));
1316 /* Used for tracing and error messages to print expanded cp */
1318 iotmp
.name
= (iotype
== IOHERE
) ? (char *) 0 : cp
;
1319 iotmp
.flag
|= IONAMEXP
;
1323 PS4_SUBSTITUTE(str_val(global("PS4"))),
1324 snptreef((char *) 0, 32, "%R", &iotmp
));
1332 flags
= O_WRONLY
| O_APPEND
| O_CREAT
;
1336 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1337 /* The stat() is here to allow redirections to
1338 * things like /dev/null without error.
1340 if (Flag(FNOCLOBBER
) && !(iop
->flag
& IOCLOB
)
1341 && (stat(cp
, &statb
) < 0 || S_ISREG(statb
.st_mode
)))
1346 flags
= O_RDWR
| O_CREAT
;
1351 /* herein() returns -2 if error has been printed */
1352 u
= herein(iop
->heredoc
, iop
->flag
& IOEVAL
);
1353 /* cp may have wrong name */
1361 if (*cp
== '-' && !cp
[1]) {
1362 u
= 1009; /* prevent error return below */
1364 } else if ((u
= check_fd(cp
,
1365 X_OK
| ((iop
->flag
& IORDUP
) ? R_OK
: W_OK
),
1368 warningf(TRUE
, "%s: %s",
1369 snptreef((char *) 0, 32, "%R", &iotmp
), emsg
);
1373 return 0; /* "dup from" == "dup to" */
1378 if (Flag(FRESTRICTED
) && (flags
& O_CREAT
)) {
1379 warningf(TRUE
, "%s: restricted", cp
);
1382 u
= open(cp
, flags
, 0666);
1384 if (u
< 0 && strcmp(cp
, "/dev/null") == 0)
1385 u
= open("nul", flags
, 0666);
1389 /* herein() may already have printed message */
1391 warningf(TRUE
, "cannot %s %s: %s",
1392 iotype
== IODUP
? "dup"
1393 : (iotype
== IOREAD
|| iotype
== IOHERE
) ?
1394 "open" : "create", cp
, strerror(errno
));
1397 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1398 if (e
->savefd
[iop
->unit
] == 0) {
1399 /* If these are the same, it means unit was previously closed */
1401 e
->savefd
[iop
->unit
] = -1;
1403 /* c_exec() assumes e->savefd[fd] set for any
1404 * redirections. Ask savefd() not to close iop->unit;
1405 * this allows error messages to be seen if iop->unit
1406 * is 2; also means we can't lose the fd (eg, both
1407 * dup2 below and dup2 in restfd() failing).
1409 e
->savefd
[iop
->unit
] = savefd(iop
->unit
, 1);
1414 else if (u
!= iop
->unit
) {
1415 if (ksh_dup2(u
, iop
->unit
, TRUE
) < 0) {
1417 "could not finish (dup) redirection %s: %s",
1418 snptreef((char *) 0, 32, "%R", &iotmp
),
1420 if (iotype
!= IODUP
)
1424 if (iotype
!= IODUP
)
1427 /* Touching any co-process fd in an empty exec
1428 * causes the shell to close its copies
1430 else if (tp
&& tp
->type
== CSHELL
&& tp
->val
.f
== c_exec
) {
1431 if (iop
->flag
& IORDUP
) /* possible exec <&p */
1432 coproc_read_close(u
);
1433 else /* possible exec >&p */
1434 coproc_write_close(u
);
1438 if (u
== 2) /* Clear any write errors */
1439 shf_reopen(2, SHF_WR
, shl_out
);
1444 * open here document temp file.
1445 * if unquoted here, expand here temp file into second temp file.
1448 herein(content
, sub
)
1449 const char *content
;
1452 volatile int fd
= -1;
1453 struct source
*s
, *volatile osource
;
1454 struct shf
*volatile shf
;
1458 /* ksh -c 'cat << EOF' can cause this... */
1459 if (content
== (char *) 0) {
1460 warningf(TRUE
, "here document missing");
1461 return -2; /* special to iosetup(): don't print error */
1464 /* Create temp file to hold content (done before newenv so temp
1465 * doesn't get removed too soon).
1467 h
= maketemp(ATEMP
, TT_HEREDOC_EXP
, &e
->temps
);
1468 if (!(shf
= h
->shf
) || (fd
= open(h
->name
, O_RDONLY
, 0)) < 0) {
1469 warningf(TRUE
, "can't %s temporary file %s: %s",
1470 !shf
? "create" : "open",
1471 h
->name
, strerror(errno
));
1474 return -2 /* special to iosetup(): don't print error */;
1479 i
= ksh_sigsetjmp(e
->jbuf
, 0);
1483 shf_close(shf
); /* after quitenv */
1485 return -2; /* special to iosetup(): don't print error */
1488 /* Do substitutions on the content of heredoc */
1489 s
= pushs(SSTRING
, ATEMP
);
1490 s
->start
= s
->str
= content
;
1492 if (yylex(ONEWORD
|HEREDOC
) != LWORD
)
1493 internal_errorf(1, "herein: yylex");
1495 shf_puts(evalstr(yylval
.cp
, 0), shf
);
1497 shf_puts(content
, shf
);
1501 if (shf_close(shf
) == EOF
) {
1503 warningf(TRUE
, "error writing %s: %s", h
->name
,
1505 return -2; /* special to iosetup(): don't print error */
1513 * ksh special - the select command processing section
1514 * print the args in column form - assuming that we can
1517 do_selectargs(ap
, print_menu
)
1521 static const char *const read_args
[] = {
1522 "read", "-r", "REPLY", (char *) 0
1527 for (argct
= 0; ap
[argct
]; argct
++)
1530 /* Menu is printed if
1531 * - this is the first time around the select loop
1532 * - the user enters a blank line
1533 * - the REPLY parameter is empty
1535 if (print_menu
|| !*str_val(global("REPLY")))
1537 shellf("%s", str_val(global("PS3")));
1538 if (call_builtin(findcom("read", FC_BI
),
1539 (char **) __UNCONST(read_args
)))
1541 s
= str_val(global("REPLY"));
1544 return (i
>= 1 && i
<= argct
) ? ap
[i
- 1] : null
;
1550 struct select_menu_info
{
1556 static char *select_fmt_entry
ARGS((void *arg
, int i
, char *buf
, int buflen
));
1558 /* format a single select menu item */
1560 select_fmt_entry(arg
, i
, buf
, buflen
)
1566 struct select_menu_info
*smi
= (struct select_menu_info
*) arg
;
1568 shf_snprintf(buf
, buflen
, "%*d) %s",
1569 smi
->num_width
, i
+ 1, smi
->args
[i
]);
1574 * print a select style menu
1580 struct select_menu_info smi
;
1585 /* Width/column calculations were done once and saved, but this
1586 * means select can't be used recursively so we re-calculate each
1587 * time (could save in a structure that is returned, but its probably
1588 * not worth the bother).
1592 * get dimensions of the list
1594 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1596 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1599 * we will print an index of the form
1601 * in front of each entry
1602 * get the max width of this
1604 for (i
= n
, dwidth
= 1; i
>= 10; i
/= 10)
1608 smi
.arg_width
= nwidth
;
1609 smi
.num_width
= dwidth
;
1610 print_columns(shl_out
, n
, select_fmt_entry
, (void *) &smi
,
1611 dwidth
+ nwidth
+ 2, 1);
1616 /* XXX: horrible kludge to fit within the framework */
1618 static char *plain_fmt_entry
ARGS((void *arg
, int i
, char *buf
, int buflen
));
1621 plain_fmt_entry(arg
, i
, buf
, buflen
)
1627 shf_snprintf(buf
, buflen
, "%s", ((char *const *)arg
)[i
]);
1639 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1641 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1643 print_columns(shl_out
, n
, plain_fmt_entry
, (void *)__UNCONST(ap
),
1652 * [[ ... ]] evaluation routines
1655 extern const char *const dbtest_tokens
[];
1656 extern const char db_close
[];
1658 /* Test if the current token is a whatever. Accepts the current token if
1659 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1660 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1663 dbteste_isa(te
, meta
)
1672 return meta
== TM_END
;
1674 /* unquoted word? */
1675 for (p
= *te
->pos
.wp
; *p
== CHAR
; p
+= 2)
1679 if (meta
== TM_UNOP
|| meta
== TM_BINOP
) {
1681 char buf
[8]; /* longer than the longest operator */
1683 for (p
= *te
->pos
.wp
; *p
== CHAR
1684 && q
< &buf
[sizeof(buf
) - 1];
1688 ret
= (int) test_isop(te
, meta
, buf
);
1690 } else if (meta
== TM_END
)
1694 && strcmp(*te
->pos
.wp
, dbtest_tokens
[(int) meta
]) == 0;
1696 /* Accept the token? */
1704 dbteste_getopnd(te
, op
, do_eval
)
1709 char *s
= *te
->pos
.wp
;
1719 if (op
== TO_STEQL
|| op
== TO_STNEQ
)
1720 s
= evalstr(s
, DOTILDE
| DOPAT
);
1722 s
= evalstr(s
, DOTILDE
);
1728 dbteste_eval(te
, op
, opnd1
, opnd2
, do_eval
)
1735 return test_eval(te
, op
, opnd1
, opnd2
, do_eval
);
1739 dbteste_error(te
, offset
, msg
)
1744 te
->flags
|= TEF_ERROR
;
1745 internal_errorf(0, "dbteste_error: %s (offset %d)", msg
, offset
);