summaryrefslogtreecommitdiffhomepage
path: root/src/exec.c
Commit message (Collapse)AuthorAgeFilesLines
* Fix redirection, parser, arithmetic, environment, and exec bugsSean Kurtz25 hours1-8/+34
| | | | | | | | | | | | | | | | | - Fail cleanly in save_fd() when sys_dupfd() fails with errno != EBADF, check moved < 0 in plan_redirs()/plan_apply(), and reject duplicating from closed descriptors in plan_redirs(). - Accept uppercase digits in parse_based() for bases <= 36 while keeping ksh case-sensitive digits for bases 37..64. - Save and restore in_cond, alias_ended_blank, and here_head/here_tail in parse_cmdsub() and parse_substring(); parse inner double quotes inside "${x:-...}" via read_double_quoted(); reject 'for x; in ...'. - Deduplicate repeated temporary assignments in var_environ_with(). - Use access(X_OK) in path_search(), expand PS4 in xtrace() with recursion guarded, report stdout write errors in run_pure()/eval_subshell(), and restore loop/dot/func depth and skip_kind on eval_pipe() error unwind. Verified locally on Linux (make, make zos-lint, make check: 128/129 pass).
* Merge main into perf/cd-inproc: one in-process `( cd dir )`, not twoSean Kurtz33 hours1-71/+152
|\ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | main gained an in-process `( cd dir )` of its own with the 2026-11-28 review merge (the uncommitted working tree the review was written against, committed as cb1688f), so this branch and main both replaced the fork for the same command, in two places. That copy has a defect this branch guards against: with readonly PWD; ( cd / ); echo after the readonly assignment raises out of the saved-cwd block and kills the whole shell - no `after` - where dash and bash both print it (dash rc=2, bash rc=1). `subshell_in_process()` here refuses to run the `cd` in-process unless PWD and OLDPWD are plain, and `builtin_cd_isolated()` holds its own exception handler, so the fork still happens in that case. Resolution: keep this branch's implementation and drop main's ad-hoc branch in eval_subshell() together with the curdir_invalidate() helper added for it, which had no other caller. The tests main brought with it (tests/zash/subshell-cd.sh, tests/proc/subshell-pure.sh) still pass. Verified on Linux (7.3.4-300.fc45.x86_64, 2026-11-28): make check 127 passed / 1 skipped / the known linux/i-dscomplete failure, make asan and make valgrind the same, make mvs-asan 127 passed, make zos-lint clean, the readonly-PWD case now matches dash. Not re-run on cbt.
| * fix(signal): install SIG_DFL with sigaction, not signal()Sean Kurtz47 hours1-1/+1
| | | | | | | | | | | | | | | | | | 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.
| * fix(exec): run the ERR trap when the last command is exec'dSean Kurtz47 hours1-2/+2
| | | | | | | | | | | | | | | | | | | | | | | | | | | | `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.
| * fix(parser): save and restore the parser state in run_inputSean Kurtz47 hours1-1/+35
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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.
| * feat: select, the ksh88 menu loopSean Kurtz2 days1-6/+45
| | | | | | | | | | | | | | | | | | | | | | | | | | IBM's /bin/sh is of the KornShell line and `select` is part of what its scripts use, so the shell that replaces it has to have it. The menu goes to stderr as "number TAB word", then PS3 (default "#? "); the answer is read with the rules of `read REPLY`; a number in range picks that word, anything else leaves the variable empty and the body still runs, a blank line only prompts again, and end of input ends the loop. The node is the `for` node with a `menu` flag, since the two differ only in what the body sees. tests/zash/select.sh prints the same bytes under zash and under the CBT /bin/sh; the specification has the rule.
| * fix: the review findings, each with a regression testSean Kurtz2 days1-67/+97
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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.
* | perf: restore cwd after a lone ( cd dir ) in-processperf/cd-inprocSean Kurtz4 days1-5/+8
| | | | | | | | | | | | | | A subshell whose body is a single cd now runs in the parent shell with the directory, PWD, OLDPWD and curdir saved and restored, instead of forking. On z/OS a fork costs ~0.4 ms there; the cd itself costs ~5 us. A readonly, integer or dynamic PWD/OLDPWD keeps the forked path.
* | perf: run a lone ( cd dir ) without forkingSean Kurtz4 days1-6/+13
|/
* C23: constexpr internal linkage, naming and trailing commas; clangd at C23Sean Kurtz4 days1-5/+12
| | | | | | | | A constexpr at file scope has external linkage, so the CSI offsets and CSI_MAX_CALLS now say static. The naming check gets the C23 spellings wrap the check itself: typed constants keep the macro case, and a local static constexpr table keeps the variable case. .clangd says -std=c23, which it still did not, so the editor could not read constexpr at all.
* C23: nullptr for null pointers, constexpr for typed constantsSean Kurtz5 days1-44/+44
| | | | | | | | | | | | | | nullptr in every place a null pointer constant was meant; NULL is gone from src/. constexpr where it improves on #define without costing anything: the IGGCSI00 work-area offsets and sizes, and the scalar sizes MVS_DSN_MAX, CSI_FIELD_LEN, CSI_WORK_MIN, PDS_DIRBLK, CSI_WORK, CSI_MAX_CALLS. A constexpr in C is a constant expression, so it still bounds the arrays that use it, and it now carries a type and can be checked with static_assert. Feature switches (#if), the CSIETYPE/EBCDIC byte constants read as octets, and the related-constant enum sets stay as they were.
* C23: compile as C23 and use its spellingSean Kurtz5 days1-3/+3
| | | | | | | | | | | | | | | | | | | | | | | The z/OS toolchain would not take C23 when this was first written; IBM Open XL C/C++ 2.2 does (clang 21.1, __STDC_VERSION__ 202311), and so does the clang on Linux. -std=c23 in the Makefile, and the standard attributes in place of the ones that were macros: _Noreturn -> [[noreturn]] (on declarations and definitions) _Static_assert -> static_assert _Alignas -> alignas NODISCARD -> [[nodiscard]] FALLTHROUGH -> [[fallthrough]] PRINTFLIKE and UNREACHABLE() stay macros: [[gnu::format]] and [[gnu::unreachable]] are vendor attributes, and the standard has no [[format]] or [[unreachable]] for a header-only project yet. Standard-library additions newer than the libc of either system (<stdbit.h>, <stdckdint.h>) are not used, so gcc -std=c2x still builds the tree warning-free. The suite, ASan/UBSan and the z/OS lint pass as before; linux/i-dscomplete remains the one local failure it was on main.
* z/OS: run 31-bit and load IGGCSI00 through the C librarySean Kurtz7 days1-11/+11
| | | | | | | | | | | | | zash was AMODE 64, so calling the AMODE 31 IGGCSI00 needed assembler glue (zos_csi.s) that switched addressing mode around the branch. Built with -m32 the program is 31-bit itself: the call goes through a plain function pointer, the work area and the saved registers live in one 31-bit block in C, and the glue is gone. The rest of the tree follows the change: the build, the off-z/OS lint shim, DESIGN.md and README.md, the benches, the Lean spec of the pattern matcher, and the tests that recorded what the extra address bits had changed.
* exec: run a subshell in process when its body cannot change anythingSean Kurtz10 days1-0/+35
| | | | | | | | | | | | | | A `fork()` copies the address space on z/OS, where a `spawn()` can share it. The subshell row measured 4.7 ms a turn there against 0.3 ms for an external command, and ksh88 does not fork for `( : )` at all. The pipeline stage check already answered the safety question with is_pure(), so a subshell whose body is one output-only builtin with no redirections and no assignments reuses the answer and runs in the shell. Expansion of the arguments is wrapped in the same capture scope a pipeline stage uses, so ${x=1} no longer escapes. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* docs: say it in short sentencesSean Kurtz11 days1-14/+15
| | | | | | | | | | | | | DESIGN.md, README.md and the Doxygen comments leaned on semicolons to join clauses and on trailing "which" clauses to add afterthoughts. Both read as machine-written prose. Each joined clause is now its own sentence, and the afterthoughts are either part of the sentence or a sentence of their own. Also corrected: README said C11 in two places (the tree builds C17), the completion section still described the pre-HLQ-rule filters and the 64-call resume limit, and the z/OS job-control note still called SPAWN_SETTCPGRP unverified.
* Read startup files like the interactive shell they belong toSean Kurtz11 days1-2/+3
| | | | | | | | | | | A failing line in $ENV ended the shell: run_input() only installed its recovering handler for the main loop, so sh_error() found no handler and called exit_shell(). An interactive shell must not exit for a command that fails (POSIX 2.5.3), and a .kshrc shared with ksh is full of lines zash rejects. Startup files now run with RI_RECOVER, which recovers from an error without printing a prompt, and the rest of the file is still read.
* fix issues with z/os build, header visibility, signalsSean Kurtz12 days1-1/+8
|
* z/OS: file tagging, catalog completion, time, and per-command optionsSean Kurtz2026-11-151-1/+227
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Tagging and conversion (sys_zos.c, redir.c, input.c, var.c, exec.c): - _TAG_REDIR_IN/OUT/ERR as /bin/sh documents them, cached by variable hooks so redirection tests a byte; honoured as a prefix on external commands and on pipeline stages. - ASCII builds tag new output and here-document files as text, tag pipes IBM-1047 (set +o pipetag to stop), and switch on autoconvert. - Scripts, . files, profile and ENV are read in either character set: tagged files get F_CONTROL_CVT, untagged ones are sniffed. - tag/chtag primitives (sys_tag_get/sys_tag_set) for a builtin to come. Data set completion (complete.c, mvsfmt.[ch], zos_csi.s): - //'HLQ.PART, "//'HLQ.PART, //NAME (user HLQ), //'DSN(MEM, //DD:NAME complete one qualifier at a time from the Catalog Search Interface, PDS directories and the TIOT. - IGGCSI00 is called through HLASM glue that switches to AMODE 31 and keeps every register and parameter below the bar (VERIFY). - The work-area, directory and TIOT decoders are portable and run on Linux against a stand-in catalog that produces the real EBCDIC bytes, including CSI resume and directory-block splits; fuzzed with libFuzzer (make fuzz). - A lone completion inside quotes now closes the quote. Other z/OS features: - time [-p] keyword with shell/children CPU split. - set -o jobnames (_BPX_JOBNAME per command), set -o shareas (_BPX_SHAREAS=YES for foreground commands only), set -o msgid (ZSHnnnnE/W message IDs), ulimit -M (MEMLIMIT), ZOS_SYSNAME, ZOS_SYSPLEX, ZOS_RELEASE, ZOS_ASID, ZOS_JOBNAME, prompt \S. - BPXWDYN entry point for an alloc builtin to come. Checking z/OS code off z/OS: - make zos-lint compiles sys_zos.c against declarations transcribed from the z/OS headers, and the rest with the MVS paths forced on. - make mvs-asan runs the suite with the MVS paths on, under ASan/UBSan. - make asan and make valgrind now check for leaks.
* Errors in command-prefixed special builtins no longer exit; no arena leakSean Kurtz2026-11-151-3/+61
| | | | | | | | | | | | | | `command eval`, `command .` and friends lose the special property that an error exits a non-interactive shell (POSIX 2.14, and dash, bash and ksh93 agree): the error now becomes the status. Only that path pays for a setjmp(). run_input() released its parse arena only on the normal path; an error caught further out (a subshell, command, the prompt) leaked it. Found by running the suite under Valgrind with leak checking, which is now on for make valgrind and make asan. Also renames two locals that shadowed the cond typedef (gcc -Wshadow).
* Add [[ ]], make coverage, and fixes found by edge-case testsSean Kurtz2026-11-151-0/+16
| | | | | | | [[ ]] is parsed into a tree and evaluated without argv or lookup. Fixes: errexit inside a tested subshell, the ${x:?} message, arithmetic on variables holding expressions, printf %c of an empty argument, job text for arithmetic, and \n and \e prompt escapes.
* Add extensions, job control and the interactive layer; convert to C11Sean Kurtz2026-11-131-348/+638
| | | | | | | | | | | | | | | | | Language: $'...', aliases, function keyword, (( )) and let, typeset and integer, print, whence, setvar, ulimit, read -t, RANDOM, SECONDS, the ERR trap, trap -p, chdir, and more set -o names. Job control: a job table, process groups, terminal hand-over through the spawn layer, jobs/fg/bg, wait %n and kill %n. Interactive: prompt expansion, a built-in line editor with emacs and vi modes, completion, history with fc and HISTFILE, and libedit as a compile-time alternative (make EDIT=libedit LDLIBS=-ledit). The source is now C11 (was C23), uses typedef'd structs and enums, and has Doxygen comments throughout. Adds .clang-tidy, .clangd and a Doxyfile.
* zash: scripting core, test suite and benchmarksSean Kurtz2026-11-121-0/+1464
A clean-slate POSIX shell for z/OS UNIX in the Almquist tradition, written in C23 for Clang (Linux) and IBM Open XL C/C++ (z/OS). - Parser, expansion, arithmetic, redirection, traps and builtins. - Spawn-first execution: fd plans instead of fork+dup2, in-shell pure builtins for pipelines and command substitution, $(a | b) without a subshell. - Flat .POSIX Makefile; asan, valgrind, bench, compdb and z/OS targets. - Tests: posix (dash-generated), zash, process accounting, linux, zos. Nothing has been compiled or run on z/OS yet.