11 #include <proto/dos.h>
13 /* Does ps4 get parameter substitutions done? */
14 #define PS4_SUBSTITUTE(s) substitute((s), 0)
16 static int comexec(struct op
*, struct tbl
*volatile, char **,
18 static void scriptexec(struct op
*, char **);
19 static int call_builtin(struct tbl
*, char **);
20 static int iosetup(struct ioword
*, struct tbl
*);
21 static int herein(const char *, int);
22 static char *do_selectargs(char **, bool);
23 static int dbteste_isa(Test_env
*, Test_meta
);
24 static const char *dbteste_getopnd(Test_env
*, Test_op
, int);
25 static int dbteste_eval(Test_env
*, Test_op
, const char *, const char *,
27 static void dbteste_error(Test_env
*, int, const char *);
28 static void blk_copy(struct block
*src
);
29 static void tbl_copy(struct table
*src
, struct table
*dst
, Area
*ap
);
32 static void printflags(struct tbl
*t
);
36 * execute command tree
39 execute(struct op
* volatile t
,
40 volatile int flags
) /* if XEXEC don't fork */
44 volatile int rv_prop
= 0; /* rv being propogated or newly generated? */
49 struct tbl
*tp
= NULL
;
54 /* Is this the end of a pipeline? If so, we want to evaluate the
56 bool eval_done = false;
57 if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
59 tp = eval_execute_args(t, &ap);
62 if ((flags
&XFORK
) && !(flags
&XEXEC
) && t
->type
!= TPIPE
)
63 return exchild(t
, flags
& ~XTIME
, -1); /* run in sub-process */
70 if (t
->type
== TCOM
) {
71 /* Clear subst_exstat before argument expansion. Used by
72 * null commands (see comexec() and c_eval()) and by c_set().
76 current_lineno
= t
->lineno
; /* for $LINENO */
78 /* POSIX says expand command words first, then redirections,
79 * and assignments last..
81 ap
= eval(t
->args
, t
->u
.evalflags
| DOBLANK
| DOGLOB
| DOTILDE
);
83 /* Allow option parsing (bizarre, but POSIX) */
85 if (Flag(FXTRACE
) && ap
[0]) {
86 shf_fprintf(shl_out
, "%s",
87 PS4_SUBSTITUTE(str_val(global("PS4"))));
88 for (i
= 0; ap
[i
]; i
++)
89 shf_fprintf(shl_out
, "%s%s", ap
[i
],
90 ap
[i
+ 1] ? space
: newline
);
94 tp
= findcom(ap
[0], FC_BI
|FC_FUNC
);
98 if (t
->ioact
!= NULL
|| t
->type
== TPIPE
|| t
->type
== TCOPROC
) {
99 e
->savefd
= (short *) alloc(sizeofN(short, NUFILE
), ATEMP
);
100 /* initialize to not redirected */
101 memset(e
->savefd
, 0, sizeofN(short, NUFILE
));
104 /* do redirection, to be restored in quitenv() */
105 if (t
->ioact
!= NULL
)
106 for (iowp
= t
->ioact
; *iowp
!= NULL
; iowp
++) {
107 if (iosetup(*iowp
, tp
) < 0) {
109 /* Redirection failures for special commands
110 * cause (non-interactive) shell to exit.
112 if (tp
&& tp
->type
== CSHELL
&&
113 (tp
->flag
& SPEC_BI
))
115 /* Deal with FERREXIT, quitenv(), etc. */
122 rv
= comexec(t
, tp
, ap
, flags
);
127 // rv = execute(t->left, flags|XFORK);
128 struct globals globenv
;
130 e
->type
= E_SUBSHELL
;
131 if(!(ksh_sigsetjmp(e
->jbuf
,0)))
133 rv
= execute(t
->left
, flags
);
141 restoreenv(&globenv
);
152 e
->savefd
[0] = savefd(0);
153 e
->savefd
[1] = savefd(1);
155 while (t
->type
== TPIPE
) {
157 (void) ksh_dup2(pv
[1], 1, false); /* stdout of curr */
159 /* Let exchild() close pv[0] in child
160 * (if this isn't done, commands like
161 * (: ; cat /etc/termcap) | sleep 1
162 * will hang forever).
164 exchild(t
->left
, flags
|XPIPEO
|XCCLOSE
, pv
[0]);
165 /* at this point if were in a chain of pipes */
166 /* then we are clsing the ouyput of the previous */
167 /* pipe. But we may not have read all data so drain it here */
168 #ifndef USE_TEMPFILES /* true pipes */
174 while((n
= read(0,buffer
,sizeof(buffer
)-1)) > 0) t
+=n
;
177 (void) ksh_dup2(pv
[0], 0, false); /* stdin of next */
180 #else /* temp files */
186 __get_default_file(0,(long *)&f
);
187 NameFromFH(f
,pname
,sizeof(pname
)-1);
190 (void) ksh_dup2(pv
[0], 0, false); /* stdin of next */
197 #endif /* USE_TEMPFILES */
203 restfd(1, e
->savefd
[1]); /* stdout of last */
204 e
->savefd
[1] = 0; /* no need to re-restore this */
205 /* Let exchild() close 0 in parent, after fork, before wait */
206 i
= exchild(t
, flags
|XPCLOSE
, 0);
207 if (!(flags
&XBGND
) && !(flags
&XXCOM
))
213 while (t
->type
== TLIST
) {
214 execute(t
->left
, flags
& XERROK
);
217 rv
= execute(t
, flags
& XERROK
);
224 /* Block sigchild as we are using things changed in the
227 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
229 i
= ksh_sigsetjmp(e
->jbuf
, 0);
231 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
236 /* Already have a (live) co-process? */
237 if (coproc
.job
&& coproc
.write
>= 0)
238 errorf("coprocess already exists");
240 /* Can we re-use the existing co-process pipe? */
241 coproc_cleanup(true);
243 /* do this before opening pipes, in case these fail */
244 e
->savefd
[0] = savefd(0);
245 e
->savefd
[1] = savefd(1);
249 ksh_dup2(pv
[0], 0, false);
252 coproc
.write
= pv
[1];
253 coproc
.job
= (void *) 0;
255 if (coproc
.readw
>= 0)
256 ksh_dup2(coproc
.readw
, 1, false);
260 ksh_dup2(pv
[1], 1, false);
261 coproc
.readw
= pv
[1]; /* closed before first read */
263 /* create new coprocess id */
266 sigprocmask(SIG_SETMASK
, &omask
, (sigset_t
*) 0);
267 e
->type
= E_EXEC
; /* no more need for error handler */
269 /* exchild() closes coproc.* in child after fork,
270 * will also increment coproc.njobs when the
271 * job is actually created.
274 exchild(t
->left
, flags
|XBGND
|XFORK
|XCOPROC
|XCCLOSE
,
280 /* XXX non-optimal, I think - "(foo &)", forks for (),
281 * forks again for async... parent should optimize
284 rv
= execute(t
->left
, (flags
&~XEXEC
)|XBGND
|XFORK
);
289 rv
= execute(t
->left
, XERROK
);
290 if ((t
->right
!= NULL
) && ((rv
== 0) == (t
->type
== TAND
)))
291 rv
= execute(t
->right
, flags
& XERROK
);
298 rv
= !execute(t
->right
, XERROK
);
305 te
.flags
= TEF_DBRACKET
;
307 te
.isa
= dbteste_isa
;
308 te
.getopnd
= dbteste_getopnd
;
309 te
.eval
= dbteste_eval
;
310 te
.error
= dbteste_error
;
312 rv
= test_parse(&te
);
319 volatile bool is_first
= true;
320 ap
= (t
->vars
!= NULL
) ? eval(t
->vars
, DOBLANK
|DOGLOB
|DOTILDE
):
324 i
= ksh_sigsetjmp(e
->jbuf
, 0);
327 if ((e
->flags
&EF_BRKCONT_PASS
) ||
328 (i
!= LBREAK
&& i
!= LCONTIN
))
332 } else if (i
== LBREAK
) {
337 rv
= 0; /* in case of a continue */
339 if (t
->type
== TFOR
) {
340 while (*ap
!= NULL
) {
341 setstr(global(t
->str
), *ap
++, KSH_UNWIND_ERROR
);
342 rv
= execute(t
->left
, flags
& XERROK
);
344 } else { /* TSELECT */
346 if (!(cp
= do_selectargs(ap
, is_first
))) {
352 setstr(global(t
->str
), cp
, KSH_UNWIND_ERROR
);
353 rv
= execute(t
->left
, flags
& XERROK
);
363 i
= ksh_sigsetjmp(e
->jbuf
, 0);
366 if ((e
->flags
&EF_BRKCONT_PASS
) ||
367 (i
!= LBREAK
&& i
!= LCONTIN
))
371 } else if (i
== LBREAK
) {
376 rv
= 0; /* in case of a continue */
377 while ((execute(t
->left
, XERROK
) == 0) == (t
->type
== TWHILE
))
378 rv
= execute(t
->right
, flags
& XERROK
);
384 if (t
->right
== NULL
)
385 break; /* should be error */
386 rv
= execute(t
->left
, XERROK
) == 0 ?
387 execute(t
->right
->left
, flags
& XERROK
) :
388 execute(t
->right
->right
, flags
& XERROK
);
393 cp
= evalstr(t
->str
, DOTILDE
);
394 for (t
= t
->left
; t
!= NULL
&& t
->type
== TPAT
; t
= t
->right
)
395 for (ap
= t
->vars
; *ap
; ap
++)
396 if ((s
= evalstr(*ap
, DOTILDE
|DOPAT
)) &&
397 gmatch(cp
, s
, false))
401 rv
= execute(t
->left
, flags
& XERROK
);
406 rv
= execute(t
->left
, flags
& XERROK
);
411 rv
= define(t
->str
, t
);
415 /* Clear XEXEC so nested execute() call doesn't exit
416 * (allows "ls -l | time grep foo").
418 rv
= timex(t
, flags
& ~XEXEC
);
422 case TEXEC
: /* an eval'd TCOM */
426 for (i
= 0; i
< sizeof(clexec_tab
); i
++)
434 if(ksh_execve(t
->str
, t
->args
, ap
, (flags
& XINTACT
) ? 1 : 0) < 0)
436 if (errno
== ENOEXEC
)
439 errorf("%s: %s", s
, strerror(errno
));
445 quitenv(NULL
); /* restores IO */
447 unwind(LEXIT
); /* exit child */
448 if (rv
!= 0 && !rv_prop
&& !(flags
& XERROK
)) {
457 * execute simple command
461 comexec(struct op
*t
, struct tbl
*volatile tp
, char **ap
, volatile int flags
)
469 int fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;
470 int bourne_function_call
= 0;
472 /* snag the last argument for $_ XXX not the same as at&t ksh,
473 * which only seems to set $_ after a newline (but not in
474 * functions/dot scripts, but in interactive and script) -
475 * perhaps save last arg here and set it in shell()?.
478 if (!Flag(FSH
) && Flag(FTALKING
) && *(lastp
= ap
)) {
481 tb
= typeset("_", LOCAL
, 0,INTEGER
,0);
483 /* setstr() can't fail here */
484 setstr(tb
, *--lastp
, KSH_RETURN_ERROR
);
487 /* Deal with the shell builtins builtin, exec and command since
488 * they can be followed by other commands. This must be done before
489 * we know if we should create a local block, which must be done
490 * before we can do a path search (in case the assignments change
493 * FOO=bar exec > /dev/null FOO is kept but not exported
494 * FOO=bar exec foobar FOO is exported
495 * FOO=bar command exec > /dev/null FOO is neither kept nor exported
496 * FOO=bar command FOO is neither kept nor exported
497 * PATH=... foobar use new PATH in foobar search
500 while (tp
&& tp
->type
== CSHELL
) {
501 fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;/* undo effects of command */
502 if (tp
->val
.f
== c_builtin
) {
503 if ((cp
= *++ap
) == NULL
) {
507 tp
= findcom(cp
, FC_BI
);
509 errorf("builtin: %s: not a builtin", cp
);
511 } else if (tp
->val
.f
== c_exec
) {
516 } else if (tp
->val
.f
== c_command
) {
519 /* Ugly dealing with options in two places (here and
520 * in c_command(), but such is life)
522 ksh_getopt_reset(&builtin_opt
, 0);
523 while ((optc
= ksh_getopt(ap
, &builtin_opt
, ":p")) == 'p')
526 break; /* command -vV or something */
527 /* don't look for functions */
528 fcflags
= FC_BI
|FC_PATH
;
530 fcflags
|= FC_DEFPATH
;
532 ap
+= builtin_opt
.optind
;
533 /* POSIX says special builtins loose their status
534 * if accessed using command.
538 /* ensure command with no args exits with 0 */
544 tp
= findcom(ap
[0], fcflags
& (FC_BI
|FC_FUNC
));
546 if (keepasn_ok
&& (!ap
[0] || (tp
&& (tp
->flag
& KEEPASN
))))
549 /* create new variable/function block */
551 /* ksh functions don't keep assignments, POSIX functions do. */
552 if (keepasn_ok
&& tp
&& tp
->type
== CFUNC
553 && !(tp
->flag
& FKSH
)) {
554 bourne_function_call
= 1;
557 type_flags
= LOCAL
|LOCAL_COPY
|EXPORTV
;
560 type_flags
|= EXPORTV
;
561 for (i
= 0; t
->vars
[i
]; i
++) {
562 cp
= evalstr(t
->vars
[i
], DOASNTILDE
);
565 shf_fprintf(shl_out
, "%s",
566 PS4_SUBSTITUTE(str_val(global("PS4"))));
567 shf_fprintf(shl_out
, "%s%s", cp
,
568 t
->vars
[i
+ 1] ? space
: newline
);
572 typeset(cp
, type_flags
, 0, 0, 0);
573 if (bourne_function_call
&& !(type_flags
& EXPORTV
))
574 typeset(cp
, LOCAL
|LOCAL_COPY
|EXPORTV
, 0, 0, 0);
577 if ((cp
= *ap
) == NULL
) {
581 tp
= findcom(cp
, fcflags
);
585 case CSHELL
: /* shell built-in */
586 rv
= call_builtin(tp
, ap
);
589 case CFUNC
: /* function call */
591 volatile int old_xflag
;
592 volatile Tflag old_inuse
;
593 const char *volatile old_kshname
;
595 if (!(tp
->flag
& ISSET
)) {
601 "%s: can't find function definition file - %s",
602 cp
, strerror(tp
->u2
.errno_
));
606 "%s: can't find function definition file", cp
);
611 if (include(tp
->u
.fpath
, 0, (char **) 0, 0) < 0) {
613 "%s: can't open function definition file %s - %s",
614 cp
, tp
->u
.fpath
, strerror(errno
));
618 if (!(ftp
= findfunc(cp
, hash(cp
), false)) ||
619 !(ftp
->flag
& ISSET
))
622 "%s: function not defined by %s",
630 /* ksh functions set $0 to function name, POSIX functions leave
633 old_kshname
= kshname
;
637 ap
[0] = (char *) kshname
;
639 for (i
= 0; *ap
++ != NULL
; i
++)
641 e
->loc
->argc
= i
- 1;
642 /* ksh-style functions handle getopts sanely,
643 * bourne/posix functions are insane...
645 if (tp
->flag
& FKSH
) {
646 e
->loc
->flags
|= BF_DOGETOPTS
;
647 e
->loc
->getopts_state
= user_opt
;
651 old_xflag
= Flag(FXTRACE
);
652 Flag(FXTRACE
) = tp
->flag
& TRACE
? true : false;
654 old_inuse
= tp
->flag
& FINUSE
;
658 i
= ksh_sigsetjmp(e
->jbuf
, 0);
660 /* seems odd to pass XERROK here, but at&t ksh does */
661 exstat
= execute(tp
->val
.t
, flags
& XERROK
);
664 kshname
= old_kshname
;
665 Flag(FXTRACE
) = old_xflag
;
666 tp
->flag
= (tp
->flag
& ~FINUSE
) | old_inuse
;
667 /* Were we deleted while executing? If so, free the execution
668 * tree. todo: Unfortunately, the table entry is never re-used
669 * until the lookup table is expanded.
671 if ((tp
->flag
& (FDELETE
|FINUSE
)) == FDELETE
) {
672 if (tp
->flag
& ALLOC
) {
674 tfree(tp
->val
.t
, tp
->areap
);
692 internal_errorf(1, "CFUNC %d", i
);
697 case CEXEC
: /* executable command */
699 case CTALIAS
: /* tracked alias */
700 if (!(tp
->flag
&ISSET
)) {
701 /* errno_ will be set if the named command was found
702 * but could not be executed (permissions, no execute
703 * bit, directory, etc). Print out a (hopefully)
704 * useful error message and set the exit status to 126.
707 warningf(true, "%s: cannot execute - %s", cp
,
708 strerror(tp
->u2
.errno_
));
709 rv
= 126; /* POSIX */
711 warningf(true, "%s: not found", cp
);
718 /* set $_ to program's full path */
719 /* setstr() can't fail here */
720 setstr(typeset("_", LOCAL
|EXPORTV
, 0, INTEGER
, 0), tp
->val
.s
,
726 if (!(flags
&XBGND
)) {
727 setexecsig(&sigtraps
[SIGINT
], SS_RESTORE_ORIG
);
728 setexecsig(&sigtraps
[SIGQUIT
], SS_RESTORE_ORIG
);
732 /* to fork we set up a TEXEC node and call execute */
734 memset(&texec
, 0, sizeof(struct op
));
736 texec
.left
= t
; /* for tprint */
737 texec
.str
= tp
->val
.s
;
741 rv
= exchild(&texec
, flags
, -1);
753 scriptexec(struct op
*tp
, char **ap
)
757 shell
= str_val(global(EXECSHELL_STR
));
759 shell
= search(shell
, path
, X_OK
, (int *) 0);
760 if (!shell
|| !*shell
)
761 shell
= strdup(EXECSHELL
);
763 *tp
->args
-- = tp
->str
;
766 if(execve(tp
->args
[0], tp
->args
, ap
) < 0)
768 /* report both the program that was run and the bogus shell */
769 errorf("%s: %s: %s", tp
->str
, shell
, strerror(errno
));
778 tp
= ktsearch(&builtins
, *wp
, hash(*wp
));
780 internal_errorf(1, "shcomexec: %s", *wp
);
781 return call_builtin(tp
, wp
);
785 * Search function tables for a function. If create set, a table entry
786 * is created if none is found.
789 findfunc(const char *name
, unsigned int h
, int create
)
792 struct tbl
*tp
= (struct tbl
*) 0;
794 for (l
= e
->loc
; l
; l
= l
->next
) {
795 tp
= ktsearch(&l
->funs
, name
, h
);
798 if (!l
->next
&& create
) {
799 tp
= ktenter(&l
->funs
, name
, h
);
802 tp
->val
.t
= (struct op
*) 0;
810 * define function. Returns 1 if function is being undefined (t == 0) and
811 * function did not exist, returns 0 otherwise.
814 define(const char *name
, struct op
*t
)
820 tp
= findfunc(name
, hash(name
), true);
822 if (tp
->flag
& ISSET
)
824 /* If this function is currently being executed, we zap this
825 * table entry so findfunc() won't see it
827 if (tp
->flag
& FINUSE
) {
829 tp
->flag
&= ~DEFINED
; /* ensure it won't be found */
835 if (tp
->flag
& ALLOC
) {
836 tp
->flag
&= ~(ISSET
|ALLOC
);
837 tfree(tp
->val
.t
, tp
->areap
);
840 if (t
== NULL
) { /* undefine */
842 return was_set
? 0 : 1;
845 tp
->val
.t
= tcopy(t
->left
, tp
->areap
);
846 tp
->flag
|= (ISSET
|ALLOC
);
857 builtin(const char *name
, int (*func
) (char **))
862 /* see if any flags should be set for this builtin */
863 for (flag
= 0; ; name
++) {
864 if (*name
== '=') /* command does variable assignment */
866 else if (*name
== '*') /* POSIX special builtin */
868 else if (*name
== '+') /* POSIX regular builtin */
874 tp
= ktenter(&builtins
, name
, hash(name
));
875 tp
->flag
= DEFINED
| flag
;
882 * either function, hashed command, or built-in (in that order)
885 findcom(const char *name
, int flags
)
887 static struct tbl temp
;
888 unsigned int h
= hash(name
);
889 struct tbl
*tp
= NULL
, *tbi
;
890 int insert
= Flag(FTRACKALL
); /* insert if not found */
891 char *fpath
; /* for function autoloading */
894 if (ksh_strchr_dirsep(name
) != NULL
) {
896 /* prevent FPATH search below */
900 tbi
= (flags
& FC_BI
) ? ktsearch(&builtins
, name
, h
) : NULL
;
901 /* POSIX says special builtins first, then functions, then
902 * POSIX regular builtins, then search path...
904 if ((flags
& FC_SPECBI
) && tbi
&& (tbi
->flag
& SPEC_BI
))
906 if (!tp
&& (flags
& FC_FUNC
)) {
907 tp
= findfunc(name
, h
, false);
908 if (tp
&& !(tp
->flag
& ISSET
)) {
909 if ((fpath
= str_val(global("FPATH"))) == null
) {
910 tp
->u
.fpath
= (char *) 0;
913 tp
->u
.fpath
= search(name
, fpath
, R_OK
,
917 if (!tp
&& (flags
& FC_REGBI
) && tbi
&& (tbi
->flag
& REG_BI
))
919 /* todo: posix says non-special/non-regular builtins must
920 * be triggered by some user-controllable means like a
921 * special directory in PATH. Requires modifications to
922 * the search() function. Tracked aliases should be
923 * modified to allow tracking of builtin commands.
924 * This should be under control of the FPOSIX flag.
925 * If this is changed, also change c_whence...
927 if (!tp
&& (flags
& FC_UNREGBI
) && tbi
)
929 if (!tp
&& (flags
& FC_PATH
) && !(flags
& FC_DEFPATH
)) {
930 tp
= ktsearch(taliases
, name
, h
);
931 if (tp
&& (tp
->flag
& ISSET
) && eaccess(tp
->val
.s
, X_OK
) != 0) {
932 if (tp
->flag
& ALLOC
) {
934 afree(tp
->val
.s
, APERM
);
941 if ((!tp
|| (tp
->type
== CTALIAS
&& !(tp
->flag
&ISSET
))) &&
945 if (insert
&& !(flags
& FC_DEFPATH
)) {
946 tp
= ktenter(taliases
, name
, h
);
952 tp
->flag
= DEFINED
; /* make ~ISSET */
954 npath
= search(name
, flags
& FC_DEFPATH
? def_path
: path
,
955 X_OK
, &tp
->u2
.errno_
);
960 tp
->val
.s
= str_save(npath
, APERM
);
964 tp
->flag
|= ISSET
|ALLOC
;
965 } else if ((flags
& FC_FUNC
)
966 && (fpath
= str_val(global("FPATH"))) != null
967 && (npath
= search(name
, fpath
, R_OK
,
968 &tp
->u2
.errno_
)) != (char *) 0)
970 /* An undocumented feature of at&t ksh is that it
971 * searches FPATH if a command is not found, even
972 * if the command hasn't been set up as an autoloaded
973 * function (ie, no typeset -uf).
977 tp
->flag
= DEFINED
; /* make ~ISSET */
985 * flush executable commands with relative paths
988 flushcom(int all
) /* just relative or all */
993 for (ktwalk(&ts
, taliases
); (tp
= ktnext(&ts
)) != NULL
; )
994 if ((tp
->flag
&ISSET
) && (all
|| !ISDIRSEP(tp
->val
.s
[0]))) {
995 if (tp
->flag
&ALLOC
) {
996 tp
->flag
&= ~(ALLOC
|ISSET
);
997 afree(tp
->val
.s
, APERM
);
1003 /* Check if path is something we want to find. Returns -1 for failure. */
1005 search_access(const char *path
, int mode
,
1006 int *errnop
) /* set if candidate found, but not suitable */
1011 if (stat(path
, &statb
) < 0)
1013 ret
= eaccess(path
, mode
);
1015 err
= errno
; /* File exists, but we can't access it */
1016 else if (mode
== X_OK
1017 && (!S_ISREG(statb
.st_mode
)
1018 /* This 'cause access() says root can execute everything */
1019 || !(statb
.st_mode
& (S_IXUSR
|S_IXGRP
|S_IXOTH
))))
1022 err
= S_ISDIR(statb
.st_mode
) ? EISDIR
: EACCES
;
1024 if (err
&& errnop
&& !*errnop
)
1030 * search for command with PATH
1033 search(const char *name
, const char *path
,
1034 int mode
, /* R_OK or X_OK */
1035 int *errnop
) /* set if candidate found, but not suitable */
1044 if (ksh_strchr_dirsep(name
)) {
1045 if (search_access(name
, mode
, errnop
) == 0)
1048 if((name
[0] == '.') && (name
[1] == '/'))
1049 return (char *) &name
[2];
1051 return (char *) name
;
1056 namelen
= strlen(name
) + 1;
1057 Xinit(xs
, xp
, 128, ATEMP
);
1060 while (sp
!= NULL
) {
1061 xp
= Xstring(xs
, xp
);
1062 if (!(p
= strchr(sp
, PATHSEP
)))
1063 p
= sp
+ strlen(sp
);
1065 XcheckN(xs
, xp
, p
- sp
);
1066 memcpy(xp
, sp
, p
- sp
);
1071 XcheckN(xs
, xp
, namelen
);
1072 memcpy(xp
, name
, namelen
);
1073 if (search_access(Xstring(xs
, xp
), mode
, errnop
) == 0)
1076 sp
= Xclose(xs
, xp
+ namelen
);
1077 if((sp
[0] == '.') && (sp
[1] == '/') && !strcmp(&sp
[2], name
))
1084 return Xclose(xs
, xp
+ namelen
);
1095 call_builtin(struct tbl
*tp
, char **wp
)
1099 builtin_argv0
= wp
[0];
1100 builtin_flag
= tp
->flag
;
1101 shf_reopen(1, SHF_WR
, shl_stdout
);
1103 ksh_getopt_reset(&builtin_opt
, GF_ERROR
);
1104 rv
= (*tp
->val
.f
)(wp
);
1105 shf_flush(shl_stdout
);
1108 builtin_argv0
= (char *) 0;
1113 * set up redirection, saving old fd's in e->savefd
1116 iosetup(struct ioword
*iop
, struct tbl
*tp
)
1119 char *cp
= iop
->name
;
1120 int iotype
= iop
->flag
& IOTYPE
;
1121 int do_open
= 1, do_close
= 0, flags
= 0;
1122 struct ioword iotmp
;
1125 if (iotype
!= IOHERE
)
1126 cp
= evalonestr(cp
, DOTILDE
|(Flag(FTALKING_I
) ? DOGLOB
: 0));
1128 /* Used for tracing and error messages to print expanded cp */
1130 iotmp
.name
= (iotype
== IOHERE
) ? (char *) 0 : cp
;
1131 iotmp
.flag
|= IONAMEXP
;
1135 PS4_SUBSTITUTE(str_val(global("PS4"))),
1136 snptreef((char *) 0, 32, "%R", &iotmp
));
1144 flags
= O_WRONLY
| O_APPEND
| O_CREAT
;
1148 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1149 /* The stat() is here to allow redirections to
1150 * things like /dev/null without error.
1152 if (Flag(FNOCLOBBER
) && !(iop
->flag
& IOCLOB
)
1153 && (stat(cp
, &statb
) < 0 || S_ISREG(statb
.st_mode
)))
1158 flags
= O_RDWR
| O_CREAT
;
1163 /* herein() returns -2 if error has been printed */
1164 u
= herein(iop
->heredoc
, iop
->flag
& IOEVAL
);
1165 /* cp may have wrong name */
1173 if (*cp
== '-' && !cp
[1]) {
1174 u
= 1009; /* prevent error return below */
1176 } else if ((u
= check_fd(cp
,
1177 X_OK
| ((iop
->flag
& IORDUP
) ? R_OK
: W_OK
),
1180 warningf(true, "%s: %s",
1181 snptreef((char *) 0, 32, "%R", &iotmp
), emsg
);
1185 return 0; /* "dup from" == "dup to" */
1190 u
= open(cp
, flags
, 0666);
1193 /* herein() may already have printed message */
1195 warningf(true, "cannot %s %s: %s",
1196 iotype
== IODUP
? "dup"
1197 : (iotype
== IOREAD
|| iotype
== IOHERE
) ?
1198 "open" : "create", cp
, strerror(errno
));
1201 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1202 if (e
->savefd
[iop
->unit
] == 0) {
1203 /* c_exec() assumes e->savefd[fd] set for any redirections.
1204 * Ask savefd() not to close iop->unit - allows error messages
1205 * to be seen if iop->unit is 2; also means we can't lose
1206 * the fd (eg, both dup2 below and dup2 in restfd() failing).
1208 e
->savefd
[iop
->unit
] = savefd(iop
->unit
);
1213 else if (u
!= iop
->unit
) {
1214 if (ksh_dup2(u
, iop
->unit
, true) < 0) {
1216 "could not finish (dup) redirection %s: %s",
1217 snptreef((char *) 0, 32, "%R", &iotmp
),
1219 if (iotype
!= IODUP
)
1223 if (iotype
!= IODUP
)
1225 /* Touching any co-process fd in an empty exec
1226 * causes the shell to close its copies
1228 else if (tp
&& tp
->type
== CSHELL
&& tp
->val
.f
== c_exec
) {
1229 if (iop
->flag
& IORDUP
) /* possible exec <&p */
1230 coproc_read_close(u
);
1231 else /* possible exec >&p */
1232 coproc_write_close(u
);
1235 if (u
== 2) /* Clear any write errors */
1236 shf_reopen(2, SHF_WR
, shl_out
);
1241 * open here document temp file.
1242 * if unquoted here, expand here temp file into second temp file.
1245 herein(const char *content
, int sub
)
1247 volatile int fd
= -1;
1248 struct source
*s
, *volatile osource
;
1249 struct shf
*volatile shf
;
1253 /* ksh -c 'cat << EOF' can cause this... */
1254 if (content
== (char *) 0) {
1255 warningf(true, "here document missing");
1256 return -2; /* special to iosetup(): don't print error */
1259 /* Create temp file to hold content (done before newenv so temp
1260 * doesn't get removed too soon).
1262 h
= maketemp(ATEMP
, TT_HEREDOC_EXP
, &e
->temps
);
1263 if (!(shf
= h
->shf
) || (fd
= open(h
->name
, O_RDONLY
, 0)) < 0) {
1264 warningf(true, "can't %s temporary file %s: %s",
1265 !shf
? "create" : "open",
1266 h
->name
, strerror(errno
));
1269 return -2 /* special to iosetup(): don't print error */;
1274 i
= ksh_sigsetjmp(e
->jbuf
, 0);
1278 shf_close(shf
); /* after quitenv */
1280 return -2; /* special to iosetup(): don't print error */
1283 /* Do substitutions on the content of heredoc */
1284 s
= pushs(SSTRING
, ATEMP
);
1285 s
->start
= s
->str
= content
;
1287 if (yylex(ONEWORD
) != LWORD
)
1288 internal_errorf(1, "herein: yylex");
1290 shf_puts(evalstr(yylval
.cp
, 0), shf
);
1292 shf_puts(content
, shf
);
1296 if (shf_close(shf
) == EOF
) {
1298 warningf(true, "error writing %s: %s", h
->name
,
1300 return -2; /* special to iosetup(): don't print error */
1307 * ksh special - the select command processing section
1308 * print the args in column form - assuming that we can
1311 do_selectargs(char **ap
, bool print_menu
)
1313 static const char *const read_args
[] = {
1314 "read", "-r", "REPLY", (char *) 0
1319 for (argct
= 0; ap
[argct
]; argct
++)
1322 /* Menu is printed if
1323 * - this is the first time around the select loop
1324 * - the user enters a blank line
1325 * - the REPLY parameter is empty
1327 if (print_menu
|| !*str_val(global("REPLY")))
1329 shellf("%s", str_val(global("PS3")));
1330 if (call_builtin(findcom("read", FC_BI
), (char **) read_args
))
1332 s
= str_val(global("REPLY"));
1335 return (i
>= 1 && i
<= argct
) ? ap
[i
- 1] : null
;
1341 struct select_menu_info
{
1347 static char *select_fmt_entry(void *arg
, int i
, char *buf
, int buflen
);
1349 /* format a single select menu item */
1351 select_fmt_entry(void *arg
, int i
, char *buf
, int buflen
)
1353 struct select_menu_info
*smi
= (struct select_menu_info
*) arg
;
1355 shf_snprintf(buf
, buflen
, "%*d) %s",
1356 smi
->num_width
, i
+ 1, smi
->args
[i
]);
1361 * print a select style menu
1364 pr_menu(char *const *ap
)
1366 struct select_menu_info smi
;
1371 /* Width/column calculations were done once and saved, but this
1372 * means select can't be used recursively so we re-calculate each
1373 * time (could save in a structure that is returned, but its probably
1374 * not worth the bother).
1378 * get dimensions of the list
1380 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1382 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1385 * we will print an index of the form
1387 * in front of each entry
1388 * get the max width of this
1390 for (i
= n
, dwidth
= 1; i
>= 10; i
/= 10)
1394 smi
.arg_width
= nwidth
;
1395 smi
.num_width
= dwidth
;
1396 print_columns(shl_out
, n
, select_fmt_entry
, (void *) &smi
,
1397 dwidth
+ nwidth
+ 2, 1);
1402 /* XXX: horrible kludge to fit within the framework */
1404 static char *plain_fmt_entry(void *arg
, int i
, char *buf
, int buflen
);
1407 plain_fmt_entry(void *arg
, int i
, char *buf
, int buflen
)
1409 shf_snprintf(buf
, buflen
, "%s", ((char *const *)arg
)[i
]);
1414 pr_list(char *const *ap
)
1420 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1422 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1424 print_columns(shl_out
, n
, plain_fmt_entry
, (void *) ap
, nwidth
+ 1, 0);
1430 * [[ ... ]] evaluation routines
1433 extern const char *const dbtest_tokens
[];
1434 extern const char db_close
[];
1436 /* Test if the current token is a whatever. Accepts the current token if
1437 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1438 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1441 dbteste_isa(Test_env
*te
, Test_meta meta
)
1448 return meta
== TM_END
;
1450 /* unquoted word? */
1451 for (p
= *te
->pos
.wp
; *p
== CHAR
; p
+= 2)
1455 if (meta
== TM_UNOP
|| meta
== TM_BINOP
) {
1457 char buf
[8]; /* longer than the longest operator */
1459 for (p
= *te
->pos
.wp
;
1460 *p
== CHAR
&& q
< &buf
[sizeof(buf
) - 1]; p
+= 2)
1463 ret
= (int) test_isop(te
, meta
, buf
);
1465 } else if (meta
== TM_END
)
1469 strcmp(*te
->pos
.wp
, dbtest_tokens
[(int) meta
]) == 0;
1471 /* Accept the token? */
1479 dbteste_getopnd(Test_env
*te
, Test_op op
, int do_eval
)
1481 char *s
= *te
->pos
.wp
;
1491 if (op
== TO_STEQL
|| op
== TO_STNEQ
)
1492 s
= evalstr(s
, DOTILDE
| DOPAT
);
1494 s
= evalstr(s
, DOTILDE
);
1500 dbteste_eval(Test_env
*te
, Test_op op
, const char *opnd1
, const char *opnd2
,
1503 return test_eval(te
, op
, opnd1
, opnd2
, do_eval
);
1507 dbteste_error(Test_env
*te
, int offset
, const char *msg
)
1509 te
->flags
|= TEF_ERROR
;
1510 internal_errorf(0, "dbteste_error: %s (offset %d)", msg
, offset
);
1514 /* have to copy stuff lacking fork () */
1516 blk_copy(struct block
*src
)
1518 /* this is the deepest nested block, also called `globals' */
1520 blk_copy(src
->next
);
1523 struct block
*l
= e
->loc
;
1524 l
->argc
= src
->argc
;
1527 /* copy the argument vector */
1529 for (tw
= src
->argv
; *tw
++ != NULL
; ) ;
1530 rw
= l
->argv
= alloc((int)(tw
- src
->argv
) * sizeof(*tw
), &l
->area
);
1531 for (tw
= src
->argv
; *tw
!= NULL
; )
1533 *rw
++ = wdcopy(*tw
++, &l
->area
);
1538 static char *empty
[] = {NULL
};
1539 l
->argv
= (char **)empty
;
1540 l
->argv
[0] = src
->argv
[0]; /* preserve only $0 */
1543 tbl_copy(&src
->vars
, &l
->vars
, &l
->area
);
1544 tbl_copy(&src
->funs
, &l
->funs
, &l
->area
);
1546 /* they're not used anyway (ie. always 0), but something like this
1547 will have to be done when they ARE used. Perhaps it will be ATEMP
1548 instead of APERM? */
1549 l
->error
= src
->error
? str_save(src
->error
, APERM
) : 0;
1550 l
->exit
= src
->exit
? str_save(src
->exit
, APERM
) : 0;
1555 tbl_copy(struct table
*src
, struct table
*dst
, Area
*ap
)
1562 while ((t
= ktnext(&ts
))) {
1563 struct tbl
*tn
= ktenter(dst
, t
->name
, hash(t
->name
));
1566 if (t
->flag
& INTEGER
)
1567 tn
->val
.i
= t
->val
.i
;
1568 else if (t
->flag
& EXPORTV
)
1569 tn
->val
.s
= str_save(t
->val
.s
, ap
);
1570 else if (t
->type
== CFUNC
)
1571 tn
->val
.t
= t
->val
.t
? tcopy(t
->val
.t
, ap
) : 0;
1573 tn
->val
.s
= (t
->flag
& ALLOC
) ? str_save(t
->val
.s
, ap
) : 0;
1575 tn
->index
= t
->index
;
1578 tn
->u2
.field
= t
->u2
.field
;
1579 if (t
->flag
& ARRAY
) {
1580 struct tbl
*tmp
, **list
= &tn
->u
.array
;
1582 for (tmp
= t
->u
.array
; tmp
; tmp
= tmp
->u
.array
) {
1583 int size
= sizeof(struct tbl
) + strlen(tmp
->name
) + 1;
1586 *list
= new = (struct tbl
*)alloc(size
, ap
);
1587 memcpy(new, tmp
, size
);
1589 if (tmp
->flag
& ALLOC
)
1590 new->val
.s
= str_save(tmp
->val
.s
, ap
);
1592 list
= &new->u
.array
;
1596 tn
->u
.array
= t
->u
.array
;
1597 if ((tn
->flag
& SPECIAL
) && !strcmp(tn
->name
, "PATH"))
1598 path
= str_save(tn
->val
.s
+ tn
->type
, ap
);
1604 copyenv(struct globals
*globenv
)
1606 /* first set everything to a known state */
1607 memset(globenv
, 0, sizeof(struct globals
));
1609 /* save pointers to current environment */
1610 globenv
->aperm
= aperm
;
1612 globenv
->homedirs
= homedirs
;
1613 globenv
->aliases
= aliases
;
1614 globenv
->taliases
= taliases
;
1615 globenv
->path
= path
; /* will be copied in tbl_copy */
1616 globenv
->current_wd
= current_wd
;
1617 globenv
->current_wd_size
= current_wd_size
;
1619 /* set up new "permanent storage" */
1620 aperm
= malloc(sizeof(Area
));
1621 if ( aperm
== NULL
) {
1622 internal_errorf(1, "out of memory");
1628 homedirs
= malloc(sizeof(struct table
));
1629 taliases
= malloc(sizeof(struct table
));
1630 aliases
= malloc(sizeof(struct table
));
1631 if ( homedirs
== NULL
|| taliases
== NULL
|| aliases
== NULL
) {
1632 internal_errorf(1, "out of memory");
1635 ktinit(taliases
, APERM
, 0);
1636 ktinit(aliases
, APERM
, 0);
1637 ktinit(homedirs
, APERM
, 0);
1639 /* setup base environment */
1640 struct env
*copy
= malloc(sizeof(struct env
));
1641 if ( copy
== NULL
) {
1642 internal_errorf(1, "out of memory");
1645 memset(copy
, 0, sizeof(struct env
));
1646 copy
->type
= E_NONE
;
1649 tbl_copy(globenv
->homedirs
, homedirs
, APERM
);
1650 tbl_copy(globenv
->taliases
, taliases
, APERM
);
1651 tbl_copy(globenv
->aliases
, aliases
, APERM
);
1653 struct block
*b
= e
->loc
;
1654 short *old
= e
->savefd
;
1656 /* now transfer environment, and use the copy */
1661 size_t size
= sizeofN(short, NUFILE
);
1662 e
->savefd
= (short*) alloc(size
, ATEMP
);
1663 memcpy(e
->savefd
, old
, size
);
1666 /* setup the current_wd in our new APERM */
1668 current_wd_size
= 0;
1669 set_current_wd(globenv
->current_wd
);
1671 /* duplicate and save file handles */
1673 for( i
=0; i
<NUFILE
;i
++) {
1674 globenv
->fd
[i
] = savefd(i
);
1677 /* copy the current state of the ctypes array */
1678 memcpy(globenv
->ctypes
, ctypes
, UCHAR_MAX
+1);
1680 /* copy the sigtraps and clear them for use by subshell */
1681 memcpy(globenv
->sigtraps
, sigtraps
, sizeof(sigtraps
));
1682 for (i
= 0; i
< (NSIG
+1); i
++) {
1683 sigtraps
[i
].trap
= 0;
1684 sigtraps
[i
].set
= 0;
1685 sigtraps
[i
].flags
= 0;
1686 sigtraps
[i
].cursig
= 0;
1687 sigtraps
[i
].shtrap
= 0;
1690 /* note other stuff nay need doing! */
1695 restoreenv(struct globals
*globenv
)
1697 /* free copy environment and it's ATEMP */
1698 struct block
*l
= e
->loc
;
1706 /* simply free the aperm area */
1713 /* restore old tables and environment */
1714 aperm
= globenv
->aperm
;
1716 homedirs
= globenv
->homedirs
;
1717 aliases
= globenv
->aliases
;
1718 taliases
= globenv
->taliases
;
1719 path
= globenv
->path
;
1721 /* restore working dir */
1722 current_wd
= globenv
->current_wd
;
1723 current_wd_size
= globenv
->current_wd_size
;
1724 (void) chdir(current_wd
);
1726 /* restore duplicated file handles */
1728 for( i
=0; i
<NUFILE
;i
++) {
1729 if(globenv
->fd
[i
] >= 0)
1730 restfd(i
,globenv
->fd
[i
]);
1733 /* restore ctypes array */
1734 memcpy(ctypes
,globenv
->ctypes
,UCHAR_MAX
+ 1);
1736 /* copy the sigtraps and clear them for use by subshell */
1737 memcpy(sigtraps
, globenv
->sigtraps
, sizeof(sigtraps
));
1741 void printflags(struct tbl
*t
)
1743 printf(" flags %d ",t
->flag
);
1744 if(t
->flag
& ALLOC
) printf("ALLOC ");
1745 if(t
->flag
& DEFINED
) printf("DEFINED ");
1746 if(t
->flag
& ISSET
) printf("ISSET ");
1747 if(t
->flag
& EXPORTV
) printf("EXPORTV ");
1748 if(t
->flag
& TRACE
) printf("TRACE ");
1749 if(t
->flag
& SPECIAL
) printf("SPECIAL ");
1750 if(t
->flag
& INTEGER
) printf("INTEGER ");
1751 if(t
->flag
& RDONLY
) printf("RDONLY ");
1752 if(t
->flag
& LOCAL
) printf("LOCAL ");
1753 if(t
->flag
& ARRAY
) printf("ARRAY ");
1754 if(t
->flag
& LJUST
) printf("LJUST ");
1755 if(t
->flag
& RJUST
) printf("RJUST ");
1756 if(t
->flag
& ZEROFIL
) printf("ZEROFIL ");
1757 if(t
->flag
& LCASEV
) printf("LCASEV ");
1758 if(t
->flag
& UCASEV_AL
) printf("UCASEV_ALTRACE ");
1759 if(t
->flag
& INT_U
) printf("INT_U ");
1760 if(t
->flag
& INT_L
) printf("INT_L");
1761 if(t
->flag
& IMPORTV
) printf("IMPORTV ");
1762 if(t
->flag
& LOCAL_COPY
) printf("LOCAL_COPY ");
1763 if(t
->flag
& EXPRINEVAL
) printf("EXPRINEVAL ");
1764 if(t
->flag
& EXPRLVALUE
) printf("EXPRLVALUE ");