From cb1688f0233d53cfca8078f812c824213a5617fd Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:07:39 -0600 Subject: wip: vi external edit and dot-repeat, in-process cd subshell, perf test The working tree the 2026-11-28 review was written against, committed unchanged so the review fixes can sit on top of it. - vi mode: `v` edits the line in $VISUAL, else $EDITOR (edit_external), and `.` repeats the last change, count and all. - `( cd dir )` runs in-process with the directory saved and restored, instead of forking, and its invalidation of the cached logical cwd. - tests/perf: a start-up cost guard; tests/run.sh runs that directory. - README: set +o pipetag for ASCII builds. - formal/zash-spec.txt regenerated as text. - .clang-tidy: two checks re-enabled (no findings after the change). - tests/scripts/webdocs: a `#` inside a fenced block is not a title. --- src/builtin.c | 5 ++ src/edit_builtin.c | 198 ++++++++++++++++++++++++++++++++++++++++++++++++++++- src/exec.h | 1 + 3 files changed, 201 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/builtin.c b/src/builtin.c index 2aa198f..ac7aa45 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -672,6 +672,11 @@ static const char *get_curdir(void) { return curdir; } +void curdir_invalidate(void) { + free(curdir); + curdir = nullptr; +} + /** * @brief Remove `.`, `..` and repeated slashes from an absolute path, textually * (the logical view `cd -L` uses). diff --git a/src/edit_builtin.c b/src/edit_builtin.c index 14ad8ac..4d5cfb1 100644 --- a/src/edit_builtin.c +++ b/src/edit_builtin.c @@ -33,6 +33,7 @@ */ #include #include +#include #include #include #include @@ -90,6 +91,17 @@ typedef struct editor { size_t undo_len; /**< Its length. */ size_t undo_pos; /**< Cursor position to restore with it. */ char search[128]; /**< vi mode: last `/` or `?` pattern. */ + + int rec[512]; /**< vi mode: the keys of the change being made. */ + size_t rec_len; /**< Keys in `rec`. */ + int last[512]; /**< vi mode: the last change, for `.` and count. */ + size_t last_len; /**< Keys in `last`. */ + bool changed; /**< vi mode: the command under way moved the line. */ + bool recording; /**< vi mode: keys are being recorded into `rec`. */ + int replay[512]; /**< vi mode: keys `.` is replaying, one pass. */ + size_t replay_len; /**< Keys in `replay`. */ + size_t replay_pos; /**< Next key to hand out. */ + size_t replay_left; /**< Keys still to hand out, passes included. */ } editor; /** @@ -579,7 +591,7 @@ static int read_byte(void) { * * @return A byte value, one of the K_ codes, or K_META plus a byte. */ -static int read_key(void) { +static int read_key_raw(void) { if (ed.unread) { int k = ed.unread; ed.unread = 0; @@ -671,6 +683,47 @@ static int read_key(void) { return bind_key(k, seq, n); } +/** + * @brief Record a key for vi mode's `.`, or give up on this change. + * + * A change longer than the record cannot be repeated, and a partial one + * would repeat the wrong thing, so recording stops instead. + * + * @param k The key, or a negative value at end of input. + * @return true while recording continues. + */ +static bool rec_add(int k) { + if (ed.rec_len == sizeof ed.rec / sizeof ed.rec[0]) { + ed.recording = false; + ed.rec_len = 0; + return false; + } + if (k >= 0) + ed.rec[ed.rec_len++] = k; + return true; +} + +/** + * @brief Read one key: from `.`'s replay, or from the terminal. + * + * Replaying through here means a repeated change is dispatched exactly + * like a typed one, insert mode and all. Every key read while a change + * is being made is recorded for the next `.`. + */ +static int read_key(void) { + if (ed.replay_left) { + int k = ed.replay[ed.replay_pos]; + if (++ed.replay_pos >= ed.replay_len) + ed.replay_pos = 0; + ed.replay_left--; + return k; + } + int k = read_key_raw(); + if (ed.recording) + rec_add(k); + return k; +} + /* ---- completion ------------------------------------------------------ */ /** @@ -842,6 +895,127 @@ static void vi_save_undo(void) { memcpy(ed.undo, ed.buf, ed.len); ed.undo_len = ed.len; ed.undo_pos = ed.pos; + ed.changed = true; +} + +/** + * @brief vi: start recording the keys of a change. + * + * A change runs from its command key through the text typed in insert + * mode, which the main loop records while `vi_cmd` is false. Keys that + * `.` hands back are not recorded: `.` keeps the change it repeated. + */ +static void vi_record_start(void) { + if (ed.replay_left) { + ed.recording = false; + return; + } + ed.rec_len = 0; + ed.changed = false; + ed.recording = true; +} + +/** + * @brief vi: keep the keys of the change just made, for `.`. + */ +static void vi_record_done(void) { + if (!ed.recording) + return; + ed.recording = false; + if (!ed.changed || !ed.rec_len) + return; + memcpy(ed.last, ed.rec, ed.rec_len * sizeof ed.last[0]); + ed.last_len = ed.rec_len; +} + +/** @brief vi: stop recording and forget the change (the line was taken). */ +static void vi_record_stop(void) { + ed.recording = false; + ed.changed = false; +} + +/** + * @brief vi: hand the last change's keys back, `times` times (`3.`). + * @param times Repeat count; 0 and 1 both mean once. + */ +static void vi_replay(int times) { + if (!ed.last_len) + return; + memcpy(ed.replay, ed.last, ed.last_len * sizeof ed.replay[0]); + ed.replay_len = ed.last_len; + ed.replay_pos = 0; + ed.replay_left = ed.last_len * (size_t)(times > 0 ? times : 1); +} + +/** + * @brief vi: edit the line in `$VISUAL` or `$EDITOR` (the `v` key). + * + * The line goes to a temporary file and the editor is run through the + * shell, so an editor given with arguments (`emacs -nw`) works. The + * terminal is handed back while it runs. A successful exit puts the + * file's first line in the buffer with the cursor at its start, ready + * for the next command-mode key. + */ +static void edit_external(void) { + const char *tmpdir = var_get("TMPDIR"); + char file[4096]; + int n = snprintf(file, sizeof file, "%s/zash-vi.XXXXXX", + tmpdir && *tmpdir ? tmpdir : "/tmp"); + if (n < 0 || (size_t)n >= sizeof file) { + ob_puts("zash: TMPDIR is too long for `v`\n"); + ob_flush(); + return; + } + int fd = mkstemp(file); + if (fd < 0) { + ob_puts("zash: `v`: cannot create a temporary file\n"); + ob_flush(); + return; + } + size_t off = 0; + while (off < ed.len) { + ssize_t w = write(fd, ed.buf + off, ed.len - off); + if (w <= 0) + break; + off += (size_t)w; + } + bool wrote = off == ed.len && write(fd, "\n", 1) == 1; + close(fd); + const char *editor = var_get("VISUAL"); + if (!editor || !*editor) + editor = var_get("EDITOR"); + if (!editor || !*editor) + editor = "vi"; + char *cmd = xmalloc(strlen(editor) + sizeof file + 2); + sprintf(cmd, "%s %s", editor, file); + raw_off(); + ob_flush(); + int status = eval_string(cmd, 0); + raw_on(); + free(cmd); + char *text = nullptr; + size_t nread = 0; + if (status == 0 && wrote && (fd = open(file, O_RDONLY)) >= 0) { + text = xmalloc(256); + size_t cap = 256; + ssize_t r; + while (nread + 1 < cap && + (r = read(fd, text + nread, cap - nread - 1)) > 0) { + nread += (size_t)r; + if (nread + 1 == cap) { + cap *= 2; + text = xrealloc(text, cap); + } + } + close(fd); + text[nread] = '\0'; + text[strcspn(text, "\n")] = '\0'; + vi_save_undo(); + set_line(text); + ed.pos = 0; + } + free(text); + unlink(file); } /** @brief vi: is this byte blank? */ @@ -1130,6 +1304,12 @@ static bool vi_command(int key) { ed.pos = prev_char(ed.pos); } break; + case '.': + vi_replay(count); + break; + case 'v': + edit_external(); + break; case 'u': if (ed.undo) { char *now = xmalloc(ed.len + 1); @@ -1419,12 +1599,17 @@ char *edit_readline(const char *prompt, size_t *len) { ed.hidx = hist_count(); ed.unread = 0; ed.vi_cmd = false; + ed.recording = false; + ed.replay_left = 0; reserve(64); raw_on(); bool eof = false; for (;;) { refresh(); + /* A change is recorded from its command key: `.` repeats it. */ + if (opt.vi && ed.vi_cmd) + vi_record_start(); int k = read_key(); if (k == K_INTR) { interrupted(); @@ -1436,19 +1621,26 @@ char *edit_readline(const char *prompt, size_t *len) { } if (opt.vi) { if (ed.vi_cmd) { - if (k == '\r' || k == '\n' || vi_command(k)) + if (k == '\r' || k == '\n' || vi_command(k)) { + vi_record_stop(); break; + } + if (ed.vi_cmd) + vi_record_done(); continue; } if (k == CH_ESC) { ed.vi_cmd = true; ed.pos = prev_char(ed.pos); + vi_record_done(); continue; } /* In insert mode the basic editing keys still work. */ } - if (edit_key(k)) + if (edit_key(k)) { + vi_record_stop(); break; + } } ed.pos = ed.len; if (!eof) diff --git a/src/exec.h b/src/exec.h index 90bc8c9..88b0b95 100644 --- a/src/exec.h +++ b/src/exec.h @@ -110,6 +110,7 @@ enum { }; void find_command(const char *name, cmdinfo *ci, unsigned flags); +void curdir_invalidate(void); void func_define(const char *name, node *body, arena *owner); bool func_unset(const char *name); void func_each(void (*fn)(const char *name, void *arg), void *arg); -- cgit 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 ++++++++++++++++++++++++++++++++++- src/parser.c | 11 ++++++++--- tests/linux/i-vi-edit.exp | 10 ++++++++++ tests/linux/i-vi-edit.sh | 44 +++++++++++++++++++++++++++++++++++++++++++ tests/posix/trap-midtoken.exp | 4 ++++ tests/posix/trap-midtoken.sh | 18 ++++++++++++++++++ 6 files changed, 119 insertions(+), 4 deletions(-) create mode 100644 tests/linux/i-vi-edit.exp create mode 100644 tests/linux/i-vi-edit.sh create mode 100644 tests/posix/trap-midtoken.exp create mode 100644 tests/posix/trap-midtoken.sh (limited to 'src') 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; } diff --git a/src/parser.c b/src/parser.c index 70bc96a..98d4c0b 100644 --- a/src/parser.c +++ b/src/parser.c @@ -112,14 +112,14 @@ static heredoc *here_head; /** * @brief Where the next pending here-document is linked. */ +static heredoc **here_tail = &here_head; + /** * @brief The lexer is inside `[[ ]]`, where `<` and `>` are comparison * operators, not redirections. */ static bool in_cond; -static heredoc **here_tail = &here_head; - /** * @brief Set by input_fill() when an alias whose value ends in a blank runs * out: the next word is then subject to alias substitution too. @@ -2139,6 +2139,8 @@ typedef struct parser_state { bool tok_pushed; heredoc *here_head; heredoc **here_tail; + bool in_cond; + bool alias_ended_blank; } parser_state; static_assert(sizeof(parser_state) <= PARSER_STATE_SIZE, @@ -2150,7 +2152,8 @@ static_assert(sizeof(parser_state) <= PARSER_STATE_SIZE, */ void parser_save(void *state) { parser_state *ps = state; - *ps = (parser_state){pa, tok, tok_pushed, here_head, here_tail}; + *ps = (parser_state){pa, tok, tok_pushed, here_head, here_tail, in_cond, + alias_ended_blank}; if (here_tail == &here_head) ps->here_tail = nullptr; parser_reset(); @@ -2166,4 +2169,6 @@ void parser_restore(const void *state) { tok_pushed = ps->tok_pushed; here_head = ps->here_head; here_tail = ps->here_tail ? ps->here_tail : &here_head; + in_cond = ps->in_cond; + alias_ended_blank = ps->alias_ended_blank; } diff --git a/tests/linux/i-vi-edit.exp b/tests/linux/i-vi-edit.exp new file mode 100644 index 0000000..fb8d9c1 --- /dev/null +++ b/tests/linux/i-vi-edit.exp @@ -0,0 +1,10 @@ +$ echo visual 'echo one' +visual echo one +$ exit +$ echo edited 'echo two' +edited echo two +$ exit +$ echo keep me +keep me +$ exit +[status 0] diff --git a/tests/linux/i-vi-edit.sh b/tests/linux/i-vi-edit.sh new file mode 100644 index 0000000..c78756a --- /dev/null +++ b/tests/linux/i-vi-edit.sh @@ -0,0 +1,44 @@ +# Interactive: vi's `v` puts the line in $VISUAL, else $EDITOR. +# +# The editor here is a script that writes the line it was given back as a +# new command, so the test sees that the editor ran and what it was +# handed: the line being edited, on its own. +# +# `v` runs the editor through eval_string() while the outer command is +# half parsed, so under `make asan` this is also a regression test for a +# nested eval that frees the parse arena (see posix/trap-midtoken). +command -v python3 >/dev/null 2>&1 || exit 77 +cat >ed.sh <<'INS' +#!/bin/sh +printf "echo edited '%s'\n" "$(cat "$1")" >"$1" +INS +cat >vis.sh <<'INS' +#!/bin/sh +printf "echo visual '%s'\n" "$(cat "$1")" >"$1" +INS +chmod +x ed.sh vis.sh +# $VISUAL wins over $EDITOR, as POSIX says. +PS1='$ ' ENV='' HISTFILE='' EDITOR="$PWD/ed.sh" VISUAL="$PWD/vis.sh" \ + python3 "$TESTS/tools/ptydrive.py" "$TSH" -o vi <<'END' +send echo one\x1bv +send \r +expect visual echo one +send exit\r +END +# With no $VISUAL, $EDITOR is used. +PS1='$ ' ENV='' HISTFILE='' VISUAL='' EDITOR="$PWD/ed.sh" \ + python3 "$TESTS/tools/ptydrive.py" "$TSH" -o vi <<'END' +send echo two\x1b0wv +send \r +expect edited echo two +send exit\r +END +# A failed editor leaves the line alone. +PS1='$ ' ENV='' HISTFILE='' VISUAL='' EDITOR=false \ + python3 "$TESTS/tools/ptydrive.py" "$TSH" -o vi <<'END' +send echo keep me\x1bv +expect echo keep me +send \r +expect keep me +send exit\r +END diff --git a/tests/posix/trap-midtoken.exp b/tests/posix/trap-midtoken.exp new file mode 100644 index 0000000..067816d --- /dev/null +++ b/tests/posix/trap-midtoken.exp @@ -0,0 +1,4 @@ +trapped +a b c x +done +[status 0] diff --git a/tests/posix/trap-midtoken.sh b/tests/posix/trap-midtoken.sh new file mode 100644 index 0000000..8d91bbe --- /dev/null +++ b/tests/posix/trap-midtoken.sh @@ -0,0 +1,18 @@ +# A trap fires while a command is half parsed: the parser must resume the +# command, not carry on from a freed arena. +# +# The writer holds the pipe open and feeds `echo "a b` first. When the +# shell has started the command it writes its pid, the trap is delivered +# mid-token, and the rest arrives after the trap has run. +rm -f pid +{ + echo 'trap "echo trapped" USR1' + echo 'echo $$ > pid' + printf 'echo "a b' + while [ ! -s pid ]; do sleep 0.01; done + sleep 0.3 + kill -USR1 "$(cat pid)" + sleep 0.3 + printf ' c" x\n' + echo 'echo done' +} | "$TSH" -- 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') 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 ec1cd3eb8e1aa177329f25d134f372d3e999d4a4 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:23:42 -0600 Subject: fix(arith): parse base#digits without signed overflow `$((99999999999999999999#1))` multiplied its way through INT_MAX: UBSan reports "signed integer overflow" at the base loop in parse_based(), and in a release build the resulting base is whatever the wrap gave. The base is now built with a bound (anything over 64 is "bad number base" at once) and the digits are read by hand against ksh's digit set, so `16#0x10`, `16# f`, `2#2` and `16#` stay errors instead of relying on strtoumax()'s quirks. The digit set is a string looked up with strchr(), not arithmetic on character codes: the letters are not contiguous in EBCDIC, and the same source has to work on both sides. That also makes bases 37 to 64 work, as they do in ksh: `$((64#z))` is 35, `64#_` is 63, `64#@` is 62. Values still wrap at UINTMAX_MAX, which is what the old code did for everything else, so a literal that does not fit is still "bad number". Verified: before the change, zash-asan reports src/arith.c:270 signed integer overflow for the huge base and rejects 64#z; after it, the new tests pass under ASan+UBSan on Linux. The EBCDIC build is untested here (the mapping is a string constant, so it does not depend on the charset). --- src/arith.c | 34 +++++++++++++++++++++++++++------- tests/zash/arith-base.exp | 13 +++++++++++++ tests/zash/arith-base.sh | 11 +++++++++++ 3 files changed, 51 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/arith.c b/src/arith.c index c7c410f..5097134 100644 --- a/src/arith.c +++ b/src/arith.c @@ -266,16 +266,36 @@ static intmax_t apply(const arith *a, binop op, intmax_t x, intmax_t y) { */ static intmax_t parse_based(arith *a, const char *p, const char *hash) { int base = 0; - for (const char *q = p; q < hash; q++) + for (const char *q = p; q < hash; q++) { base = base * 10 + (*q - '0'); - if (base < 2 || base > 36) + if (base > 64) + arith_error(a, "bad number base"); + } + if (base < 2) 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 == '_') + /* + * The digit set of ksh and bash. Spelling it out beats arithmetic on + * character codes: the letters are not contiguous in EBCDIC. + */ + static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ@_"; + uintmax_t v = 0; + const char *q = hash + 1; + for (; *q; q++) { + const char *d = strchr(digits, *q); + if (!d) + break; + uintmax_t dv = (uintmax_t)(d - digits); + if (dv >= (uintmax_t)base) + break; + if (v > (UINTMAX_MAX - dv) / (uintmax_t)base) + arith_error(a, "bad number"); + v = v * base + dv; + } + /* No digits, or a digit the base does not have (16#0x10, 16# f). */ + if (q == hash + 1 || (*q && strchr(digits, *q))) arith_error(a, "bad number"); - a->p = end; + a->p = q; return (intmax_t)v; } diff --git a/tests/zash/arith-base.exp b/tests/zash/arith-base.exp index 9fb1dd6..93d4055 100644 --- a/tests/zash/arith-base.exp +++ b/tests/zash/arith-base.exp @@ -2,4 +2,17 @@ 8 rc=2 arithmetic: bad number base: "1#0" +rc=2 +arithmetic: bad number base: "99999999999999999999#1" +rc=2 +arithmetic: bad number: "16# f" +rc=2 +arithmetic: bad number: "16#0x10" +rc=2 +arithmetic: bad number: "2#2" +rc=2 +arithmetic: bad number: "36#zzzzzzzzzzzzzz" +rc=2 +arithmetic: bad number: "16#" +35 63 61 62 [status 0] diff --git a/tests/zash/arith-base.sh b/tests/zash/arith-base.sh index 5414e08..c361eae 100644 --- a/tests/zash/arith-base.sh +++ b/tests/zash/arith-base.sh @@ -5,3 +5,14 @@ "$TSH" -c 'echo $((1#0))' >/dev/null 2>err echo "rc=$?" sed 's/^[^:]*: line [0-9]*: //' err +# A base too large to be a base, a missing digit, and a digit the base +# does not have are errors, not an overflow trap: the base is built with a +# bound and every digit is validated against the base. +for e in '99999999999999999999#1' '16# f' '16#0x10' '2#2' \ + '36#zzzzzzzzzzzzzz' '16#'; do + "$TSH" -c "echo \$(($e))" >/dev/null 2>err + echo "rc=$?" + sed 's/^[^:]*: line [0-9]*: //' err +done +# ksh's digit set: 10-35 are a-z, 36-61 are A-Z, 62 is '@', 63 is '_'. +"$TSH" -c 'echo $((64#z)) $((64#_)) $((64#Z)) $((64#@))' -- cgit From a5a920383fe85f4dada0cb80418f7a935c12dc4a Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:26:01 -0600 Subject: fix(printf): a negative '*' precision is no precision `printf '%.*d' -5 1` built the conversion "%.-5jd" and printed it literally: a width and precision taken with '*' were written with "%d" of an (int) cast, so a negative precision produced ".-5" in the spec. copy_number() now writes the value with "%jd" - no narrowing, which the review asked for - and, for a precision, drops the '.' again when the value is negative: C99 says a negative precision is as if it were omitted. A negative width stays, where snprintf() reads the '-' as a flag. tests/posix/printf-ext.sh covers all four shapes; the expected output is what dash and bash print. Verified: make check, and the same test under ASan+UBSan on Linux. --- src/printf.c | 20 ++++++++++++++++---- tests/posix/printf-ext.exp | Bin 315 -> 338 bytes tests/posix/printf-ext.sh | 3 +++ 3 files changed, 19 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/printf.c b/src/printf.c index 3e33c53..f366f2d 100644 --- a/src/printf.c +++ b/src/printf.c @@ -150,12 +150,23 @@ static double arg_double(printf_state *pf) { * @param f Position in the format. * @param spec Specification being built. * @param n Receives the new length of `spec`. + * @param dot Length of `spec` before the '.' that starts this precision, + * or 0 when this is the width. * @return Position in the format after the number. */ static const char *copy_number(printf_state *pf, const char *f, char *spec, - size_t *n) { + size_t *n, size_t dot) { if (*f == '*') { - *n += (size_t)snprintf(spec + *n, 16, "%d", (int)arg_int(pf)); + intmax_t v = arg_int(pf); + /* + * C99: a negative precision is as if the precision were omitted, + * so drop the '.' as well; a negative width is a '-' flag, which + * snprintf() reads from the "%*d" this writes. + */ + if (dot && v < 0) + *n = dot; + else + *n += (size_t)snprintf(spec + *n, 24, "%jd", v); return f + 1; } int digits = 0; @@ -184,10 +195,11 @@ static const char *convert(printf_state *pf, const char *f) { spec[n++] = *f; f++; } - f = copy_number(pf, f, spec, &n); + f = copy_number(pf, f, spec, &n, 0); if (*f == '.') { + size_t dot = n; spec[n++] = '.'; - f = copy_number(pf, f + 1, spec, &n); + f = copy_number(pf, f + 1, spec, &n, dot); } switch (*f) { case 'd': diff --git a/tests/posix/printf-ext.exp b/tests/posix/printf-ext.exp index a94b9f3..8ddaab7 100644 Binary files a/tests/posix/printf-ext.exp and b/tests/posix/printf-ext.exp differ diff --git a/tests/posix/printf-ext.sh b/tests/posix/printf-ext.sh index 60bc69c..066aa2e 100644 --- a/tests/posix/printf-ext.sh +++ b/tests/posix/printf-ext.sh @@ -1,6 +1,9 @@ # printf: conversions, widths, escapes and errors. printf '%5.2f|%-8.3e|%g|%G\n' 3.14159 31415.9 0.0001 1e20 printf '%*d|%-*d|%.*f\n' 6 42 6 42 2 2.71828 +# A negative '*' precision means no precision at all; a negative width +# is a '-' flag. (It used to build "%.-5jd", which printf rejected.) +printf '%.*d|%.*s|%*.*f|%0*d|\n' -5 1 -1 abc 3 -2 1.5 -6 42 printf '%c%c%c\n' abc "" z | od -An -c | tr -s ' ' printf '%5c|%-5c|\n' x y printf '%x %X %o %u %i\n' 255 255 8 42 -7 -- cgit From 56bd0e6c2ab87ab140cef35882cff52153f36b7c Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:30:30 -0600 Subject: fix(edit): vi `y` keeps the line and never pastes the old kill `y0` with the cursor at column 0 yanks an empty range, and the old code then inserted the kill buffer at the cursor: with nothing killed yet that was memcpy(dst, nullptr, 0), which UBSan rejects at src/edit_builtin.c:375; with an earlier `cw` behind it, the old kill text was pasted into the line (vi `y` changes nothing on the line). The `y` case now copies the range into the kill buffer with kill_set() - the same block remove_range() used - and puts the cursor at the start of the range, which is where vi leaves it. insert() also returns early for an empty string, so a later caller cannot repeat the null memcpy. Test: tests/linux/i-vi.sh yanks an empty range after a `cw`, so the kill buffer holds text that must not appear. Before the change UBSan reports "null pointer passed as argument 2" and the line comes out as "oneecho yank"; after it, the line is "echo yank". Verified on Linux with make check and the same pty session under ASan+UBSan. --- src/edit_builtin.c | 30 +++++++++++++++++++----------- tests/linux/i-vi.exp | 10 ++++++---- tests/linux/i-vi.sh | 4 ++++ 3 files changed, 29 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/edit_builtin.c b/src/edit_builtin.c index 4d5cfb1..75dd31e 100644 --- a/src/edit_builtin.c +++ b/src/edit_builtin.c @@ -370,6 +370,8 @@ static void reserve(size_t extra) { * @param n How many. */ static void insert(const char *s, size_t n) { + if (!n) /* `y` over an empty range has no kill buffer to paste */ + return; reserve(n); memmove(ed.buf + ed.pos + n, ed.buf + ed.pos, ed.len - ed.pos); memcpy(ed.buf + ed.pos, s, n); @@ -377,6 +379,16 @@ static void insert(const char *s, size_t n) { ed.pos += n; } +/** @brief Make the bytes in [from, to) the kill buffer. */ +static void kill_set(size_t from, size_t to) { + if (from >= to) + return; + free(ed.kill); + ed.kill_len = to - from; + ed.kill = xmalloc(ed.kill_len); + memcpy(ed.kill, ed.buf + from, ed.kill_len); +} + /** * @brief Remove the bytes in [from, to) and put the cursor at `from`. * @param from First byte to remove. @@ -386,12 +398,8 @@ static void insert(const char *s, size_t n) { static void remove_range(size_t from, size_t to, bool save) { if (from >= to) return; - if (save) { - free(ed.kill); - ed.kill_len = to - from; - ed.kill = xmalloc(ed.kill_len); - memcpy(ed.kill, ed.buf + from, ed.kill_len); - } + if (save) + kill_set(from, to); memmove(ed.buf + from, ed.buf + to, ed.len - to); ed.len -= to - from; ed.pos = from; @@ -1281,11 +1289,11 @@ static bool vi_command(int key) { } } if (key == 'y') { - size_t keep = ed.pos; - vi_save_undo(); - remove_range(from, to, true); - insert(ed.kill, ed.kill_len); - ed.pos = keep < from ? keep : from; + /* Yank: the text becomes the kill buffer and stays put. Going + * through remove_range() and inserting it back pasted an older + * kill buffer when the range was empty (`y0` at column 0). */ + kill_set(from, to); + ed.pos = from; break; } vi_save_undo(); diff --git a/tests/linux/i-vi.exp b/tests/linux/i-vi.exp index d9b4e7d..91ef7c6 100644 --- a/tests/linux/i-vi.exp +++ b/tests/linux/i-vi.exp @@ -19,18 +19,20 @@ UPPER $ echo BYE world BYE world $ ech count -/home/skurtz/src/zash/zash: ech: not found +SHELL: ech: not found $ #echo comment $ echo done done $ echo def def $ two three -/home/skurtz/src/zash/zash: two: not found +SHELL: two: not found $ ZZ ZZ two three -/home/skurtz/src/zash/zash: ZZ: not found +SHELL: ZZ: not found +$ echo yank +yank $ abcdef -/home/skurtz/src/zash/zash: abcdef: not found +SHELL: abcdef: not found $ echo bdef bdef $ exit diff --git a/tests/linux/i-vi.sh b/tests/linux/i-vi.sh index 2279886..348d14e 100644 --- a/tests/linux/i-vi.sh +++ b/tests/linux/i-vi.sh @@ -32,6 +32,10 @@ send echo one two three\x1b0dw.\r expect two three send echo one two three\x1b0cwZZ\x1bw.\r expect ZZ ZZ two three +# `y` over an empty range, with nothing killed yet: nothing is pasted and +# no null buffer reaches memcpy (ASan sees that one). +send \x15echo yank\x1b0y0\r +expect echo yank # ... and a count repeats it that many times, on top of the change's own send echo abcdef\x1b0x3.\r expect abcdef -- cgit From 447151dabfbad0a41c8f049938042cd886d9f451 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:31:36 -0600 Subject: fix(ulimit): refuse a limit that does not fit rlim_t `ulimit -s 18014398509481984` (2^54 kbytes = 2^64 bytes) multiplied a 64-bit value by 1024 and wrapped to 0: the command succeeded and set the stack limit to zero. It is now "limit out of range" and status 1, and so is a value that would come out exactly RLIM_INFINITY without the user writing "unlimited". The `ulimit -a` label was copied into a 64-byte buffer for no reason; "% -20s" gets the name straight from the table. And if a build has no RLIMIT_FSIZE entry there is no default resource at all, so say that instead of dereferencing a null pointer. Test: tests/zash/ulimit.sh, in a subshell so a broken build cannot take the test shell down with it. Verified on Linux: before the change the command exits 0 and `ulimit -s` reports 0; after it, the warning and status 1. --- src/builtin_ext.c | 23 +++++++++++++++-------- tests/zash/ulimit.exp | 2 ++ tests/zash/ulimit.sh | 4 ++++ 3 files changed, 21 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/builtin_ext.c b/src/builtin_ext.c index 2f0271a..8983e5a 100644 --- a/src/builtin_ext.c +++ b/src/builtin_ext.c @@ -377,16 +377,12 @@ int builtin_ulimit(int argc, char **argv) { } if (all) { for (size_t k = 0; k < ARRAY_LEN(limits); k++) { - char label[64]; const limit *e = &limits[k]; - size_t n = 0; - for (const char *s = e->name; *s; s++) - label[n++] = *s; - label[n] = '\0'; if (e->unit) - out_printf(&out1, "%-20s (%s, -%c) ", label, e->unit, e->opt); + out_printf(&out1, "%-20s (%s, -%c) ", e->name, e->unit, + e->opt); else - out_printf(&out1, "%-20s (-%c) ", label, e->opt); + out_printf(&out1, "%-20s (-%c) ", e->name, e->opt); limit_print(e, hard && !soft); } return 0; @@ -397,6 +393,11 @@ int builtin_ulimit(int argc, char **argv) { l = &limits[k]; } } + if (!l) { + /* Built without RLIMIT_FSIZE: there is no default resource. */ + sh_warn("ulimit: -f: not supported here"); + return 1; + } if (i >= argc) { limit_print(l, hard && !soft); return 0; @@ -417,7 +418,13 @@ int builtin_ulimit(int argc, char **argv) { sh_warn("ulimit: %s: bad limit", argv[i]); return 2; } - v = (rlim_t)n * l->scale; + /* n * scale may not wrap, and may not quietly mean "unlimited". */ + if (n > RLIM_INFINITY / l->scale || + n * l->scale == RLIM_INFINITY) { + sh_warn("ulimit: %s: limit out of range", argv[i]); + return 1; + } + v = (rlim_t)n * (rlim_t)l->scale; } if (hard || !soft) rl.rlim_max = v; diff --git a/tests/zash/ulimit.exp b/tests/zash/ulimit.exp index 75ed7d8..11fbc2f 100644 --- a/tests/zash/ulimit.exp +++ b/tests/zash/ulimit.exp @@ -9,4 +9,6 @@ same status=2 status=2 0 +status=1 +ulimit: 18014398509481984: limit out of range [status 0] diff --git a/tests/zash/ulimit.sh b/tests/zash/ulimit.sh index a00c2f6..a335e37 100644 --- a/tests/zash/ulimit.sh +++ b/tests/zash/ulimit.sh @@ -9,3 +9,7 @@ ulimit -a | grep -c -- '-n)' ulimit -Z 2>/dev/null; echo "status=$?" ulimit -n abc 2>/dev/null; echo "status=$?" (ulimit -c 0; ulimit -c) +# A limit whose byte count does not fit rlim_t is refused, not wrapped to +# zero: 2^54 kbytes is 2^64 bytes, and it used to become a 0-byte stack. +(ulimit -s 18014398509481984) 2>err; echo "status=$?" +sed 's/^[^:]*: line [0-9]*: //' err -- cgit From 662f3b37dcfad0fd2f193762464c1b9701c96db9 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:33:12 -0600 Subject: fix(expand): trim each positional parameter for ${@#pat} `"${@#ab}"` with `set -- abc abd` joined the parameters first ("abc abd"), trimmed the join, and emitted that as a single field ("c abd"). ksh93 and bash trim each parameter and then apply the "$@" rules: two fields, "c" and "d". expand_all_params() takes the pattern and the operator and trims every parameter before emitting, so `"${@#pat}"` still gives one field each, `"${*#pat}"` one field joined by IFS, and unquoted both split as before. join_params_trimmed() is the join path, and trim() gets a forward declaration because it sits further down the file. Test: tests/zash/trim-all.sh, twelve lines covering all four operators, @ and *, quoted and unquoted, empty parameters and a non-blank IFS. The expected output is ksh93's and bash's, which agree line for line. Verified on Linux with make check. --- src/expand.c | 56 ++++++++++++++++++++++++++++++++++++++++++------- tests/zash/trim-all.exp | 13 ++++++++++++ tests/zash/trim-all.sh | 20 ++++++++++++++++++ 3 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 tests/zash/trim-all.exp create mode 100644 tests/zash/trim-all.sh (limited to 'src') diff --git a/src/expand.c b/src/expand.c index 89106ad..1699fb8 100644 --- a/src/expand.c +++ b/src/expand.c @@ -338,6 +338,9 @@ static void emit_assign_lit(expansion *x, const char *s, size_t n, /* ---- parameters ------------------------------------------------------ */ +static const char *trim(const char *val, const char *pat, param_op op, + size_t *lenp); + /** * @brief Join the positional parameters into one string. * @param sep Separator, or NUL for none. @@ -354,6 +357,27 @@ static const char *join_params(char sep) { return sb_cstr(&sb); } +/** + * @brief Join the positional parameters after trimming each one. + * @param sep Separator, or NUL for none. + * @param pat Pattern for trim(). + * @param op Which trim. + * @return The joined string, in scratch memory. + */ +static const char *join_params_trimmed(char sep, const char *pat, + param_op op) { + strbuf sb; + sb_init(&sb, &scratch); + for (int i = 0; i < shellparam.n; i++) { + if (i && sep) + sb_putc(&sb, sep); + size_t len; + const char *s = trim(shellparam.p[i], pat, op, &len); + sb_put(&sb, s, len); + } + return sb_cstr(&sb); +} + /** * @brief Expand `$@` or `$*` with no operator. * @@ -363,27 +387,38 @@ static const char *join_params(char sep) { * @param x Expansion state. * @param which `@` or `*`. * @param quoted Whether the expansion is inside double quotes. + * @param pat Pattern for `${@#pat}`, or nullptr for plain `$@`. + * @param op Which trim, when `pat` is not nullptr. */ -static void expand_all_params(expansion *x, char which, bool quoted) { +static void expand_all_params(expansion *x, char which, bool quoted, + const char *pat, param_op op) { int n = shellparam.n; char **p = shellparam.p; if (x->mode != X_FIELDS) { - const char *s = join_params(which == '*' ? ifs_first : ' '); + const char *s = + pat ? join_params_trimmed(which == '*' ? ifs_first : ' ', pat, op) + : join_params(which == '*' ? ifs_first : ' '); emit(x, s, strlen(s), quoted); return; } if (quoted && which == '*') { - const char *s = join_params(ifs_first); + const char *s = + pat ? join_params_trimmed(ifs_first, pat, op) + : join_params(ifs_first); emit_quoted(x, s, strlen(s)); return; } for (int i = 0; i < n; i++) { + const char *s = p[i]; + size_t len = strlen(s); + if (pat) + s = trim(s, pat, op, &len); if (quoted) { /* "$@": one field per parameter, even if empty */ - emit_quoted(x, p[i], strlen(p[i])); + emit_quoted(x, s, len); if (i < n - 1) field_end(x); } else { - emit_split(x, p[i], strlen(p[i])); + emit_split(x, s, len); if (i < n - 1 && x->have) { field_end(x); x->sep = SEP_SPACE; @@ -521,7 +556,7 @@ static void expand_param(expansion *x, const param *pm, bool quoted) { if (all) { if (pm->op == PS_NORMAL) { - expand_all_params(x, pm->special, quoted); + expand_all_params(x, pm->special, quoted, nullptr, PS_NORMAL); return; } val = shellparam.n ? join_params(pm->special == '*' ? ifs_first : ' ') @@ -569,7 +604,7 @@ static void expand_param(expansion *x, const param *pm, bool quoted) { if (all && !missing && pm->op != PS_LENGTH && pm->op < PS_TRIML) { /* "${@-word}" with parameters set is just "$@". */ - expand_all_params(x, pm->special, quoted); + expand_all_params(x, pm->special, quoted, nullptr, PS_NORMAL); return; } @@ -580,6 +615,13 @@ static void expand_param(expansion *x, const param *pm, bool quoted) { return; } + if (all && pm->op >= PS_TRIML) { + /* "${@#pat}" trims each parameter; "$@" / "$*" rules follow. */ + expand_all_params(x, pm->special, quoted, expand_pattern(pm->arg), + pm->op); + return; + } + if (!val) { if (opt.nounset && !all) sh_error("%s: parameter not set", pm->name); diff --git a/tests/zash/trim-all.exp b/tests/zash/trim-all.exp new file mode 100644 index 0000000..0380161 --- /dev/null +++ b/tests/zash/trim-all.exp @@ -0,0 +1,13 @@ + + + + + +<> + + + + +[] + +[status 0] diff --git a/tests/zash/trim-all.sh b/tests/zash/trim-all.sh new file mode 100644 index 0000000..1b45bf2 --- /dev/null +++ b/tests/zash/trim-all.sh @@ -0,0 +1,20 @@ +# `${@#pat}` and `${*#pat}`: the trim applies to each positional parameter, +# and then the usual `"$@"` / `"$*"` rules decide the fields. ksh93 and +# bash agree on every line, which is where the expectations come from. +set -- abc abd +printf "<%s>" "${@#ab}"; echo +printf "<%s>" ${@#ab}; echo +printf "<%s>" "${*#ab}"; echo +printf "<%s>" ${*#ab}; echo +printf "<%s>" "${@%c}"; echo +printf "<%s>" "${@%%*d}"; echo +printf "<%s>" "${@##a*b}"; echo +set -- "a b" "a c" +printf "<%s>" "${@#a }"; echo +printf "<%s>" ${@#a\ }; echo +printf "<%s>" "${*% c}"; echo +set -- +printf "[%s]" "${@#a}"; echo +set -- one two +IFS=: +printf "<%s>" "${*#o}"; echo -- cgit From d538cc8ce9c32c932e12134b7bd59a88e88d748c Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:37:39 -0600 Subject: fix(edit): quote the temporary file name for the editor `v` and `fc -e` handed the editor "%s %s" of the editor and the mkstemp file name, unquoted: with a TMPDIR holding a space or a `$` the editor saw a path cut at the space, wrote nothing, and `fc` ran the original commands again. The name now goes through out_quote() into an OUT_MEM buffer, so the shell reads it back as one word; `sprintf` is gone. Both commands also left the file behind when the editor command raised an exception (a syntax error in $EDITOR, for one), because the raise jumps past unlink(). They now catch it, unlink, and re-raise, the same way the builtin wrapper in exec.c does. fc_edit() also ignored a write error on the temporary file and went on to run the editor; it now reports it and removes the file. Test: tests/linux/i-fc-tmpdir.sh runs fc and `v` with TMPDIR="tmp dir$x" through ptydrive, including a raising editor command, and then checks the directory is empty. Without the change the editor is handed the broken path and no file appears. Verified on Linux with make check and the test under ASan+UBSan. --- src/edit_builtin.c | 26 ++++++++++++++++++++++---- src/history.c | 31 +++++++++++++++++++++++++------ tests/linux/i-fc-tmpdir.exp | 11 +++++++++++ tests/linux/i-fc-tmpdir.sh | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 10 deletions(-) create mode 100644 tests/linux/i-fc-tmpdir.exp create mode 100644 tests/linux/i-fc-tmpdir.sh (limited to 'src') diff --git a/src/edit_builtin.c b/src/edit_builtin.c index 75dd31e..b0558f4 100644 --- a/src/edit_builtin.c +++ b/src/edit_builtin.c @@ -994,13 +994,31 @@ static void edit_external(void) { editor = var_get("EDITOR"); if (!editor || !*editor) editor = "vi"; - char *cmd = xmalloc(strlen(editor) + sizeof file + 2); - sprintf(cmd, "%s %s", editor, file); + /* The editor is a shell command, the file name is a word: quote it, so + * a TMPDIR with a space or a `$` in it still names the file. */ + output cmd = {.fd = OUT_MEM}; + out_puts(&cmd, editor); + out_putc(&cmd, ' '); + out_quote(&cmd, file); + out_write(&cmd, "", 1); /* the NUL */ raw_off(); ob_flush(); - int status = eval_string(cmd, 0); + jmploc jl; + jmploc *prev = exc_handler; + int status; + if (setjmp(jl.buf)) { + /* The editor command raised: the file must not be left behind. */ + exc_handler = prev; + raw_on(); + free(cmd.buf); + unlink(file); + exc_raise(exc_code); + } + exc_catch(&jl); + status = eval_string(cmd.buf, 0); + exc_handler = prev; raw_on(); - free(cmd); + free(cmd.buf); char *text = nullptr; size_t nread = 0; if (status == 0 && wrote && (fd = open(file, O_RDONLY)) >= 0) { diff --git a/src/history.c b/src/history.c index 011e0db..b15d6b8 100644 --- a/src/history.c +++ b/src/history.c @@ -291,14 +291,33 @@ static int fc_edit(const char *editor, int lo, int hi) { break; } out_flush(&o); + if (o.err) { + close(fd); + unlink(file); + sh_warn("fc: write error: %s", strerror(o.err)); + return 1; + } close(fd); - strbuf cmd; - sb_init(&cmd, &scratch); - sb_puts(&cmd, editor); - sb_putc(&cmd, ' '); - sb_puts(&cmd, file); - int status = eval_string(sb_cstr(&cmd), 0); + output cmd = {.fd = OUT_MEM}; + out_puts(&cmd, editor); + out_putc(&cmd, ' '); + out_quote(&cmd, file); /* TMPDIR may hold a space or a `$` */ + out_write(&cmd, "", 1); + jmploc jl; + jmploc *prev = exc_handler; + int status; + if (setjmp(jl.buf)) { + /* The editor command raised: the file must not be left behind. */ + exc_handler = prev; + free(cmd.buf); + unlink(file); + exc_raise(exc_code); + } + exc_catch(&jl); + status = eval_string(cmd.buf, 0); + exc_handler = prev; + free(cmd.buf); size_t len = 0; char *text = status == 0 ? read_file(file, &len) : nullptr; unlink(file); diff --git a/tests/linux/i-fc-tmpdir.exp b/tests/linux/i-fc-tmpdir.exp new file mode 100644 index 0000000..f0b9bc0 --- /dev/null +++ b/tests/linux/i-fc-tmpdir.exp @@ -0,0 +1,11 @@ +$ echo hello +hello +$ fc -e "$PWD/ed.sh" +echo fc-edited +fc-edited +$ echo vi-edited +vi-edited +$ fc -e 'echo (' +SHELL: syntax error: unexpected 'WORK/tmp dir$x/zash-fc.XXXX' +$ exit +[status 0] diff --git a/tests/linux/i-fc-tmpdir.sh b/tests/linux/i-fc-tmpdir.sh new file mode 100644 index 0000000..a6177b0 --- /dev/null +++ b/tests/linux/i-fc-tmpdir.sh @@ -0,0 +1,35 @@ +# The editor commands fc and vi's `v` put the temporary file name on a +# command line, so a TMPDIR with a space and a `$` in it has to survive +# quoting. Unquoted, the editor got a path cut at the space, and fc ran the +# original commands again. +command -v python3 >/dev/null 2>&1 || exit 77 +mkdir -p 'tmp dir$x' +cat >ed.sh <<'INS' +#!/bin/sh +printf 'echo fc-edited\n' >"$1" +INS +cat >vis.sh <<'INS' +#!/bin/sh +printf 'echo vi-edited\n' >"$1" +INS +chmod +x ed.sh vis.sh +# The syntax error names the temporary file, whose name has the work +# directory and a random suffix in it: fold both, or the .exp could not be +# compared. +{ +TMPDIR="$PWD/tmp dir\$x" PS1='$ ' ENV='' HISTFILE='' VISUAL="$PWD/vis.sh" \ + python3 "$TESTS/tools/ptydrive.py" "$TSH" -o vi <<'END' +send echo hello\r +expect hello +send fc -e "$PWD/ed.sh"\r +expect fc-edited +send echo hi\x1bv\r +expect vi-edited +# An editor command that raises an exception must not leave the file +# behind either: `echo (` is a syntax error, raised past the unlink(). +send fc -e 'echo ('\r +send exit\r +END +} | sed -e "s|$PWD|WORK|g" -e 's/zash-fc\.[A-Za-z0-9]*/zash-fc.XXXX/' +# Neither editor may leave its file behind. +ls -A 'tmp dir$x' -- cgit From 95bf87d4ed037e6d6786cc395d94dbe44ee88e32 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:39:28 -0600 Subject: fix(edit): vi search reads its pattern into a buffer of its own `/` wrote the new pattern over the old one in ed.search and only wrote a terminator when something had been typed. Type `ban` over `apple`, delete the three letters, press Enter: the buffer still held "banle", so the "empty pattern repeats the previous search" case searched a mix of the two and found nothing (the terminal just beeped). vi_read_pattern() collects the pattern in a local array and copies it into ed.search only when it is non-empty; an empty pattern now really does leave the previous one alone. Test: tests/linux/i-vi.sh searches for apple, then types `ban` + three backspaces + Enter, and expects `echo apple` back. Without the change the line stays empty. Verified on Linux with make check. --- src/edit_builtin.c | 13 +++++++++---- tests/linux/i-vi.exp | 8 ++++++++ tests/linux/i-vi.sh | 10 ++++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/edit_builtin.c b/src/edit_builtin.c index b0558f4..bc66b5a 100644 --- a/src/edit_builtin.c +++ b/src/edit_builtin.c @@ -1161,11 +1161,14 @@ static bool vi_search(bool backwards) { * @return false if the user gave up with ESC or an interrupt. */ static bool vi_read_pattern(char lead) { + /* Read into a buffer of its own: typing over the old pattern and then + * backspacing past it would otherwise leave a mix of two patterns. */ + char pat[sizeof ed.search]; size_t n = 0; for (;;) { ob_putc('\r'); ob_putc(lead); - ob_put(ed.search, n); + ob_put(pat, n); ob_csi(0, 'K'); ob_flush(); int k = read_key(); @@ -1179,12 +1182,14 @@ static bool vi_read_pattern(char lead) { if (k == CH_DEL || k == CH_CTRL_H) { if (n) n--; - } else if (k < 0x100 && !iscntrl(k) && n + 1 < sizeof ed.search) { - ed.search[n++] = (char)k; + } else if (k < 0x100 && !iscntrl(k) && n + 1 < sizeof pat) { + pat[n++] = (char)k; } } - if (n) /* an empty pattern repeats the previous search */ + if (n) { /* an empty pattern repeats the previous search */ + memcpy(ed.search, pat, n); ed.search[n] = '\0'; + } return ed.search[0] != '\0'; } diff --git a/tests/linux/i-vi.exp b/tests/linux/i-vi.exp index 91ef7c6..891cde4 100644 --- a/tests/linux/i-vi.exp +++ b/tests/linux/i-vi.exp @@ -35,5 +35,13 @@ $ abcdef SHELL: abcdef: not found $ echo bdef bdef +$ echo apple +apple +$ echo banana +banana +$ echo apple +apple +$ echo apple +apple $ exit [status 0] diff --git a/tests/linux/i-vi.sh b/tests/linux/i-vi.sh index 348d14e..d5fb71f 100644 --- a/tests/linux/i-vi.sh +++ b/tests/linux/i-vi.sh @@ -44,5 +44,15 @@ send echo abcdef\x1b0wx send l. send \r expect echo bdef +# `/` typed over the previous pattern and backspaced to empty repeats the +# previous search, not a mix of the two patterns. +send echo apple\r +expect apple +send echo banana\r +expect banana +send \x1b/apple\r\r +expect echo apple +send \x1b/ban\x7f\x7f\x7f\r\r +expect echo apple send exit\r END -- cgit From 06e1dd50e4c2e93150b4e14ee2cbed566900cd3a Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:44:42 -0600 Subject: fix(util): refuse an arena size that would overflow arena_alloc() aligned the size and arena_add_chunk() added sizeof (arena_chunk) to it before malloc(), so a size near SIZE_MAX wrapped and handed back a short block. Both now go through out_of_memory() above SIZE_MAX / 2, the same way xmalloc() treats a failed malloc. --- src/util.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/util.c b/src/util.c index c671d77..bdb5431 100644 --- a/src/util.c +++ b/src/util.c @@ -156,6 +156,8 @@ static void arena_drop_chunk(arena *a, arena_chunk *c) { static void arena_add_chunk(arena *a, size_t need) { size_t size = ARENA_CHUNK - sizeof(arena_chunk); arena_chunk *c; + if (need > SIZE_MAX / 2) /* sizeof *c + size must not wrap */ + out_of_memory(); if (need <= size && a->spare) { c = a->spare; a->spare = nullptr; @@ -183,6 +185,8 @@ static void arena_add_chunk(arena *a, size_t need) { * @return Uninitialised memory aligned for any object. */ void *arena_alloc(arena *a, size_t n) { + if (n > SIZE_MAX / 2) /* align_up() must not wrap */ + out_of_memory(); n = align_up(n); if ((size_t)(a->end - a->next) < n) arena_add_chunk(a, n); -- cgit From de0d26a1e6b2916996867c4c11f5146302720587 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:44:42 -0600 Subject: fix(redir): reject a TMPDIR too long for the here-document path The snprintf() into path[PATH_MAX] was unchecked: with a TMPDIR longer than that, the name was truncated and mkstemp() could be pointed at a different directory than the one meant. The length is now checked and the here document falls back to the pipe it already uses on failure. --- src/redir.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/redir.c b/src/redir.c index 2d328a9..edfc212 100644 --- a/src/redir.c +++ b/src/redir.c @@ -109,7 +109,10 @@ static int heredoc_open(const redir *r) { } const char *dir = var_get("TMPDIR"); char path[PATH_MAX]; - snprintf(path, sizeof path, "%s/zashXXXXXX", dir && *dir ? dir : "/tmp"); + int n = snprintf(path, sizeof path, "%s/zashXXXXXX", + dir && *dir ? dir : "/tmp"); + if (n < 0 || (size_t)n >= sizeof path) /* a TMPDIR longer than PATH_MAX */ + return -1; int fd = mkstemp(path); if (fd < 0) return -1; -- 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') 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 From 3abe682147f74104f1f1225e8c142b80018e17e7 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:48:18 -0600 Subject: perf(glob): do not lstat() a component readdir() just named The last component of a pattern was matched by readdir() and then stat'ed again by the recursive call, only to learn that the name it had just read exists. When nothing follows the component, add it straight away; a literal tail and a trailing `/` still go through lstat(), the second because `*/` must not match a file. Measured on Linux (x86-64) with 3000 names in one directory and `set -- d/*` run 200 times: 0.20 s before, 0.05 s after, three runs each, same result count. make check unchanged (126 passed, 1 skipped, the known linux/i-dscomplete failure on this machine). --- src/pattern.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/pattern.c b/src/pattern.c index 0dabc15..46c667c 100644 --- a/src/pattern.c +++ b/src/pattern.c @@ -255,7 +255,12 @@ static void glob_from(globber *g, const char *pat) { continue; g->path.len = dirlen; sb_puts(&g->path, name); - glob_from(g, rest); + /* readdir() already named this entry: the last component needs + * no lstat(), only a literal tail or a trailing `/` does. */ + if (!*rest) + g->add(g->ctx, sb_cstr(&g->path)); + else + glob_from(g, rest); } closedir(dir); } -- cgit From d60c99985c1c4e058dd2de7e6272ef4d48a14686 Mon Sep 17 00:00:00 2001 From: Sean Kurtz Date: Sat, 28 Nov 2026 00:50:57 -0600 Subject: perf(pattern,printf): skip the class table on ASCII, a bare %s through vsnprintf in_range() looked the two ends of `[a-z]` up in the alpha/digit tables to get alphabet order. In ASCII the code order *is* the alphabet order, so the compiler can take one comparison; the tables stay for EBCDIC. convert() formatted a bare "%s" through the spec builder and vsnprintf(), which pads, truncates and checks flags it was never given. Out it goes straight to out_puts(); anything with a flag, width or precision still takes the general path. make check unchanged (126 passed, 1 skipped, known linux/i-dscomplete); the whole suite under ASan+UBSan reports nothing. --- src/pattern.c | 5 +++++ src/printf.c | 4 ++++ 2 files changed, 9 insertions(+) (limited to 'src') diff --git a/src/pattern.c b/src/pattern.c index 46c667c..dded417 100644 --- a/src/pattern.c +++ b/src/pattern.c @@ -30,6 +30,10 @@ static int index_in(const char *set, unsigned char c) { * alphabet. Any other range is by character code. */ static bool in_range(unsigned char lo, unsigned char hi, unsigned char c) { +#if ZASH_ASCII + /* Code order is alphabet order here: one comparison, no table. */ + return lo <= c && c <= hi; +#else static const char *const sets[] = { "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", @@ -44,6 +48,7 @@ static bool in_range(unsigned char lo, unsigned char hi, unsigned char c) { } } return lo <= c && c <= hi; +#endif } /** diff --git a/src/printf.c b/src/printf.c index f366f2d..fabc0b3 100644 --- a/src/printf.c +++ b/src/printf.c @@ -240,6 +240,10 @@ static const char *convert(printf_state *pf, const char *f) { } case 's': { const char *s = next_arg(pf); + if (n == 1) { /* a bare "%s": there is nothing to pad or truncate */ + out_puts(&out1, s ? s : ""); + break; + } spec[n++] = 's'; spec[n] = '\0'; out_printf(&out1, spec, s ? s : ""); -- cgit