1 /* $OpenBSD: exec.c,v 1.73 2018/03/15 16:51:29 anton Exp $ */
21 /* Does ps4 get parameter substitutions done? */
22 # define PS4_SUBSTITUTE(s) substitute((s), 0)
24 static int comexec(struct op
*, struct tbl
*volatile, char **,
25 int volatile, volatile int *);
26 static void scriptexec(struct op
*, char **);
27 static int call_builtin(struct tbl
*, char **);
28 static int iosetup(struct ioword
*, struct tbl
*);
29 static int herein(const char *, int);
30 static char *do_selectargs(char **, bool);
31 static int dbteste_isa(Test_env
*, Test_meta
);
32 static const char *dbteste_getopnd(Test_env
*, Test_op
, int);
33 static int dbteste_eval(Test_env
*, Test_op
, const char *, const char *,
35 static void dbteste_error(Test_env
*, int, const char *);
39 * execute command tree
42 execute(struct op
*volatile t
,
43 volatile int flags
, /* if XEXEC don't fork */
44 volatile int *xerrok
) /* inform recursive callers in -e mode that
45 * short-circuit && or || shouldn't be treated
48 int i
, dummy
= 0, save_xerrok
= 0;
54 struct tbl
*tp
= NULL
;
59 /* Caller doesn't care if XERROK should propagate. */
63 /* Is this the end of a pipeline? If so, we want to evaluate the
65 bool eval_done = false;
66 if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
68 tp = eval_execute_args(t, &ap);
71 if ((flags
&XFORK
) && !(flags
&XEXEC
) && t
->type
!= TPIPE
)
72 return exchild(t
, flags
& ~XTIME
, xerrok
, -1); /* run in sub-process */
78 if (t
->type
== TCOM
) {
79 /* Clear subst_exstat before argument expansion. Used by
80 * null commands (see comexec() and c_eval()) and by c_set().
84 current_lineno
= t
->lineno
; /* for $LINENO */
86 /* POSIX says expand command words first, then redirections,
87 * and assignments last..
89 ap
= eval(t
->args
, t
->u
.evalflags
| DOBLANK
| DOGLOB
| DOTILDE
);
91 /* Allow option parsing (bizarre, but POSIX) */
93 if (Flag(FXTRACE
) && ap
[0]) {
94 shf_fprintf(shl_out
, "%s",
95 PS4_SUBSTITUTE(str_val(global("PS4"))));
96 for (i
= 0; ap
[i
]; i
++)
97 shf_fprintf(shl_out
, "%s%s", ap
[i
],
98 ap
[i
+ 1] ? " " : "\n");
102 tp
= findcom(ap
[0], FC_BI
|FC_FUNC
);
106 if (t
->ioact
!= NULL
|| t
->type
== TPIPE
|| t
->type
== TCOPROC
) {
107 genv
->savefd
= areallocarray(NULL
, NUFILE
, sizeof(short), ATEMP
);
108 /* initialize to not redirected */
109 memset(genv
->savefd
, 0, NUFILE
* sizeof(short));
112 /* do redirection, to be restored in quitenv() */
113 if (t
->ioact
!= NULL
)
114 for (iowp
= t
->ioact
; *iowp
!= NULL
; iowp
++) {
115 if (iosetup(*iowp
, tp
) < 0) {
117 /* Redirection failures for special commands
118 * cause (non-interactive) shell to exit.
120 if (tp
&& tp
->type
== CSHELL
&&
121 (tp
->flag
& SPEC_BI
))
123 /* Deal with FERREXIT, quitenv(), etc. */
130 rv
= comexec(t
, tp
, ap
, flags
, xerrok
);
134 rv
= execute(t
->left
, flags
|XFORK
, xerrok
);
140 genv
->savefd
[0] = savefd(0);
141 genv
->savefd
[1] = savefd(1);
142 while (t
->type
== TPIPE
) {
144 (void) ksh_dup2(pv
[1], 1, false); /* stdout of curr */
145 /* Let exchild() close pv[0] in child
146 * (if this isn't done, commands like
147 * (: ; cat /etc/termcap) | sleep 1
148 * will hang forever).
150 exchild(t
->left
, flags
|XPIPEO
|XCCLOSE
, NULL
, pv
[0]);
151 (void) ksh_dup2(pv
[0], 0, false); /* stdin of next */
156 restfd(1, genv
->savefd
[1]); /* stdout of last */
157 genv
->savefd
[1] = 0; /* no need to re-restore this */
158 /* Let exchild() close 0 in parent, after fork, before wait */
159 i
= exchild(t
, flags
|XPCLOSE
, xerrok
, 0);
160 if (!(flags
&XBGND
) && !(flags
&XXCOM
))
165 while (t
->type
== TLIST
) {
166 execute(t
->left
, flags
& XERROK
, NULL
);
169 rv
= execute(t
, flags
& XERROK
, xerrok
);
176 /* Block sigchild as we are using things changed in the
179 sigprocmask(SIG_BLOCK
, &sm_sigchld
, &omask
);
181 i
= sigsetjmp(genv
->jbuf
, 0);
183 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
188 /* Already have a (live) co-process? */
189 if (coproc
.job
&& coproc
.write
>= 0)
190 errorf("coprocess already exists");
192 /* Can we re-use the existing co-process pipe? */
193 coproc_cleanup(true);
195 /* do this before opening pipes, in case these fail */
196 genv
->savefd
[0] = savefd(0);
197 genv
->savefd
[1] = savefd(1);
201 ksh_dup2(pv
[0], 0, false);
204 coproc
.write
= pv
[1];
207 if (coproc
.readw
>= 0)
208 ksh_dup2(coproc
.readw
, 1, false);
212 ksh_dup2(pv
[1], 1, false);
213 coproc
.readw
= pv
[1]; /* closed before first read */
215 /* create new coprocess id */
218 sigprocmask(SIG_SETMASK
, &omask
, NULL
);
219 genv
->type
= E_EXEC
; /* no more need for error handler */
221 /* exchild() closes coproc.* in child after fork,
222 * will also increment coproc.njobs when the
223 * job is actually created.
226 exchild(t
->left
, flags
|XBGND
|XFORK
|XCOPROC
|XCCLOSE
,
232 /* XXX non-optimal, I think - "(foo &)", forks for (),
233 * forks again for async... parent should optimize
236 rv
= execute(t
->left
, (flags
&~XEXEC
)|XBGND
|XFORK
, xerrok
);
241 rv
= execute(t
->left
, XERROK
, xerrok
);
242 if ((rv
== 0) == (t
->type
== TAND
))
243 rv
= execute(t
->right
, flags
& XERROK
, xerrok
);
251 rv
= !execute(t
->right
, XERROK
, xerrok
);
260 te
.flags
= TEF_DBRACKET
;
262 te
.isa
= dbteste_isa
;
263 te
.getopnd
= dbteste_getopnd
;
264 te
.eval
= dbteste_eval
;
265 te
.error
= dbteste_error
;
267 rv
= test_parse(&te
);
274 volatile bool is_first
= true;
275 ap
= (t
->vars
!= NULL
) ? eval(t
->vars
, DOBLANK
|DOGLOB
|DOTILDE
) :
279 i
= sigsetjmp(genv
->jbuf
, 0);
282 if ((genv
->flags
&EF_BRKCONT_PASS
) ||
283 (i
!= LBREAK
&& i
!= LCONTIN
)) {
286 } else if (i
== LBREAK
) {
291 rv
= 0; /* in case of a continue */
292 if (t
->type
== TFOR
) {
293 save_xerrok
= *xerrok
;
294 while (*ap
!= NULL
) {
295 setstr(global(t
->str
), *ap
++, KSH_UNWIND_ERROR
);
296 /* undo xerrok in all iterations except the
298 *xerrok
= save_xerrok
;
299 rv
= execute(t
->left
, flags
& XERROK
, xerrok
);
301 /* ripple xerrok set at final iteration */
302 } else { /* TSELECT */
304 if (!(cp
= do_selectargs(ap
, is_first
))) {
309 setstr(global(t
->str
), cp
, KSH_UNWIND_ERROR
);
310 rv
= execute(t
->left
, flags
& XERROK
, xerrok
);
320 i
= sigsetjmp(genv
->jbuf
, 0);
323 if ((genv
->flags
&EF_BRKCONT_PASS
) ||
324 (i
!= LBREAK
&& i
!= LCONTIN
)) {
327 } else if (i
== LBREAK
) {
332 rv
= 0; /* in case of a continue */
333 while ((execute(t
->left
, XERROK
, NULL
) == 0) == (t
->type
== TWHILE
))
334 rv
= execute(t
->right
, flags
& XERROK
, xerrok
);
339 if (t
->right
== NULL
)
340 break; /* should be error */
341 rv
= execute(t
->left
, XERROK
, NULL
) == 0 ?
342 execute(t
->right
->left
, flags
& XERROK
, xerrok
) :
343 execute(t
->right
->right
, flags
& XERROK
, xerrok
);
347 cp
= evalstr(t
->str
, DOTILDE
);
348 for (t
= t
->left
; t
!= NULL
&& t
->type
== TPAT
; t
= t
->right
) {
349 for (ap
= t
->vars
; *ap
; ap
++) {
350 if ((s
= evalstr(*ap
, DOTILDE
|DOPAT
)) &&
351 gmatch(cp
, s
, false))
357 rv
= execute(t
->left
, flags
& XERROK
, xerrok
);
361 rv
= execute(t
->left
, flags
& XERROK
, xerrok
);
365 rv
= define(t
->str
, t
);
369 /* Clear XEXEC so nested execute() call doesn't exit
370 * (allows "ls -l | time grep foo").
372 rv
= timex(t
, flags
& ~XEXEC
, xerrok
);
375 case TEXEC
: /* an eval'd TCOM */
380 execve(t
->str
, t
->args
, ap
);
381 if (errno
== ENOEXEC
)
384 errorf("%s: %s", s
, strerror(errno
));
389 quitenv(NULL
); /* restores IO */
391 unwind(LEXIT
); /* exit child */
392 if (rv
!= 0 && !(flags
& XERROK
) && !*xerrok
) {
401 * execute simple command
405 comexec(struct op
*t
, struct tbl
*volatile tp
, char **ap
, volatile int flags
,
406 volatile int *xerrok
)
415 int fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;
416 int bourne_function_call
= 0;
418 /* snag the last argument for $_ XXX not the same as at&t ksh,
419 * which only seems to set $_ after a newline (but not in
420 * functions/dot scripts, but in interactive and script) -
421 * perhaps save last arg here and set it in shell()?.
423 if (!Flag(FSH
) && Flag(FTALKING
) && *(lastp
= ap
)) {
426 /* setstr() can't fail here */
427 setstr(typeset("_", LOCAL
, 0, INTEGER
, 0), *--lastp
,
431 /* Deal with the shell builtins builtin, exec and command since
432 * they can be followed by other commands. This must be done before
433 * we know if we should create a local block, which must be done
434 * before we can do a path search (in case the assignments change
437 * FOO=bar exec > /dev/null FOO is kept but not exported
438 * FOO=bar exec foobar FOO is exported
439 * FOO=bar command exec > /dev/null FOO is neither kept nor exported
440 * FOO=bar command FOO is neither kept nor exported
441 * PATH=... foobar use new PATH in foobar search
444 while (tp
&& tp
->type
== CSHELL
) {
445 fcflags
= FC_BI
|FC_FUNC
|FC_PATH
;/* undo effects of command */
446 if (tp
->val
.f
== c_builtin
) {
447 if ((cp
= *++ap
) == NULL
) {
451 tp
= findcom(cp
, FC_BI
);
453 errorf("builtin: %s: not a builtin", cp
);
455 } else if (tp
->val
.f
== c_exec
) {
460 } else if (tp
->val
.f
== c_command
) {
463 /* Ugly dealing with options in two places (here and
464 * in c_command(), but such is life)
466 ksh_getopt_reset(&builtin_opt
, 0);
467 while ((optc
= ksh_getopt(ap
, &builtin_opt
, ":p")) == 'p')
470 break; /* command -vV or something */
471 /* don't look for functions */
472 fcflags
= FC_BI
|FC_PATH
;
474 if (Flag(FRESTRICTED
)) {
476 "command -p: restricted");
480 fcflags
|= FC_DEFPATH
;
482 ap
+= builtin_opt
.optind
;
483 /* POSIX says special builtins lose their status
484 * if accessed using command.
488 /* ensure command with no args exits with 0 */
494 tp
= findcom(ap
[0], fcflags
& (FC_BI
|FC_FUNC
));
496 if (keepasn_ok
&& (!ap
[0] || (tp
&& (tp
->flag
& KEEPASN
))))
499 /* create new variable/function block */
501 /* ksh functions don't keep assignments, POSIX functions do. */
502 if (keepasn_ok
&& tp
&& tp
->type
== CFUNC
&&
503 !(tp
->flag
& FKSH
)) {
504 bourne_function_call
= 1;
507 type_flags
= LOCAL
|LOCAL_COPY
|EXPORT
;
510 type_flags
|= EXPORT
;
511 for (i
= 0; t
->vars
[i
]; i
++) {
512 cp
= evalstr(t
->vars
[i
], DOASNTILDE
);
515 shf_fprintf(shl_out
, "%s",
516 PS4_SUBSTITUTE(str_val(global("PS4"))));
517 shf_fprintf(shl_out
, "%s%s", cp
,
518 t
->vars
[i
+ 1] ? " " : "\n");
522 typeset(cp
, type_flags
, 0, 0, 0);
523 if (bourne_function_call
&& !(type_flags
& EXPORT
))
524 typeset(cp
, LOCAL
|LOCAL_COPY
|EXPORT
, 0, 0, 0);
527 if ((cp
= *ap
) == NULL
) {
531 if (Flag(FRESTRICTED
) && strchr(cp
, '/')) {
532 warningf(true, "%s: restricted", cp
);
536 tp
= findcom(cp
, fcflags
);
540 case CSHELL
: /* shell built-in */
541 rv
= call_builtin(tp
, ap
);
544 case CFUNC
: /* function call */
546 volatile int old_xflag
, old_inuse
;
547 const char *volatile old_kshname
;
549 if (!(tp
->flag
& ISSET
)) {
555 "%s: can't find function "
556 "definition file - %s",
557 cp
, strerror(tp
->u2
.errno_
));
561 "%s: can't find function "
562 "definition file", cp
);
567 if (include(tp
->u
.fpath
, 0, NULL
, 0) < 0) {
569 "%s: can't open function definition file %s - %s",
570 cp
, tp
->u
.fpath
, strerror(errno
));
574 if (!(ftp
= findfunc(cp
, hash(cp
), false)) ||
575 !(ftp
->flag
& ISSET
)) {
577 "%s: function not defined by %s",
585 /* ksh functions set $0 to function name, POSIX functions leave
588 old_kshname
= kshname
;
592 ap
[0] = (char *) kshname
;
593 genv
->loc
->argv
= ap
;
594 for (i
= 0; *ap
++ != NULL
; i
++)
596 genv
->loc
->argc
= i
- 1;
597 /* ksh-style functions handle getopts sanely,
598 * bourne/posix functions are insane...
600 if (tp
->flag
& FKSH
) {
601 genv
->loc
->flags
|= BF_DOGETOPTS
;
602 genv
->loc
->getopts_state
= user_opt
;
606 old_xflag
= Flag(FXTRACE
);
607 Flag(FXTRACE
) = tp
->flag
& TRACE
? true : false;
609 old_inuse
= tp
->flag
& FINUSE
;
613 i
= sigsetjmp(genv
->jbuf
, 0);
615 /* seems odd to pass XERROK here, but at&t ksh does */
616 exstat
= execute(tp
->val
.t
, flags
& XERROK
, xerrok
);
619 kshname
= old_kshname
;
620 Flag(FXTRACE
) = old_xflag
;
621 tp
->flag
= (tp
->flag
& ~FINUSE
) | old_inuse
;
622 /* Were we deleted while executing? If so, free the execution
623 * tree. todo: Unfortunately, the table entry is never re-used
624 * until the lookup table is expanded.
626 if ((tp
->flag
& (FDELETE
|FINUSE
)) == FDELETE
) {
627 if (tp
->flag
& ALLOC
) {
629 tfree(tp
->val
.t
, tp
->areap
);
647 internal_errorf("CFUNC %d", i
);
652 case CEXEC
: /* executable command */
653 case CTALIAS
: /* tracked alias */
654 if (!(tp
->flag
&ISSET
)) {
655 /* errno_ will be set if the named command was found
656 * but could not be executed (permissions, no execute
657 * bit, directory, etc). Print out a (hopefully)
658 * useful error message and set the exit status to 126.
661 warningf(true, "%s: cannot execute - %s", cp
,
662 strerror(tp
->u2
.errno_
));
663 rv
= 126; /* POSIX */
665 warningf(true, "%s: not found", cp
);
672 /* set $_ to program's full path */
673 /* setstr() can't fail here */
674 setstr(typeset("_", LOCAL
|EXPORT
, 0, INTEGER
, 0),
675 tp
->val
.s
, KSH_RETURN_ERROR
);
680 if (!(flags
&XBGND
) || Flag(FMONITOR
)) {
681 setexecsig(&sigtraps
[SIGINT
], SS_RESTORE_ORIG
);
682 setexecsig(&sigtraps
[SIGQUIT
], SS_RESTORE_ORIG
);
686 /* to fork we set up a TEXEC node and call execute */
687 memset(&texec
, 0, sizeof(texec
));
689 texec
.left
= t
; /* for tprint */
690 texec
.str
= tp
->val
.s
;
692 rv
= exchild(&texec
, flags
, xerrok
, -1);
704 scriptexec(struct op
*tp
, char **ap
)
708 shell
= str_val(global("EXECSHELL"));
710 shell
= search(shell
, search_path
, X_OK
, NULL
);
711 if (!shell
|| !*shell
)
712 shell
= _PATH_BSHELL
;
714 *tp
->args
-- = tp
->str
;
717 execve(tp
->args
[0], tp
->args
, ap
);
719 /* report both the program that was run and the bogus shell */
720 errorf("%s: %s: %s", tp
->str
, shell
, strerror(errno
));
728 tp
= ktsearch(&builtins
, *wp
, hash(*wp
));
730 internal_errorf("%s: %s", __func__
, *wp
);
731 return call_builtin(tp
, wp
);
735 * Search function tables for a function. If create set, a table entry
736 * is created if none is found.
739 findfunc(const char *name
, unsigned int h
, int create
)
742 struct tbl
*tp
= NULL
;
744 for (l
= genv
->loc
; l
; l
= l
->next
) {
745 tp
= ktsearch(&l
->funs
, name
, h
);
748 if (!l
->next
&& create
) {
749 tp
= ktenter(&l
->funs
, name
, h
);
760 * define function. Returns 1 if function is being undefined (t == 0) and
761 * function did not exist, returns 0 otherwise.
764 define(const char *name
, struct op
*t
)
770 tp
= findfunc(name
, hash(name
), true);
772 if (tp
->flag
& ISSET
)
774 /* If this function is currently being executed, we zap this
775 * table entry so findfunc() won't see it
777 if (tp
->flag
& FINUSE
) {
779 tp
->flag
&= ~DEFINED
; /* ensure it won't be found */
785 if (tp
->flag
& ALLOC
) {
786 tp
->flag
&= ~(ISSET
|ALLOC
);
787 tfree(tp
->val
.t
, tp
->areap
);
790 if (t
== NULL
) { /* undefine */
792 return was_set
? 0 : 1;
795 tp
->val
.t
= tcopy(t
->left
, tp
->areap
);
796 tp
->flag
|= (ISSET
|ALLOC
);
807 builtin(const char *name
, int (*func
) (char **))
812 /* see if any flags should be set for this builtin */
813 for (flag
= 0; ; name
++) {
814 if (*name
== '=') /* command does variable assignment */
816 else if (*name
== '*') /* POSIX special builtin */
818 else if (*name
== '+') /* POSIX regular builtin */
824 tp
= ktenter(&builtins
, name
, hash(name
));
825 tp
->flag
= DEFINED
| flag
;
832 * either function, hashed command, or built-in (in that order)
835 findcom(const char *name
, int flags
)
837 static struct tbl temp
;
838 unsigned int h
= hash(name
);
839 struct tbl
*tp
= NULL
, *tbi
;
840 int insert
= Flag(FTRACKALL
); /* insert if not found */
841 char *fpath
; /* for function autoloading */
844 if (strchr(name
, '/') != NULL
) {
846 /* prevent FPATH search below */
850 tbi
= (flags
& FC_BI
) ? ktsearch(&builtins
, name
, h
) : NULL
;
851 /* POSIX says special builtins first, then functions, then
852 * POSIX regular builtins, then search path...
854 if ((flags
& FC_SPECBI
) && tbi
&& (tbi
->flag
& SPEC_BI
))
856 if (!tp
&& (flags
& FC_FUNC
)) {
857 tp
= findfunc(name
, h
, false);
858 if (tp
&& !(tp
->flag
& ISSET
)) {
859 if ((fpath
= str_val(global("FPATH"))) == null
) {
863 tp
->u
.fpath
= search(name
, fpath
, R_OK
,
867 if (!tp
&& (flags
& FC_REGBI
) && tbi
&& (tbi
->flag
& REG_BI
))
869 /* todo: posix says non-special/non-regular builtins must
870 * be triggered by some user-controllable means like a
871 * special directory in PATH. Requires modifications to
872 * the search() function. Tracked aliases should be
873 * modified to allow tracking of builtin commands.
874 * This should be under control of the FPOSIX flag.
875 * If this is changed, also change c_whence...
877 if (!tp
&& (flags
& FC_UNREGBI
) && tbi
)
879 if (!tp
&& (flags
& FC_PATH
) && !(flags
& FC_DEFPATH
)) {
880 tp
= ktsearch(&taliases
, name
, h
);
881 if (tp
&& (tp
->flag
& ISSET
) && access(tp
->val
.s
, X_OK
) != 0) {
882 if (tp
->flag
& ALLOC
) {
884 afree(tp
->val
.s
, APERM
);
891 if ((!tp
|| (tp
->type
== CTALIAS
&& !(tp
->flag
&ISSET
))) &&
894 if (insert
&& !(flags
& FC_DEFPATH
)) {
895 tp
= ktenter(&taliases
, name
, h
);
901 tp
->flag
= DEFINED
; /* make ~ISSET */
903 npath
= search(name
, flags
& FC_DEFPATH
? def_path
:
904 search_path
, X_OK
, &tp
->u2
.errno_
);
909 tp
->val
.s
= str_save(npath
, APERM
);
913 tp
->flag
|= ISSET
|ALLOC
;
914 } else if ((flags
& FC_FUNC
) &&
915 (fpath
= str_val(global("FPATH"))) != null
&&
916 (npath
= search(name
, fpath
, R_OK
,
917 &tp
->u2
.errno_
)) != NULL
) {
918 /* An undocumented feature of at&t ksh is that it
919 * searches FPATH if a command is not found, even
920 * if the command hasn't been set up as an autoloaded
921 * function (ie, no typeset -uf).
925 tp
->flag
= DEFINED
; /* make ~ISSET */
933 * flush executable commands with relative paths
936 flushcom(int all
) /* just relative or all */
941 for (ktwalk(&ts
, &taliases
); (tp
= ktnext(&ts
)) != NULL
; )
942 if ((tp
->flag
&ISSET
) && (all
|| tp
->val
.s
[0] != '/')) {
943 if (tp
->flag
&ALLOC
) {
944 tp
->flag
&= ~(ALLOC
|ISSET
);
945 afree(tp
->val
.s
, APERM
);
951 /* Check if path is something we want to find. Returns -1 for failure. */
953 search_access(const char *path
, int mode
,
954 int *errnop
) /* set if candidate found, but not suitable */
959 if (stat(path
, &statb
) < 0)
961 ret
= access(path
, mode
);
963 err
= errno
; /* File exists, but we can't access it */
964 else if (mode
== X_OK
&& (!S_ISREG(statb
.st_mode
) ||
965 !(statb
.st_mode
& (S_IXUSR
|S_IXGRP
|S_IXOTH
)))) {
966 /* This 'cause access() says root can execute everything */
968 err
= S_ISDIR(statb
.st_mode
) ? EISDIR
: EACCES
;
970 if (err
&& errnop
&& !*errnop
)
976 * search for command with PATH
979 search(const char *name
, const char *path
,
980 int mode
, /* R_OK or X_OK */
981 int *errnop
) /* set if candidate found, but not suitable */
990 if (strchr(name
, '/')) {
991 if (search_access(name
, mode
, errnop
) == 0)
992 return (char *) name
;
996 namelen
= strlen(name
) + 1;
997 Xinit(xs
, xp
, 128, ATEMP
);
1000 while (sp
!= NULL
) {
1001 xp
= Xstring(xs
, xp
);
1002 if (!(p
= strchr(sp
, ':')))
1003 p
= sp
+ strlen(sp
);
1005 XcheckN(xs
, xp
, p
- sp
);
1006 memcpy(xp
, sp
, p
- sp
);
1011 XcheckN(xs
, xp
, namelen
);
1012 memcpy(xp
, name
, namelen
);
1013 if (search_access(Xstring(xs
, xp
), mode
, errnop
) == 0)
1014 return Xclose(xs
, xp
+ namelen
);
1023 call_builtin(struct tbl
*tp
, char **wp
)
1027 builtin_argv0
= wp
[0];
1028 builtin_flag
= tp
->flag
;
1029 shf_reopen(1, SHF_WR
, shl_stdout
);
1031 ksh_getopt_reset(&builtin_opt
, GF_ERROR
);
1032 rv
= (*tp
->val
.f
)(wp
);
1033 shf_flush(shl_stdout
);
1036 builtin_argv0
= NULL
;
1041 * set up redirection, saving old fd's in e->savefd
1044 iosetup(struct ioword
*iop
, struct tbl
*tp
)
1047 char *cp
= iop
->name
;
1048 int iotype
= iop
->flag
& IOTYPE
;
1049 int do_open
= 1, do_close
= 0, flags
= 0;
1050 struct ioword iotmp
;
1053 if (iotype
!= IOHERE
)
1054 cp
= evalonestr(cp
, DOTILDE
|(Flag(FTALKING_I
) ? DOGLOB
: 0));
1056 /* Used for tracing and error messages to print expanded cp */
1058 iotmp
.name
= (iotype
== IOHERE
) ? NULL
: cp
;
1059 iotmp
.flag
|= IONAMEXP
;
1063 PS4_SUBSTITUTE(str_val(global("PS4"))),
1064 snptreef(NULL
, 32, "%R", &iotmp
));
1072 flags
= O_WRONLY
| O_APPEND
| O_CREAT
;
1076 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
1077 /* The stat() is here to allow redirections to
1078 * things like /dev/null without error.
1080 if (Flag(FNOCLOBBER
) && !(iop
->flag
& IOCLOB
) &&
1081 (stat(cp
, &statb
) < 0 || S_ISREG(statb
.st_mode
)))
1086 flags
= O_RDWR
| O_CREAT
;
1091 /* herein() returns -2 if error has been printed */
1092 u
= herein(iop
->heredoc
, iop
->flag
& IOEVAL
);
1093 /* cp may have wrong name */
1101 if (*cp
== '-' && !cp
[1]) {
1102 u
= 1009; /* prevent error return below */
1104 } else if ((u
= check_fd(cp
,
1105 X_OK
| ((iop
->flag
& IORDUP
) ? R_OK
: W_OK
),
1107 warningf(true, "%s: %s",
1108 snptreef(NULL
, 32, "%R", &iotmp
), emsg
);
1112 return 0; /* "dup from" == "dup to" */
1118 if (Flag(FRESTRICTED
) && (flags
& O_CREAT
)) {
1119 warningf(true, "%s: restricted", cp
);
1122 u
= open(cp
, flags
, 0666);
1125 /* herein() may already have printed message */
1127 warningf(true, "cannot %s %s: %s",
1128 iotype
== IODUP
? "dup" :
1129 (iotype
== IOREAD
|| iotype
== IOHERE
) ?
1130 "open" : "create", cp
, strerror(errno
));
1133 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1134 if (genv
->savefd
[iop
->unit
] == 0) {
1135 /* If these are the same, it means unit was previously closed */
1137 genv
->savefd
[iop
->unit
] = -1;
1139 /* c_exec() assumes e->savefd[fd] set for any
1140 * redirections. Ask savefd() not to close iop->unit;
1141 * this allows error messages to be seen if iop->unit
1142 * is 2; also means we can't lose the fd (eg, both
1143 * dup2 below and dup2 in restfd() failing).
1145 genv
->savefd
[iop
->unit
] = savefd(iop
->unit
);
1150 else if (u
!= iop
->unit
) {
1151 if (ksh_dup2(u
, iop
->unit
, true) < 0) {
1153 "could not finish (dup) redirection %s: %s",
1154 snptreef(NULL
, 32, "%R", &iotmp
),
1156 if (iotype
!= IODUP
)
1160 if (iotype
!= IODUP
)
1162 /* Touching any co-process fd in an empty exec
1163 * causes the shell to close its copies
1165 else if (tp
&& tp
->type
== CSHELL
&& tp
->val
.f
== c_exec
) {
1166 if (iop
->flag
& IORDUP
) /* possible exec <&p */
1167 coproc_read_close(u
);
1168 else /* possible exec >&p */
1169 coproc_write_close(u
);
1172 if (u
== 2) /* Clear any write errors */
1173 shf_reopen(2, SHF_WR
, shl_out
);
1178 * open here document temp file.
1179 * if unquoted here, expand here temp file into second temp file.
1182 herein(const char *content
, int sub
)
1184 volatile int fd
= -1;
1185 struct source
*s
, *volatile osource
;
1186 struct shf
*volatile shf
;
1190 /* ksh -c 'cat << EOF' can cause this... */
1191 if (content
== NULL
) {
1192 warningf(true, "here document missing");
1193 return -2; /* special to iosetup(): don't print error */
1196 /* Create temp file to hold content (done before newenv so temp
1197 * doesn't get removed too soon).
1199 h
= maketemp(ATEMP
, TT_HEREDOC_EXP
, &genv
->temps
);
1200 if (!(shf
= h
->shf
) || (fd
= open(h
->name
, O_RDONLY
, 0)) < 0) {
1201 warningf(true, "can't %s temporary file %s: %s",
1202 !shf
? "create" : "open",
1203 h
->name
, strerror(errno
));
1206 return -2 /* special to iosetup(): don't print error */;
1211 i
= sigsetjmp(genv
->jbuf
, 0);
1216 return -2; /* special to iosetup(): don't print error */
1219 /* Do substitutions on the content of heredoc */
1220 s
= pushs(SSTRING
, ATEMP
);
1221 s
->start
= s
->str
= content
;
1223 if (yylex(ONEWORD
|HEREDOC
) != LWORD
)
1224 internal_errorf("%s: yylex", __func__
);
1226 shf_puts(evalstr(yylval
.cp
, 0), shf
);
1228 shf_puts(content
, shf
);
1232 if (shf_close(shf
) == EOF
) {
1234 warningf(true, "error writing %s: %s", h
->name
,
1236 return -2; /* special to iosetup(): don't print error */
1243 * ksh special - the select command processing section
1244 * print the args in column form - assuming that we can
1247 do_selectargs(char **ap
, bool print_menu
)
1249 static const char *const read_args
[] = {
1250 "read", "-r", "REPLY", NULL
1256 for (argct
= 0; ap
[argct
]; argct
++)
1259 /* Menu is printed if
1260 * - this is the first time around the select loop
1261 * - the user enters a blank line
1262 * - the REPLY parameter is empty
1264 if (print_menu
|| !*str_val(global("REPLY")))
1266 shellf("%s", str_val(global("PS3")));
1267 if (call_builtin(findcom("read", FC_BI
), (char **) read_args
))
1269 s
= str_val(global("REPLY"));
1271 i
= strtonum(s
, 1, argct
, &errstr
);
1280 struct select_menu_info
{
1286 static char *select_fmt_entry(void *arg
, int i
, char *buf
, int buflen
);
1288 /* format a single select menu item */
1290 select_fmt_entry(void *arg
, int i
, char *buf
, int buflen
)
1292 struct select_menu_info
*smi
= (struct select_menu_info
*) arg
;
1294 shf_snprintf(buf
, buflen
, "%*d) %s",
1295 smi
->num_width
, i
+ 1, smi
->args
[i
]);
1300 * print a select style menu
1303 pr_menu(char *const *ap
)
1305 struct select_menu_info smi
;
1310 /* Width/column calculations were done once and saved, but this
1311 * means select can't be used recursively so we re-calculate each
1312 * time (could save in a structure that is returned, but its probably
1313 * not worth the bother).
1317 * get dimensions of the list
1319 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1321 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1324 * we will print an index of the form
1326 * in front of each entry
1327 * get the max width of this
1329 for (i
= n
, dwidth
= 1; i
>= 10; i
/= 10)
1333 smi
.arg_width
= nwidth
;
1334 smi
.num_width
= dwidth
;
1335 print_columns(shl_out
, n
, select_fmt_entry
, (void *) &smi
,
1336 dwidth
+ nwidth
+ 2, 1);
1341 /* XXX: horrible kludge to fit within the framework */
1343 static char *plain_fmt_entry(void *arg
, int i
, char *buf
, int buflen
);
1346 plain_fmt_entry(void *arg
, int i
, char *buf
, int buflen
)
1348 shf_snprintf(buf
, buflen
, "%s", ((char *const *)arg
)[i
]);
1353 pr_list(char *const *ap
)
1359 for (n
= 0, nwidth
= 0, pp
= ap
; *pp
; n
++, pp
++) {
1361 nwidth
= (i
> nwidth
) ? i
: nwidth
;
1363 print_columns(shl_out
, n
, plain_fmt_entry
, (void *) ap
, nwidth
+ 1, 0);
1369 * [[ ... ]] evaluation routines
1372 extern const char *const dbtest_tokens
[];
1373 extern const char db_close
[];
1375 /* Test if the current token is a whatever. Accepts the current token if
1376 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1377 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1380 dbteste_isa(Test_env
*te
, Test_meta meta
)
1387 return meta
== TM_END
;
1389 /* unquoted word? */
1390 for (p
= *te
->pos
.wp
; *p
== CHAR
; p
+= 2)
1394 if (meta
== TM_UNOP
|| meta
== TM_BINOP
) {
1396 char buf
[8]; /* longer than the longest operator */
1398 for (p
= *te
->pos
.wp
;
1399 *p
== CHAR
&& q
< &buf
[sizeof(buf
) - 1]; p
+= 2)
1402 ret
= (int) test_isop(te
, meta
, buf
);
1404 } else if (meta
== TM_END
)
1408 strcmp(*te
->pos
.wp
, dbtest_tokens
[(int) meta
]) == 0;
1410 /* Accept the token? */
1418 dbteste_getopnd(Test_env
*te
, Test_op op
, int do_eval
)
1420 char *s
= *te
->pos
.wp
;
1430 if (op
== TO_STEQL
|| op
== TO_STNEQ
)
1431 s
= evalstr(s
, DOTILDE
| DOPAT
);
1433 s
= evalstr(s
, DOTILDE
);
1439 dbteste_eval(Test_env
*te
, Test_op op
, const char *opnd1
, const char *opnd2
,
1442 return test_eval(te
, op
, opnd1
, opnd2
, do_eval
);
1446 dbteste_error(Test_env
*te
, int offset
, const char *msg
)
1448 te
->flags
|= TEF_ERROR
;
1449 internal_warningf("%s: %s (offset %d)", __func__
, msg
, offset
);