1 /* $NetBSD: exec.c,v 1.15 2012/03/25 17:23:48 christos Exp $ */
9 __RCSID("$NetBSD: exec.c,v 1.15 2012/03/25 17:23:48 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
;
463 register char **lastp
;
464 static struct op texec
; /* Must be static (XXX but why?) */
467 int fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;
468 int bourne_function_call
= 0;
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
)) {
479 /* setstr() can't fail here */
480 setstr(typeset("_", LOCAL
, 0, INTEGER
, 0), *--lastp
,
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
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
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
) {
505 tp
= findcom(cp
, FC_BI
);
507 errorf("builtin: %s: not a builtin", cp
);
509 } else if (tp
->val
.f
== c_exec
) {
514 } else if (tp
->val
.f
== c_command
) {
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"))
525 break; /* command -vV or something */
526 /* don't look for functions */
527 fcflags
= FC_BI
|FC_PATH
;
529 if (Flag(FRESTRICTED
)) {
531 "command -p: restricted");
535 fcflags
|= FC_DEFPATH
;
537 ap
+= builtin_opt
.optind
;
538 /* POSIX says special builtins lose their status
539 * if accessed using command.
543 /* ensure command with no args exits with 0 */
549 tp
= findcom(ap
[0], fcflags
& (FC_BI
|FC_FUNC
));
551 if (keepasn_ok
&& (!ap
[0] || (tp
&& (tp
->flag
& KEEPASN
))))
554 /* create new variable/function block */
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;
562 type_flags
= LOCAL
|LOCAL_COPY
|EXPORT
;
565 type_flags
|= EXPORT
;
566 for (i
= 0; t
->vars
[i
]; i
++) {
567 cp
= evalstr(t
->vars
[i
], DOASNTILDE
);
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
);
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
) {
586 if (Flag(FRESTRICTED
) && ksh_strchr_dirsep(cp
)) {
587 warningf(TRUE
, "%s: restricted", cp
);
591 tp
= findcom(cp
, fcflags
);
595 case CSHELL
: /* shell built-in */
596 rv
= call_builtin(tp
, ap
);
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
)) {
611 "%s: can't find function definition file - %s",
612 cp
, strerror(tp
->u2
.errno_
));
616 "%s: can't find function definition file", cp
);
621 if (include(tp
->u
.fpath
, 0, (char **) 0, 0) < 0) {
623 "%s: can't open function definition file %s - %s",
624 cp
, tp
->u
.fpath
, strerror(errno
));
628 if (!(ftp
= findfunc(cp
, hash(cp
), FALSE
))
629 || !(ftp
->flag
& ISSET
))
632 "%s: function not defined by %s",
640 /* ksh functions set $0 to function name, POSIX functions leave
643 old_kshname
= kshname
;
647 ap
[0] = (char *) __UNCONST(kshname
);
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
;
661 old_xflag
= Flag(FXTRACE
);
662 Flag(FXTRACE
) = tp
->flag
& TRACE
? TRUE
: FALSE
;
664 old_inuse
= tp
->flag
& FINUSE
;
668 i
= ksh_sigsetjmp(e
->jbuf
, 0);
670 /* seems odd to pass XERROK here, but at&t ksh does */
671 exstat
= execute(tp
->val
.t
, flags
& XERROK
);
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
) {
684 tfree(tp
->val
.t
, tp
->areap
);
702 internal_errorf(1, "CFUNC %d", i
);
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.
716 warningf(TRUE
, "%s: cannot execute - %s", cp
,
717 strerror(tp
->u2
.errno_
));
718 rv
= 126; /* POSIX */
720 warningf(TRUE
, "%s: not found", cp
);
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
);
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 */
743 texec
.left
= t
; /* for tprint */
744 texec
.str
= tp
->val
.s
;
746 rv
= exchild(&texec
, flags
, -1);
760 register struct op
*tp
;
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
;
779 if ((fd
= open(tp
->str
, O_RDONLY
)) >= 0) {
780 if ((n
= read(fd
, buf
, LINE
- 1)) > 0)
784 if ((buf
[0] == '#' && buf
[1] == '!' && (cp
= &buf
[2]))
786 || (strncmp(buf
, "extproc", 7) == 0 && isspace((unsigned char)buf
[7])
791 while (*cp
&& (*cp
== ' ' || *cp
== '\t'))
793 if (*cp
&& *cp
!= '\n') {
794 char *a0
= cp
, *a1
= (char *) 0;
799 while (*cp
&& *cp
!= '\n' && *cp
!= ' '
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.
813 if (*cp
&& *cp
!= '\n') {
816 && (*cp
== ' ' || *cp
== '\t'))
818 if (*cp
&& *cp
!= '\n') {
820 /* all one argument */
821 while (*cp
&& *cp
!= '\n')
831 char *tmp_a0
= str_nsave(a0
,
832 strlen(a0
) + 5, ATEMP
);
833 if (search_access(tmp_a0
, X_OK
,
836 afree(tmp_a0
, ATEMP
);
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.
850 shellv
= str_val(global("EXECSHELL"));
851 if (shellv
&& *shellv
)
852 shellv
= search(shellv
, path
, X_OK
, (int *) 0);
853 if (!shellv
|| !*shellv
) {
856 for (p
= tp
->str
; *p
; p
++)
863 #endif /* SHARPBANG */
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
));
876 register struct tbl
*tp
;
878 tp
= tsearch(&builtins
, *wp
, hash(*wp
));
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.
889 findfunc(name
, h
, create
)
895 struct tbl
*tp
= (struct tbl
*) 0;
897 for (l
= e
->loc
; l
; l
= l
->next
) {
898 tp
= tsearch(&l
->funs
, name
, h
);
901 if (!l
->next
&& create
) {
902 tp
= tenter(&l
->funs
, name
, h
);
905 tp
->val
.t
= (struct op
*) 0;
913 * define function. Returns 1 if function is being undefined (t == 0) and
914 * function did not exist, returns 0 otherwise.
925 tp
= findfunc(name
, hash(name
), TRUE
);
927 if (tp
->flag
& ISSET
)
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
) {
934 tp
->flag
&= ~DEFINED
; /* ensure it won't be found */
940 if (tp
->flag
& ALLOC
) {
941 tp
->flag
&= ~(ISSET
|ALLOC
);
942 tfree(tp
->val
.t
, tp
->areap
);
945 if (t
== NULL
) { /* undefine */
947 return was_set
? 0 : 1;
950 tp
->val
.t
= tcopy(t
->left
, tp
->areap
);
951 tp
->flag
|= (ISSET
|ALLOC
);
964 int (*func
) ARGS((char **));
966 register struct tbl
*tp
;
969 /* see if any flags should be set for this builtin */
970 for (flag
= 0; ; name
++) {
971 if (*name
== '=') /* command does variable assignment */
973 else if (*name
== '*') /* POSIX special builtin */
975 else if (*name
== '+') /* POSIX regular builtin */
981 tp
= tenter(&builtins
, name
, hash(name
));
982 tp
->flag
= DEFINED
| flag
;
989 * either function, hashed command, or built-in (in that order)
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 */
1003 if (ksh_strchr_dirsep(name
) != NULL
) {
1005 /* prevent FPATH search below */
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
))
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;
1022 tp
->u
.fpath
= search(name
, fpath
, R_OK
,
1026 if (!tp
&& (flags
& FC_REGBI
) && tbi
&& (tbi
->flag
& REG_BI
))
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
)
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
) {
1043 afree(tp
->val
.s
, APERM
);
1050 if ((!tp
|| (tp
->type
== CTALIAS
&& !(tp
->flag
&ISSET
)))
1051 && (flags
& FC_PATH
))
1054 if (insert
&& !(flags
& FC_DEFPATH
)) {
1055 tp
= tenter(&taliases
, name
, h
);
1061 tp
->flag
= DEFINED
; /* make ~ISSET */
1063 npath
= search(name
, flags
& FC_DEFPATH
? def_path
: path
,
1064 X_OK
, &tp
->u2
.errno_
);
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).
1085 tp
->flag
= DEFINED
; /* make ~ISSET */
1086 tp
->u
.fpath
= npath
;
1093 * flush executable commands with relative paths
1097 int all
; /* just relative or all */
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
);
1112 /* Check if path is something we want to find. Returns -1 for failure. */
1114 search_access(pathx
, mode
, errnop
)
1117 int *errnop
; /* set if candidate found, but not suitable */
1123 if (stat(pathx
, &statb
) < 0)
1125 ret
= eaccess(pathx
, mode
);
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
))))
1134 err
= S_ISDIR(statb
.st_mode
) ? EISDIR
: EACCES
;
1136 if (err
&& errnop
&& !*errnop
)
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",
1153 char *mpath
= (char *) pathx
;
1154 char *tp
= mpath
+ strlen(mpath
);
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
, '.'))) {
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)
1184 search_access1(pathx
, mode
, errnop
)
1187 int *errnop
; /* set if candidate found, but not suitable */
1192 if (stat(pathx
, &statb
) < 0)
1194 ret
= eaccess(pathx
, mode
);
1196 err
= errno
; /* File exists, but we can't access it */
1197 else if (!S_ISREG(statb
.st_mode
)) {
1199 err
= S_ISDIR(statb
.st_mode
) ? EISDIR
: EACCES
;
1201 if (err
&& errnop
&& !*errnop
)
1208 * search for command with PATH
1211 search(name
, pathx
, mode
, errnop
)
1214 int mode
; /* R_OK or X_OK */
1215 int *errnop
; /* set if candidate found, but not suitable */
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 */
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 */
1243 if (ksh_strchr_dirsep(name
)) {
1244 if (search_access(name
, mode
, errnop
) == 0)
1245 return (char *)__UNCONST(name
);
1249 namelen
= strlen(name
) + 1;
1250 Xinit(xs
, xp
, 128, ATEMP
);
1254 while (sp
!= NULL
) {
1255 xp
= Xstring(xs
, xp
);
1256 if (!(p
= strchr(sp
, PATHSEP
)))
1257 p
= sp
+ strlen(sp
);
1259 XcheckN(xs
, xp
, p
- sp
);
1260 memcpy(xp
, sp
, p
- sp
);
1265 XcheckN(xs
, xp
, namelen
);
1266 memcpy(xp
, name
, namelen
);
1267 if (search_access(Xstring(xs
, xp
), mode
, errnop
) == 0)
1269 return Xstring(xs
, xp
); /* Not Xclose() - see above */
1271 return Xclose(xs
, xp
+ namelen
);
1281 call_builtin(tp
, wp
)
1287 builtin_argv0
= wp
[0];
1288 builtin_flag
= tp
->flag
;
1289 shf_reopen(1, SHF_WR
, shl_stdout
);
1291 ksh_getopt_reset(&builtin_opt
, GF_ERROR
);
1292 rv
= (*tp
->val
.f
)(wp
);
1293 shf_flush(shl_stdout
);
1296 builtin_argv0
= (char *) 0;
1301 * set up redirection, saving old fd's in e->savefd
1305 register struct ioword
*iop
;
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
;
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 */
1320 iotmp
.name
= (iotype
== IOHERE
) ? (char *) 0 : cp
;
1321 iotmp
.flag
|= IONAMEXP
;
1325 PS4_SUBSTITUTE(str_val(global("PS4"))),
1326 snptreef((char *) 0, 32, "%R", &iotmp
));
1334 flags
= O_WRONLY
| O_APPEND
| O_CREAT
;
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
)))
1348 flags
= O_RDWR
| O_CREAT
;
1353 /* herein() returns -2 if error has been printed */
1354 u
= herein(iop
->heredoc
, iop
->flag
& IOEVAL
);
1355 /* cp may have wrong name */
1363 if (*cp
== '-' && !cp
[1]) {
1364 u
= 1009; /* prevent error return below */
1366 } else if ((u
= check_fd(cp
,
1367 X_OK
| ((iop
->flag
& IORDUP
) ? R_OK
: W_OK
),
1370 warningf(TRUE
, "%s: %s",
1371 snptreef((char *) 0, 32, "%R", &iotmp
), emsg
);
1375 return 0; /* "dup from" == "dup to" */
1380 if (Flag(FRESTRICTED
) && (flags
& O_CREAT
)) {
1381 warningf(TRUE
, "%s: restricted", cp
);
1384 u
= open(cp
, flags
, 0666);
1386 if (u
< 0 && strcmp(cp
, "/dev/null") == 0)
1387 u
= open("nul", flags
, 0666);
1391 /* herein() may already have printed message */
1393 warningf(TRUE
, "cannot %s %s: %s",
1394 iotype
== IODUP
? "dup"
1395 : (iotype
== IOREAD
|| iotype
== IOHERE
) ?
1396 "open" : "create", cp
, strerror(errno
));
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 */
1403 e
->savefd
[iop
->unit
] = -1;
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);
1416 else if (u
!= iop
->unit
) {
1417 if (ksh_dup2(u
, iop
->unit
, TRUE
) < 0) {
1419 "could not finish (dup) redirection %s: %s",
1420 snptreef((char *) 0, 32, "%R", &iotmp
),
1422 if (iotype
!= IODUP
)
1426 if (iotype
!= IODUP
)
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
);
1440 if (u
== 2) /* Clear any write errors */
1441 shf_reopen(2, SHF_WR
, shl_out
);
1446 * open here document temp file.
1447 * if unquoted here, expand here temp file into second temp file.
1450 herein(content
, sub
)
1451 const char *content
;
1454 volatile int fd
= -1;
1455 struct source
*s
, *volatile osource
;
1456 struct shf
*volatile shf
;
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
));
1476 return -2 /* special to iosetup(): don't print error */;
1481 i
= ksh_sigsetjmp(e
->jbuf
, 0);
1485 shf_close(shf
); /* after quitenv */
1487 return -2; /* special to iosetup(): don't print error */
1490 /* Do substitutions on the content of heredoc */
1491 s
= pushs(SSTRING
, ATEMP
);
1492 s
->start
= s
->str
= content
;
1494 if (yylex(ONEWORD
|HEREDOC
) != LWORD
)
1495 internal_errorf(1, "herein: yylex");
1497 shf_puts(evalstr(yylval
.cp
, 0), shf
);
1499 shf_puts(content
, shf
);
1503 if (shf_close(shf
) == EOF
) {
1505 warningf(TRUE
, "error writing %s: %s", h
->name
,
1507 return -2; /* special to iosetup(): don't print error */
1515 * ksh special - the select command processing section
1516 * print the args in column form - assuming that we can
1519 do_selectargs(ap
, print_menu
)
1523 static const char *const read_args
[] = {
1524 "read", "-r", "REPLY", (char *) 0
1529 for (argct
= 0; ap
[argct
]; argct
++)
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")))
1539 shellf("%s", str_val(global("PS3")));
1540 if (call_builtin(findcom("read", FC_BI
),
1541 (char **) __UNCONST(read_args
)))
1543 s
= str_val(global("REPLY"));
1546 return (i
>= 1 && i
<= argct
) ? ap
[i
- 1] : null
;
1552 struct select_menu_info
{
1558 static char *select_fmt_entry
ARGS((void *arg
, int i
, char *buf
, int buflen
));
1560 /* format a single select menu item */
1562 select_fmt_entry(arg
, i
, buf
, 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
]);
1576 * print a select style menu
1582 struct select_menu_info smi
;
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
++) {
1598 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1601 * we will print an index of the form
1603 * in front of each entry
1604 * get the max width of this
1606 for (i
= n
, dwidth
= 1; i
>= 10; i
/= 10)
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);
1618 /* XXX: horrible kludge to fit within the framework */
1620 static char *plain_fmt_entry
ARGS((void *arg
, int i
, char *buf
, int buflen
));
1623 plain_fmt_entry(arg
, i
, buf
, buflen
)
1629 shf_snprintf(buf
, buflen
, "%s", ((char *const *)arg
)[i
]);
1641 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1643 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1645 print_columns(shl_out
, n
, plain_fmt_entry
, (void *)__UNCONST(ap
),
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).
1665 dbteste_isa(te
, meta
)
1674 return meta
== TM_END
;
1676 /* unquoted word? */
1677 for (p
= *te
->pos
.wp
; *p
== CHAR
; p
+= 2)
1681 if (meta
== TM_UNOP
|| meta
== TM_BINOP
) {
1683 char buf
[8]; /* longer than the longest operator */
1685 for (p
= *te
->pos
.wp
; *p
== CHAR
1686 && q
< &buf
[sizeof(buf
) - 1];
1690 ret
= (int) test_isop(te
, meta
, buf
);
1692 } else if (meta
== TM_END
)
1696 && strcmp(*te
->pos
.wp
, dbtest_tokens
[(int) meta
]) == 0;
1698 /* Accept the token? */
1706 dbteste_getopnd(te
, op
, do_eval
)
1711 char *s
= *te
->pos
.wp
;
1721 if (op
== TO_STEQL
|| op
== TO_STNEQ
)
1722 s
= evalstr(s
, DOTILDE
| DOPAT
);
1724 s
= evalstr(s
, DOTILDE
);
1730 dbteste_eval(te
, op
, opnd1
, opnd2
, do_eval
)
1737 return test_eval(te
, op
, opnd1
, opnd2
, do_eval
);
1741 dbteste_error(te
, offset
, msg
)
1746 te
->flags
|= TEF_ERROR
;
1747 internal_errorf(0, "dbteste_error: %s (offset %d)", msg
, offset
);