# zash: fixes from the 2026-11-27 code review Work list for an implementing agent. Each item has the location, a reproduction, the required fix and the regression test that proves it. Work in priority order; items 1–3 are memory-safety bugs and come first. Reviewed at commit `e8f3a27` (merge of PR #42). Line numbers refer to that commit and will drift; search by function name. ## Ground rules - Language level is C23 (`CSTD = -std=c23`). GCC 13 needs `CSTD=-std=c2x`; clang needs 19+ (`constexpr` in C). - Format with the repo's `.clang-format` (`make format`) and keep `make tidy` clean. Doxygen `/** @brief ... */` comments on anything new. - Plain POSIX `.POSIX` Makefile. Never add a recursive make invocation. - Fail fast and early, but no checks that slow down correct hot paths. - Every fix gets a regression test in the existing format: a `NAME.sh` script and its expected output `NAME.exp` under `tests/posix/`, `tests/zash/`, `tests/linux/` (interactive, driven by `tests/tools/ptydrive.py`) or `tests/zos/`. Use `tests/regen.sh` only after checking the new output by hand. - Before calling an item done, all of these must pass: `make check`, `make asan`, and for item 1 `make valgrind`. - Commit as Sean Kurtz (the repo owner), not as Claude. One commit per item. - Don't touch `formal/` unless an item says so. Where behaviour changes, note it for the spec (non-POSIX behaviour must be documented there). --- ## 1. Error unwinding reads dead stack frames (UB) — critical **Where:** `util.c` `exc_raise`; `exec.c` `unwind_save`/`unwind_restore` and every handler that calls `unwind_restore` after `setjmp` (`run_input`, `guarded_prep`, `run_special_guarded`, `run_pure`, `eval_pipe`). **Problem:** `varscope` and `redirsave` records live on the stack in `run_builtin`, `run_function`, `eval_node`, `eval_pipe`, `eval_background`, `cmdsub_run`, etc., and are linked through `var_scope` / `redir_top`. After `longjmp` those frames are gone, but the handler then calls `unwind_restore()`, which walks the chains through the dead frames. The handler's own calls (`redir_unwind` → `redir_pop` → `dup2`/`close`) overwrite the same stack region while it is being read. C11 7.13.2.1: the lifetime of those objects has ended. ASan can't see this (it unpoisons the stack on `longjmp`); Valgrind can. **Repro (non-interactive):** ```sh cat > /tmp/t2.sh <<'EOF' f() { x=1 let "1/0"; } command eval f >/dev/null 2>&1 echo "after: x=[$x]" EOF valgrind -q ./zash /tmp/t2.sh # Invalid read of size 8 ... in redir_pop / scope_pop, "N bytes below stack pointer" ``` Interactive variant: feed `f() { x=1 let '1/0' 2>/dev/null; }; { f; } >/dev/null` to `./zash -i` on stdin. **Fix:** unwind *before* the `longjmp`, while the frames are still alive. - Add an `unwind` snapshot to `jmploc` (move `unwind` from `exec.h` into `shell.h`, or give `jmploc` an opaque snapshot plus a hook, so that `util.c` doesn't depend on `exec.c` internals). - Every place that installs a handler records the snapshot at `setjmp` time. A small helper is fine, e.g. `exc_catch(jmploc *)` that saves `var_scope`, `redir_top` and `input`. Inside the `run_input` recover loop, record the snapshot again on each iteration. - `exc_raise` calls the restore for `exc_handler`'s snapshot (redirects, then scopes, then input, the same order as `unwind_restore` today), then `longjmp`s. - The existing `unwind_restore` calls after `setjmp` then become no-ops; remove them. - Check every handler, including the ones that don't unwind today (`call_function`, `var_value_expr`, `trap_run_err`, `child_eval`, `exit_shell`, `main`). Their state must still be right when exceptions pass through them. In particular, `call_function` must still restore `shellparam`, `loop_depth` and `func_depth`, and drop its function reference, before it re-raises. - Don't call any function on the abandoned frames after the jump. **Test:** add the repro above (and the interactive variant as a `tests/linux` pty test) to the suite. Extend the `valgrind` target so it also runs the interactive tests; it must report zero errors. --- ## 2. Use-after-free in `for` without `in` **Where:** `exec.c` `eval_for`, the `!has_in` branch; `var.c` `params_set` / `params_free`. **Problem:** the loop copies `shellparam.p` (pointers into `shellparam.base`). A `set --` in the body calls `params_set`, which frees the old base, so later iterations read freed memory. **Repro:** ```sh ./zash-asan -c 'set -- one two three; for a; do set -- xxxxxxxxxxxxxxxx y; echo "[$a]"; done' # AddressSanitizer: heap-use-after-free ... var_set_n <- eval_for ``` **Fix:** keep the parameter block alive for the loop's lifetime. Preferred: reference-count the params block (`shparam.base`) and have `eval_for` hold a reference that it releases when the loop ends, including on exceptions (which item 1's unwind hook can cover). Avoid copying every string per loop. The expected output is `[one] [two] [three]` on separate lines, matching dash and bash. **Test:** `tests/posix/for-params.sh` with the repro, plus the same with `shift` and with nested functions that call `set --`. --- ## 3. Out-of-bounds read with huge positional numbers **Where:** `parser.c` `new_param` (`pm->pos = atoi(name)`); `expand.c` `param_value`. **Problem:** `atoi` overflow is UB, and in practice gives a negative `pos`; `param_value` then reads `shellparam.p[pos - 1]` out of bounds. **Repro:** ```sh ./zash-asan -c 'set -- a b; echo ${4294967295}x' # heap-buffer-overflow ./zash -c 'echo ${99999999999999999999}x' # prints "-cx" ``` **Fix:** parse with `strtol` (or a hand loop) and clamp to `INT_MAX`; anything too large is simply unset. In `param_value`, require `pm->pos >= 1 && pm->pos <= shellparam.n`. **Test:** both repros expand to `x` (unset); under `set -u` they report "parameter not set". --- ## 4. Traps never run again after a trap action raises an error **Where:** `trap.c` `trap_poll` (static `running`). **Problem:** if `eval_string` raises, `running` stays `true` and `exitstatus` isn't restored, so every later trap is silently skipped. **Repro (interactive or stdin):** ```sh printf '%s\n' "trap 'echo trap ran; \${x?boom}' USR1" 'kill -USR1 $$' 'echo a1' \ 'kill -USR1 $$' 'echo a2' | ./zash -i # "trap ran" printed only once ``` **Fix:** install a handler around the action, as `trap_run_err` already does. On an exception, clear `running`, restore `exitstatus` and the scratch arena mark, then re-raise. Also re-check `trap_pending` for signals that were left in `got_signal[]` when the raise cut the loop short. **Test:** the repro prints "trap ran" twice. Add a non-interactive check that an `exit 3` inside a trap still exits with status 3. --- ## 5. `wait $pid` returns 127 after the job was reaped **Where:** `jobs.c` `jobs_reap` (non-interactive branch frees finished jobs); `builtin_wait`. **Problem:** finished background jobs are freed unless they own `$!`, so a later `wait $pid` can't find them. POSIX requires the shell to remember the statuses of known async PIDs. **Repro:** ```sh printf 'false & a=$!\ntrue & b=$!\nsleep 0.3\n:\nwait $a; echo "wait a: $?"\n' > /tmp/w.sh ./zash /tmp/w.sh # wait a: 127 (bash/dash: 1) ``` **Fix:** in non-interactive mode, keep finished jobs (or just `pid → status` records) until `wait` collects them, or until a bound is reached (`sysconf(_SC_CHILD_MAX)`; drop the oldest first). `wait` with no operands clears them. Keep the per-command reap cheap; this is on the hot path for scripts. **Test:** the repro prints `wait a: 1`. Also cover `wait $a $b` and `wait` with no operands. --- ## 6. All external commands report 127 if SIGCHLD is ignored at startup **Where:** `main.c` startup; `jobs.c` `wait_fg`. **Problem:** an inherited `SIGCHLD = SIG_IGN` makes `waitpid` fail with ECHILD, and `wait_fg` then returns 127 for every command. **Repro:** ```sh python3 -c 'import signal,os; signal.signal(signal.SIGCHLD, signal.SIG_IGN); os.execv("./zash",["zash","-c","/bin/true; echo rc=$?"])' # rc=127 ``` **Fix:** set SIGCHLD to `SIG_DFL` early in `main` (before any spawn). On z/OS, check that this doesn't conflict with `_EDC_SIG_DFLT` handling in `sys_init`. **Test:** a small C helper in `tests/tools/` (or the Python one-liner, if the suite already depends on Python) that starts zash with SIGCHLD ignored; expect `rc=0`. --- ## 7. A failed `exec` kills an interactive shell **Where:** `builtin.c` `builtin_exec` → `exec.c` `shell_exec` → `_exit`. **Problem:** POSIX 2.8.1: a special built-in error must not make an interactive shell exit. `exec /nonexistent` currently ends a login shell. The `_exit` path also skips the EXIT trap in non-interactive shells. **Fix:** split out a variant of `shell_exec` that returns the error status instead of exiting. In `builtin_exec`, when `opt.interactive` (and not in a subshell), print the error and return 126/127. Otherwise exit through `exit_shell` so the EXIT trap runs. Fds 0–9 must be restored after a failed `exec cmd` with redirections (`redir_pop(true)` currently keeps them). **Test:** `tests/linux` pty test: `exec /nonexistent/cmd` then `echo survived` prints `survived`. Non-interactive: `trap 'echo bye' EXIT; exec /nonexistent` prints the error, then `bye`, and exits 127. --- ## 8. `set -C` (noclobber) has a race **Where:** `redir.c` `open_file`, `R_OUT` case. **Problem:** it calls `stat()`, then `open(O_TRUNC)`. Two processes using the lock idiom `set -C; echo $$ > lock` can both succeed. **Fix:** under noclobber, `open(path, O_WRONLY|O_CREAT|O_EXCL)`. On `EEXIST`, `stat` the file: if it is *not* a regular file (e.g. `/dev/null`, a FIFO), open without `O_EXCL`/`O_TRUNC`, as bash does. Otherwise fail with EEXIST. On z/OS, keep the tagging (`redir_tag`) behaviour for newly created files. **Test:** existing noclobber tests still pass; add `set -C; : >/dev/null` (must succeed) and a parallel-lock test (two background writers, exactly one succeeds). --- ## 9. A here-doc cut off by end of input uses the delimiter as its body **Where:** `parser.c` `parse_redir` (sets `r->target = tok.word`, the delimiter); `next_token` only calls `read_heredocs()` on `T_NL`. **Repro:** `./zash -c 'cat <target` or use a separate field. Decide whether a missing terminator warns (bash does) and record that choice in the spec. **Test:** the repro prints nothing (or warns and prints nothing). Also test `printf 'cat < /tmp/deep1.sh ./zash /tmp/deep1.sh; echo $? # 139 ``` **Fix:** check `stack_low()` in `parse_unary` (it's on every recursion path) and fail with `arith_error(a, "expression nested too deeply")`. The cost is one compare per unary operator, which is acceptable. Also: `parse_command_node` reports "expansions nested too deeply" for deeply nested `{ }` groups. Make it say "commands nested too deeply". **Test:** the repro exits 2 with a diagnostic; nothing crashes. --- ## 12. EBCDIC build: catalog entry type is converted twice **Where:** `mvsfmt.c` `csi_parse`: `char type = (char)mvs_e2a[e[1]];` **Problem:** in the EBCDIC build (`ZASH_ASCII == 0`) the type byte is already EBCDIC, so converting it gives an ASCII code point. Then `type != 'U'` and `complete.c` `mvs_add`'s `type == 'X'` never match, so aliases don't complete as a level. **Fix:** `char type = ZASH_ASCII ? (char)mvs_e2a[e[1]] : (char)e[1];` (the same rule `mvs_from_ebcdic` follows). Search for any other unconditional `mvs_e2a` / `mvs_a2e` use outside test stubs. **Test:** `make zos-lint` must still pass. If the EBCDIC suite on z/OS (`tests/zos/ebcdic`) can exercise catalog completion, add an alias case there. Otherwise add a unit test in `fuzz/` style that runs `csi_parse` on an EBCDIC entry of type `X`. --- ## 13. Read errors on script input are treated as end of file **Where:** `input.c` `input_fill`; `main.c` script open. **Repro:** `./zash /tmp; echo $?` prints nothing and gives `0`. **Fix:** - In `input_fill`, a `read` error other than EINTR reports `sh_warn("%s: %s", name, strerror(err))` and exits with status 2 for the top-level script (bash: 126 for a directory). Pick one and document it. - In `main`, "cannot open %s" should include `strerror(errno)` and exit 127 for ENOENT, 126 for other errors. **Test:** `zash /tmp` fails with a non-zero status and an "Is a directory" message; a missing script exits 127; an unreadable one (mode 000, skip when running as root) exits 126. --- ## Minor items (do after 1–13) - **Aliases redefined or removed while in use** (`alias.c`): `alias_set` leaks the old value when `in_use`, and `input_fill` computes `alias_ended_blank` from the *new* value. Keep the value that is being read in `input_src` (pointer and length), free superseded values in `input_pop`, and free removed in-use aliases there too. Test under ASan with leak detection on. - **`trap -p SIG`** (`trap.c` `builtin_trap`): with operands, print only those signals' traps instead of treating the first operand as an action. - **`read -t` with a huge timeout** (`builtin.c` `b_read`): `(time_t)timeout` is UB for out-of-range doubles. Clamp the timeout (e.g. to `INT_MAX` seconds) before converting, and clamp `ms` before the `(int)` cast for `poll`. - **ksh compatibility:** - support `base#n` in arithmetic (`$((2#101))`, `16#ff`, bases 2–64); - make `${#@}` and `${#*}` give `$#`, as ksh and bash do. Record both in the spec as extensions. - **`jobs` is marked `BI_PURE`** but `builtin_jobs` frees finished jobs and clears `announce`. Either drop `BI_PURE`, or make it skip changing state when run in-process for a pipeline stage or command substitution. - **`arena_grow` contract** (`util.c`): `newn < oldn` underflows `newa - olda` and the fallback copies `oldn` bytes into a `newn` block. Add `assert(newn >= oldn)` (debug builds only), or handle shrinking, and document the contract in the Doxygen comment. - **`sys_posix.c` uses `pipe2`**, which macOS lacks. If that file is meant to be generic POSIX, fall back to `pipe` plus `fcntl(FD_CLOEXEC)`. ## Investigate, don't fix blind - **`linux/i-dscomplete` fails** on Ubuntu 24.04 / GCC 13 (both normal and ASan builds): completion lists `BIG.DATA.SET112`–`SET119` where the `.exp` doesn't. Determine whether the `.exp` or the code (CSI resume / `CSI_MAX_CALLS` / `MVS_MAX_CANDIDATES` in the test stub) is wrong before regenerating anything. - **z/OS tagging of the shell's own stdout** (`sys_zos.c` `sys_init`): untagged empty regular files or FIFOs on fds 1–2 are tagged 1047 with conversion on. That state lives on the shared open file description, so ASCII-mode children inherit it. Write a `tests/zos/tagging` case like `zash -c 'gzip -c f' > f.gz` with a zopen (ASCII) gzip and check that the archive is byte-identical to one made without zash. Report the result to Sean before changing any behaviour; this is a design decision, not a clear bug. ## Status (working tree, 2026-11-27) Every item above is fixed and has a regression test, except where noted. | # | Fix | Test | |---|-----|------| | 1 | snapshot/restore unwind state in `jmploc` (`shell.h`, `util.c`, `exec.c`, handlers) | `tests/posix/unwind.sh`, `tests/linux/i-unwind.sh` | | 2 | positional parameters reference-counted | `tests/posix/for-params.sh` | | 3 | `${99999999999999999999}` clamped | `tests/posix/pos-large.sh` | | 4 | trap re-armed after its action fails | `tests/posix/trap-raise.sh` | | 5 | `wait $pid` after reaping returns the status | `tests/posix/wait-reap.sh` | | 6 | SIGCHLD ignored at startup reset to SIG_DFL | `tests/posix/sigchld-ign.sh` | | 7 | failed `exec` keeps the shell (and its EXIT trap) alive | `tests/posix/exec-fail.sh`, `tests/linux/i-exec-fail.sh` | | 8 | `set -C` uses `O_EXCL` | `tests/posix/noclobber.sh` | | 9 | here-doc at EOF reads the body, not the delimiter | `tests/posix/heredoc-eof.sh` | | 10 | `cd --` accepted; `PWD` from `getcwd()` on fallback | `tests/posix/cd-dash.sh` | | 11 | arithmetic depth limit | `tests/zash/deep-arith.sh` | | 12 | no double EBCDIC conversion of the CSI type byte | `tests/tools/csi.c` + `tests/zos/csi-parse.sh`: the decoder built twice on z/OS, once per character set, each printing a verdict | | 13 | read errors reported (`2` at top level; `126`/`127` for the script); a directory as the script is refused up front, because z/OS would otherwise read it as empty input | `tests/zash/script-errors.sh`, `tests/zos/script-errors.sh` | Minors: `trap -p SIG` (`tests/zash/trap-p.sh`), `read -t` clamping and NaN (`tests/zash/read-timeout.sh`), `base#n` arithmetic (`tests/zash/arith-base.sh`), `${#@}`/`${#*}` as `$#` (`tests/zash/param-len-at.sh`; `tests/posix/expand-edge.sh` gave that line up because dash disagrees), `jobs` no longer mutates the job table from a pipeline or `$( )` (`tests/zash/jobs-cmdsub.sh`), `arena_grow` contract asserted and documented, `sys_pipe` no longer uses `pipe2`, alias text copied into the input so redefining or removing an alias while its own text is being read is safe (`tests/zash/alias-redefine.sh`; the memory side is covered by `make asan`, which runs it with LSan on). ### Investigation results - `linux/i-dscomplete`: not the line wrapping described above any more. Both the `.exp` and the current build print four names per line and end in `... and 3 more`, but they show *different* names: the `.exp` omits `BIG.DATA.SET112`–`SET119`, the build lists them and drops entries from the end of the window instead. So the candidate pool the stub catalog hands the completion differs from the one the `.exp` was recorded with — a resume / candidate-cap question in `sys_posix.c`'s CSI stand-in, not in the display code. Left failing on purpose; deciding it needs a real catalog (`MVS_MAX_CANDIDATES`, `CSI_MAX_CALLS`) rather than a regenerated `.exp`. - z/OS stdout tagging: investigated on the host, and the suspicion in item 12's neighbourhood does not hold. `gzip -c f > g1.gz` under `/bin/sh`, `zash -c 'gzip -c f' > g2.gz` and `zash -c 'gzip -c f > g3.gz'` produce the same 63 bytes (`cmp` identical, `gzip -dc` works on each), because an ASCII gzip turns conversion off for its own descriptor. The 1047 tag on those files is what `/bin/sh` leaves too: the host runs with `_BPXK_AUTOCVT=ON` and `_CEE_RUNOPTS=FILETAG(AUTOCVT,AUTOTAG)`. `python3` output is converted under both shells alike. So no behaviour changed: the review's case is now pinned in `tests/zos/tagging.sh` (`-- binary output through a redirect`), and DESIGN.md's "File tags" table and its "the tag follows the writer" paragraph were corrected to describe what `sys_zos.c` does (hard IBM-1047 text plus conversion for a file the shell creates; a deferred tag only for the `_TAG_REDIR_*` cases). - The two deliberate divergences are now in the specification instead of only in this file: R-LEX-17 says zash does not warn about a here-document cut off by input (`bash` does), and the new zash-only ERR rule gives the statuses for a script that cannot be opened (127, 126) and for a read error while input is being read (2, after the `EXIT` trap). ### z/OS results (2026-11-27) Built and tested on the z/OS host with IBM make and IBM Open XL, in a copy of the tree rather than in place: `tar` the tracked and untracked files, extract into `~/src/zash-rv`, `chtag -R -t -c ISO8859-1 .`, then `/bin/make zos-check`. ibm-clang compiles the whole shell without a warning. - `make zos-ascii` and `make zos-ebcdic` work with IBM make; `make` itself still dispatches to `zos-ascii` on OS/390. - ASCII suite on z/OS: 113 passed, 6 skipped, 0 failed. The skips are the three character-set ones (`posix/printf-ext`, `zash/ash-differences`, `zash/script-errors`), `perf/startup`, and the two z/OS tests the ASCII pass leaves to the EBCDIC pass (`zos/builtins`, `zos/ebcdic`). `zos/csi-parse` runs there and builds its own decoder twice, so both `ZASH_ASCII` branches are exercised on the host. - EBCDIC subset: `tests/run.sh ./zash-ebcdic zos/ebcdic` passes. - `zash/script-errors` cannot expect the same output on both hosts, so the POSIX cases stay in it and the runner skips it on z/OS (`zos_skip`), while `tests/zos/script-errors.sh` records what z/OS does: a mode 000 script still runs, because bit mode does not decide access there. - `zash/deep-arith` had to change shape to pass on z/OS: the generated script is piped into the shell's stdin instead of being written to a file, because a redirect of another program's output is tagged and converted there, and only the head of the message is matched, because z/OS `sed` gives up on a 400 KB line with a regex backtracking error. - Interactive tests (`tests/linux/*`) do not run on z/OS: `tests/tools/ptydrive.py` is a Linux tool and the pty path is untested there. - `linux/i-dscomplete` stays a Linux-only test and its failure is a property of the stub catalog in `sys_posix.c`: Linux has no datasets and no CSI, so the `.exp` cannot describe anything real. Answering it needs the z/OS catalog, not a regenerated `.exp`.