diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-28 14:34:40 -0600 |
|---|---|---|
| committer | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-28 14:34:40 -0600 |
| commit | 78d73092a29cca7e3ce4ef6b5e2c6cd244f40202 (patch) | |
| tree | 11e54f24ebb2d3f528ec31ac467fa864fe92595b /src/exec.c | |
| parent | 93bbcf2f9a75bb5090d96ec9908594e15aa5908b (diff) | |
| parent | 95d31d2d7d5fd7de81d6d5e2caedcdc369ca0fcf (diff) | |
| download | zash-78d73092a29cca7e3ce4ef6b5e2c6cd244f40202.tar.gz | |
Merge main into perf/cd-inproc: one in-process `( cd dir )`, not two
main gained an in-process `( cd dir )` of its own with the 2026-11-28
review merge (the uncommitted working tree the review was written
against, committed as cb1688f), so this branch and main both replaced
the fork for the same command, in two places.
That copy has a defect this branch guards against: with
readonly PWD; ( cd / ); echo after
the readonly assignment raises out of the saved-cwd block and kills the
whole shell - no `after` - where dash and bash both print it (dash rc=2,
bash rc=1). `subshell_in_process()` here refuses to run the `cd`
in-process unless PWD and OLDPWD are plain, and `builtin_cd_isolated()`
holds its own exception handler, so the fork still happens in that case.
Resolution: keep this branch's implementation and drop main's ad-hoc
branch in eval_subshell() together with the curdir_invalidate() helper
added for it, which had no other caller. The tests main brought with it
(tests/zash/subshell-cd.sh, tests/proc/subshell-pure.sh) still pass.
Verified on Linux (7.3.4-300.fc45.x86_64, 2026-11-28): make check 127
passed / 1 skipped / the known linux/i-dscomplete failure, make asan and
make valgrind the same, make mvs-asan 127 passed, make zos-lint clean,
the readonly-PWD case now matches dash. Not re-run on cbt.
Diffstat (limited to 'src/exec.c')
| -rw-r--r-- | src/exec.c | 223 |
1 files changed, 152 insertions, 71 deletions
@@ -9,6 +9,7 @@ * parent: its arguments, its environment and a plan for its descriptors. */ #include "exec.h" +#include "var.h" #include <errno.h> #include <fcntl.h> @@ -488,26 +489,6 @@ void exec_init(void) { var_find("OPTIND", 6, true)->hook = getopts_reset; } -/* ---- unwinding ------------------------------------------------------- */ - -/** - * @brief Record the state an exception handler must put back. - */ -void unwind_save(unwind *u) { - u->scope = var_scope; - u->redir = redir_top; - u->input = input; -} - -/** - * @brief Undo redirections, variable scopes and inputs back to a saved state. - */ -void unwind_restore(const unwind *u) { - redir_unwind(u->redir); - scope_unwind(u->scope); - input_unwind(u->input); -} - /* ---- processes ------------------------------------------------------- */ /** @@ -546,7 +527,7 @@ pid_t fork_shell(void) { [[noreturn]] static void child_eval(node *n) { jmploc jl; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); eval_node(n, EV_EXIT); } exit_shell(exitstatus); @@ -627,7 +608,8 @@ static int exec_error(const char *name, int err) { */ [[noreturn]] static void exec_path(const char *path, char **argv, char **envp) { flush_all(); - trap_reset_child(); + trap_reset_exec(); /* not trap_reset_child: see below, a failed exec runs + * the EXIT trap */ COVERAGE_FLUSH(); execve(path, argv, envp); if (errno == ENOEXEC) { @@ -637,29 +619,63 @@ static int exec_error(const char *name, int err) { } int status = exec_error(argv[0], errno); flush_all(); - _exit(status); + exit_shell(status); /* runs the EXIT trap */ } /** - * @brief The `exec` builtin with a command: find it and replace the shell. + * @brief Find the program `exec` should run. + * @return Its path, or nullptr if it is not found. */ -void shell_exec(char **argv, char **envp) { +static const char *exec_lookup(char **argv) { cmdinfo ci; find_command(argv[0], &ci, FC_NOFUNC); - const char *path = ci.kind == C_EXTERNAL ? ci.path : nullptr; - if (!path && !strchr(argv[0], '/')) { - const char *search = var_get("PATH"); - path = path_search(argv[0], search ? search : default_path, true); - } + if (ci.kind == C_EXTERNAL) + return ci.path; + if (strchr(argv[0], '/')) + return nullptr; + const char *search = var_get("PATH"); + return path_search(argv[0], search ? search : default_path, true); +} + +/** + * @brief The `exec` builtin with a command: find it and replace the shell. + */ +void shell_exec(char **argv, char **envp) { + const char *path = exec_lookup(argv); if (!path) { int status = exec_error(argv[0], ENOENT); flush_all(); - _exit(status); + exit_shell(status); } exec_path(path, argv, envp); } /** + * @brief `exec` for a shell that must survive a failure. + * + * POSIX 2.8.1: a special built-in that fails does not end an interactive + * shell, so the error is reported and returned. The program is exec'd + * without resetting the shell's traps first, since it may still be here + * afterwards. + * + * @return The status to report if the exec did not happen. + */ +int shell_exec_try(char **argv, char **envp) { + const char *path = exec_lookup(argv); + if (!path) + return exec_error(argv[0], ENOENT); + flush_all(); + COVERAGE_FLUSH(); + execve(path, argv, envp); + if (errno == ENOEXEC) { + char **nv = script_argv(path, argv); + if (nv) + execve(nv[0], nv, envp); + } + return exec_error(argv[0], errno); +} + +/** * @brief spawn() a program. * * On failure the message goes where the command's own stderr would have @@ -814,14 +830,11 @@ static void simple_prep(node *n, simple_cmd *sc) { static bool guarded_prep(node *n, simple_cmd *sc) { jmploc jl; jmploc *prev = exc_handler; - unwind u; bool ok = true; - unwind_save(&u); if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); simple_prep(n, sc); } else { - unwind_restore(&u); ok = false; } exc_handler = prev; @@ -944,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); @@ -1004,8 +1017,6 @@ static int finish_builtin(int status) { static int run_special_guarded(const builtin *bi, simple_cmd *sc) { jmploc jl; jmploc *prev = exc_handler; - unwind u; - unwind_save(&u); arena_marker mark = arena_mark(&scratch); int saved_loop = loop_depth; int saved_dot = dot_depth; @@ -1014,7 +1025,6 @@ static int run_special_guarded(const builtin *bi, simple_cmd *sc) { exc_handler = prev; if (exc_code == EXC_EXIT) exc_raise(EXC_EXIT); - unwind_restore(&u); arena_release(&scratch, mark); loop_depth = saved_loop; dot_depth = saved_dot; @@ -1022,7 +1032,7 @@ static int run_special_guarded(const builtin *bi, simple_cmd *sc) { skip_kind = SKIP_NONE; return exitstatus ? exitstatus : 2; } - exc_handler = &jl; + exc_catch(&jl); int status = bi->fn(sc->argc, sc->argv); exc_handler = prev; return status; @@ -1059,8 +1069,10 @@ static int run_builtin(simple_cmd *sc) { status = finish_builtin(sc->via_command && (bi->flags & BI_SPECIAL) ? run_special_guarded(bi, sc) : bi->fn(sc->argc, sc->argv)); + /* `exec >file` keeps the redirections; a failed `exec cmd` must put + * the shell's own descriptors back. */ if (n->redirs) - redir_pop(bi->fn == builtin_exec); + redir_pop(bi->fn == builtin_exec && sc->argc <= 1); } if (scoped) scope_pop(); @@ -1089,7 +1101,7 @@ int call_function(func *fn, int argc, char **argv, unsigned flags) { loop_depth = 0; shellparam = (shparam){argc - 1, argv + 1, nullptr}; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); eval_node(fn->body, flags & EV_TESTED); } else { raised = true; @@ -1177,7 +1189,7 @@ static int simple_run(simple_cmd *sc, unsigned flags) { [[noreturn]] static void child_simple(simple_cmd *sc) { jmploc jl; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); exitstatus = simple_run(sc, EV_EXIT); } exit_shell(exitstatus); @@ -1203,16 +1215,13 @@ static int run_pure(simple_cmd *sc, output *o) { output saved = out1; jmploc jl; jmploc *prev = exc_handler; - unwind u; int status; - unwind_save(&u); out1 = *o; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); status = sc->cmd.bi->fn(sc->argc, sc->argv); } else { - unwind_restore(&u); status = exitstatus ? exitstatus : 2; } exc_handler = prev; @@ -1362,7 +1371,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); @@ -1459,7 +1468,8 @@ static int eval_pipe(node *n, unsigned flags, strbuf *cap) { * every stage is a process, the last included: a stage running inside * the shell could not be stopped with the rest of the job. */ - job *jb = !cap && jc_active() && !job_launching ? job_begin(n, true) : nullptr; + job *jb = + !cap && jc_active() && !job_launching ? job_begin(n, true) : nullptr; varscope vs; scope_push(&vs, true, false); bool any_deferred = false; @@ -1492,11 +1502,9 @@ static int eval_pipe(node *n, unsigned flags, strbuf *cap) { */ jmploc jl; jmploc *prev = exc_handler; - unwind u; volatile bool raised = false; - unwind_save(&u); if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); bool last_started = false; if (lc->kind == N_SIMPLE) { simple_prep(lc, &last->sc); @@ -1530,8 +1538,15 @@ static int eval_pipe(node *n, unsigned flags, strbuf *cap) { redir_pop(false); } } else { - unwind_restore(&u); - raised = true; + /* + * A fatal error in the stage ends the stage, not the script: ksh93 + * and dash both run on after `echo x | echo "${unset?}"`. Only + * `exit` in the last stage ends the shell. + */ + if (exc_code == EXC_EXIT) + raised = true; + else + last->status = exitstatus; } exc_handler = prev; @@ -1791,27 +1806,84 @@ static int eval_loop(node *n, unsigned flags) { } /** - * @brief Run a `for` loop. + * @brief Run one `select` pass: menu, prompt, one line of answer. + * + * Kept apart from eval_for() only so the `for` case stays readable. + * + * @param n The loop node. + * @param flags Evaluation flags. + * @param words The words the menu offers. + * @param count How many there are. + * @return The status of the last command run in the body. + */ +static int select_loop(node *n, unsigned flags, char **words, int count) { + int status = 0; + for (;;) { + for (int i = 0; i < count; i++) + out_printf(&out2, "%d\t%s\n", i + 1, words[i]); + const char *ps3 = var_get("PS3"); + out_puts(&out2, ps3 ? ps3 : "#? "); + out_flush(&out2); + if (builtin_read_reply() != 0) /* end of input ends the loop */ + break; + const char *reply = var_get("REPLY"); + if (!reply || !*reply) /* a blank line only prompts again */ + continue; + char *end; + long pick = strtol(reply, &end, 10); + bool chosen = *end == '\0' && pick >= 1 && pick <= count; + var_set(n->u.for_.var, chosen ? words[pick - 1] : "", 0); + status = eval_node(n->u.for_.body, flags & EV_TESTED); + if (loop_should_stop()) + break; + } + return status; +} + +/** + * @brief Run a `for` or `select` loop. */ static int eval_for(node *n, unsigned flags) { int count; char **words; + shparam held = {0, nullptr, nullptr}; if (n->u.for_.has_in) { words = expand_words(n->u.for_.words, &count); } else { - count = shellparam.n; + /* A `set --` in the body replaces the parameters, so the words this + * loop iterates over need a reference of their own. */ + held = shellparam; + params_hold(&held); + count = held.n; words = arena_alloc(&scratch, ((size_t)count + 1) * sizeof *words); - memcpy(words, shellparam.p, (size_t)count * sizeof *words); + memcpy(words, held.p, (size_t)count * sizeof *words); } - int status = 0; - loop_depth++; - for (int i = 0; i < count; i++) { - var_set(n->u.for_.var, words[i], 0); - status = eval_node(n->u.for_.body, flags & EV_TESTED); - if (loop_should_stop()) - break; + volatile int status = 0; + jmploc jl; + jmploc *prev = exc_handler; + volatile bool raised = false; + if (setjmp(jl.buf) == 0) { + exc_catch(&jl); + loop_depth++; + if (n->u.for_.menu) { + status = select_loop(n, flags, words, count); + } else { + for (int i = 0; i < count; i++) { + var_set(n->u.for_.var, words[i], 0); + status = eval_node(n->u.for_.body, flags & EV_TESTED); + if (loop_should_stop()) + break; + } + } + loop_depth--; + } else { + loop_depth--; + raised = true; } - loop_depth--; + exc_handler = prev; + params_free(&held); + if (raised) + exc_raise(exc_code); return status; } @@ -1835,7 +1907,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; @@ -2026,20 +2098,27 @@ 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; jmploc *prev = exc_handler; - unwind u; int saved_loop = loop_depth; bool recover = ((flags & RI_TOP) && opt.interactive) || (flags & RI_RECOVER); - unwind_save(&u); if (stack_low()) { 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 @@ -2050,9 +2129,10 @@ int run_input(unsigned flags) { if (setjmp(jl.buf)) { exc_handler = prev; arena_unref(pa); + parser_restore(pstate); exc_raise(exc_code); } - exc_handler = &jl; + exc_catch(&jl); } for (;;) { if (recover) { @@ -2061,9 +2141,9 @@ int run_input(unsigned flags) { if (exc_code == EXC_EXIT) { exc_handler = prev; arena_unref(pa); + parser_restore(pstate); exc_raise(EXC_EXIT); } - unwind_restore(&u); arena_release(&scratch, mark); parser_reset(); input_discard_line(); @@ -2072,7 +2152,7 @@ int run_input(unsigned flags) { dot_depth = 0; job_launching = nullptr; } - exc_handler = &jl; + exc_catch(&jl); if (flags & RI_TOP) prompt_state = 1; } @@ -2101,6 +2181,7 @@ int run_input(unsigned flags) { } exc_handler = prev; arena_unref(pa); + parser_restore(pstate); return exitstatus; } |
