zash

# zash design

Sean Kurtz

This is the reference for how zash is built and why. It records decisions, not a wish list. Where something is planned but not built, or written but not yet verified on z/OS, it says so. ## Contents 1. [What zash is](#what-zash-is) 2. [Language level](#language-level) 3. [Source layout](#source-layout) 4. [Process creation](#process-creation) (the central design point) 5. [Character sets](#character-sets) 6. [Memory](#memory) 7. [Parsing](#parsing) 8. [Expansion](#expansion) 9. [Redirection](#redirection) 10. [Variables](#variables) 11. [Errors and unwinding](#errors-and-unwinding) 12. [Signals and traps](#signals-and-traps) 13. [Builtins](#builtins) 14. [The z/OS layer](#the-zos-layer) - [File tags and automatic conversion](#file-tags-and-automatic-conversion) - [MVS names: completion and the catalog](#mvs-names-completion-and-the-catalog) - [Per-command z/OS options](#per-command-zos-options) - [Checking z/OS code off z/OS](#checking-zos-code-off-zos) 15. [HLASM](#hlasm) 16. [Testing](#testing) 17. [Deliberate differences from other shells](#deliberate-differences-from-other-shells) 18. [Extensions](#extensions) 19. [The interactive layer](#the-interactive-layer) 20. [Job control](#job-control) 21. [Roadmap](#roadmap) 22. [Open questions](#open-questions) ## What zash is A replacement for the z/OS `/bin/sh`, modelled on FreeBSD's `sh`: a small, quick POSIX shell of the Almquist family, with enough interactive support to serve as a login shell. The intended users are shops with tight MSU budgets, or shops that care how much CPU their scripts burn and do not want to move every UNIX user to bash or zsh. zash is new code. FreeBSD sh and dash are the models for behaviour and for the overall shape (a tree-walking evaluator, a stack allocator, buffered builtin output), but the internals differ where z/OS makes the classic ash choices expensive or unsafe. The two main cases are process creation and character encoding. ## Language level - C23, compiled with `-std=c23` and no compiler extensions beyond a few attributes that are wrapped in macros. C17 was the default until both toolchains could be relied on at C23: IBM Open XL C/C++ 2.2 (clang 21.1) reports `__STDC_VERSION__` 202311 and accepts `-std=c23`, so there is nothing left to hold back for. - Clang on Linux, IBM Open XL C/C++ (Clang-based) on z/OS. The tree also builds cleanly with GCC (`-std=c2x -pedantic -Wall -Wextra`), which is checked from time to time to keep the code honest. The legacy z/OS XL C/C++ (`xlc`) is not a target. - What the code uses from C23: `[[noreturn]]`, `[[nodiscard]]`, `[[fallthrough]]`, `static_assert`, `alignas`, ``, designated initialisers, compound literals, flexible array members, `static` array parameters. Standard-library additions newer than both systems' libcs (``, ``) are not used. - Three attributes are used directly, as standard attributes: `[[noreturn]]` and `[[nodiscard]]` on declarations and `[[fallthrough]]` in a `switch`. Two more, `UNREACHABLE()` and `PRINTFLIKE` for format checking, remain macros in `shell.h` because the standard has no spelling for them yet. - Constants are `constexpr` where a typed constant is better: the IGGCSI00 work-area offsets and sizes, `MVS_DSN_MAX`, `CSI_WORK`, `PDS_DIRBLK`. A `constexpr` in C is a constant expression, so it can still bound an array (`unsigned char work[CSI_WORK]`), give a type to a value, and be checked with `static_assert`. Feature switches that `#if` reads, and sets of related integer constants, stay macros and anonymous `enum`s: `#if` cannot see a `constexpr`. - `nullptr` everywhere a null pointer constant is meant; `NULL` is not used. - Warnings: `-Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wconversion`, and the tree stays warning-free. ### Style - Formatting: clang-format (`.clang-format`: LLVM base, 4-space indent, 80 columns). `make format` applies it. - Types are declared as `typedef struct name { ... } name;` and `typedef enum name { ... } name;` and are then used by the bare name. A struct that refers to itself uses `struct name *` inside its own body. An enum that only groups constants (flag bits, key codes) stays anonymous and gets no typedef. - Because typedef names share a namespace with variables, a type is never given the name of an existing variable or function: hence `input_src` (there is a global `input`), `tok_kind` (the current token is `tok`) and `arena_marker` (the function is `arena_mark()`). - Every function, type, global and macro has a Doxygen comment (`/** @brief ... */`) at its definition. Struct members and enum constants are documented with `/**< ... */`. Prototypes in headers are not documented a second time. Longer explanations use Markdown. `make doc` runs Doxygen if it is installed, and `make docs` renders this file and README.md to HTML and PDF in `docs/`, which is generated and not committed. The PDF comes from the HTML through a headless browser, so no LaTeX installation is needed. The colours are the ones `formal/zash-spec.typ` uses, and the README's logo is the colour one there; the monochrome pair exists for the browsers' dark mode on the repository page. - `.clang-tidy` and `.clangd` are provided, and `make tidy` and `make compdb` drive them. ## Source layout One directory, one module per file, each with a narrow header. | File | Contents | | --- | --- | | `shell.h`, `util.c` | heap, arenas, string builder, buffered output, errors | | `charset.h` | control characters that differ between ASCII and EBCDIC | | `ast.h` | parse tree types | | `input.c`, `parser.c`, `parser.h` | input stack, lexer, recursive-descent parser | | `alias.c` | alias table, `alias`, `unalias` | | `var.c`, `var.h` | variables, scopes, positional parameters, environment | | `expand.c`, `expand.h` | word expansion, field splitting, globbing | | `pattern.c` | `case`/glob/trim pattern matching | | `arith.c` | `$(( ))`, `(( ))`, `let` | | `exec.c`, `exec.h` | evaluator, pipelines, command substitution | | `jobs.c` | child processes, the job table, job control, `jobs` `fg` `bg` `wait` | | `unparse.c` | command text for job listings | | `redir.c` | redirection: real and planned | | `trap.c` | signals, `trap`, `kill` | | `builtin.c`, `test.c`, `printf.c` | POSIX builtins | | `builtin_ext.c` | `print`, `whence`, `typeset`, `let`, `setvar`, `ulimit` | | `interact.c`, `interact.h` | prompts and reading lines from a terminal | | `history.c` | history list, `HISTFILE`, `fc` | | `edit_builtin.c` | the built-in line editor (emacs and vi modes) | | `edit_libedit.c` | the same interface on top of libedit (optional) | | `complete.c` | completion candidates for the built-in editor | | `sys_posix.c`, `sys_zos.c`, `sys.h` | the only platform-specific code | | `main.c` | startup, options, exit | Everything except `sys_zos.c` compiles and runs on Linux. That is a design constraint, not a convenience: it is what lets the sanitizers and Valgrind cover almost the whole shell. ## Process creation This is where zash differs most from a classic ash, and where the z/OS performance comes from. ### The cost model On z/OS, `fork()` creates a new address space and copies the parent into it. `spawn()` creates the child directly, and with `_BPX_SHAREAS=YES` (or `REUSE`) in the child's environment the child runs as a task in the *parent's* address space. That is far cheaper again. `/bin/sh` is fast on z/OS largely because it uses `spawn()` this way. A forked child can never share the address space. So the rule is: > **Never create a process if the work can be done in the shell. If a > process is needed, use `spawn()`. Use `fork()` only when the language > requires a copy of the shell itself.** Measured on z/OS, with the same compiler and source in both address modes, several of these assumptions turn out to need qualifying: | | `-m64` | `-m32` | | --- | --- | --- | | `fork()` + `wait()`, empty parent | 0.10 ms | 0.10 ms | | `fork()` + `wait()`, 64 MB touched | 28.2 ms | 27.7 ms | | start a trivial program | 1.5 ms | 1.5 ms | There was a fixed penalty for Language Environment at 64 bits, about 4 ms per fork and 28 ms per program start whatever the program did or held, when these numbers were first taken. It was not the address mode (an assembler program with no C run-time starts in 0.8 ms at either width) and not the enclave: it was the 64-bit C run-time on the linklist, loaded and relocated in every new address space. In the dynamic LPA it costs nothing, the two widths measure the same, and the real remaining cost is the one both modes pay: - A copy cost both modes pay, about 0.4 ms per MB of touched private storage. At 64 MB it swamps the address-mode difference and the two modes converge. Two consequences. The rule above still holds, since `spawn()` costs no more than `fork()` and avoids the copy, and now it rests on the copy alone: z/OS `fork()` on a small address space is as cheap as any other system's. The three rows zash used to lose on z/OS (`( : ) &`, `( cd / ) &`, `( cd / )`) were lost to the run-time load and are no longer losses, which is why the z/OS build is 64-bit. The start-up figure does not appear in `make bench`, which measures CPU and not wall time, but it is what a `#!` script or a `zash -c` pays. LE's `HEAP64`/`HEAPPOOLS64`/`STACK64` settings make no measurable difference to either cost, so there is nothing to tune there. [bench/README.md](bench/README.md) has the numbers and the method; [notes/investigation.md](notes/investigation.md) has the probe programs and what they leave open; [README.md](README.md#recommendations) has the LPA change for a z/OS system. ### What each construct costs | Construct | Mechanism | | --- | --- | | `cmd args` (external) | one `spawn()` | | `builtin args`, function call | none | | `a \| b \| c`, all external | one `spawn()` each, no forks | | `echo x \| cmd` (output-only builtin, not last) | builtin runs in the shell and writes to the pipe, `spawn()` for `cmd` | | `cmd \| while read ...` (last stage not external) | last stage runs in the shell, `spawn()` for `cmd` | | `$(cmd args)` (external) | one `spawn()` with stdout on a pipe | | `$(echo ...)`, `$(printf ...)`, `$(pwd)` | none: output captured in memory | | `$(`. Bracket ranges such as `[a-z]` are matched by alphabet position when both ends are letters of the same case (or both digits), and by code point otherwise. - No tables sorted by hand. Lookup tables are hashed, not binary searched in source order, because collation differs. - Character literals only. Never a numeric code for a character. ## Memory - `scratch`: a bump arena used as a stack. A command takes a mark, expands its words into the arena, runs, and releases to the mark. No per-string `free()`. - Parse arenas: each top-level command is parsed into a reference-counted arena. Normally it is reset and reused for the next command. If the command defines a function, the function takes a reference and the read loop moves on to a fresh arena. Function bodies are therefore never copied, and are freed when the function is redefined or unset and no call is in progress. - Heap: long-lived things only: variables, the command table, traps. Each arena keeps one released chunk for reuse, so a loop body crossing a chunk boundary does not `malloc()` and `free()` on every iteration. Recursion depth (functions, `eval`, `.`, nested commands and expansions) is bounded by the stack in use, measured from a frame address taken in `main()` against half of `RLIMIT_STACK`, not by a count: frame sizes differ too much between platforms and build types for a count to mean anything. Running out produces "nested too deeply", not a crash. ## Parsing A hand-written lexer and recursive-descent parser produce the tree in `ast.h`. Notes: - Words are parsed into parts once, at parse time. A word that is a plain literal is flagged so that expansion is a pointer copy. - Command substitutions are parsed recursively into subtrees when the enclosing word is read, not re-parsed at each expansion. - Here-document bodies are read when the newline after the command is consumed, and parsed into parts unless the delimiter was quoted. - `$((` always starts arithmetic. Write `$( (` for a subshell inside a command substitution (dash has the same rule). - Input is a stack of sources (file, string). Commands read from stdin are never over-read: see `input.c`. ## Expansion One pass over a word's parts produces fields. Each byte written carries one bit of provenance (quoted or not), kept in a parallel buffer. Field splitting and globbing read that buffer instead of the text, so quote characters are never re-scanned. Field splitting happens as unquoted expansion results are appended. A field is globbed only if it contains an unquoted metacharacter. Globbing and pattern matching are zash's own (`pattern.c`), not the C library's, so behaviour is identical on every platform and in both character sets. ## Redirection Redirections are resolved (files opened, here-documents materialised) by one routine and then applied in one of two ways: - Planned, for external commands. An `fdplan` is an array saying which parent descriptor each child descriptor 0..9 should be. Redirections edit the array. Nothing is `dup2()`ed in the shell. The plan is handed to `spawn()` as its `fd_map` on z/OS and translated to `posix_spawn` file actions elsewhere. - Real, for builtins, functions and compound commands. The affected descriptors are saved above 10, replaced, and restored afterwards. Here-documents up to `PIPE_BUF` are written into a pipe by the shell; larger ones go to an unlinked temporary file. Neither needs a process. User-visible descriptors are 0..9. The shell's own descriptors live at 10 and above and are close-on-exec. ## Variables A hash table of `name=value` strings, so building `envp` is a matter of collecting pointers. The array is cached and rebuilt only when an exported variable changes. Variables inherited from the environment are referenced in place, not copied. Scopes are a single mechanism with three uses: `local` variables in functions, temporary assignments (`VAR=x cmd` for builtins and functions), and the capture scope described under [Process creation](#running-builtins-without-a-subshell). A scope is a list of saved variable states that is replayed when the scope is popped. ## Errors and unwinding Errors that abort a command (`sh_error`) raise an exception with `setjmp`/`longjmp`. `break`, `continue` and `return` do *not* use `longjmp`. They set a flag that the evaluator's loops check, keeping the common paths free of `setjmp`. Code that holds state across a possible exception (pushed redirections, variable scopes, input sources) registers it on a global stack. Whoever catches the exception unwinds those stacks to where they were. A non-interactive shell exits on such errors, as POSIX requires. Signal handlers only set flags. Nothing is ever `longjmp`ed out of a handler. ## Signals and traps `trap` actions run between commands. Signals that were ignored when a non-interactive shell started cannot be trapped. A spawned child gets default dispositions for anything the shell catches (automatic on exec) and for anything the shell ignores for its own purposes (passed to `spawn()` explicitly). On z/OS the shell sets `_EDC_SIG_DFLT=1` in its own environment at start-up (unless the user set it). Language Environment otherwise prints `CEE5208S The signal SIGxxx was received.` on stderr whenever a process dies of a signal with the default action, which is noise in a script's output that `/bin/sh` does not produce; the runtime reads the variable when the signal arrives, so the children the shell forks inherit it too. Job control (process groups, `fg`, `bg`, `^Z`) is part of the interactive milestone. ## Builtins `.` `:` `[` `break` `cd` `command` `continue` `echo` `eval` `exec` `exit` `export` `false` `getopts` `hash` `kill` `local` `printf` `pwd` `read` `readonly` `return` `set` `shift` `test` `times` `trap` `true` `type` `umask` `unset` `wait`. `echo`, `printf` and `test` are builtins because scripts call them constantly and a process each would dominate run time. `echo` follows XSI, like the z/OS `/bin/sh` and dash: `-n` is recognised and backslash escapes are always interpreted. ## The z/OS layer `sys_zos.c` is the only C file that knows about z/OS, and the whole z/OS layer is C: there is no assembler left in the tree. It provides: - `sys_spawn()`: `spawn()` with `fd_map` taken from the fd plan and a `struct inheritance` for signal defaults and process group. - `sys_pipe()`, `sys_dupfd()`, `sys_open()`: close-on-exec variants. - File tags and conversion (below). - System facts from control blocks, the catalog, PDS directories, the TIOT and BPXWDYN (below). `sys_posix.c` has the same interface. Its tagging calls are no-ops, and its MVS calls work against a stand-in catalog file so the code above them can be tested (see [Checking z/OS code off z/OS](#checking-zos-code-off-zos)). Code outside `sys_*.c` tests `SYS_MVS`, a compile-time 0 or 1, so the Linux build compiles the z/OS-only branches away entirely. It compiles and runs on z/OS. `make zos-ascii` and `make zos-ebcdic` build it with ibm-clang for both character sets (ASCII is the default `./zash`, the build zopen uses, and EBCDIC is `./zash-ebcdic`). `tests/zos/*` drive spawn, pipes, the environment handed to `spawn()`, tagging, TSO and the MVS decoders there, and `make zos-heapcheck` runs the whole suite under LE `HEAPCHK` and `HEAPZONES`, the nearest thing z/OS has to ASan. In that mode two signal tests (`posix/traps`, `scripts/signals`) fail, because a self-`kill` no longer ends the shell the way it does under `zos-check`; they pass in `zos-check` and pass individually under the same run options, and they have not been rewritten to allow for the mode. What no test reaches is still marked `VERIFY` in the source: - the tagging system calls: a deferred tag applied by a writer with autoconversion off, `SETCVTON` with `pccsid` 0 after `spawn()`, an explicit `fccsid` on an untagged file, `__ae_autoconvert_state()`, `__chattr()`; - the control-block offsets behind `sysinfo`, `\S` and the job name, and the TIOT walk; - PDSE directories as `fopen()` delivers them. ### File tags and automatic conversion The z/OS shell's rules (z/OS UNIX Command Reference, `sh`, "Shell variables for automatic conversion") are followed, and an ASCII build adds what it needs to work beside EBCDIC programs. | Situation | EBCDIC build | ASCII build | | --- | --- | --- | | `>`, `>\|`, `>>` creating or truncating an untagged file, variable unset | nothing (as `/bin/sh`) | deferred text tag: CCSID of the first writer | | `_TAG_REDIR_OUT` / `_ERR` = `TXT` or `BIN`, untagged empty target on fd 1 / 2 | deferred tag, text flag on / off | same | | target already tagged, or has data, or is a device | left alone | left alone | | `_TAG_REDIR_IN=TXT`, tagged input on fd 0 | `F_CONTROL_CVT` `SETCVTON` from the tag | same | | `_TAG_REDIR_IN=BIN` | `SETCVTOFF` | same | | pipe, `_TAG_REDIR_OUT` set | deferred tag on the write end | same | | pipe, variable unset | nothing | tagged IBM-1047 text (`set +o pipetag` to stop) | | here-document temp file | nothing | tagged IBM-1047 text | | script, `.` file, profile, `ENV` tagged in the other CCSID | conversion on for the descriptor | same | | untagged script | first 512 bytes sniffed (0x15 vs 0x0A newlines) | same | | process start | autoconvert left as the user set it | autoconvert switched on if off | Decisions and reasons: - Hooks, not lookups. `_TAG_REDIR_*` are watched by variable hooks (as `PATH` and `IFS` are), so a redirection tests a cached byte. A prefix on an external command (`_TAG_REDIR_OUT=TXT cmd >f`) never becomes a shell variable. `run_external()` therefore scans the command's own assignments, and only when there are any. - Pipeline stages. A prefix on a stage tags that stage's pipe end: `_TAG_REDIR_OUT=TXT a | b` tags `a`'s output, as documented for `/bin/sh`. - The tag follows the writer. A deferred tag takes the CCSID of the first program that writes, so an EBCDIC tool behind `>` in an ASCII shell still produces a correctly tagged IBM-1047 file. - Pipes in ASCII builds are IBM-1047. If they were tagged 819 (as zoslib does) an EBCDIC reader would see ASCII. Tagged 1047, ASCII writers are converted on write and ASCII readers on read. Between two ASCII programs that costs two conversions per byte. `set +o pipetag` avoids it when no EBCDIC program is involved. - Sniffing. Single-byte CCSIDs only, so file offsets are unchanged and the `lseek()` that keeps a shared stdin correct still works. Standard input is never converted: its conversion state is shared with the commands the shell runs. - Recommendation. For a `/bin/sh` replacement, build EBCDIC: 1047 scripts need no conversion at all. Build ASCII for zopen environments. Cost: one `fstat()`/`fcntl()` per redirection, here-document or script, never per byte in the shell. With the variables unset an EBCDIC build does nothing. Linux compiles it all out. The kernel's conversion CPU is paid only where tag and program CCSID differ, as with `/bin/sh`. `bench/tagging.sh` measures it on z/OS against `/bin/sh` and bash. VERIFY on z/OS: - that a deferred tag is applied by a writer with autoconversion off - `SETCVTON` with `pccsid` 0 after `spawn()` - `SETCVTON` with an explicit `fccsid` on an untagged file - `__ae_autoconvert_state()` and its constants - `__chattr()` for `sys_tag_set()` ### MVS names: completion and the catalog Tab after a word starting `//` completes MVS names: | Typed | Completes to | Source | | --- | --- | --- | | `"//'SYS1.MA` or `//\'SYS1.MA` | `//'SYS1.MACLIB'`, `//'SYS1.MACROS.` | catalog | | `//NAME`, `"//'SY` | nothing: the high-level qualifier is incomplete | (none) | | `"//'SYS1.MACLIB(GE` | `//'SYS1.MACLIB(GETMAIN)'` | PDS directory | | `//DD:SYSP` | `//DD:SYSPRINT` | TIOT | Names complete one qualifier at a time, like directories: a candidate with more below it ends in `.` and takes another Tab. A lone final candidate inside `"` gets the closing quote and a space. Outside quotes the editor adds the backslashes the shell needs (`\'`, `\(`). Input is folded to upper case. Nothing is searched until a whole high-level qualifier has been typed: `//'SYS1.` and no less. A filter whose first qualifier is generic (`SYS*`) would make Catalog Management resolve aliases generically, and Managing Catalogs warns that such a high-level qualifier can select several catalogs at once, with `**` meaning every user catalog. A Tab key is no reason to ask that of the catalog address space. Two catalog searches per Tab: `PREFIX*` (names ending in the qualifier being typed) and `PREFIX*.**` (names below it). Filter keys are validated before the catalog is asked (`csi_filter_ok()`): 1-44 characters, qualifiers of 1-8, legal characters, and a first qualifier that is not all wildcard. The catalog search interface. IGGCSI00 takes three addresses in a standard OS parameter list: reason area, selection criteria, work area, with the VL bit on the last. IGGCSI00 is AMODE 31, and zash reaches it through a function pointer: the compiler's OS linkage builds the parameter list and switches to 31-bit addressing for the call, so there is no mode switch of our own and no assembler. `fetch()` loads the module on the first search, and it stays loaded for the life of the shell: a Tab already asks the catalog as much as a screen can show, and it should not also ask the system to search its directories every time. Two details matter, and the second is not obvious: - The function type is declared with `#pragma linkage(iggcsi_fn, OS_UPSTACK)` at `-m32`, **not** plain `OS`. Under `-m32` (XPLINK) `OS` means `OS_NOSTACK`, which does not give the callee a standard 72-byte save area on R13. IGGCSI00 is a traditional upward-stack OS routine, so it takes a program check on the first call. Measured on z/OS: `OS` abends, `OS_UPSTACK` returns rc=0 with 15,250 bytes of entries for `SYS1.**`. `OS_UPSTACK` does not exist at `-m64`, where plain `OS` is the linkage the compiler documents for an XPLINK caller of an AMODE 31 routine, so that is what the 64-bit build uses. - The name handed to `fetch()` is an ordinary `"IGGCSI00"` literal, and **not** the eight IBM-1047 bytes the assembler used to pass to LOAD. Under `-fzos-le-char-mode=ascii`, `fetch` is remapped to `__fetch_a`, which converts the name itself, so handing it EBCDIC bytes double-converts them and LOAD returns nothing. `sys_dynalloc()` fetches `"BPXWDY2 "` the same way, and at 31-bit that fetch really does succeed, which is why tests that used to skip now run. The searches are narrow on purpose: - `CSIS1CAT` is `Y`, so a search touches one catalog and then the master catalog. The caution about generic high-level qualifiers is about exactly this. - The entry types are non-VSAM, generation data group and data set, cluster, alternate index and VSAM path (`ABCGHR`). Blank would add user catalog connectors and aliases, and those are not data set names. - The work area is 32 KB (32768 bytes); IBM recommends 64,000. One call returns about 560 names at roughly 58 bytes an entry, and the search stops after `CSI_MAX_CALLS` = 3 of them: more names than a completion screen can show. - Before a resume, the required length (`CSIREQLN`) is compared with the work area. Managing Catalogs asks for that check, and an entry that no longer fits ends the search instead of being asked for again. The request asks for one field, `VOLSER`, as IBM's samples do. That makes every data entry's layout certain (`CSITOTLN`, reserved, one length, the data) rather than depending on how zero fields are returned. Halfword lengths. Catalog entries (type `0`) and entries in error (flag X'40') are skipped. One search at a time: a nested search is refused rather than given a second block, because the work area carries the resume name and the return code of the search that is running. The block is taken per search and freed before the search returns, so a forked child carries no idle 32 KB. The loaded module stays loaded unless an abend retires it; MVS drops it at task end. **Failure is final.** A search that fails returns false and is not retried: `csi_dead` makes every later search return at once without calling IGGCSI00. The one failure that is new at 31-bit is a program check or abend inside the module, which arrives as a signal; `csi_call()` catches `SIGABND`, `SIGSEGV`, `SIGILL`, `SIGFPE` and `SIGBUS` for the length of that call only and longjmps back into itself, so no frame of `csi_search()` or `csi_parse()` is skipped and a completion list is never abandoned half-built. `sigsetjmp(..., 1)` saves the mask, so the jump unblocks the signal it caught. Nothing switches addressing mode and no register is kept across the call, so the C run-time needs no repair afterwards; the shell's own handlers only record the signal (see [Signals and traps](#signals-and-traps)), so one arriving during the call cannot disturb it. PDS directories are read with `fopen("//'DSN'", "rb,recfm=u,blksize=256")` and decoded block by block. DD names come from walking the TIOT (PSATOLD, TCBTIO, entries from +24). `mvsfmt.c`: portable C over byte buffers, every length checked before use, big-endian fields read a byte at a time. They run (and are fuzzed) on Linux. Checked on z/OS rather than left for later: `SYS1.*` returns 135 names and `SYS1.MA*` returns SYS1.MACLIB, and Tab in an interactive shell completes `//'SYS1.MA` to `//'SYS1.MACLIB'` and lists that PDS's members. Those checks were made at AMODE 64 through the assembler glue; re-running them against the 31-bit build (which calls IGGCSI00 from C) is the remaining item, together with the abend path: a probe pointed at protected storage has to leave the shell alive, fail that one search, and see the next Tab return at once without a call. `make zos-amblist` still maps the load module, which is how the AMODE and the absence of any assembler CSECT are confirmed, and `make zos-heapcheck` runs the suite with the catalog work under LE heap checking. At 31-bit `malloc()` is below 2 GB, so the work area needs no `__malloc31()`, and one block per search means a second search straight after the first succeeds without the first's resume name leaking into it. Still VERIFY: `fopen()` delivering PDSE directories in PDS format, and the TIOT walk. Neither is reached by a test on the machine. ### Per-command z/OS options | Option or feature | What it does | Cost when off | | --- | --- | --- | | `set -o jobnames` | `_BPX_JOBNAME=` the command name (upper case, 8 valid characters) for each external command, so SDSF, SMF 30 and WLM see `CC` or `MAKE` rather than `USERID3`. Needs READ to `BPX.JOBNAME` | two byte tests per external command | | `set -o shareas` | `_BPX_SHAREAS=YES` for foreground commands only: background jobs and pipeline stages keep their own address spaces | same two tests | | `set -o msgid` | `ZSHnnnnE`/`ZSHnnnnW` in front of every diagnostic. The number is a hash of the message's format string over the portable character set, so it is the same in both builds and stable while the wording is | one byte test per message | | `time [-p] pipeline` | a keyword (times builtins, functions, whole pipelines, no process). Reports shell and children CPU separately | none | | `ulimit -M` | MEMLIMIT (`RLIMIT_MEMLIMIT`), in MB | none | | `ZOS_SYSNAME`, `ZOS_SYSPLEX`, `ZOS_RELEASE`, `ZOS_ASID`, `ZOS_JOBNAME` and prompt `\S` | read from CVT, ECVT, ASCB when expanded | none: dynamic variables are computed only when read | A variable the user exported or put on the command is never overridden. Builtins that exist only in z/OS builds (so that `free` does not hide procps elsewhere): | Builtin | | | --- | --- | | `tag [-p] file...` | show tags in `chtag -p` form without spawning `chtag` | | `tag -t\|-m -c codeset`, `tag -b`, `tag -r` | set text, mixed or binary tags, or remove them (`__chattr()`) | | `alloc keyword...`, `free keyword...` | BPXWDYN requests (`alloc 'dd(in)' "da('x.y')" shr`). The DD belongs to the shell's address space, so commands see it only when they share it (`set -o shareas`) | ### Checking z/OS code off z/OS z/OS has dbx but no ASan, UBSan or Valgrind. As much of the z/OS code as possible is therefore made to run, or at least compile, on Linux: - `make zos-lint`: `sys_zos.c` compiled with all warnings against `tests/tools/zos-shim/zos_shim.h` (declarations transcribed from the z/OS headers), and every other file with the MVS branches forced on. - `make mvs-asan`: the whole suite under ASan/UBSan with the MVS branches on over the Linux platform layer: tagging hooks, `_TAG_REDIR_*` prefixes, `ZOS_*` variables. - Stand-in catalog. With `ZASH_TEST_CATALOG` naming a file, `sys_posix.c` builds real IGGCSI00 work areas (EBCDIC, small, so the resume protocol runs), PDS directory blocks (members split across blocks, varying user data) and TIOT entries, and the completion code decodes them with the z/OS build's decoders. `tests/linux/i-dscomplete.sh` drives it through a pseudo-terminal. - `make fuzz`: libFuzzer with ASan/UBSan on the three decoders and the filter-key checks. What none of this covers: the real control blocks, the real IGGCSI00, the glue, the tagging system calls. Those are the `VERIFY` items. ## HLASM Open XL's code generator is good but not perfect, and a shell has a few loops that dominate its profile (scanning for IFS or metacharacters, hashing names, pattern matching). z/Architecture has instructions that fit these exactly (`TRT`/`TRTE`, `SRST`, `CLST`) and that a C compiler will not always emit. Policy: 1. Measure first, on z/OS, with a real workload. 2. Rewrite only a leaf routine with a narrow, documented interface. 3. Keep the C version. It is the reference implementation, it is what Linux builds use, and the tests run against both so the two cannot drift. 4. The choice is made at build time. The default build is pure C. None so far. The catalog used to need `zos_csi.s`, an AMODE switch to reach the AMODE 31 IGGCSI00 from a 64-bit program. At 31-bit the C code calls it directly and the assembler is gone (see [MVS names](#mvs-names-completion-and-the-catalog)). The policy above stands for any future candidate. ## Testing Tests are written with the code, not after it. | Layer | What it catches | Where | | --- | --- | --- | | `tests/posix/`: behaviour all POSIX shells share, expected output generated by dash | wrong results, disagreement with an established ash | Linux, z/OS | | `tests/zash/`: behaviour specific to zash | regressions in the deliberate differences | Linux, z/OS | | `tests/proc/`: process accounting (`ZASH_PROCSTAT`) | an unexpected `fork()` or extra process | Linux, z/OS | | `tests/linux/`, `tests/zos/` | platform-specific behaviour (`/dev/full`, `spawn()`, BPX variables, address spaces) | one platform each | | `tests/linux/i-*.sh`: the interactive shell driven through a pseudo-terminal | editor keys, completion, history, prompts, job control | Linux (needs python3, skipped without it) | | `make asan`: the suite under ASan + UBSan | memory errors, undefined behaviour | Linux | | `make valgrind`: the suite under Valgrind, leak checking on | uninitialised reads, invalid frees, definite leaks | Linux | | `make asan` also runs LeakSanitizer | leaks, including memory lost when an error unwinds | Linux | | `make mvs-asan`, `make zos-lint`, `make fuzz` | the z/OS code paths, see [Checking z/OS code off z/OS](#checking-zos-code-off-zos) | Linux | | differential runs against dash, bash, ksh93 and mksh | disagreements on POSIX and ksh behaviour (`tests/posix/` expectations come from dash) | Linux | | `clang-tidy` (`make tidy`), `gcc -fanalyzer`, clang static analyzer | defects without a test | Linux | `make zos-check` is the z/OS entry point: the same runner, functionality only. There is no ASan, UBSan or Valgrind on z/OS, and the target does not pretend otherwise. Linux sanitizer coverage stands in for z/OS: the bug classes involved (out-of-bounds access, use after free, signed overflow, uninitialised memory) do not depend on the platform, and all but one source file is shared. What Linux cannot cover is charset-dependent behaviour and `sys_zos.c`. Those rely on the behavioural suite run on z/OS in both character modes. Rules: - A bug fix comes with a test that fails without it. - The suite must pass under ASan/UBSan and under Valgrind before a milestone is called done. - Tests use only POSIX utilities, so that they run unchanged on z/OS. Where the z/OS utility disagrees with the one the expectations were made with, the test normalises it rather than skipping: `wc` pads its count (a `| tr -d ' '` after it), EBCDIC `tr` ranges are not contiguous and `tr -c` with a class does not strip punctuation (splitting is done with `sed`), and `od` can print upper-case hex. `make zos-check` also puts a bundled `sleep` (`tests/tools/zos-sleep.c`) first in `PATH`, because `/bin/sleep` rejects a fractional interval and four tests of job ordering need one. - A test that depends on ASCII ordering or code points is named `*.ascii.sh` and is skipped for an EBCDIC build. Anywhere else such a dependency is a bug in the test. - The `tests/zos/` expectations were written from documentation and have since been run on the machine: `make zos-check` passes in both character modes, and what the suite still misses is marked `VERIFY` in the source. - The interactive tests are the one exception to "POSIX utilities only": they need a pseudo-terminal, and `tests/tools/ptydrive.py` provides one. They run on Linux. On z/OS the interactive layer has to be tried by hand until there is a driver that runs there. - Under Valgrind only the outer shell of each test is instrumented. A shell that a test starts itself (`$TSH -c ...`, the interactive tests) runs natively. The ASan build has no such gap. ## Deliberate differences from other shells - The last stage of a pipeline runs in the current shell when it is not an external command, as in ksh and the z/OS `/bin/sh` (unlike dash and bash). `cmd | while read x; do ...; done` therefore needs no `fork()`, and variables set in the loop survive it. - Consequently `cmd | exit 3` exits the shell, and `cmd | cd dir` changes its directory. - Under job control every stage is a process. In an interactive shell with `set -m` (the default there) the last stage is not run in the shell, because it could not be stopped with the rest of the job. `cmd | read x` therefore does not set `x` at the prompt. bash makes the same choice. - `$((` is always arithmetic (as in dash). - `((` at the start of a command is arithmetic only if it can be. `((a) | b)` and `((echo x))` remain nested subshells, as POSIX has them. See `parse_arith_command()` for the rule, and write `( (` to be certain of a subshell. - `trap` in a pipeline or `$( )` prints the traps of the shell that started it, until that subshell sets a trap of its own. - `function` is a reserved word, so a command cannot be named `function`. - Arithmetic has `++`, `--`, the comma operator and every `op=`. - A script on standard input shares it with its commands. zash never reads ahead of the command it is running, so `printf 'read v\ndata\necho $v\n' | zash` prints `data` (dash does not). - Exit statuses follow the ash family: 2 for a failed redirection, 127 from `type` and `command -v` for an unknown name. - An expansion error in a command the shell prepares for a child (a pipeline stage, `&`, `$( )`) is reported on the shell's stderr, not on the stderr that command would have had. - `local` is provided (as in FreeBSD sh and dash) although POSIX does not define it. - `set -o pipefail` is provided (POSIX.1-2024). - The extensions listed under [Extensions](#extensions). ## Extensions Features beyond POSIX `sh`, taken from FreeBSD `sh` and the Korn shell. The z/OS `/bin/sh` is described by IBM as based on the KornShell and conforming to POSIX 1003.2-1992. Scripts written for it use `print`, `whence`, `typeset`, `alias` and `function name { }`. The Korn items are here to keep those scripts running. ### The performance rule An extension is accepted only if it costs a script that does not use it nothing measurable. Concretely: - Parse-time or lookup-time only. `function f { }` and `$'...'` are gone after parsing. New builtins are rows in the builtin table. - Computed on read. `RANDOM` and `SECONDS` are `V_DYNAMIC`: an unused one costs nothing. - Inside a branch that is already taken. The `ERR` trap is tested only after a command has failed, where `errexit` was already tested. Integer and dynamic variables share the one flag test that read-only variables already needed in `var_set_n()`. - Guarded by one test. Alias lookup is skipped while no alias is defined, and happens while parsing, so a loop body pays once. - Measured. Instruction counts (`valgrind --tool=callgrind`) of the benchmarks before and after the whole extension and interactive work differ by about 0.1% (loop, strings, functions, read loop). One real regression was found this way and fixed: more builtins meant longer hash chains in the command table. Entries now store their hash and compare it before the name. ### Implemented | Item | From | Notes | | --- | --- | --- | | `$'...'` | FreeBSD, ksh93 | decoded in the lexer, `\cX` in ASCII builds only | | `alias`, `unalias` | POSIX/XSI | command position, and a value ending in a blank chains | | `function name { }` | ksh | same node as `name() { }` | | `(( expr ))`, `let` | ksh | reuse `arith.c` | | `typeset [-irx]`, `integer` | ksh | local inside a function | | `print [-nrR] [-u fd]` | ksh | pure builtin: runs in-shell in pipelines and `$( )` | | `whence [-pv]` | ksh | | | `RANDOM`, `SECONDS` | ksh | assignable (seed, restart) | | `trap ... ERR` | ksh | | | `read -t seconds` | ksh, FreeBSD | status above 128 on timeout | | `setvar name value` | FreeBSD | assignment by name without `eval` | | `ulimit` | FreeBSD, XSI | resources present on the platform | | `chdir`, `trap -p` | FreeBSD | | | `[[ ]]` | ksh | own parser and evaluator (`cond.c`), about 27% fewer instructions than `[ ]` | | `time [-p]` | ksh, POSIX | keyword, shell and children CPU split | | `command` on special builtins | POSIX | errors inside become the status instead of exiting, as in dash, bash and ksh93 | | `set -o` `notify trackall nolog ignoreeof emacs vi` | both | the first three are accepted and have no effect | | `jobs`, `fg`, `bg`, `wait %n`, `kill %n` | POSIX | see [Job control](#job-control) | | `fc`, `HISTFILE`, `HISTSIZE` | POSIX | interactive shells only | ### Deferred or declined - Indexed arrays. Variables hold one string, and arrays touch `var.c` and `expand.c` on the hot path. Only if real scripts need them, and measured first. - Extended globbing (`@(a|b)`, `*(x)`), co-processes (`|&`, `print -p`), `typeset -u/-l/-L/-R`, `select`. - ksh93 and bash extras: associative arrays, `${v/pat/repl}`, `${v:off:len}`, floating point, process substitution. - `MAIL` checking, `bind`, and FreeBSD's `-p` privileged mode. ## The interactive layer Nothing here is reached by a script. The single hook on the shared path is one test in `input_fill()`: "is this input a terminal in an interactive shell?" - Prompts (`interact.c`). PS1 and PS2 get FreeBSD's backslash escapes (`\h \H \u \w \W \$`) and then parameter, command and arithmetic expansion. The prompt is expanded from inside the lexer, so the parser's state is saved around it, and an error in the expansion falls back to the raw text instead of failing at every prompt. - The built-in editor (`edit_builtin.c`) needs only a terminal that understands four ANSI sequences. There is no terminfo or curses dependency. The line is drawn on one row that scrolls sideways, and is redrawn in a single `write()` per key. Emacs mode has the usual motion, kill and yank keys, `^R` incremental search and Tab completion. Vi mode has insert and command modes with counts, the common motions, `d c y` with motions, `x X r ~ D C S p P u`, history with `k j G / ? n N`. UTF-8 is handled as far as single-width characters. - libedit (`edit_libedit.c`) implements the same two functions: `make EDIT=libedit LDLIBS=-ledit`. The shell's own history list stays authoritative and is copied into libedit before each line. - Completion (`complete.c`) covers variables after `$`, aliases, functions, builtins and `PATH` programs in command position, and files elsewhere, with `/` after a directory. Completed text is backslash-escaped unless the word is inside quotes. - History (`history.c`): whole commands (a PS2 line is appended to its entry), `HISTSIZE`, `HISTFILE` (mode 0600), and `fc -l`, `fc -s`, `fc -e`. - Character sets. Key codes and ESC come from `charset.h`. The EBCDIC values are IBM-1047 and have not been tried on a z/OS terminal. ## Job control Job control is on when `set -m` is. For an interactive shell on a terminal that is the default (`jobs.c`). - Without it, nothing changes: a foreground child is one `waitpid()`, and no process group or job record exists for it. Background children are recorded so that `wait`, `jobs`, `kill %n` and `$!` work. - With it, each command that creates processes is a job in its own process group. The evaluator brackets process creation with `job_begin()` and `job_wait_fg()` or `job_end_bg()`. While a job is being launched, `fork_shell()` and `spawn_command()` ask `jobs.c` for the group to join. - Spawn and the terminal. A forked child puts itself in the group and takes the terminal before it runs anything. A spawned child cannot run code, so the platform layer does it: `POSIX_SPAWN_SETPGROUP` plus, on glibc 2.35 and later, the `tcsetpgrp` file action. On z/OS it is `SPAWN_SETGROUP` and `SPAWN_SETTCPGRP` in the inheritance structure. Where neither exists the parent hands over the terminal and sends `SIGCONT`, in case the child touched the terminal first. - The shell ignores `SIGTSTP`, `SIGTTIN` and `SIGTTOU`, takes the terminal back when a job stops or ends, and restores the terminal modes if the job stopped or was killed. - `^C` reaches only the foreground job. When a job dies of `SIGINT` the shell abandons the rest of the command line, as it would without job control. - Job listings need command text. The shell does not keep it, so `unparse.c` rebuilds it from the tree when a job is recorded. ## Roadmap 1. Scripting core (done on Linux). 2. Extensions, job control and the interactive layer (done on Linux, tested there under ASan/UBSan, and the interactive tests need a pseudo-terminal). 3. First z/OS build (done): compiles with Open XL in both character modes, the suite passes under the LE heap checker, and the benchmarks beat every shell there except ksh88, which zash matches on external commands (see the tables in README). Still open: the remaining `VERIFY` notes in `sys_zos.c` and the benchmarks under `_BPX_SHAREAS=` other than the default. 4. `[[ ]]` (done), then whatever real z/OS scripts turn out to need. 5. z/OS features: file tagging and auto-conversion, data set completion, `time`, job names, message IDs and `ZOS_*` (written, VERIFY on z/OS). `tag` and the `alloc`/`free` builtins, MVS data set redirection and `tso` are to do. 6. Tuning: profile on z/OS, and use HLASM where it is justified. First finding, and the largest: Language Environment's 64-bit start-up costs about 4 ms per `fork()` and 28 ms per program start. The address mode is not the cause: a bare assembler program starts in 0.8 ms at 64 bits. The cost cannot be tuned away through LE options. See [the cost model](#the-cost-model). ## Open questions - Should `set -o shareas` become the default once measured on z/OS? (It is opt-in now and never applies to background jobs or pipeline stages.) - Is `read` from a pipe worth optimising beyond one byte per `read()`? - Should a vi-mode user get `v` (edit the line in `$EDITOR`) and `.` (repeat)? They are the two commonly used vi keys still missing. - Should an interactive shell predefine the Korn aliases (`history`, `r`)? At present nothing is predefined, so the alias table stays empty unless the user fills it. - `a | b &` and `{ a; } | b` still fork where a spawn-only plan exists. The measurement says a z/OS fork costs 0.10 ms once the C run-time is in the LPA and 4.2 ms when it is not (see [the cost model](#the-cost-model)), so the gain comes from the run-time load, not from the plan. - Should the z/OS build be 64-bit? It is now the default. 31-bit used to be the default to remove the 4 ms fork and the 28 ms start-up; both turned out to be the 64-bit C run-time load, which the LPA fixes ([README.md](README.md#recommendations)), and the widths then measure the same. The 64-bit build has no 2 GB address-space limit, and its catalog linkage is the one item still unverified on this system.