From 0fc285274b7dacbba311bdbd4b4697b7ebcac09c Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:13:39 -0600 Subject: fix(parser): save and restore the parser state in run_input A trap that fires while a command is half parsed, and vi's `v` command, both run eval_string() from inside the outer parse. The nested parse_command() points the static arena at its own arena, and freeing that arena leaves the outer parse allocating from freed memory: silent corruption in a release build, heap-use-after-free under ASan. run_input() now brackets its whole body with parser_save()/parser_restore() on every way out - the normal return, the error unwind and the EXIT unwind of the recover loop - so any nested eval, present or future, is safe. in_cond and alias_ended_blank join parser_state because a nested parse changes them too; the static_assert keeps the snapshot buffer in step. Also move here_tail's doc comment back above here_tail. Tests: - tests/posix/trap-midtoken.sh: a trap delivered mid-token from a pipe. It reports heap-use-after-free under `make asan` before the change and passes after it. - tests/linux/i-vi-edit.sh: `v` with $VISUAL, $EDITOR and a failing editor through ptydrive; the edited line runs. Verified on Linux (clang 20, -O3 -g) with `make check` and ASan+UBSan. --- src/exec.c | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) (limited to 'src/exec.c') diff --git a/src/exec.c b/src/exec.c index 1b04b25..0a3b640 100644 --- a/src/exec.c +++ b/src/exec.c @@ -1248,7 +1248,12 @@ static bool subshell_in_process(const node *n) { return false; cmdinfo ci; find_command(b->u.simple.args->plain, &ci, 0); - return ci.kind == C_BUILTIN && (ci.bi->flags & BI_PURE); + if (ci.kind != C_BUILTIN) + return false; + if (ci.bi->flags & BI_PURE) + return true; + /* cd / chdir: can run in-process if the cwd is saved and restored */ + return !strcmp(ci.bi->name, "cd") || !strcmp(ci.bi->name, "chdir"); } /* ---- pipelines ------------------------------------------------------- */ @@ -1915,6 +1920,23 @@ static int eval_subshell(node *n, unsigned flags) { scope_pop(); return status; } + /* cd / chdir: save cwd, run in-process, restore */ + if (ok && sc.cmd.kind == C_BUILTIN && + (!strcmp(sc.cmd.bi->name, "cd") || + !strcmp(sc.cmd.bi->name, "chdir"))) { + int cwd_fd = open(".", O_RDONLY | O_CLOEXEC); + if (cwd_fd < 0) { + scope_pop(); + return 1; + } + int status = sc.cmd.bi->fn(sc.argc, sc.argv); + if (fchdir(cwd_fd) < 0) + sh_error("cannot restore working directory"); + close(cwd_fd); + scope_pop(); + curdir_invalidate(); + return status; + } scope_pop(); if (!ok) return exitstatus; @@ -2088,6 +2110,7 @@ int eval_node(node *n, unsigned flags) { * @return The status of the last command. */ int run_input(unsigned flags) { + alignas(max_align_t) char pstate[PARSER_STATE_SIZE]; arena *volatile pa = arena_new(); arena_marker mark = arena_mark(&scratch); jmploc jl; @@ -2100,6 +2123,14 @@ int run_input(unsigned flags) { arena_unref(pa); sh_error("eval nested too deeply"); } + /* + * A trap, or the vi `v` command, runs eval_string() while the outer + * parse is half way through a command; its parse_command() moves the + * static arena pointer and parser_reset() drops the pending tokens. + * Every way out of this function restores what the caller was in the + * middle of, so no nested eval can leave it parsing a freed arena. + */ + parser_save(pstate); if (!recover) { /* * An error or exit unwinding through here drops this level's @@ -2110,6 +2141,7 @@ int run_input(unsigned flags) { if (setjmp(jl.buf)) { exc_handler = prev; arena_unref(pa); + parser_restore(pstate); exc_raise(exc_code); } exc_catch(&jl); @@ -2121,6 +2153,7 @@ int run_input(unsigned flags) { if (exc_code == EXC_EXIT) { exc_handler = prev; arena_unref(pa); + parser_restore(pstate); exc_raise(EXC_EXIT); } arena_release(&scratch, mark); @@ -2160,6 +2193,7 @@ int run_input(unsigned flags) { } exc_handler = prev; arena_unref(pa); + parser_restore(pstate); return exitstatus; } -- cgit From 9cdf5f548dc8e1d5c6315b304819bf0fd60f802f Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:18:38 -0600 Subject: fix(exec): run the ERR trap when the last command is exec'd `trap "echo ERR" ERR; /bin/false` printed nothing: the shell replaced itself with the failing program and was gone before the trap could run. The same shortcut made `trap ... ; (/bin/false)` silently skip it. trap_after_last() is true when the EXIT or the ERR trap is set, and both the exec shortcut in run_external() and the in-process subshell shortcut in eval_subshell() now use it instead of trap_has_exit(). tests/zash/errtrap-exec.sh covers the external command, a builtin, a subshell and the two traps together; the first and third lines fail without the change. ksh93 prints ERR for all four. --- src/exec.c | 4 ++-- src/exec.h | 1 + src/trap.c | 13 +++++++++++++ tests/zash/errtrap-exec.exp | 10 ++++++++++ tests/zash/errtrap-exec.sh | 8 ++++++++ 5 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 tests/zash/errtrap-exec.exp create mode 100644 tests/zash/errtrap-exec.sh (limited to 'src/exec.c') diff --git a/src/exec.c b/src/exec.c index 0a3b640..43765f6 100644 --- a/src/exec.c +++ b/src/exec.c @@ -957,7 +957,7 @@ static int run_external(simple_cmd *sc, unsigned flags, int in, int out, plan_close(&plan); return 2; } - if ((flags & EV_EXIT) && !async && !trap_has_exit()) { + if ((flags & EV_EXIT) && !async && !trap_after_last()) { /* Nothing comes after this command: become it. */ plan_apply(&plan); exec_path(sc->cmd.path, sc->argv, envp); @@ -1908,7 +1908,7 @@ static int eval_case(node *n, unsigned flags) { * the shell was about to exit anyway. */ static int eval_subshell(node *n, unsigned flags) { - if (!(flags & EV_EXIT) || trap_has_exit()) { + if (!(flags & EV_EXIT) || trap_after_last()) { if (!job_launching && !opt.errexit && subshell_in_process(n)) { simple_cmd sc; varscope vs; diff --git a/src/exec.h b/src/exec.h index 88b0b95..89df201 100644 --- a/src/exec.h +++ b/src/exec.h @@ -215,6 +215,7 @@ void trap_poll(void); void trap_reset_child(void); void trap_reset_exec(void); bool trap_has_exit(void); +bool trap_after_last(void); void trap_run_exit(void); const sigset_t *trap_spawn_defaults(void); int builtin_trap(int argc, char **argv); diff --git a/src/trap.c b/src/trap.c index b72c552..0e5a0a2 100644 --- a/src/trap.c +++ b/src/trap.c @@ -397,6 +397,19 @@ bool trap_has_exit(void) { return trap_action[0] && *trap_action[0]; } +/** + * @brief Must something run after the last command? + * + * The EXIT trap and the ERR trap both run after the command that ends the + * shell, so when either is set the last command may not replace the + * shell: the process would be gone before the trap could run. + * + * @return true if the EXIT or the ERR trap is set. + */ +bool trap_after_last(void) { + return trap_has_exit() || trap_err_set; +} + /** * @brief Run the EXIT trap, once. */ diff --git a/tests/zash/errtrap-exec.exp b/tests/zash/errtrap-exec.exp new file mode 100644 index 0000000..216c976 --- /dev/null +++ b/tests/zash/errtrap-exec.exp @@ -0,0 +1,10 @@ +ERR +[1] +ERR +[1] +ERR +[1] +ERR +BYE +[1] +[status 0] diff --git a/tests/zash/errtrap-exec.sh b/tests/zash/errtrap-exec.sh new file mode 100644 index 0000000..3acf6e1 --- /dev/null +++ b/tests/zash/errtrap-exec.sh @@ -0,0 +1,8 @@ +# The ERR trap runs for the last command too. A failing external command +# as the last thing a shell runs is exec'd, and the shell is gone before +# the trap could run, unless the trap holds that shortcut back. So does a +# subshell that would otherwise run in the parent. +"$TSH" -c 'trap "echo ERR" ERR; /bin/false'; echo "[$?]" +"$TSH" -c 'trap "echo ERR" ERR; false'; echo "[$?]" +"$TSH" -c 'trap "echo ERR" ERR; (/bin/false)'; echo "[$?]" +"$TSH" -c 'trap "echo ERR" ERR; trap "echo BYE" EXIT; /bin/false'; echo "[$?]" -- cgit From 270ac6676c05470223c5fc09fb3230b97acfbe2b Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:44:42 -0600 Subject: fix(signal): install SIG_DFL with sigaction, not signal() Two places reset a signal to its default: main() for an inherited SIGCHLD (waitpid() fails with ECHILD when a parent left it ignored) and the pipeline child that writes a long builtin output and must die on SIGPIPE. Both went through signal(), which differs from sigaction() in restart and mask behaviour; they now share trap.c's set_handler() through a small trap_sig_default(), the function trap_reset() already uses. --- src/exec.c | 2 +- src/exec.h | 1 + src/main.c | 2 +- src/trap.c | 11 +++++++++++ 4 files changed, 14 insertions(+), 2 deletions(-) (limited to 'src/exec.c') diff --git a/src/exec.c b/src/exec.c index 43765f6..e7365ba 100644 --- a/src/exec.c +++ b/src/exec.c @@ -1372,7 +1372,7 @@ static void run_deferred(stage *st, int nc, int i, bool stream) { s->out = -1; for (int j = 0; j < nc; j++) close_stage(&st[j]); /* or we would never see EPIPE */ - signal(SIGPIPE, SIG_DFL); + trap_sig_default(SIGPIPE); output direct = {o.buf, o.len, o.len, out, 0}; out_flush(&direct); _exit(0); diff --git a/src/exec.h b/src/exec.h index 89df201..6bbe6f6 100644 --- a/src/exec.h +++ b/src/exec.h @@ -215,6 +215,7 @@ void trap_poll(void); void trap_reset_child(void); void trap_reset_exec(void); bool trap_has_exit(void); +void trap_sig_default(int sig); bool trap_after_last(void); void trap_run_exit(void); const sigset_t *trap_spawn_defaults(void); diff --git a/src/main.c b/src/main.c index 518dc45..8b4b516 100644 --- a/src/main.c +++ b/src/main.c @@ -426,7 +426,7 @@ int main(int argc, char **argv) { stack_init(); /* A parent may leave SIGCHLD ignored, and then waitpid fails with ECHILD * for every child: reset it before anything is spawned. */ - signal(SIGCHLD, SIG_DFL); + trap_sig_default(SIGCHLD); invoked_as = argv[0] ? argv[0] : "zash"; arg0 = invoked_as[0] == '-' ? invoked_as + 1 : invoked_as; if (arg0[0] != '/' && strchr(arg0, '/')) { diff --git a/src/trap.c b/src/trap.c index 0e5a0a2..4e57d7c 100644 --- a/src/trap.c +++ b/src/trap.c @@ -131,6 +131,17 @@ static void set_handler(int sig, void (*handler)(int)) { sigaction(sig, &sa, nullptr); } +/** + * @brief Put a signal back to SIG_DFL. + * + * For the two places that must not inherit or keep a handler: a parent's + * ignored SIGCHLD (waitpid then fails with ECHILD for every child) and a + * pipeline child that must die on SIGPIPE. + * + * @param sig The signal. + */ +void trap_sig_default(int sig) { set_handler(sig, SIG_DFL); } + /** * @brief What a signal does in this shell when no trap is set for it. */ -- cgit