diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-27 17:26:45 -0600 |
|---|---|---|
| committer | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-27 17:26:45 -0600 |
| commit | 90e25207c41010a5307beff7fd7a5a9e4be3653e (patch) | |
| tree | f257cce6d24590e5e41af525dcb85931ab39002d /src | |
| parent | e8f3a27f981f2d13cf6ccc9f9a08bebe3d44ac60 (diff) | |
| download | zash-90e25207c41010a5307beff7fd7a5a9e4be3653e.tar.gz | |
fix: the review findings, each with a regression test
Notes in notes/review-2026-11-27.md, one item per finding:
1. error unwinding read dead stack frames: the scope/redirection/input
snapshot now lives in jmploc and is restored before the longjmp
2. `for` without `in` iterated over parameters that `set --` could free:
the parameter block is reference-counted
3. `${4294967295}` and `${99999999999999999999}` indexed past the end:
strtol, clamped to 1..$#
4. a trap stopped running after its own action raised: the re-entry flag
is cleared before the action runs
5. `wait $pid` returned 127 once the job had been reaped
6. every external command failed with 127 when SIGCHLD was ignored at
startup: dispositions are reset before the first child
7. a failed `exec` killed an interactive shell and skipped its EXIT trap:
the shell returns 126/127, keeping the traps and restoring fds 0-9
8. `set -C` opened with O_TRUNC after a stat: O_EXCL, with the
non-regular-file case worked around
9. a here-doc cut off by EOF used the delimiter as its body
10. `cd -- dir` failed and PWD came from the failed logical path
11. deep arithmetic recursion overflowed the stack: a depth check
12. the CSI type byte was converted twice on EBCDIC: guarded by ZASH_ASCII
13. a script that could not be read looked like an empty script: reported,
with 2 at top level and 126/127 for the script; a directory is refused
up front, because z/OS would otherwise read it as empty input
Minors: `trap -p SIG`, `read -t` clamping and NaN, ksh `base#n` arithmetic,
`${#@}`/`${#*}` as `$#`, `jobs` no longer mutating its table from a
pipeline, the arena_grow contract, no pipe2 on macOS, and alias text copied
into the input so redefining an alias while it is being read is safe.
Diffstat (limited to 'src')
| -rw-r--r-- | src/alias.c | 20 | ||||
| -rw-r--r-- | src/arith.c | 32 | ||||
| -rw-r--r-- | src/builtin.c | 30 | ||||
| -rw-r--r-- | src/builtin_ext.c | 8 | ||||
| -rw-r--r-- | src/complete.c | 1 | ||||
| -rw-r--r-- | src/cond.c | 1 | ||||
| -rw-r--r-- | src/exec.c | 164 | ||||
| -rw-r--r-- | src/exec.h | 22 | ||||
| -rw-r--r-- | src/expand.c | 11 | ||||
| -rw-r--r-- | src/history.c | 3 | ||||
| -rw-r--r-- | src/input.c | 51 | ||||
| -rw-r--r-- | src/interact.c | 7 | ||||
| -rw-r--r-- | src/jobs.c | 68 | ||||
| -rw-r--r-- | src/main.c | 23 | ||||
| -rw-r--r-- | src/mvsfmt.c | 22 | ||||
| -rw-r--r-- | src/parser.c | 18 | ||||
| -rw-r--r-- | src/parser.h | 2 | ||||
| -rw-r--r-- | src/redir.c | 31 | ||||
| -rw-r--r-- | src/shell.h | 29 | ||||
| -rw-r--r-- | src/sys_posix.c | 28 | ||||
| -rw-r--r-- | src/trap.c | 94 | ||||
| -rw-r--r-- | src/util.c | 48 | ||||
| -rw-r--r-- | src/var.c | 31 | ||||
| -rw-r--r-- | src/var.h | 9 |
24 files changed, 566 insertions, 187 deletions
diff --git a/src/alias.c b/src/alias.c index bf1a236..da40661 100644 --- a/src/alias.c +++ b/src/alias.c @@ -70,18 +70,15 @@ void alias_each(void (*fn)(const char *name, void *arg), void *arg) { void alias_set(const char *name, const char *value) { alias *a = alias_find(name); if (a) { - /* - * The old text may still be the lexer's input if this command line - * used the alias. Leaking it in that case is the safe choice. - */ - if (!a->in_use) - free(a->value); + /* The lexer reads its own copy of the text (input_push_alias()), so + * the old one can go even while it is being read. */ + free(a->value); a->value = xstrdup(value); return; } a = xmalloc(sizeof *a); alias **bucket = &atab[alias_hash(name)]; - *a = (alias){*bucket, xstrdup(name), xstrdup(value), false}; + *a = (alias){*bucket, xstrdup(name), xstrdup(value)}; *bucket = a; alias_count++; } @@ -98,11 +95,10 @@ static bool alias_remove(const char *name) { continue; *pa = a->next; alias_count--; - if (!a->in_use) { /* otherwise the lexer still reads from it */ - free(a->value); - free(a->name); - free(a); - } + /* The lexer reads its own copy of the text (input_push_alias()). */ + free(a->value); + free(a->name); + free(a); return true; } return false; diff --git a/src/arith.c b/src/arith.c index b1e7fb0..c7c410f 100644 --- a/src/arith.c +++ b/src/arith.c @@ -94,7 +94,7 @@ static NOINLINE intmax_t var_value_expr(const arith *a, const char *s, depth = 0; exc_raise(exc_code); } - exc_handler = &jl; + exc_catch(&jl); intmax_t v = arith_eval(s); exc_handler = prev; depth--; @@ -258,6 +258,28 @@ static intmax_t apply(const arith *a, binop op, intmax_t x, intmax_t y) { } /** + * @brief Parse `base#digits`, the way ksh and bash write a number in a base. + * @param a The arithmetic state. + * @param p Start of the base digits. + * @param hash The `#` that ends them. + * @return The value. + */ +static intmax_t parse_based(arith *a, const char *p, const char *hash) { + int base = 0; + for (const char *q = p; q < hash; q++) + base = base * 10 + (*q - '0'); + if (base < 2 || base > 36) + arith_error(a, "bad number base"); + char *end; + errno = 0; + uintmax_t v = strtoumax(hash + 1, &end, base); + if (errno || end == hash + 1 || isalnum((unsigned char)*end) || *end == '_') + arith_error(a, "bad number"); + a->p = end; + return (intmax_t)v; +} + +/** * @brief Parse a number, a variable, or a parenthesised expression. * @return Its value. */ @@ -274,6 +296,11 @@ static intmax_t parse_primary(arith *a) { return v; } if (is_digit(*p)) { + const char *hash = p; + while (is_digit(*hash)) + hash++; + if (*hash == '#') + return parse_based(a, p, hash); if (*p != '0') { /* decimal: no need for strtoumax() */ intmax_t v = 0; int n = 0; @@ -312,6 +339,9 @@ static intmax_t parse_primary(arith *a) { * @return Its value. */ static intmax_t parse_unary(arith *a) { + /* Every recursion in the grammar passes through here. */ + if (stack_low()) + arith_error(a, "expression nested too deeply"); skip_space(a); const char *p = a->p; if ((p[0] == '+' || p[0] == '-') && p[1] == p[0] && diff --git a/src/builtin.c b/src/builtin.c index 8497a0d..855f3ad 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -20,6 +20,7 @@ #include <unistd.h> #include "exec.h" +#include "var.h" #include "sys.h" #include "parser.h" #include "interact.h" @@ -209,6 +210,8 @@ int builtin_exec(int argc, char **argv) { i++; if (i >= argc) return 0; /* redirections only: the caller makes them permanent */ + if (opt.interactive && !in_subshell) + return shell_exec_try(argv + i, var_environ()); shell_exec(argv + i, var_environ()); } @@ -361,10 +364,12 @@ static int b_read(int argc, char **argv) { const char *num = p[1] ? p + 1 : i + 1 < argc ? argv[++i] : ""; char *end; timeout = strtod(num, &end); - if (end == num || *end || timeout < 0) { + if (end == num || *end || !(timeout >= 0)) { sh_warn("read: -t: bad timeout"); return 2; } + if (timeout > 1e9) /* clamping keeps the deadline finite */ + timeout = 1e9; break; } else { sh_warn("read: -%c: bad option", *p); @@ -428,7 +433,9 @@ static int b_read(int argc, char **argv) { struct pollfd pfd = {.fd = 0, .events = POLLIN}; int ready = 1; if (!always_ready) - ready = ms > 0 ? poll(&pfd, 1, (int)ms) : 0; + ready = + ms > 0 ? poll(&pfd, 1, ms < INT_MAX ? (int)ms : INT_MAX) + : 0; if (ready == 0) return 128 + SIGALRM; if (ready < 0 && errno == EINTR) { @@ -739,6 +746,10 @@ static int b_cd(int argc, char **argv) { bool print = false; int i = 1; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { + if (!strcmp(argv[i], "--")) { + i++; + break; + } if (!strcmp(argv[i], "-P")) physical = true; else if (!strcmp(argv[i], "-L")) @@ -767,13 +778,18 @@ static int b_cd(int argc, char **argv) { const char *target = dest[0] == '/' ? dest : join_path(old, dest); if (!physical) target = normalize_path(target); - if (chdir(target) < 0 && chdir(dest) < 0) { - sh_warn("cd: %s: %s", dest, strerror(errno)); - return 1; - } char buf[PATH_MAX]; - if (physical && getcwd(buf, sizeof buf)) + if (chdir(target) < 0) { + if (chdir(dest) < 0) { + sh_warn("cd: %s: %s", dest, strerror(errno)); + return 1; + } + /* The logical path did not exist: record where we really are. */ + if (getcwd(buf, sizeof buf)) + target = buf; + } else if (physical && getcwd(buf, sizeof buf)) { target = buf; + } var_set("OLDPWD", old, V_EXPORT); var_set("PWD", target, V_EXPORT); free(curdir); diff --git a/src/builtin_ext.c b/src/builtin_ext.c index f693552..2f0271a 100644 --- a/src/builtin_ext.c +++ b/src/builtin_ext.c @@ -17,6 +17,7 @@ #include <unistd.h> #include "exec.h" +#include "var.h" #include "expand.h" #include "sys.h" @@ -143,9 +144,10 @@ int builtin_whence(int argc, char **argv) { continue; } const char *path = var_get("PATH"); - const char *full = strchr(argv[i], '/') - ? (access(argv[i], X_OK) == 0 ? argv[i] : nullptr) - : path_search(argv[i], path ? path : "", true); + const char *full = + strchr(argv[i], '/') + ? (access(argv[i], X_OK) == 0 ? argv[i] : nullptr) + : path_search(argv[i], path ? path : "", true); if (full) out_printf(&out1, "%s\n", full); else diff --git a/src/complete.c b/src/complete.c index 17239b2..ea12197 100644 --- a/src/complete.c +++ b/src/complete.c @@ -32,6 +32,7 @@ #include <unistd.h> #include "exec.h" +#include "var.h" #include "interact.h" #include "sys.h" @@ -30,6 +30,7 @@ #include <string.h> #include "exec.h" +#include "var.h" #include "expand.h" /** @@ -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; @@ -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; @@ -1455,7 +1464,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; @@ -1488,11 +1498,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); @@ -1526,8 +1534,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; @@ -1792,22 +1807,40 @@ static int eval_loop(node *n, unsigned flags) { 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++; + 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; } @@ -2020,12 +2053,10 @@ int run_input(unsigned flags) { 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"); @@ -2042,7 +2073,7 @@ int run_input(unsigned flags) { arena_unref(pa); exc_raise(exc_code); } - exc_handler = &jl; + exc_catch(&jl); } for (;;) { if (recover) { @@ -2053,7 +2084,6 @@ int run_input(unsigned flags) { arena_unref(pa); exc_raise(EXC_EXIT); } - unwind_restore(&u); arena_release(&scratch, mark); parser_reset(); input_discard_line(); @@ -2062,7 +2092,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; } @@ -1,6 +1,7 @@ /** * @file exec.h * @brief Command evaluation, redirection, jobs, traps and builtins. + * @note The unwind snapshot and the exception handler live in shell.h. */ #ifndef ZASH_EXEC_H #define ZASH_EXEC_H @@ -9,7 +10,6 @@ #include "ast.h" #include "sys.h" -#include "var.h" /* ---- evaluation (exec.c) --------------------------------------------- */ @@ -53,6 +53,7 @@ int run_input(unsigned flags); char *cmdsub_run(node *n, size_t *len); void exec_init(void); [[noreturn]] void shell_exec(char **argv, char **envp); +int shell_exec_try(char **argv, char **envp); /* ---- command table --------------------------------------------------- */ @@ -195,22 +196,10 @@ int builtin_bg(int argc, char **argv); char *node_text(const node *n); -/* ---- unwinding ------------------------------------------------------- */ - -/* Defined in parser.h. */ -typedef struct input_src input_src; - -/** - * @brief State that an exception handler must put back before continuing. +/* + * Unwinding: the unwind snapshot and exc_catch() live in shell.h, and the + * exception itself is raised by exc_raise() in util.c. */ -typedef struct unwind { - varscope *scope; - redirsave *redir; - input_src *input; -} unwind; - -void unwind_save(unwind *u); -void unwind_restore(const unwind *u); /* ---- traps (trap.c) -------------------------------------------------- */ @@ -223,6 +212,7 @@ void trap_run_err(void); void trap_init(void); void trap_poll(void); void trap_reset_child(void); +void trap_reset_exec(void); bool trap_has_exit(void); void trap_run_exit(void); const sigset_t *trap_spawn_defaults(void); diff --git a/src/expand.c b/src/expand.c index e81f5c2..89106ad 100644 --- a/src/expand.c +++ b/src/expand.c @@ -431,7 +431,9 @@ static const char *param_value(const param *pm, char *buf, size_t size) { case PT_POS: if (pm->pos == 0) return arg0; - return pm->pos <= shellparam.n ? shellparam.p[pm->pos - 1] : nullptr; + if (pm->pos < 1 || pm->pos > shellparam.n) + return nullptr; + return shellparam.p[pm->pos - 1]; case PT_SPECIAL: return special_value(pm->special, buf, size); } @@ -571,6 +573,13 @@ static void expand_param(expansion *x, const param *pm, bool quoted) { return; } + if (all && pm->op == PS_LENGTH) { + /* "${#@}" and "${#*}" count the parameters, as ksh has it. */ + snprintf(buf, sizeof buf, "%d", shellparam.n); + emit(x, buf, strlen(buf), quoted); + return; + } + if (!val) { if (opt.nounset && !all) sh_error("%s: parameter not set", pm->name); diff --git a/src/history.c b/src/history.c index 26846c3..011e0db 100644 --- a/src/history.c +++ b/src/history.c @@ -16,6 +16,7 @@ #include <unistd.h> #include "exec.h" +#include "var.h" #include "interact.h" /** @brief Entries kept when HISTSIZE is unset or not a number. */ @@ -219,7 +220,7 @@ static int hist_run(const char *text) { jmploc *prev = exc_handler; int status; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); status = eval_string(copy, 0); } else { exc_handler = prev; diff --git a/src/input.c b/src/input.c index 3bad009..5ae722c 100644 --- a/src/input.c +++ b/src/input.c @@ -81,18 +81,40 @@ void input_push_string(const char *s, size_t len) { } /** + * @brief Is this alias's text still being read? + * @param a The alias. + * @return true while some input source is reading it. + */ +bool input_alias_active(const alias *a) { + for (const input_src *in = input; in; in = in->prev) { + if (in->alias == a) + return true; + } + return false; +} + +/** * @brief Push the text of an alias as input. * * The input removes itself when it runs out (see input_fill()), so the - * lexer carries straight on with whatever followed the alias name. + * lexer carries straight on with whatever followed the alias name. The + * text is copied: the alias itself may be redefined or removed while it + * is being read. * - * @param a The alias. Marked in use until its text has been read. + * @param a The alias. */ void input_push_alias(alias *a) { - input_push_string(a->value, strlen(a->value)); - input->autopop = true; - input->alias = a; - a->in_use = true; + size_t n = strlen(a->value); + input_push_string(a->value, n); + input_src *in = input; + /* The input owns a copy: this very command line may redefine or remove + * the alias while its text is still being read. */ + in->buf = xmalloc(n + 1); + memcpy(in->buf, a->value, n + 1); + in->p = in->buf; + in->end = in->buf + n; + in->autopop = true; + in->alias = a; } /** @@ -115,9 +137,7 @@ void input_push_back(const char *s, size_t len) { void input_pop(void) { input_src *in = input; input = in->prev; - if (in->alias) - in->alias->in_use = false; - else if (in->autopop && input) + if (!in->alias && in->autopop && input) input->lineno = in->lineno; if (in->fd > 2) /* a script or dot file we opened */ close(in->fd); @@ -142,8 +162,10 @@ int input_fill(void) { if (in->autopop) { /* Alias or pushed-back text has run out: carry on underneath. */ if (in->alias) { - size_t n = strlen(in->alias->value); - char last = n ? in->alias->value[n - 1] : '\0'; + /* POSIX: a value ending in a blank lets the next word be + * expanded too. The text read decides, not the alias it came + * from, which may have been replaced by now. */ + char last = in->end > in->buf ? in->end[-1] : '\0'; alias_ended_blank = last == ' ' || last == '\t'; } input_pop(); @@ -169,6 +191,13 @@ int input_fill(void) { break; trap_poll(); } + if (n < 0) { + /* A read error is not the end of the input. At the outermost level + * nothing can recover from it, so the shell fails. */ + if (!in->prev) + sh_error("cannot read input: %s", strerror(errno)); + sh_warn("cannot read input: %s", strerror(errno)); + } if (n <= 0) { in->eof = true; return PEOF; diff --git a/src/interact.c b/src/interact.c index e6f8990..c4b8ed0 100644 --- a/src/interact.c +++ b/src/interact.c @@ -19,6 +19,7 @@ #include "charset.h" #include "exec.h" +#include "var.h" #include "expand.h" #include "interact.h" #include "sys.h" @@ -277,19 +278,15 @@ const char *expand_quietly(const char *raw, bool escapes) { alignas(max_align_t) char pstate[PARSER_STATE_SIZE]; jmploc jl; jmploc *prev = exc_handler; - unwind u; arena *volatile pa = arena_new(); const char *volatile result = raw; int saved_status = exitstatus; parser_save(pstate); - unwind_save(&u); if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); const char *text = escapes ? prompt_escapes(raw) : raw; result = expand_string(parse_text_parts(pa, text, strlen(text)), 0); - } else { - unwind_restore(&u); } exc_handler = prev; parser_restore(pstate); @@ -70,6 +70,23 @@ job *job_launching; /** @brief `$!`: process ID of the most recent background command. */ pid_t last_bg_pid; +/** @brief A background process reaped before anything waited for it. */ +typedef struct reaped { + pid_t pid; + int status; +} reaped; + +/** + * @brief Statuses `wait` has not collected yet, oldest first. + * + * A non-interactive shell frees a finished job as soon as it is reaped, but + * POSIX lets `wait $pid` ask for it afterwards. The list is bounded by + * _SC_CHILD_MAX; past that the oldest entry is forgotten. + */ +static reaped *reaped_list; +static int reaped_n; +static int reaped_cap; + static bool launching_fg; /**< The job being launched gets the terminal. */ static bool jc_on; /**< Job control is active in this process. */ static int tty_fd = -1; /**< The controlling terminal, when jc_on. */ @@ -313,6 +330,46 @@ static void job_print(output *o, const job *j, unsigned flags) { * at once, except the one `$!` names: its status must stay available to * `wait $!`. */ +/** + * @brief Remember the status of a reaped background process. + */ +static void reaped_add(pid_t pid, int status) { + if (reaped_n == reaped_cap) { + long max = sysconf(_SC_CHILD_MAX); + int cap = reaped_cap ? reaped_cap * 2 : 16; + if (max > 0 && cap > max) + cap = (int)max; + if (cap > reaped_n) { + reaped_list = + xrealloc(reaped_list, (size_t)cap * sizeof *reaped_list); + reaped_cap = cap; + } else { + memmove(reaped_list, reaped_list + 1, + (size_t)(reaped_n - 1) * sizeof *reaped_list); + reaped_n--; + } + } + reaped_list[reaped_n++] = (reaped){pid, status}; +} + +/** + * @brief Status of a finished background process. + * + * The entry stays, because `wait` on a pid it has already collected answers + * with the same status, as dash and bash do. + * + * @return true if that process was one of the remembered ones. + */ +static bool reaped_find(long pid, int *status) { + for (int i = 0; i < reaped_n; i++) { + if ((long)reaped_list[i].pid != pid) + continue; + *status = reaped_list[i].status; + return true; + } + return false; +} + void jobs_reap(void) { int flags = poll_flags(); for (job *j = job_list, *next; j; j = next) { @@ -333,6 +390,8 @@ void jobs_reap(void) { j->announce = after != JOB_RUNNING; } else if (after == JOB_DONE && j->procs[j->nprocs - 1].pid != last_bg_pid) { + for (int i = 0; i < j->nprocs; i++) + reaped_add(j->procs[i].pid, j->procs[i].status); job_free(j); } } @@ -777,15 +836,16 @@ int builtin_wait(int argc, char **argv) { if (job_get_state(j) == JOB_DONE) job_free(j); } + reaped_n = 0; return 0; } int status = 0; for (int i = 1; i < argc; i++) { job *j = nullptr; + long pid = 0; if (argv[i][0] == '%') { j = job_find(argv[i]); } else { - long pid; if (!parse_long(argv[i], &pid)) { sh_warn("wait: %s: bad process id", argv[i]); return 2; @@ -798,7 +858,8 @@ int builtin_wait(int argc, char **argv) { } } if (!j) { - status = 127; + if (!reaped_find(pid, &status)) + status = 127; continue; } status = job_wait(j); @@ -853,9 +914,6 @@ int builtin_jobs(int argc, char **argv) { for (k = 0; k < n; k++) { job *j = order[k]; job_print(&out1, j, flags); - j->announce = false; - if (job_get_state(j) == JOB_DONE) - job_free(j); } return 0; } @@ -2,14 +2,18 @@ * @file main.c * @brief Options, startup and exit. */ +#include <errno.h> #include <fcntl.h> #include <limits.h> +#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/stat.h> #include <unistd.h> #include "exec.h" +#include "var.h" #include "interact.h" #include "parser.h" @@ -281,7 +285,7 @@ void exit_shell(int status) { exitstatus = status; jmploc jl; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); trap_run_exit(); } else if (exc_code == EXC_EXIT) { code = exitstatus; /* the trap called exit itself */ @@ -308,6 +312,13 @@ static int open_script(const char *path) { int fd = sys_open(path, O_RDONLY, 0); if (fd < 0) return -1; + /* open() accepts a directory; z/OS then reads it as empty, so say so. */ + struct stat st; + if (fstat(fd, &st) == 0 && S_ISDIR(st.st_mode)) { + close(fd); + errno = EISDIR; + return -1; + } int high = sys_dupfd(fd, SYS_NFD); close(fd); return high; @@ -413,6 +424,9 @@ int main(int argc, char **argv) { bool ignored = false; 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); invoked_as = argv[0] ? argv[0] : "zash"; arg0 = invoked_as[0] == '-' ? invoked_as + 1 : invoked_as; if (arg0[0] != '/' && strchr(arg0, '/')) { @@ -435,7 +449,7 @@ int main(int argc, char **argv) { usage_print(&out2, false); exit_shell(exitstatus); } - exc_handler = &jl; + exc_catch(&jl); /* Only as the first argument, so that it cannot be an operand. */ if (argc > 1 && !strcmp(argv[1], "--help")) { @@ -496,8 +510,9 @@ int main(int argc, char **argv) { } else if (script) { int fd = open_script(script); if (fd < 0) { - sh_warn("cannot open %s", script); - exit_shell(127); + int perr = errno; + sh_warn("cannot open %s: %s", script, strerror(perr)); + exit_shell(perr == ENOENT || perr == ENOTDIR ? 127 : 126); } input_push_fd(fd, false); run_input(RI_TOP); diff --git a/src/mvsfmt.c b/src/mvsfmt.c index a182e1f..9dddeec 100644 --- a/src/mvsfmt.c +++ b/src/mvsfmt.c @@ -157,13 +157,15 @@ static constexpr unsigned CSIREQLN = 4; /**< length of the entry that failed */ * reserved bytes, one length per field and the fields. */ static constexpr unsigned CSIUSDLN = 8; /**< bytes of return information used */ -static constexpr unsigned CSI_FIRST = 14; /**< offset of the first entry */ -static constexpr unsigned CSIE_NAME = 2; /**< name, within an entry */ +static constexpr unsigned CSI_FIRST = 14; /**< offset of the first entry */ +static constexpr unsigned CSIE_NAME = 2; /**< name, within an entry */ static constexpr unsigned CSIE_FIXED = 46; /**< bytes before the lengths */ -static constexpr unsigned CSIE_RETINFO = 50; /**< bytes of an entry with return info */ -static constexpr unsigned char CSIENTER = 0x40; /**< CSIEFLAG: error, return info follows */ -#define EB_ZERO 0xf0 /* CSIETYPE of a catalog entry, EBCDIC '0' */ -#define EB_Y 0xe8 /* EBCDIC 'Y' */ +static constexpr unsigned CSIE_RETINFO = + 50; /**< bytes of an entry with return info */ +static constexpr unsigned char CSIENTER = + 0x40; /**< CSIEFLAG: error, return info follows */ +#define EB_ZERO 0xf0 /* CSIETYPE of a catalog entry, EBCDIC '0' */ +#define EB_Y 0xe8 /* EBCDIC 'Y' */ /** * @brief Is this a filter key the CSI accepts? @@ -281,7 +283,8 @@ bool csi_parse(const unsigned char *work, size_t worklen, mvs_name_fn *fn, return false; /* also guarantees progress */ char name[MVS_DSN_MAX + 1]; mvs_name(e + CSIE_NAME, MVS_DSN_MAX, name); - char type = (char)mvs_e2a[e[1]]; + /* In an EBCDIC build the byte already is the character. */ + char type = ZASH_ASCII ? (char)mvs_e2a[e[1]] : (char)e[1]; if (type != 'U' && name[0]) fn(name, type, arg); off += CSIE_FIXED + total; @@ -361,8 +364,9 @@ bool pds_parse_block(const unsigned char *blk, mvs_name_fn *fn, void *arg, if (used - off < 8) return false; const unsigned char *e = blk + off; - static const unsigned char last[8] = {0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff,}; + static const unsigned char last[8] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + }; if (!memcmp(e, last, 8)) { *end = true; return true; diff --git a/src/parser.c b/src/parser.c index 0677b37..228acb2 100644 --- a/src/parser.c +++ b/src/parser.c @@ -12,6 +12,8 @@ #include "charset.h" #include <ctype.h> +#include <errno.h> +#include <limits.h> #include <stdlib.h> #include <string.h> @@ -279,7 +281,12 @@ static param *new_param(const char *name, size_t nlen) { pm->op = PS_NORMAL; if (isdigit((unsigned char)name[0])) { pm->type = PT_POS; - pm->pos = atoi(name); + /* A number too large for any parameter list is simply unset; INT_MAX + * is not a valid index, so the range check in param_value rejects it. + */ + errno = 0; + long v = strtol(name, nullptr, 10); + pm->pos = errno == 0 && v <= INT_MAX ? (int)v : INT_MAX; } else if (is_special_param((unsigned char)name[0])) { pm->type = PT_SPECIAL; pm->special = name[0]; @@ -934,6 +941,11 @@ static void lex_token(void) { tok.kw = KW_NONE; switch (c) { case PEOF: + /* A here-document with no body before the end of input has an empty + * body, not the delimiter as its body. Read it so the delimiter + * word never stands in for one. */ + if (here_head) + read_heredocs(); tok.t = T_EOF; return; case '\n': @@ -1029,7 +1041,7 @@ static bool alias_expand(void) { if (!alias_count || !tok.bare) return false; alias *a = alias_find(tok.word->parts->u.lit.s); - if (!a || a->in_use) + if (!a || input_alias_active(a)) return false; tok_pushed = false; input_push_alias(a); @@ -2118,7 +2130,7 @@ typedef struct parser_state { } parser_state; static_assert(sizeof(parser_state) <= PARSER_STATE_SIZE, - "PARSER_STATE_SIZE in parser.h is too small"); + "PARSER_STATE_SIZE in parser.h is too small"); /** * @brief Save the parser's state and reset it. diff --git a/src/parser.h b/src/parser.h index 7926e9d..a4059f4 100644 --- a/src/parser.h +++ b/src/parser.h @@ -44,7 +44,6 @@ typedef struct alias { struct alias *next; char *name; char *value; - bool in_use; /**< its text is being read: do not expand it again */ } alias; extern int alias_count; /**< number of aliases defined */ @@ -53,6 +52,7 @@ alias *alias_find(const char *name); void alias_set(const char *name, const char *value); void alias_each(void (*fn)(const char *name, void *arg), void *arg); void input_push_alias(alias *a); +bool input_alias_active(const alias *a); void input_push_back(const char *s, size_t len); extern input_src *input; diff --git a/src/redir.c b/src/redir.c index b6d4da6..2d328a9 100644 --- a/src/redir.c +++ b/src/redir.c @@ -18,6 +18,7 @@ #include <unistd.h> #include "exec.h" +#include "var.h" #include "expand.h" /* A here-document up to this size fits in a pipe without blocking. */ @@ -125,6 +126,27 @@ static int heredoc_open(const redir *r) { } /** + * @brief Open an output file under `set -C`. + * + * O_EXCL makes the check and the creation one step, so the `set -C; echo $$ > + * lock` idiom has one winner. A file that exists and is not a regular file + * (/dev/null, a FIFO) is opened as usual, as bash does. + * + * @param path The file name. + * @return A descriptor, or -1 with errno set (EEXIST if the file exists). + */ +static int open_noclobber(const char *path) { + int fd = sys_open(path, O_WRONLY | O_CREAT | O_EXCL, 0666); + if (fd >= 0 || errno != EEXIST) + return fd; + struct stat st; + if (stat(path, &st) == 0 && !S_ISREG(st.st_mode)) + return sys_open(path, O_WRONLY, 0666); + errno = EEXIST; + return -1; +} + +/** * @brief Open the file a redirection names, honouring `noclobber`. * @param r The redirection (its operator decides the open mode). * @param path The expanded file name. @@ -143,13 +165,8 @@ static int open_file(const redir *r, const char *path) { flags = O_WRONLY | O_CREAT | O_APPEND; break; case R_OUT: - if (opt.noclobber) { - struct stat st; - if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) { - errno = EEXIST; - return -1; - } - } + if (opt.noclobber) + return open_noclobber(path); [[fallthrough]]; default: flags = O_WRONLY | O_CREAT | O_TRUNC; diff --git a/src/shell.h b/src/shell.h index 6a92a02..f83e80a 100644 --- a/src/shell.h +++ b/src/shell.h @@ -228,17 +228,44 @@ static inline void out_putc(output *o, char c) { */ enum { EXC_ERROR = 1, EXC_EXIT }; +/* + * Global state an exception must put back: the variable scopes, redirections + * and inputs that were pushed below the frame that catches it. The records + * themselves live in the frames in between, so they are captured when the + * handler is armed and put back by exc_raise() before the jump, while those + * frames are still alive. + */ +struct varscope; +struct redirsave; +struct input_src; + /** - * @brief A place exc_raise() can jump to. Set with setjmp(jl.buf). + * @brief Shell state that an exception handler restores. + */ +typedef struct unwind { + struct varscope *scope; + struct redirsave *redir; + struct input_src *input; +} unwind; + +/** + * @brief A place exc_raise() can jump to. + * + * Arm it with exc_catch() before setjmp(jl.buf); the snapshot so taken is + * what exc_raise() puts back before the jump. */ typedef struct jmploc { jmp_buf buf; + unwind u; /**< state to restore, captured by exc_catch() */ } jmploc; extern jmploc *exc_handler; extern int exc_code; /**< the exception being propagated */ extern int exitstatus; +void exc_catch(jmploc *jl); +void unwind_save(unwind *u); +void unwind_restore(const unwind *u); [[noreturn]] void exc_raise(int exc); [[noreturn]] void sh_error(const char *fmt, ...) PRINTFLIKE(1, 2); void sh_warn(const char *fmt, ...) PRINTFLIKE(1, 2); diff --git a/src/sys_posix.c b/src/sys_posix.c index 92f2d42..2517d3f 100644 --- a/src/sys_posix.c +++ b/src/sys_posix.c @@ -3,7 +3,7 @@ * @brief Platform layer for Linux and other POSIX systems, built on * posix_spawn(). */ -#define _GNU_SOURCE /* pipe2() */ +#define _GNU_SOURCE /* posix_spawn_file_actions_addtcsetpgrp_np() */ #include <errno.h> #include <fcntl.h> @@ -176,21 +176,29 @@ pid_t sys_spawn(const spawn_req *rq) { * descriptor the script names in a redirection. */ int sys_pipe(int fd[2]) { - if (pipe2(fd, O_CLOEXEC) < 0) + /* pipe2() is not on every POSIX platform (macOS lacks it), so the ends + * are made close-on-exec here instead. */ + if (pipe(fd) < 0) return -1; for (int i = 0; i < 2; i++) { - if (fd[i] >= SYS_NFD) - continue; - int high = fcntl(fd[i], F_DUPFD_CLOEXEC, SYS_NFD); - if (high < 0) { - int err = errno; + if (fd[i] < SYS_NFD) { + int high = fcntl(fd[i], F_DUPFD_CLOEXEC, SYS_NFD); + if (high < 0) { + int perr = errno; + close(fd[0]); + close(fd[1]); + errno = perr; + return -1; + } + close(fd[i]); + fd[i] = high; + } else if (fcntl(fd[i], F_SETFD, FD_CLOEXEC) < 0) { + int perr = errno; close(fd[0]); close(fd[1]); - errno = err; + errno = perr; return -1; } - close(fd[i]); - fd[i] = high; } return 0; } @@ -267,10 +267,28 @@ void trap_poll(void) { got_signal[sig] = 0; const char *action = trap_action[sig]; if (action && *action) { - /* Run a copy: the action may replace its own trap. */ + /* Run a copy: the action may replace its own trap. An error + * in the action raises after the state is back, so the next + * poll runs the remaining signals instead of skipping them. */ int saved = exitstatus; arena_marker mark = arena_mark(&scratch); - eval_string(arena_strndup(&scratch, action, strlen(action)), 0); + jmploc jl; + jmploc *prev = exc_handler; + if (setjmp(jl.buf) == 0) { + exc_catch(&jl); + eval_string(arena_strndup(&scratch, action, strlen(action)), + 0); + } else { + exc_handler = prev; + running = false; + for (int s = sig; s <= MAXSIG; s++) + if (got_signal[s]) { + trap_pending = (sig_atomic_t)s; + break; + } + exc_raise(exc_code); /* exitstatus is the shell's now */ + } + exc_handler = prev; arena_release(&scratch, mark); exitstatus = saved; } else if (sig == SIGINT && opt.interactive) { @@ -321,6 +339,27 @@ void trap_reset_child(void) { } /** + * @brief Give up the signals the shell ignored for itself, before `exec`. + * + * A trapped signal's handler is reset by the kernel when the image is + * replaced, so only SIG_IGN needs undoing here. The trap text is left + * alone: a failed `exec` leaves the shell running, and its EXIT trap still + * has to run. Nothing else calls this after a failure, so the shell_ignored + * bookkeeping is simply cleared. + */ +void trap_reset_exec(void) { + if (!have_shell_ignored) + return; + set_handler(SIGINT, SIG_DFL); + for (int sig = 1; sig <= MAXSIG; sig++) { + if (sigismember(&shell_ignored, sig) == 1 && !trap_action[sig]) + set_handler(sig, SIG_DFL); + } + sigemptyset(&shell_ignored); + have_shell_ignored = false; +} + +/** * @brief Run the ERR trap after a command has failed. * * The action sees the failing status in `$?`, and that status is still @@ -338,7 +377,7 @@ void trap_run_err(void) { jmploc jl; jmploc *prev = exc_handler; if (setjmp(jl.buf) == 0) { - exc_handler = &jl; + exc_catch(&jl); eval_string(arena_strndup(&scratch, action, strlen(action)), 0); } else { exc_handler = prev; @@ -427,26 +466,49 @@ static void print_signal(int sig) { * @brief The `trap` builtin: `trap [-p]`, `trap action signal...`, * `trap - signal...`. */ +/** + * @brief Print one signal's trap in the form that would set it. + * @param sig Signal number, 0 for EXIT, TRAP_ERR for ERR. + */ +static void print_trap(int sig) { + const char *shown = trap_action[sig]; + if (!shown && show_parent) + shown = parent_action[sig]; + if (!shown) + return; + out_puts(&out1, "trap -- "); + out_quote(&out1, shown); + out_putc(&out1, ' '); + print_signal(sig); + out_putc(&out1, '\n'); +} + int builtin_trap(int argc, char **argv) { + bool print = false; int i = 1; - if (i < argc && !strcmp(argv[i], "-p")) - i++; /* "trap -p" prints, like "trap" alone */ + if (i < argc && !strcmp(argv[i], "-p")) { + print = true; /* "trap -p" prints, like "trap" alone */ + i++; + } if (i < argc && !strcmp(argv[i], "--")) i++; if (i >= argc) { - for (int sig = 0; sig <= TRAP_ERR; sig++) { - const char *shown = trap_action[sig]; - if (!shown && show_parent) - shown = parent_action[sig]; - if (!shown) + for (int sig = 0; sig <= TRAP_ERR; sig++) + print_trap(sig); + return 0; + } + if (print) { + int status = 0; + for (; i < argc; i++) { + int sig = signal_number(argv[i]); + if (sig < 0) { + sh_warn("trap: %s: bad signal", argv[i]); + status = 1; continue; - out_puts(&out1, "trap -- "); - out_quote(&out1, shown); - out_putc(&out1, ' '); - print_signal(sig); - out_putc(&out1, '\n'); + } + print_trap(sig); } - return 0; + return status; } const char *action = nullptr; if (!strcmp(argv[i], "-")) @@ -5,6 +5,7 @@ */ #include "shell.h" +#include <assert.h> #include <ctype.h> #include <errno.h> #include <limits.h> @@ -15,6 +16,8 @@ #include <sys/resource.h> #include <unistd.h> +#include "exec.h" +#include "var.h" #include "parser.h" /* ---- heap ------------------------------------------------------------ */ @@ -200,8 +203,10 @@ void *arena_alloc(arena *a, size_t n) { * @param oldn Its size. * @param newn Size wanted. * @return The block, possibly moved. + * @pre `newn >= oldn`: this grows a block, it never shrinks one. */ void *arena_grow(arena *a, void *p, size_t oldn, size_t newn) { + assert(newn >= oldn); size_t olda = align_up(oldn); size_t newa = align_up(newn); if (p && (char *)p + olda == a->next && @@ -515,11 +520,49 @@ int exc_code; */ int exitstatus; +/* + * Restore what exc_raise() unwinds. Defined here, next to the jump, because + * they reach into the arenas, scopes and inputs that modules own. + */ + +/** + * @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); +} + +/** + * @brief Arm a handler: capture the state to restore and make it innermost. + * + * Follow with setjmp(jl->buf) in the same frame. + * + * @param jl The handler. + */ +void exc_catch(jmploc *jl) { + unwind_save(&jl->u); + exc_handler = jl; +} + /** * @brief Raise a shell exception. * - * Control passes to the innermost handler installed in #exc_handler. With - * no handler the shell exits. + * The handler's recorded state is put back first, while the frames that own + * it are still alive: after longjmp() they are gone, and walking the chains + * through them would read dead stack (C11 7.13.2.1). Control then passes to + * the innermost handler installed in #exc_handler. With no handler the shell + * exits. * * @param exc EXC_ERROR or EXC_EXIT. */ @@ -527,6 +570,7 @@ void exc_raise(int exc) { if (!exc_handler) exit_shell(exitstatus); exc_code = exc; + unwind_restore(&exc_handler->u); longjmp(exc_handler->buf, exc); } @@ -700,10 +700,30 @@ void var_init(char **envp) { /* ---- positional parameters ------------------------------------------- */ /** + * @brief Header of the heap block holding a set of positional parameters. + * + * It carries a reference count so that a `for` loop iterating over the + * parameters keeps them alive across a `set --` in the loop body. + */ +struct paramblk { + int refs; /**< number of shparam copies owning this block */ + char **p; /**< the argument vector, inside the same allocation */ +}; + +/** + * @brief Take another reference to a block of positional parameters. + */ +void params_hold(shparam *sp) { + if (sp->base) + sp->base->refs++; +} + +/** * @brief Free a heap copy of positional parameters. */ void params_free(shparam *sp) { - free(sp->base); + if (sp->base && --sp->base->refs <= 0) + free(sp->base); sp->base = nullptr; } @@ -712,10 +732,13 @@ void params_free(shparam *sp) { */ void params_set(char **argv, int n) { size_t bytes = ((size_t)n + 1) * sizeof(char *); - size_t total = bytes; + size_t total = sizeof(struct paramblk) + bytes; for (int i = 0; i < n; i++) total += strlen(argv[i]) + 1; - char **p = xmalloc(total); + struct paramblk *b = xmalloc(total); + b->refs = 1; + char **p = (char **)(b + 1); + b->p = p; char *s = (char *)p + bytes; for (int i = 0; i < n; i++) { size_t len = strlen(argv[i]) + 1; @@ -724,5 +747,5 @@ void params_set(char **argv, int n) { } p[n] = nullptr; params_free(&shellparam); - shellparam = (shparam){n, p, p}; + shellparam = (shparam){n, p, b}; } @@ -96,17 +96,24 @@ extern char ifs_first; /**< separator for "$*"; '\0' if IFS is empty */ /* ---- positional parameters ------------------------------------------- */ +struct paramblk; /**< defined in var.c */ + /** * @brief A set of positional parameters. + * + * The block is shared: a `for` loop without `in` holds a reference while it + * iterates, so that a `set --` in the body cannot free the words it reads. */ typedef struct shparam { int n; char **p; - void *base; /**< heap block holding p and the strings, or nullptr */ + struct paramblk + *base; /**< heap block holding p and the strings, or nullptr */ } shparam; extern shparam shellparam; void params_set(char **argv, int n); +void params_hold(shparam *sp); void params_free(shparam *sp); #endif |
