1 /* $OpenBSD: exec.c,v 1.52 2015/09/10 22:48:58 nicm Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015, 2016
6 * mirabilos <m@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.186 2016/11/11 23:31:34 tg Exp $");
28 #ifndef MKSH_DEFAULT_EXECSHELL
29 #define MKSH_DEFAULT_EXECSHELL MKSH_UNIXROOT "/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 const char *do_selectargs(const char **, bool);
38 static Test_op dbteste_isa(Test_env *, Test_meta);
39 static const char *dbteste_getopnd(Test_env *, Test_op, bool);
40 static void dbteste_error(Test_env *, int, const char *);
41 /* XXX: horrible kludge to fit within the framework */
42 static void plain_fmt_entry(char *, size_t, unsigned int, const void *);
43 static void select_fmt_entry(char *, size_t, unsigned int, const void *);
46 * execute command tree
49 execute(struct op * volatile t,
50 /* if XEXEC don't fork */
52 volatile int * volatile xerrok)
55 volatile int rv = 0, dummy = 0;
57 const char ** volatile ap = NULL;
61 struct tbl *tp = NULL;
66 /* Caller doesn't care if XERROK should propagate. */
70 if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
71 /* run in sub-process */
72 return (exchild(t, flags & ~XTIME, xerrok, -1));
78 /* we want to run an executable, do some variance checks */
79 if (t->type == TCOM) {
81 * Clear subst_exstat before argument expansion. Used by
82 * null commands (see comexec() and c_eval()) and by c_set().
87 current_lineno = t->lineno;
89 /* check if this is 'var=<<EOF' */
91 /* we have zero arguments, i.e. no program to run */
93 /* we have exactly one variable assignment */
94 t->vars[0] != NULL && t->vars[1] == NULL &&
95 /* we have exactly one I/O redirection */
96 t->ioact != NULL && t->ioact[0] != NULL &&
97 t->ioact[1] == NULL &&
98 /* of type "here document" (or "here string") */
99 (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
100 /* the variable assignment begins with a valid varname */
101 (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
102 /* and has no right-hand side (i.e. "varname=") */
103 ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
104 /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
105 ccp[3] == '=' && ccp[4] == EOS))) {
108 if ((rv = herein(t->ioact[0], &cp) /*? 1 : 0*/))
110 dp = shf_smprintf(Tf_ss, evalstr(t->vars[0],
111 DOASNTILDE | DOSCALAR), rv ? null : cp);
112 typeset(dp, Flag(FEXPORT) ? EXPORT : 0, 0, 0, 0);
113 /* free the expanded value */
120 * POSIX says expand command words first, then redirections,
121 * and assignments last..
123 up = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
125 /* Allow option parsing (bizarre, but POSIX) */
127 ap = (const char **)up;
129 tp = findcom(ap[0], FC_BI|FC_FUNC);
133 if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
134 e->savefd = alloc2(NUFILE, sizeof(short), ATEMP);
135 /* initialise to not redirected */
136 memset(e->savefd, 0, NUFILE * sizeof(short));
139 /* mark for replacement later (unless TPIPE) */
140 vp_pipest->flag |= INT_L;
142 /* do redirection, to be restored in quitenv() */
143 if (t->ioact != NULL)
144 for (iowp = t->ioact; *iowp != NULL; iowp++) {
145 if (iosetup(*iowp, tp) < 0) {
148 * Redirection failures for special commands
149 * cause (non-interactive) shell to exit.
151 if (tp && tp->type == CSHELL &&
152 (tp->flag & SPEC_BI))
154 /* Deal with FERREXIT, quitenv(), etc. */
161 rv = comexec(t, tp, (const char **)ap, flags, xerrok);
165 rv = execute(t->left, flags | XFORK, xerrok);
171 e->savefd[0] = savefd(0);
172 e->savefd[1] = savefd(1);
173 while (t->type == TPIPE) {
176 ksh_dup2(pv[1], 1, false);
178 * Let exchild() close pv[0] in child
179 * (if this isn't done, commands like
180 * (: ; cat /etc/termcap) | sleep 1
181 * will hang forever).
183 exchild(t->left, flags | XPIPEO | XCCLOSE,
186 ksh_dup2(pv[0], 0, false);
192 restfd(1, e->savefd[1]);
193 /* no need to re-restore this */
195 /* Let exchild() close 0 in parent, after fork, before wait */
196 i = exchild(t, flags | XPCLOSE | XPIPEST, xerrok, 0);
197 if (!(flags&XBGND) && !(flags&XXCOM))
202 while (t->type == TLIST) {
203 execute(t->left, flags & XERROK, NULL);
206 rv = execute(t, flags & XERROK, xerrok);
210 #ifndef MKSH_NOPROSPECTOFWORK
214 * Block sigchild as we are using things changed in the
217 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
219 if ((i = kshsetjmp(e->jbuf))) {
220 sigprocmask(SIG_SETMASK, &omask, NULL);
226 /* Already have a (live) co-process? */
227 if (coproc.job && coproc.write >= 0)
228 errorf("coprocess already exists");
230 /* Can we re-use the existing co-process pipe? */
231 coproc_cleanup(true);
233 /* do this before opening pipes, in case these fail */
234 e->savefd[0] = savefd(0);
235 e->savefd[1] = savefd(1);
239 ksh_dup2(pv[0], 0, false);
242 coproc.write = pv[1];
245 if (coproc.readw >= 0)
246 ksh_dup2(coproc.readw, 1, false);
250 ksh_dup2(pv[1], 1, false);
251 /* closed before first read */
252 coproc.readw = pv[1];
254 /* create new coprocess id */
257 #ifndef MKSH_NOPROSPECTOFWORK
258 sigprocmask(SIG_SETMASK, &omask, NULL);
259 /* no more need for error handler */
264 * exchild() closes coproc.* in child after fork,
265 * will also increment coproc.njobs when the
266 * job is actually created.
269 exchild(t->left, flags | XBGND | XFORK | XCOPROC | XCCLOSE,
276 * XXX non-optimal, I think - "(foo &)", forks for (),
277 * forks again for async... parent should optimise
280 rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK, xerrok);
285 rv = execute(t->left, XERROK, NULL);
286 if ((rv == 0) == (t->type == TAND))
287 rv = execute(t->right, flags & XERROK, xerrok);
296 rv = !execute(t->right, XERROK, xerrok);
305 te.flags = TEF_DBRACKET;
307 te.isa = dbteste_isa;
308 te.getopnd = dbteste_getopnd;
310 te.error = dbteste_error;
312 rv = test_parse(&te);
318 volatile bool is_first = true;
320 ap = (t->vars == NULL) ? e->loc->argv + 1 :
321 (const char **)eval((const char **)t->vars,
322 DOBLANK | DOGLOB | DOTILDE);
324 while ((i = kshsetjmp(e->jbuf))) {
325 if ((e->flags&EF_BRKCONT_PASS) ||
326 (i != LBREAK && i != LCONTIN)) {
329 } else if (i == LBREAK) {
334 /* in case of a continue */
336 if (t->type == TFOR) {
337 while (*ap != NULL) {
338 setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
339 rv = execute(t->left, flags & XERROK, xerrok);
343 if ((ccp = do_selectargs(ap, is_first))) {
345 setstr(global(t->str), ccp, KSH_UNWIND_ERROR);
346 execute(t->left, flags & XERROK, xerrok);
357 while ((i = kshsetjmp(e->jbuf))) {
358 if ((e->flags&EF_BRKCONT_PASS) ||
359 (i != LBREAK && i != LCONTIN)) {
362 } else if (i == LBREAK) {
367 /* in case of a continue */
369 while ((execute(t->left, XERROK, NULL) == 0) ==
371 rv = execute(t->right, flags & XERROK, xerrok);
376 if (t->right == NULL)
377 /* should be error */
379 rv = execute(t->left, XERROK, NULL) == 0 ?
380 execute(t->right->left, flags & XERROK, xerrok) :
381 execute(t->right->right, flags & XERROK, xerrok);
386 ccp = evalstr(t->str, DOTILDE | DOSCALAR);
387 for (t = t->left; t != NULL && t->type == TPAT; t = t->right) {
388 for (ap = (const char **)t->vars; *ap; ap++) {
389 if (i || ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
390 gmatchx(ccp, s, false))) {
392 rv = execute(t->left, flags & XERROK,
395 switch (t->u.charflag) {
413 rv = execute(t->left, flags & XERROK, xerrok);
417 rv = define(t->str, t);
422 * Clear XEXEC so nested execute() call doesn't exit
423 * (allows "ls -l | time grep foo").
425 rv = timex(t, flags & ~XEXEC, xerrok);
434 union mksh_ccphack cargs;
437 execve(t->str, cargs.rw, up);
441 scriptexec(t, (const char **)up);
443 errorf(Tf_sD_s, t->str, cstrerror(rv));
447 if (vp_pipest->flag & INT_L) {
449 vp_pipest->flag = DEFINED | ISSET | INTEGER | RDONLY |
450 ARRAY | INT_U | INT_L;
451 vp_pipest->val.i = rv;
459 if (rv != 0 && !(flags & XERROK) &&
460 (xerrok == NULL || !*xerrok)) {
461 if (Flag(FERREXIT) & 0x80) {
474 * execute simple command
478 comexec(struct op *t, struct tbl * volatile tp, const char **ap,
479 volatile int flags, volatile int *xerrok)
485 /* Must be static (XXX but why?) */
486 static struct op texec;
489 int fcflags = FC_BI|FC_FUNC|FC_PATH;
490 struct block *l_expand, *l_assign;
492 const char *exec_argv0 = NULL;
493 bool exec_clrenv = false;
495 /* snag the last argument for $_ */
496 if (Flag(FTALKING) && *(lastp = ap)) {
498 * XXX not the same as AT&T ksh, which only seems to set $_
499 * after a newline (but not in functions/dot scripts, but in
500 * interactive and script) - perhaps save last arg here and
501 * set it in shell()?.
505 /* setstr() can't fail here */
506 setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
511 * Deal with the shell builtins builtin, exec and command since
512 * they can be followed by other commands. This must be done before
513 * we know if we should create a local block which must be done
514 * before we can do a path search (in case the assignments change
517 * FOO=bar exec >/dev/null FOO is kept but not exported
518 * FOO=bar exec foobar FOO is exported
519 * FOO=bar command exec >/dev/null FOO is neither kept nor exported
520 * FOO=bar command FOO is neither kept nor exported
521 * PATH=... foobar use new PATH in foobar search
524 while (tp && tp->type == CSHELL) {
525 /* undo effects of command */
526 fcflags = FC_BI|FC_FUNC|FC_PATH;
527 if (tp->val.f == c_builtin) {
528 if ((cp = *++ap) == NULL ||
529 (!strcmp(cp, "--") && (cp = *++ap) == NULL)) {
533 if ((tp = findcom(cp, FC_BI)) == NULL)
534 errorf(Tf_sD_sD_s, Tbuiltin, cp, Tnot_found);
535 if (tp->type == CSHELL && (tp->flag & LOW_BI))
538 } else if (tp->val.f == c_exec) {
541 ksh_getopt_reset(&builtin_opt, GF_ERROR);
542 while ((optc = ksh_getopt(ap, &builtin_opt, "a:c")) != -1)
545 exec_argv0 = builtin_opt.optarg;
549 /* ensure we can actually do this */
556 ap += builtin_opt.optind;
558 } else if (tp->val.f == c_command) {
562 * Ugly dealing with options in two places (here
563 * and in c_command(), but such is life)
565 ksh_getopt_reset(&builtin_opt, 0);
566 while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
569 /* command -vV or something */
571 /* don't look for functions */
572 fcflags = FC_BI|FC_PATH;
574 if (Flag(FRESTRICTED)) {
575 warningf(true, Tf_sD_s,
576 "command -p", "restricted");
580 fcflags |= FC_DEFPATH;
582 ap += builtin_opt.optind;
584 * POSIX says special builtins lose their status
585 * if accessed using command.
589 /* ensure command with no args exits with 0 */
593 } else if (tp->flag & LOW_BI) {
594 /* if we have any flags, do not use the builtin */
595 if ((ap[1] && ap[1][0] == '-' && ap[1][1] != '\0' &&
596 /* argument, begins with -, is not - or -- */
597 (ap[1][1] != '-' || ap[1][2] != '\0')) ||
598 /* always prefer the external utility */
599 (tp->flag & LOWER_BI)) {
602 ext_cmd = findcom(tp->name, FC_PATH | FC_FUNC);
603 if (ext_cmd && (ext_cmd->type != CTALIAS ||
604 (ext_cmd->flag & ISSET)))
608 } else if (tp->val.f == c_trap) {
609 t->u.evalflags &= ~DOTCOMEXEC;
613 tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
615 if (t->u.evalflags & DOTCOMEXEC)
618 if (!resetspec && (!ap[0] || (tp && (tp->flag & KEEPASN))))
621 /* create new variable/function block */
623 /* ksh functions don't keep assignments, POSIX functions do. */
624 if (!resetspec && tp && tp->type == CFUNC &&
628 type_flags = LOCAL|LOCAL_COPY|EXPORT;
632 l_assign->flags |= BF_STOPENV;
634 type_flags |= EXPORT;
636 change_xtrace(2, false);
637 for (i = 0; t->vars[i]; i++) {
638 /* do NOT lookup in the new var/fn block just created */
640 cp = evalstr(t->vars[i], DOASNTILDE | DOSCALAR);
645 ccp = skip_varname(cp, true);
650 shf_write(cp, ccp - cp, shl_xtrace);
651 print_value_quoted(shl_xtrace, ccp);
652 shf_putc(' ', shl_xtrace);
654 /* but assign in there as usual */
655 typeset(cp, type_flags, 0, 0, 0);
659 change_xtrace(2, false);
662 print_value_quoted(shl_xtrace, ap[rv]);
664 shf_putc(' ', shl_xtrace);
668 change_xtrace(1, false);
671 if ((cp = *ap) == NULL) {
675 if (Flag(FRESTRICTED) && mksh_vdirsep(cp)) {
676 warningf(true, Tf_sD_s, cp, "restricted");
680 tp = findcom(cp, fcflags);
688 rv = call_builtin(tp, (const char **)ap, null, resetspec);
689 if (resetspec && tp->val.f == c_shift) {
690 l_expand->argc = l_assign->argc;
691 l_expand->argv = l_assign->argv;
697 volatile uint32_t old_inuse;
698 const char * volatile old_kshname;
699 volatile uint8_t old_flags[FNFLAGS];
701 if (!(tp->flag & ISSET)) {
706 rv = (tp->u2.errnov == ENOENT) ? 127 : 126;
707 warningf(true, Tf_sD_s_sD_s, cp,
708 Tcant_find, Tfile_fd,
709 cstrerror(tp->u2.errnov));
713 if (include(tp->u.fpath, 0, NULL, false) < 0 ||
714 !(ftp = findfunc(cp, hash(cp), false)) ||
715 !(ftp->flag & ISSET)) {
717 if ((ftp = findcom(cp, FC_BI)) &&
718 (ftp->type == CSHELL) &&
719 (ftp->flag & LOW_BI)) {
721 goto do_call_builtin;
728 warningf(true, Tf_sD_s_s, cp,
729 "function not defined by", tp->u.fpath);
737 * ksh functions set $0 to function name, POSIX
738 * functions leave $0 unchanged.
740 old_kshname = kshname;
746 for (i = 0; *ap++ != NULL; i++)
748 e->loc->argc = i - 1;
750 * ksh-style functions handle getopts sanely,
751 * Bourne/POSIX functions are insane...
753 if (tp->flag & FKSH) {
754 e->loc->flags |= BF_DOGETOPTS;
755 e->loc->getopts_state = user_opt;
759 for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
760 old_flags[type_flags] = shell_flags[type_flags];
761 change_xtrace((Flag(FXTRACEREC) ? Flag(FXTRACE) : 0) |
762 ((tp->flag & TRACE) ? 1 : 0), false);
763 old_inuse = tp->flag & FINUSE;
767 if (!(i = kshsetjmp(e->jbuf))) {
768 execute(tp->val.t, flags & XERROK, NULL);
772 kshname = old_kshname;
773 change_xtrace(old_flags[(int)FXTRACE], false);
774 #ifndef MKSH_LEGACY_MODE
775 if (tp->flag & FKSH) {
776 /* Korn style functions restore Flags on return */
777 old_flags[(int)FXTRACE] = Flag(FXTRACE);
778 for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
779 shell_flags[type_flags] = old_flags[type_flags];
782 tp->flag = (tp->flag & ~FINUSE) | old_inuse;
785 * Were we deleted while executing? If so, free the
788 if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
789 if (tp->flag & ALLOC) {
791 tfree(tp->val.t, tp->areap);
809 internal_errorf(Tf_sd, "CFUNC", i);
814 /* executable command */
818 if (!(tp->flag&ISSET)) {
819 if (tp->u2.errnov == ENOENT) {
821 warningf(true, Tf_sD_s, cp, Tnot_found);
824 warningf(true, Tf_sD_sD_s, cp, "can't execute",
825 cstrerror(tp->u2.errnov));
830 /* set $_ to program's full path */
831 /* setstr() can't fail here */
832 setstr(typeset("_", LOCAL | EXPORT, 0, INTEGER, 0),
833 tp->val.s, KSH_RETURN_ERROR);
835 /* to fork, we set up a TEXEC node and call execute */
837 /* for vistree/dumptree */
839 texec.str = tp->val.s;
842 /* in this case we do not fork, of course */
845 texec.args[0] = exec_argv0;
848 #ifndef MKSH_UNEMPLOYED
852 setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
853 setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
857 rv = exchild(&texec, flags, xerrok, -1);
869 scriptexec(struct op *tp, const char **ap)
874 unsigned char buf[68];
876 union mksh_ccphack args, cap;
878 sh = str_val(global(TEXECSHELL));
880 sh = search_path(sh, path, X_OK, NULL);
882 sh = MKSH_DEFAULT_EXECSHELL;
884 *tp->args-- = tp->str;
887 if ((fd = binopen2(tp->str, O_RDONLY)) >= 0) {
892 /* read first couple of octets from file */
893 n = read(fd, buf, sizeof(buf) - 1);
895 /* read error or short read? */
898 /* terminate buffer */
901 /* skip UTF-8 Byte Order Mark, if present */
902 cp = buf + (n = ((buf[0] == 0xEF) && (buf[1] == 0xBB) &&
903 (buf[2] == 0xBF)) ? 3 : 0);
905 /* scan for newline or NUL (end of buffer) */
906 while (*cp && *cp != '\n')
908 /* if the shebang line is longer than MAXINTERP, bail out */
911 /* replace newline by NUL */
914 /* restore start of shebang position (buf+0 or buf+3) */
916 /* bail out if no shebang magic found */
917 if (cp[0] == '#' && cp[1] == '!')
920 else if (!strncmp(cp, Textproc, 7) &&
921 (cp[7] == ' ' || cp[7] == '\t'))
926 /* skip whitespace before shell name */
927 while (*cp == ' ' || *cp == '\t')
929 /* just whitespace on the line? */
932 /* no, we actually found an interpreter name */
934 /* look for end of shell/interpreter name */
935 while (*cp != ' ' && *cp != '\t' && *cp != '\0')
940 /* skip spaces before arguments */
941 while (*cp == ' ' || *cp == '\t')
943 /* pass it all in ONE argument (historic reasons) */
945 *tp->args-- = (char *)cp;
949 m = buf[0] << 8 | buf[1];
950 if (m == 0x7F45 && buf[2] == 'L' && buf[3] == 'F')
951 errorf("%s: not executable: %d-bit ELF file", tp->str,
953 if ((m == /* OMAGIC */ 0407) ||
954 (m == /* NMAGIC */ 0410) ||
955 (m == /* ZMAGIC */ 0413) ||
956 (m == /* QMAGIC */ 0314) ||
957 (m == /* ECOFF_I386 */ 0x4C01) ||
958 (m == /* ECOFF_M68K */ 0x0150 || m == 0x5001) ||
959 (m == /* ECOFF_SH */ 0x0500 || m == 0x0005) ||
960 (m == /* bzip */ 0x425A) || (m == /* "MZ" */ 0x4D5A) ||
961 (m == /* "NE" */ 0x4E45) || (m == /* "LX" */ 0x4C58) ||
962 (m == /* ksh93 */ 0x0B13) || (m == /* LZIP */ 0x4C5A) ||
963 (m == /* xz */ 0xFD37 && buf[2] == 'z' && buf[3] == 'X' &&
964 buf[4] == 'Z') || (m == /* 7zip */ 0x377A) ||
965 (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D))
966 errorf("%s: not executable: magic %04X", tp->str, m);
975 execve(args.rw[0], args.rw, cap.rw);
977 /* report both the programme that was run and the bogus interpreter */
978 errorf(Tf_sD_sD_s, tp->str, sh, cstrerror(errno));
982 shcomexec(const char **wp)
986 tp = ktsearch(&builtins, *wp, hash(*wp));
987 return (call_builtin(tp, wp, "shcomexec", false));
991 * Search function tables for a function. If create set, a table entry
992 * is created if none is found.
995 findfunc(const char *name, uint32_t h, bool create)
998 struct tbl *tp = NULL;
1000 for (l = e->loc; l; l = l->next) {
1001 tp = ktsearch(&l->funs, name, h);
1004 if (!l->next && create) {
1005 tp = ktenter(&l->funs, name, h);
1016 * define function. Returns 1 if function is being undefined (t == 0) and
1017 * function did not exist, returns 0 otherwise.
1020 define(const char *name, struct op *t)
1024 bool was_set = false;
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|FKSH);
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 */
1078 /* command does variable assignment */
1082 /* POSIX special builtin */
1086 /* external utility overrides built-in utility, always */
1090 /* external utility overrides built-in utility, with flags */
1100 /* enter into the builtins hash table */
1101 tp = ktenter(&builtins, name, hash(name));
1106 /* return name, for direct builtin call check in main.c */
1112 * either function, hashed command, or built-in (in that order)
1115 findcom(const char *name, int flags)
1117 static struct tbl temp;
1118 uint32_t h = hash(name);
1119 struct tbl *tp = NULL, *tbi;
1120 /* insert if not found */
1121 unsigned char insert = Flag(FTRACKALL);
1122 /* for function autoloading */
1124 union mksh_cchack npath;
1126 if (mksh_vdirsep(name)) {
1128 /* prevent FPATH search below */
1132 tbi = (flags & FC_BI) ? ktsearch(&builtins, name, h) : NULL;
1134 * POSIX says special builtins first, then functions, then
1135 * regular builtins, then search path...
1137 if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
1139 if (!tp && (flags & FC_FUNC)) {
1140 tp = findfunc(name, h, false);
1141 if (tp && !(tp->flag & ISSET)) {
1142 if ((fpath = str_val(global(TFPATH))) == null) {
1144 tp->u2.errnov = ENOENT;
1146 tp->u.fpath = search_path(name, fpath, R_OK,
1150 if (!tp && (flags & FC_NORMBI) && tbi)
1152 if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
1153 tp = ktsearch(&taliases, name, h);
1154 if (tp && (tp->flag & ISSET) &&
1155 ksh_access(tp->val.s, X_OK) != 0) {
1156 if (tp->flag & ALLOC) {
1158 afree(tp->val.s, APERM);
1165 if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
1166 (flags & FC_PATH)) {
1168 if (insert && !(flags & FC_DEFPATH)) {
1169 tp = ktenter(&taliases, name, h);
1178 npath.ro = search_path(name,
1179 (flags & FC_DEFPATH) ? def_path : path,
1180 X_OK, &tp->u2.errnov);
1182 strdupx(tp->val.s, npath.ro, APERM);
1183 if (npath.ro != name)
1184 afree(npath.rw, ATEMP);
1185 tp->flag |= ISSET|ALLOC;
1186 } else if ((flags & FC_FUNC) &&
1187 (fpath = str_val(global(TFPATH))) != null &&
1188 (npath.ro = search_path(name, fpath, R_OK,
1189 &tp->u2.errnov)) != NULL) {
1191 * An undocumented feature of AT&T ksh is that
1192 * it searches FPATH if a command is not found,
1193 * even if the command hasn't been set up as an
1194 * autoloaded function (ie, no typeset -uf).
1200 tp->u.fpath = npath.ro;
1207 * flush executable commands with relative paths
1208 * (just relative or all?)
1216 for (ktwalk(&ts, &taliases); (tp = ktnext(&ts)) != NULL; )
1217 if ((tp->flag&ISSET) && (all || !mksh_abspath(tp->val.s))) {
1218 if (tp->flag&ALLOC) {
1219 tp->flag &= ~(ALLOC|ISSET);
1220 afree(tp->val.s, APERM);
1226 /* check if path is something we want to find */
1228 search_access(const char *fn, int mode)
1232 if (stat(fn, &sb) < 0)
1233 /* file does not exist */
1235 /* LINTED use of access */
1236 if (access(fn, mode) < 0) {
1237 /* file exists, but we can't access it */
1241 return (eno ? eno : EACCES);
1244 /* treat all files as executable on OS/2 */
1245 sb.st_mode &= S_IXUSR | S_IXGRP | S_IXOTH;
1247 if (mode == X_OK && (!S_ISREG(sb.st_mode) ||
1248 !(sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
1249 /* access(2) may say root can execute everything */
1250 return (S_ISDIR(sb.st_mode) ? EISDIR : EACCES);
1255 * search for command with PATH
1258 search_path(const char *name, const char *lpath,
1261 /* set if candidate found, but not suitable */
1270 if (mksh_vdirsep(name)) {
1271 if ((ec = search_access(name, mode)) == 0) {
1277 goto search_path_err;
1280 namelen = strlen(name) + 1;
1281 Xinit(xs, xp, 128, ATEMP);
1284 while (sp != NULL) {
1285 xp = Xstring(xs, xp);
1286 if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
1287 p = sp + strlen(sp);
1289 XcheckN(xs, xp, p - sp);
1290 memcpy(xp, sp, p - sp);
1295 XcheckN(xs, xp, namelen);
1296 memcpy(xp, name, namelen);
1297 if ((ev = search_access(Xstring(xs, xp), mode)) == 0) {
1298 name = Xclose(xs, xp + namelen);
1299 goto search_path_ok;
1301 /* accumulate non-ENOENT errors only */
1302 if (ev != ENOENT && ec == 0)
1310 *errnop = ec ? ec : ENOENT;
1315 call_builtin(struct tbl *tp, const char **wp, const char *where, bool resetspec)
1320 internal_errorf(Tf_sD_s, where, wp[0]);
1321 builtin_argv0 = wp[0];
1322 builtin_spec = tobool(!resetspec &&
1323 /*XXX odd use of KEEPASN */
1324 ((tp->flag & SPEC_BI) || (Flag(FPOSIX) && (tp->flag & KEEPASN))));
1325 shf_reopen(1, SHF_WR, shl_stdout);
1326 shl_stdout_ok = true;
1327 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1328 rv = (*tp->val.f)(wp);
1329 shf_flush(shl_stdout);
1330 shl_stdout_ok = false;
1331 builtin_argv0 = NULL;
1332 builtin_spec = false;
1337 * set up redirection, saving old fds in e->savefd
1340 iosetup(struct ioword *iop, struct tbl *tp)
1343 char *cp = iop->ioname;
1344 int iotype = iop->ioflag & IOTYPE;
1345 bool do_open = true, do_close = false, do_fstat = false;
1347 struct ioword iotmp;
1350 if (iotype != IOHERE)
1351 cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1353 /* Used for tracing and error messages to print expanded cp */
1355 iotmp.ioname = (iotype == IOHERE) ? NULL : cp;
1356 iotmp.ioflag |= IONAMEXP;
1358 if (Flag(FXTRACE)) {
1359 change_xtrace(2, false);
1360 fptreef(shl_xtrace, 0, Tft_R, &iotmp);
1361 change_xtrace(1, false);
1370 flags = O_WRONLY | O_APPEND | O_CREAT;
1374 if (Flag(FNOCLOBBER) && !(iop->ioflag & IOCLOB)) {
1375 /* >file under set -C */
1376 if (stat(cp, &statb)) {
1377 /* nonexistent file */
1378 flags = O_WRONLY | O_CREAT | O_EXCL;
1379 } else if (S_ISREG(statb.st_mode)) {
1380 /* regular file, refuse clobbering */
1381 goto clobber_refused;
1384 * allow redirections to things
1385 * like /dev/null without error
1388 /* but check again after opening */
1392 /* >|file or set +C */
1393 flags = O_WRONLY | O_CREAT | O_TRUNC;
1398 flags = O_RDWR | O_CREAT;
1403 /* herein() returns -2 if error has been printed */
1404 u = herein(iop, NULL);
1405 /* cp may have wrong name */
1412 if (ksh_isdash(cp)) {
1413 /* prevent error return below */
1416 } else if ((u = check_fd(cp,
1417 X_OK | ((iop->ioflag & IORDUP) ? R_OK : W_OK),
1421 warningf(true, Tf_sD_s,
1422 (sp = snptreef(NULL, 32, Tft_R, &iotmp)), emsg);
1426 if (u == (int)iop->unit)
1427 /* "dup from" == "dup to" */
1434 if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
1435 warningf(true, Tf_sD_s, cp, "restricted");
1438 u = binopen3(cp, flags, 0666);
1439 if (do_fstat && u >= 0) {
1440 /* prevent race conditions */
1441 if (fstat(u, &statb) || S_ISREG(statb.st_mode)) {
1450 /* herein() may already have printed message */
1453 warningf(true, Tf_cant,
1454 iotype == IODUP ? "dup" :
1455 (iotype == IOREAD || iotype == IOHERE) ?
1456 Topen : Tcreate, cp, cstrerror(u));
1460 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1461 if (e->savefd[iop->unit] == 0) {
1462 /* If these are the same, it means unit was previously closed */
1463 if (u == (int)iop->unit)
1464 e->savefd[iop->unit] = -1;
1467 * c_exec() assumes e->savefd[fd] set for any
1468 * redirections. Ask savefd() not to close iop->unit;
1469 * this allows error messages to be seen if iop->unit
1470 * is 2; also means we can't lose the fd (eg, both
1471 * dup2 below and dup2 in restfd() failing).
1473 e->savefd[iop->unit] = savefd(iop->unit);
1478 else if (u != (int)iop->unit) {
1479 if (ksh_dup2(u, iop->unit, true) < 0) {
1484 warningf(true, Tf_s_sD_s, Tredirection_dup,
1485 (sp = snptreef(NULL, 32, Tft_R, &iotmp)),
1488 if (iotype != IODUP)
1492 if (iotype != IODUP)
1495 * Touching any co-process fd in an empty exec
1496 * causes the shell to close its copies
1498 else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1499 if (iop->ioflag & IORDUP)
1500 /* possible exec <&p */
1501 coproc_read_close(u);
1503 /* possible exec >&p */
1504 coproc_write_close(u);
1508 /* Clear any write errors */
1509 shf_reopen(2, SHF_WR, shl_out);
1514 * Process here documents by providing the content, either as
1515 * result (globally allocated) string or in a temp file; if
1516 * unquoted, the string is expanded first.
1519 hereinval(struct ioword *iop, int sub, char **resbuf, struct shf *shf)
1521 const char * volatile ccp = iop->heredoc;
1522 struct source *s, *osource;
1526 if (kshsetjmp(e->jbuf)) {
1529 /* special to iosetup(): don't print error */
1532 if (iop->ioflag & IOHERESTR) {
1533 ccp = evalstr(iop->delim, DOHERESTR | DOSCALAR | DOHEREDOC);
1535 /* do substitutions on the content of heredoc */
1536 s = pushs(SSTRING, ATEMP);
1537 s->start = s->str = ccp;
1539 if (yylex(sub) != LWORD)
1540 internal_errorf("herein: yylex");
1542 ccp = evalstr(yylval.cp, DOSCALAR | DOHEREDOC);
1548 strdupx(*resbuf, ccp, APERM);
1555 herein(struct ioword *iop, char **resbuf)
1562 /* lexer substitution flags */
1563 i = (iop->ioflag & IOEVAL) ? (ONEWORD | HEREDOC) : 0;
1565 /* skip all the fd setup if we just want the value */
1567 return (hereinval(iop, i, resbuf, NULL));
1570 * Create temp file to hold content (done before newenv
1571 * so temp doesn't get removed too soon).
1573 h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1574 if (!(shf = h->shf) || (fd = binopen3(h->tffn, O_RDONLY, 0)) < 0) {
1576 warningf(true, Tf_temp,
1577 !shf ? Tcreate : Topen, h->tffn, cstrerror(i));
1580 /* special to iosetup(): don't print error */
1584 if (hereinval(iop, i, NULL, shf) == -2) {
1586 /* special to iosetup(): don't print error */
1590 if (shf_close(shf) == -1) {
1593 warningf(true, Tf_temp,
1594 Twrite, h->tffn, cstrerror(i));
1595 /* special to iosetup(): don't print error */
1603 * ksh special - the select command processing section
1604 * print the args in column form - assuming that we can
1607 do_selectargs(const char **ap, bool print_menu)
1609 static const char *read_args[] = {
1610 Tread, "-r", "REPLY", NULL
1615 for (argct = 0; ap[argct]; argct++)
1617 while (/* CONSTCOND */ 1) {
1619 * Menu is printed if
1620 * - this is the first time around the select loop
1621 * - the user enters a blank line
1622 * - the REPLY parameter is empty
1624 if (print_menu || !*str_val(global("REPLY")))
1626 shellf(Tf_s, str_val(global("PS3")));
1627 if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect,
1630 if (*(s = str_val(global("REPLY"))))
1631 return ((getn(s, &i) && i >= 1 && i <= argct) ?
1637 struct select_menu_info {
1638 const char * const *args;
1642 /* format a single select menu item */
1644 select_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1646 const struct select_menu_info *smi =
1647 (const struct select_menu_info *)arg;
1649 shf_snprintf(buf, buflen, "%*u) %s",
1650 smi->num_width, i + 1, smi->args[i]);
1654 * print a select style menu
1657 pr_menu(const char * const *ap)
1659 struct select_menu_info smi;
1660 const char * const *pp;
1661 size_t acols = 0, aocts = 0, i;
1663 struct columnise_opts co;
1666 * width/column calculations were done once and saved, but this
1667 * means select can't be used recursively so we re-calculate
1668 * each time (could save in a structure that is returned, but
1669 * it's probably not worth the bother)
1673 * get dimensions of the list
1675 for (n = 0, pp = ap; *pp; n++, pp++) {
1679 i = utf_mbswidth(*pp);
1685 * we will print an index of the form "%d) " in front of
1686 * each entry, so get the maximum width of this
1688 for (i = n, smi.num_width = 1; i >= 10; i /= 10)
1694 co.prefcol = co.do_last = true;
1695 print_columns(&co, n, select_fmt_entry, (void *)&smi,
1696 smi.num_width + 2 + aocts, smi.num_width + 2 + acols);
1700 plain_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1702 strlcpy(buf, ((const char * const *)arg)[i], buflen);
1706 pr_list(struct columnise_opts *cop, char * const *ap)
1708 size_t acols = 0, aocts = 0, i;
1712 for (n = 0, pp = ap; *pp; n++, pp++) {
1716 i = utf_mbswidth(*pp);
1721 print_columns(cop, n, plain_fmt_entry, (const void *)ap,
1726 * [[ ... ]] evaluation routines
1730 * Test if the current token is a whatever. Accepts the current token if
1731 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1732 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1735 dbteste_isa(Test_env *te, Test_meta meta)
1737 Test_op ret = TO_NONOP;
1742 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
1744 /* unquoted word? */
1745 for (p = *te->pos.wp; *p == CHAR; p += 2)
1749 if (meta == TM_UNOP || meta == TM_BINOP) {
1751 /* longer than the longest operator */
1756 while (*p++ == CHAR &&
1757 (size_t)(q - buf) < sizeof(buf) - 1)
1760 ret = test_isop(meta, buf);
1762 } else if (meta == TM_END)
1765 ret = (uqword && !strcmp(*te->pos.wp,
1766 dbtest_tokens[(int)meta])) ? TO_NONNULL : TO_NONOP;
1768 /* Accept the token? */
1769 if (ret != TO_NONOP)
1776 dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
1778 const char *s = *te->pos.wp;
1779 int flags = DOTILDE | DOSCALAR;
1789 if (op == TO_STEQL || op == TO_STNEQ)
1792 return (evalstr(s, flags));
1796 dbteste_error(Test_env *te, int offset, const char *msg)
1798 te->flags |= TEF_ERROR;
1799 internal_warningf("dbteste_error: %s (offset %d)", msg, offset);