1 /* $OpenBSD: exec.c,v 1.51 2015/04/18 18:28:36 deraadt Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015
6 * Thorsten Glaser <tg@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 __RCSID("$MirOS: src/bin/mksh/exec.c,v 1.137.2.4 2015/04/19 19:18:15 tg Exp $");
28 #ifndef MKSH_DEFAULT_EXECSHELL
29 #define MKSH_DEFAULT_EXECSHELL "/bin/sh"
32 static int comexec(struct op *, struct tbl * volatile, const char **,
33 int volatile, volatile int *);
34 static void scriptexec(struct op *, const char **) MKSH_A_NORETURN;
35 static int call_builtin(struct tbl *, const char **, const char *, bool);
36 static int iosetup(struct ioword *, struct tbl *);
37 static int herein(struct ioword *, char **);
38 static const char *do_selectargs(const char **, bool);
39 static Test_op dbteste_isa(Test_env *, Test_meta);
40 static const char *dbteste_getopnd(Test_env *, Test_op, bool);
41 static void dbteste_error(Test_env *, int, const char *);
42 static int search_access(const char *, int);
43 /* XXX: horrible kludge to fit within the framework */
44 static char *plain_fmt_entry(char *, size_t, unsigned int, const void *);
45 static char *select_fmt_entry(char *, size_t, unsigned int, const void *);
48 * execute command tree
51 execute(struct op * volatile t,
52 /* if XEXEC don't fork */
54 volatile int * volatile xerrok)
57 volatile int rv = 0, dummy = 0;
59 const char ** volatile ap = NULL;
63 struct tbl *tp = NULL;
69 /* Caller doesn't care if XERROK should propagate. */
73 if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
74 /* run in sub-process */
75 return (exchild(t, flags & ~XTIME, xerrok, -1));
81 /* we want to run an executable, do some variance checks */
82 if (t->type == TCOM) {
83 /* check if this is 'var=<<EOF' */
84 /*XXX this is broken, don’t use! */
85 /*XXX https://bugs.launchpad.net/mksh/+bug/1380389 */
87 /* we have zero arguments, i.e. no programme to run */
89 /* we have exactly one variable assignment */
90 t->vars[0] != NULL && t->vars[1] == NULL &&
91 /* we have exactly one I/O redirection */
92 t->ioact != NULL && t->ioact[0] != NULL &&
93 t->ioact[1] == NULL &&
94 /* of type "here document" (or "here string") */
95 (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
96 /* the variable assignment begins with a valid varname */
97 (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
98 /* and has no right-hand side (i.e. "varname=") */
99 ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
100 /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
101 ccp[3] == '=' && ccp[4] == EOS)) &&
102 /* plus we can have a here document content */
103 herein(t->ioact[0], &cp) == 0 && cp && *cp) {
105 size_t n = ccp - t->vars[0] + (ccp[1] == '+' ? 4 : 2);
108 /* drop redirection (will be garbage collected) */
111 /* set variable to its expanded value */
113 if (notoktomul(z, 2) || notoktoadd(z * 2, n + 1))
114 internal_errorf(Toomem, (size_t)-1);
115 dp = alloc(z * 2 + n + 1, APERM);
116 memcpy(dp, t->vars[0], n);
124 /* free the expanded value */
129 * Clear subst_exstat before argument expansion. Used by
130 * null commands (see comexec() and c_eval()) and by c_set().
135 current_lineno = t->lineno;
138 * POSIX says expand command words first, then redirections,
139 * and assignments last..
141 up = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
143 /* Allow option parsing (bizarre, but POSIX) */
145 ap = (const char **)up;
147 tp = findcom(ap[0], FC_BI|FC_FUNC);
151 if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
152 e->savefd = alloc2(NUFILE, sizeof(short), ATEMP);
153 /* initialise to not redirected */
154 memset(e->savefd, 0, NUFILE * sizeof(short));
157 /* mark for replacement later (unless TPIPE) */
158 vp_pipest->flag |= INT_L;
160 /* do redirection, to be restored in quitenv() */
161 if (t->ioact != NULL)
162 for (iowp = t->ioact; *iowp != NULL; iowp++) {
163 if (iosetup(*iowp, tp) < 0) {
166 * Redirection failures for special commands
167 * cause (non-interactive) shell to exit.
169 if (tp && tp->type == CSHELL &&
170 (tp->flag & SPEC_BI))
172 /* Deal with FERREXIT, quitenv(), etc. */
179 rv = comexec(t, tp, (const char **)ap, flags, xerrok);
183 rv = execute(t->left, flags | XFORK, xerrok);
189 e->savefd[0] = savefd(0);
190 e->savefd[1] = savefd(1);
191 while (t->type == TPIPE) {
194 ksh_dup2(pv[1], 1, false);
196 * Let exchild() close pv[0] in child
197 * (if this isn't done, commands like
198 * (: ; cat /etc/termcap) | sleep 1
199 * will hang forever).
201 exchild(t->left, flags | XPIPEO | XCCLOSE,
204 ksh_dup2(pv[0], 0, false);
210 restfd(1, e->savefd[1]);
211 /* no need to re-restore this */
213 /* Let exchild() close 0 in parent, after fork, before wait */
214 i = exchild(t, flags | XPCLOSE | XPIPEST, xerrok, 0);
215 if (!(flags&XBGND) && !(flags&XXCOM))
220 while (t->type == TLIST) {
221 execute(t->left, flags & XERROK, NULL);
224 rv = execute(t, flags & XERROK, xerrok);
228 #ifndef MKSH_NOPROSPECTOFWORK
232 * Block sigchild as we are using things changed in the
235 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
237 if ((i = kshsetjmp(e->jbuf))) {
238 sigprocmask(SIG_SETMASK, &omask, NULL);
244 /* Already have a (live) co-process? */
245 if (coproc.job && coproc.write >= 0)
246 errorf("coprocess already exists");
248 /* Can we re-use the existing co-process pipe? */
249 coproc_cleanup(true);
251 /* do this before opening pipes, in case these fail */
252 e->savefd[0] = savefd(0);
253 e->savefd[1] = savefd(1);
257 ksh_dup2(pv[0], 0, false);
260 coproc.write = pv[1];
263 if (coproc.readw >= 0)
264 ksh_dup2(coproc.readw, 1, false);
268 ksh_dup2(pv[1], 1, false);
269 /* closed before first read */
270 coproc.readw = pv[1];
272 /* create new coprocess id */
275 #ifndef MKSH_NOPROSPECTOFWORK
276 sigprocmask(SIG_SETMASK, &omask, NULL);
277 /* no more need for error handler */
282 * exchild() closes coproc.* in child after fork,
283 * will also increment coproc.njobs when the
284 * job is actually created.
287 exchild(t->left, flags | XBGND | XFORK | XCOPROC | XCCLOSE,
294 * XXX non-optimal, I think - "(foo &)", forks for (),
295 * forks again for async... parent should optimise
298 rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK, xerrok);
303 rv = execute(t->left, XERROK, xerrok);
304 if ((rv == 0) == (t->type == TAND))
305 rv = execute(t->right, flags & XERROK, xerrok);
314 rv = !execute(t->right, XERROK, xerrok);
323 te.flags = TEF_DBRACKET;
325 te.isa = dbteste_isa;
326 te.getopnd = dbteste_getopnd;
328 te.error = dbteste_error;
330 rv = test_parse(&te);
336 volatile bool is_first = true;
338 ap = (t->vars == NULL) ? e->loc->argv + 1 :
339 (const char **)eval((const char **)t->vars,
340 DOBLANK | DOGLOB | DOTILDE);
342 while ((i = kshsetjmp(e->jbuf))) {
343 if ((e->flags&EF_BRKCONT_PASS) ||
344 (i != LBREAK && i != LCONTIN)) {
347 } else if (i == LBREAK) {
352 /* in case of a continue */
354 if (t->type == TFOR) {
355 while (*ap != NULL) {
356 setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
357 rv = execute(t->left, flags & XERROK, xerrok);
362 if (!(ccp = do_selectargs(ap, is_first))) {
367 setstr(global(t->str), ccp, KSH_UNWIND_ERROR);
368 execute(t->left, flags & XERROK, xerrok);
377 while ((i = kshsetjmp(e->jbuf))) {
378 if ((e->flags&EF_BRKCONT_PASS) ||
379 (i != LBREAK && i != LCONTIN)) {
382 } else if (i == LBREAK) {
387 /* in case of a continue */
389 while ((execute(t->left, XERROK, NULL) == 0) ==
391 rv = execute(t->right, flags & XERROK, xerrok);
396 if (t->right == NULL)
397 /* should be error */
399 rv = execute(t->left, XERROK, NULL) == 0 ?
400 execute(t->right->left, flags & XERROK, xerrok) :
401 execute(t->right->right, flags & XERROK, xerrok);
406 ccp = evalstr(t->str, DOTILDE | DOSCALAR);
407 for (t = t->left; t != NULL && t->type == TPAT; t = t->right) {
408 for (ap = (const char **)t->vars; *ap; ap++) {
409 if (i || ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
410 gmatchx(ccp, s, false))) {
411 rv = execute(t->left, flags & XERROK,
414 switch (t->u.charflag) {
432 rv = execute(t->left, flags & XERROK, xerrok);
436 rv = define(t->str, t);
441 * Clear XEXEC so nested execute() call doesn't exit
442 * (allows "ls -l | time grep foo").
444 rv = timex(t, flags & ~XEXEC, xerrok);
453 union mksh_ccphack cargs;
456 execve(t->str, cargs.rw, up);
460 scriptexec(t, (const char **)up);
462 errorf("%s: %s", t->str, cstrerror(rv));
466 if (vp_pipest->flag & INT_L) {
468 vp_pipest->flag = DEFINED | ISSET | INTEGER | RDONLY |
469 ARRAY | INT_U | INT_L;
470 vp_pipest->val.i = rv;
478 if (rv != 0 && !(flags & XERROK) &&
479 (xerrok == NULL || !*xerrok)) {
480 if (Flag(FERREXIT) & 0x80) {
493 * execute simple command
497 comexec(struct op *t, struct tbl * volatile tp, const char **ap,
498 volatile int flags, volatile int *xerrok)
504 /* Must be static (XXX but why?) */
505 static struct op texec;
508 int fcflags = FC_BI|FC_FUNC|FC_PATH;
509 struct block *l_expand, *l_assign;
511 const char *exec_argv0 = NULL;
512 bool exec_clrenv = false;
514 /* snag the last argument for $_ */
515 if (Flag(FTALKING) && *(lastp = ap)) {
517 * XXX not the same as AT&T ksh, which only seems to set $_
518 * after a newline (but not in functions/dot scripts, but in
519 * interactive and script) - perhaps save last arg here and
520 * set it in shell()?.
524 /* setstr() can't fail here */
525 setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
530 * Deal with the shell builtins builtin, exec and command since
531 * they can be followed by other commands. This must be done before
532 * we know if we should create a local block which must be done
533 * before we can do a path search (in case the assignments change
536 * FOO=bar exec >/dev/null FOO is kept but not exported
537 * FOO=bar exec foobar FOO is exported
538 * FOO=bar command exec >/dev/null FOO is neither kept nor exported
539 * FOO=bar command FOO is neither kept nor exported
540 * PATH=... foobar use new PATH in foobar search
543 while (tp && tp->type == CSHELL) {
544 /* undo effects of command */
545 fcflags = FC_BI|FC_FUNC|FC_PATH;
546 if (tp->val.f == c_builtin) {
547 if ((cp = *++ap) == NULL ||
548 (!strcmp(cp, "--") && (cp = *++ap) == NULL)) {
552 if ((tp = findcom(cp, FC_BI)) == NULL)
553 errorf("%s: %s: %s", Tbuiltin, cp, "not a builtin");
555 } else if (tp->val.f == c_exec) {
558 ksh_getopt_reset(&builtin_opt, GF_ERROR);
559 while ((optc = ksh_getopt(ap, &builtin_opt, "a:c")) != -1)
562 exec_argv0 = builtin_opt.optarg;
566 /* ensure we can actually do this */
573 ap += builtin_opt.optind;
575 } else if (tp->val.f == c_command) {
579 * Ugly dealing with options in two places (here
580 * and in c_command(), but such is life)
582 ksh_getopt_reset(&builtin_opt, 0);
583 while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
586 /* command -vV or something */
588 /* don't look for functions */
589 fcflags = FC_BI|FC_PATH;
591 if (Flag(FRESTRICTED)) {
592 warningf(true, "%s: %s",
593 "command -p", "restricted");
597 fcflags |= FC_DEFPATH;
599 ap += builtin_opt.optind;
601 * POSIX says special builtins lose their status
602 * if accessed using command.
606 /* ensure command with no args exits with 0 */
610 #ifndef MKSH_NO_EXTERNAL_CAT
611 } else if (tp->val.f == c_cat) {
613 * if we have any flags, do not use the builtin
614 * in theory, we could allow -u, but that would
615 * mean to use ksh_getopt here and possibly ad-
616 * ded complexity and more code and isn't worth
617 * additional hassle (and the builtin must call
618 * ksh_getopt already but can't come back here)
620 if (ap[1] && ap[1][0] == '-' && ap[1][1] != '\0' &&
621 /* argument, begins with -, is not - or -- */
622 (ap[1][1] != '-' || ap[1][2] != '\0'))
623 /* don't look for builtins or functions */
626 /* go on, use the builtin */
629 } else if (tp->val.f == c_trap) {
630 t->u.evalflags &= ~DOTCOMEXEC;
634 tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
636 if (t->u.evalflags & DOTCOMEXEC)
639 if (!resetspec && (!ap[0] || (tp && (tp->flag & KEEPASN))))
642 /* create new variable/function block */
644 /* ksh functions don't keep assignments, POSIX functions do. */
645 if (!resetspec && tp && tp->type == CFUNC &&
649 type_flags = LOCAL|LOCAL_COPY|EXPORT;
653 l_assign->flags |= BF_STOPENV;
655 type_flags |= EXPORT;
657 change_xtrace(2, false);
658 for (i = 0; t->vars[i]; i++) {
659 /* do NOT lookup in the new var/fn block just created */
661 cp = evalstr(t->vars[i], DOASNTILDE | DOSCALAR);
666 ccp = skip_varname(cp, true);
671 shf_write(cp, ccp - cp, shl_xtrace);
672 print_value_quoted(shl_xtrace, ccp);
673 shf_putc(' ', shl_xtrace);
675 /* but assign in there as usual */
676 typeset(cp, type_flags, 0, 0, 0);
680 change_xtrace(2, false);
683 print_value_quoted(shl_xtrace, ap[rv]);
685 shf_putc(' ', shl_xtrace);
689 change_xtrace(1, false);
692 if ((cp = *ap) == NULL) {
696 if (Flag(FRESTRICTED) && vstrchr(cp, '/')) {
697 warningf(true, "%s: %s", cp, "restricted");
701 tp = findcom(cp, fcflags);
708 rv = call_builtin(tp, (const char **)ap, null, resetspec);
709 if (resetspec && tp->val.f == c_shift) {
710 l_expand->argc = l_assign->argc;
711 l_expand->argv = l_assign->argv;
717 volatile unsigned char old_xflag;
718 volatile uint32_t old_inuse;
719 const char * volatile old_kshname;
721 if (!(tp->flag & ISSET)) {
725 rv = (tp->u2.errnov == ENOENT) ? 127 : 126;
726 warningf(true, "%s: %s %s: %s", cp,
727 "can't find", "function definition file",
728 cstrerror(tp->u2.errnov));
731 if (include(tp->u.fpath, 0, NULL, false) < 0) {
732 warningf(true, "%s: %s %s %s: %s", cp,
733 "can't open", "function definition file",
734 tp->u.fpath, cstrerror(errno));
738 if (!(ftp = findfunc(cp, hash(cp), false)) ||
739 !(ftp->flag & ISSET)) {
740 warningf(true, "%s: %s %s", cp,
741 "function not defined by", tp->u.fpath);
749 * ksh functions set $0 to function name, POSIX
750 * functions leave $0 unchanged.
752 old_kshname = kshname;
758 for (i = 0; *ap++ != NULL; i++)
760 e->loc->argc = i - 1;
762 * ksh-style functions handle getopts sanely,
763 * Bourne/POSIX functions are insane...
765 if (tp->flag & FKSH) {
766 e->loc->flags |= BF_DOGETOPTS;
767 e->loc->getopts_state = user_opt;
771 old_xflag = Flag(FXTRACE) ? 1 : 0;
772 change_xtrace((Flag(FXTRACEREC) ? old_xflag : 0) |
773 ((tp->flag & TRACE) ? 1 : 0), false);
774 old_inuse = tp->flag & FINUSE;
778 if (!(i = kshsetjmp(e->jbuf))) {
779 execute(tp->val.t, flags & XERROK, NULL);
783 kshname = old_kshname;
784 change_xtrace(old_xflag, false);
785 tp->flag = (tp->flag & ~FINUSE) | old_inuse;
788 * Were we deleted while executing? If so, free the
791 if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
792 if (tp->flag & ALLOC) {
794 tfree(tp->val.t, tp->areap);
812 internal_errorf("%s %d", "CFUNC", i);
817 /* executable command */
821 if (!(tp->flag&ISSET)) {
822 if (tp->u2.errnov == ENOENT) {
824 warningf(true, "%s: %s", cp, "not found");
827 warningf(true, "%s: %s: %s", cp, "can't execute",
828 cstrerror(tp->u2.errnov));
833 /* set $_ to program's full path */
834 /* setstr() can't fail here */
835 setstr(typeset("_", LOCAL | EXPORT, 0, INTEGER, 0),
836 tp->val.s, KSH_RETURN_ERROR);
838 /* to fork, we set up a TEXEC node and call execute */
840 /* for vistree/dumptree */
842 texec.str = tp->val.s;
845 /* in this case we do not fork, of course */
848 texec.args[0] = exec_argv0;
851 #ifndef MKSH_UNEMPLOYED
855 setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
856 setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
860 rv = exchild(&texec, flags, xerrok, -1);
872 scriptexec(struct op *tp, const char **ap)
877 unsigned char buf[68];
879 union mksh_ccphack args, cap;
881 sh = str_val(global("EXECSHELL"));
883 sh = search_path(sh, path, X_OK, NULL);
885 sh = MKSH_DEFAULT_EXECSHELL;
887 *tp->args-- = tp->str;
890 if ((fd = open(tp->str, O_RDONLY | O_BINARY)) >= 0) {
895 /* read first couple of octets from file */
896 n = read(fd, buf, sizeof(buf) - 1);
898 /* read error or short read? */
901 /* terminate buffer */
904 /* skip UTF-8 Byte Order Mark, if present */
905 cp = buf + (n = ((buf[0] == 0xEF) && (buf[1] == 0xBB) &&
906 (buf[2] == 0xBF)) ? 3 : 0);
908 /* scan for newline or NUL (end of buffer) */
909 while (*cp && *cp != '\n')
911 /* if the shebang line is longer than MAXINTERP, bail out */
914 /* replace newline by NUL */
917 /* restore begin of shebang position (buf+0 or buf+3) */
919 /* bail out if no shebang magic found */
920 if ((cp[0] != '#') || (cp[1] != '!'))
924 /* skip whitespace before shell name */
925 while (*cp == ' ' || *cp == '\t')
927 /* just whitespace on the line? */
930 /* no, we actually found an interpreter name */
932 /* look for end of shell/interpreter name */
933 while (*cp != ' ' && *cp != '\t' && *cp != '\0')
938 /* skip spaces before arguments */
939 while (*cp == ' ' || *cp == '\t')
941 /* pass it all in ONE argument (historic reasons) */
943 *tp->args-- = (char *)cp;
947 m = buf[0] << 8 | buf[1];
948 if (m == 0x7F45 && buf[2] == 'L' && buf[3] == 'F')
949 errorf("%s: not executable: %d-bit ELF file", tp->str,
951 if ((m == /* OMAGIC */ 0407) ||
952 (m == /* NMAGIC */ 0410) ||
953 (m == /* ZMAGIC */ 0413) ||
954 (m == /* QMAGIC */ 0314) ||
955 (m == /* ECOFF_I386 */ 0x4C01) ||
956 (m == /* ECOFF_M68K */ 0x0150 || m == 0x5001) ||
957 (m == /* ECOFF_SH */ 0x0500 || m == 0x0005) ||
958 (m == /* "MZ" */ 0x4D5A) ||
959 (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D))
960 errorf("%s: not executable: magic %04X", tp->str, m);
969 execve(args.rw[0], args.rw, cap.rw);
971 /* report both the programme that was run and the bogus interpreter */
972 errorf("%s: %s: %s", tp->str, sh, cstrerror(errno));
976 shcomexec(const char **wp)
980 tp = ktsearch(&builtins, *wp, hash(*wp));
981 return (call_builtin(tp, wp, "shcomexec", false));
985 * Search function tables for a function. If create set, a table entry
986 * is created if none is found.
989 findfunc(const char *name, uint32_t h, bool create)
992 struct tbl *tp = NULL;
994 for (l = e->loc; l; l = l->next) {
995 tp = ktsearch(&l->funs, name, h);
998 if (!l->next && create) {
999 tp = ktenter(&l->funs, name, h);
1010 * define function. Returns 1 if function is being undefined (t == 0) and
1011 * function did not exist, returns 0 otherwise.
1014 define(const char *name, struct op *t)
1018 bool was_set = false;
1022 if (t != NULL && !tobool(t->u.ksh_func)) {
1023 /* drop same-name aliases for POSIX functions */
1024 if ((tp = ktsearch(&aliases, name, nhash)))
1028 while (/* CONSTCOND */ 1) {
1029 tp = findfunc(name, nhash, true);
1031 if (tp->flag & ISSET)
1034 * If this function is currently being executed, we zap
1035 * this table entry so findfunc() won't see it
1037 if (tp->flag & FINUSE) {
1039 /* ensure it won't be found */
1040 tp->flag &= ~DEFINED;
1041 tp->flag |= FDELETE;
1046 if (tp->flag & ALLOC) {
1047 tp->flag &= ~(ISSET|ALLOC);
1048 tfree(tp->val.t, tp->areap);
1054 return (was_set ? 0 : 1);
1057 tp->val.t = tcopy(t->left, tp->areap);
1058 tp->flag |= (ISSET|ALLOC);
1069 builtin(const char *name, int (*func) (const char **))
1072 uint32_t flag = DEFINED;
1074 /* see if any flags should be set for this builtin */
1077 /* command does variable assignment */
1079 else if (*name == '*')
1080 /* POSIX special builtin */
1087 tp = ktenter(&builtins, name, hash(name));
1097 * either function, hashed command, or built-in (in that order)
1100 findcom(const char *name, int flags)
1102 static struct tbl temp;
1103 uint32_t h = hash(name);
1104 struct tbl *tp = NULL, *tbi;
1105 /* insert if not found */
1106 unsigned char insert = Flag(FTRACKALL);
1107 /* for function autoloading */
1109 union mksh_cchack npath;
1111 if (vstrchr(name, '/')) {
1113 /* prevent FPATH search below */
1117 tbi = (flags & FC_BI) ? ktsearch(&builtins, name, h) : NULL;
1119 * POSIX says special builtins first, then functions, then
1120 * regular builtins, then search path...
1122 if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
1124 if (!tp && (flags & FC_FUNC)) {
1125 tp = findfunc(name, h, false);
1126 if (tp && !(tp->flag & ISSET)) {
1127 if ((fpath = str_val(global("FPATH"))) == null) {
1129 tp->u2.errnov = ENOENT;
1131 tp->u.fpath = search_path(name, fpath, R_OK,
1135 if (!tp && (flags & FC_NORMBI) && tbi)
1137 if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
1138 tp = ktsearch(&taliases, name, h);
1139 if (tp && (tp->flag & ISSET) &&
1140 ksh_access(tp->val.s, X_OK) != 0) {
1141 if (tp->flag & ALLOC) {
1143 afree(tp->val.s, APERM);
1150 if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
1151 (flags & FC_PATH)) {
1153 if (insert && !(flags & FC_DEFPATH)) {
1154 tp = ktenter(&taliases, name, h);
1163 npath.ro = search_path(name,
1164 (flags & FC_DEFPATH) ? def_path : path,
1165 X_OK, &tp->u2.errnov);
1167 strdupx(tp->val.s, npath.ro, APERM);
1168 if (npath.ro != name)
1169 afree(npath.rw, ATEMP);
1170 tp->flag |= ISSET|ALLOC;
1171 } else if ((flags & FC_FUNC) &&
1172 (fpath = str_val(global("FPATH"))) != null &&
1173 (npath.ro = search_path(name, fpath, R_OK,
1174 &tp->u2.errnov)) != NULL) {
1176 * An undocumented feature of AT&T ksh is that
1177 * it searches FPATH if a command is not found,
1178 * even if the command hasn't been set up as an
1179 * autoloaded function (ie, no typeset -uf).
1185 tp->u.fpath = npath.ro;
1192 * flush executable commands with relative paths
1193 * (just relative or all?)
1201 for (ktwalk(&ts, &taliases); (tp = ktnext(&ts)) != NULL; )
1202 if ((tp->flag&ISSET) && (all || tp->val.s[0] != '/')) {
1203 if (tp->flag&ALLOC) {
1204 tp->flag &= ~(ALLOC|ISSET);
1205 afree(tp->val.s, APERM);
1211 /* check if path is something we want to find */
1213 search_access(const char *fn, int mode)
1217 if (stat(fn, &sb) < 0)
1218 /* file does not exist */
1220 /* LINTED use of access */
1221 if (access(fn, mode) < 0)
1222 /* file exists, but we can't access it */
1224 if (mode == X_OK && (!S_ISREG(sb.st_mode) ||
1225 !(sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))))
1226 /* access(2) may say root can execute everything */
1227 return (S_ISDIR(sb.st_mode) ? EISDIR : EACCES);
1232 * search for command with PATH
1235 search_path(const char *name, const char *lpath,
1238 /* set if candidate found, but not suitable */
1247 if (vstrchr(name, '/')) {
1248 if ((ec = search_access(name, mode)) == 0) {
1254 goto search_path_err;
1257 namelen = strlen(name) + 1;
1258 Xinit(xs, xp, 128, ATEMP);
1261 while (sp != NULL) {
1262 xp = Xstring(xs, xp);
1263 if (!(p = cstrchr(sp, ':')))
1264 p = sp + strlen(sp);
1266 XcheckN(xs, xp, p - sp);
1267 memcpy(xp, sp, p - sp);
1272 XcheckN(xs, xp, namelen);
1273 memcpy(xp, name, namelen);
1274 if ((ev = search_access(Xstring(xs, xp), mode)) == 0) {
1275 name = Xclose(xs, xp + namelen);
1276 goto search_path_ok;
1278 /* accumulate non-ENOENT errors only */
1279 if (ev != ENOENT && ec == 0)
1287 *errnop = ec ? ec : ENOENT;
1292 call_builtin(struct tbl *tp, const char **wp, const char *where, bool resetspec)
1297 internal_errorf("%s: %s", where, wp[0]);
1298 builtin_argv0 = wp[0];
1299 builtin_spec = tobool(!resetspec && (tp->flag & SPEC_BI));
1300 shf_reopen(1, SHF_WR, shl_stdout);
1301 shl_stdout_ok = true;
1302 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1303 rv = (*tp->val.f)(wp);
1304 shf_flush(shl_stdout);
1305 shl_stdout_ok = false;
1306 builtin_argv0 = NULL;
1307 builtin_spec = false;
1312 * set up redirection, saving old fds in e->savefd
1315 iosetup(struct ioword *iop, struct tbl *tp)
1318 char *cp = iop->name;
1319 int iotype = iop->ioflag & IOTYPE;
1320 bool do_open = true, do_close = false;
1322 struct ioword iotmp;
1325 if (iotype != IOHERE)
1326 cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1328 /* Used for tracing and error messages to print expanded cp */
1330 iotmp.name = (iotype == IOHERE) ? NULL : cp;
1331 iotmp.ioflag |= IONAMEXP;
1333 if (Flag(FXTRACE)) {
1334 change_xtrace(2, false);
1335 fptreef(shl_xtrace, 0, "%R", &iotmp);
1336 change_xtrace(1, false);
1345 flags = O_WRONLY | O_APPEND | O_CREAT;
1349 flags = O_WRONLY | O_CREAT | O_TRUNC;
1351 * The stat() is here to allow redirections to
1352 * things like /dev/null without error.
1354 if (Flag(FNOCLOBBER) && !(iop->ioflag & IOCLOB) &&
1355 (stat(cp, &statb) < 0 || S_ISREG(statb.st_mode)))
1360 flags = O_RDWR | O_CREAT;
1365 /* herein() returns -2 if error has been printed */
1366 u = herein(iop, NULL);
1367 /* cp may have wrong name */
1374 if (*cp == '-' && !cp[1]) {
1375 /* prevent error return below */
1378 } else if ((u = check_fd(cp,
1379 X_OK | ((iop->ioflag & IORDUP) ? R_OK : W_OK),
1383 warningf(true, "%s: %s",
1384 (sp = snptreef(NULL, 32, "%R", &iotmp)), emsg);
1388 if (u == (int)iop->unit)
1389 /* "dup from" == "dup to" */
1396 if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
1397 warningf(true, "%s: %s", cp, "restricted");
1400 u = open(cp, flags | O_BINARY, 0666);
1403 /* herein() may already have printed message */
1406 warningf(true, "can't %s %s: %s",
1407 iotype == IODUP ? "dup" :
1408 (iotype == IOREAD || iotype == IOHERE) ?
1409 "open" : "create", cp, cstrerror(u));
1413 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1414 if (e->savefd[iop->unit] == 0) {
1415 /* If these are the same, it means unit was previously closed */
1416 if (u == (int)iop->unit)
1417 e->savefd[iop->unit] = -1;
1420 * c_exec() assumes e->savefd[fd] set for any
1421 * redirections. Ask savefd() not to close iop->unit;
1422 * this allows error messages to be seen if iop->unit
1423 * is 2; also means we can't lose the fd (eg, both
1424 * dup2 below and dup2 in restfd() failing).
1426 e->savefd[iop->unit] = savefd(iop->unit);
1431 else if (u != (int)iop->unit) {
1432 if (ksh_dup2(u, iop->unit, true) < 0) {
1437 warningf(true, "%s %s %s",
1438 "can't finish (dup) redirection",
1439 (sp = snptreef(NULL, 32, "%R", &iotmp)),
1442 if (iotype != IODUP)
1446 if (iotype != IODUP)
1449 * Touching any co-process fd in an empty exec
1450 * causes the shell to close its copies
1452 else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1453 if (iop->ioflag & IORDUP)
1454 /* possible exec <&p */
1455 coproc_read_close(u);
1457 /* possible exec >&p */
1458 coproc_write_close(u);
1462 /* Clear any write errors */
1463 shf_reopen(2, SHF_WR, shl_out);
1468 * Process here documents by providing the content, either as
1469 * result (globally allocated) string or in a temp file; if
1470 * unquoted, the string is expanded first.
1473 hereinval(const char *content, int sub, char **resbuf, struct shf *shf)
1475 const char * volatile ccp = content;
1476 struct source *s, *osource;
1480 if (kshsetjmp(e->jbuf)) {
1483 /* special to iosetup(): don't print error */
1487 /* do substitutions on the content of heredoc */
1488 s = pushs(SSTRING, ATEMP);
1489 s->start = s->str = ccp;
1491 if (yylex(sub) != LWORD)
1492 internal_errorf("%s: %s", "herein", "yylex");
1494 ccp = evalstr(yylval.cp, DOSCALAR | DOHEREDOC);
1500 strdupx(*resbuf, ccp, APERM);
1507 herein(struct ioword *iop, char **resbuf)
1514 /* ksh -c 'cat <<EOF' can cause this... */
1515 if (iop->heredoc == NULL) {
1516 warningf(true, "%s missing", "here document");
1517 /* special to iosetup(): don't print error */
1521 /* lexer substitution flags */
1522 i = (iop->ioflag & IOEVAL) ? (ONEWORD | HEREDOC) : 0;
1524 /* skip all the fd setup if we just want the value */
1526 return (hereinval(iop->heredoc, i, resbuf, NULL));
1529 * Create temp file to hold content (done before newenv
1530 * so temp doesn't get removed too soon).
1532 h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1533 if (!(shf = h->shf) || (fd = open(h->tffn, O_RDONLY | O_BINARY, 0)) < 0) {
1535 warningf(true, "can't %s temporary file %s: %s",
1536 !shf ? "create" : "open", h->tffn, cstrerror(i));
1539 /* special to iosetup(): don't print error */
1543 if (hereinval(iop->heredoc, i, NULL, shf) == -2) {
1545 /* special to iosetup(): don't print error */
1549 if (shf_close(shf) == -1) {
1552 warningf(true, "can't %s temporary file %s: %s",
1553 "write", h->tffn, cstrerror(i));
1554 /* special to iosetup(): don't print error */
1562 * ksh special - the select command processing section
1563 * print the args in column form - assuming that we can
1566 do_selectargs(const char **ap, bool print_menu)
1568 static const char *read_args[] = {
1569 "read", "-r", "REPLY", NULL
1574 for (argct = 0; ap[argct]; argct++)
1576 while (/* CONSTCOND */ 1) {
1578 * Menu is printed if
1579 * - this is the first time around the select loop
1580 * - the user enters a blank line
1581 * - the REPLY parameter is empty
1583 if (print_menu || !*str_val(global("REPLY")))
1585 shellf("%s", str_val(global("PS3")));
1586 if (call_builtin(findcom("read", FC_BI), read_args, Tselect,
1589 if (*(s = str_val(global("REPLY"))))
1590 return ((getn(s, &i) && i >= 1 && i <= argct) ?
1596 struct select_menu_info {
1597 const char * const *args;
1601 /* format a single select menu item */
1603 select_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1605 const struct select_menu_info *smi =
1606 (const struct select_menu_info *)arg;
1608 shf_snprintf(buf, buflen, "%*u) %s",
1609 smi->num_width, i + 1, smi->args[i]);
1614 * print a select style menu
1617 pr_menu(const char * const *ap)
1619 struct select_menu_info smi;
1620 const char * const *pp;
1621 size_t acols = 0, aocts = 0, i;
1625 * width/column calculations were done once and saved, but this
1626 * means select can't be used recursively so we re-calculate
1627 * each time (could save in a structure that is returned, but
1628 * it's probably not worth the bother)
1632 * get dimensions of the list
1634 for (n = 0, pp = ap; *pp; n++, pp++) {
1638 i = utf_mbswidth(*pp);
1644 * we will print an index of the form "%d) " in front of
1645 * each entry, so get the maximum width of this
1647 for (i = n, smi.num_width = 1; i >= 10; i /= 10)
1651 print_columns(shl_out, n, select_fmt_entry, (void *)&smi,
1652 smi.num_width + 2 + aocts, smi.num_width + 2 + acols,
1657 plain_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1659 strlcpy(buf, ((const char * const *)arg)[i], buflen);
1664 pr_list(char * const *ap)
1666 size_t acols = 0, aocts = 0, i;
1670 for (n = 0, pp = ap; *pp; n++, pp++) {
1674 i = utf_mbswidth(*pp);
1679 print_columns(shl_out, n, plain_fmt_entry, (const void *)ap,
1680 aocts, acols, false);
1684 * [[ ... ]] evaluation routines
1688 * Test if the current token is a whatever. Accepts the current token if
1689 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1690 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1693 dbteste_isa(Test_env *te, Test_meta meta)
1695 Test_op ret = TO_NONOP;
1700 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
1702 /* unquoted word? */
1703 for (p = *te->pos.wp; *p == CHAR; p += 2)
1707 if (meta == TM_UNOP || meta == TM_BINOP) {
1709 /* longer than the longest operator */
1714 while (*p++ == CHAR &&
1715 (size_t)(q - buf) < sizeof(buf) - 1)
1718 ret = test_isop(meta, buf);
1720 } else if (meta == TM_END)
1723 ret = (uqword && !strcmp(*te->pos.wp,
1724 dbtest_tokens[(int)meta])) ? TO_NONNULL : TO_NONOP;
1726 /* Accept the token? */
1727 if (ret != TO_NONOP)
1734 dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
1736 const char *s = *te->pos.wp;
1737 int flags = DOTILDE | DOSCALAR;
1747 if (op == TO_STEQL || op == TO_STNEQ)
1750 return (evalstr(s, flags));
1754 dbteste_error(Test_env *te, int offset, const char *msg)
1756 te->flags |= TEF_ERROR;
1757 internal_warningf("dbteste_error: %s (offset %d)", msg, offset);