diff options
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | DESIGN.md | 201 | ||||
| -rw-r--r-- | Doxyfile | 19 | ||||
| -rw-r--r-- | Makefile | 148 | ||||
| -rw-r--r-- | README.md | 43 | ||||
| -rw-r--r-- | bench/README.md | 297 | ||||
| -rw-r--r-- | formal/zash_spec/.github/workflows/lean_action_ci.yml | 14 | ||||
| -rw-r--r-- | formal/zash_spec/.gitignore | 1 | ||||
| -rw-r--r-- | formal/zash_spec/Main.lean | 4 | ||||
| -rw-r--r-- | formal/zash_spec/ZashSpec.lean | 226 | ||||
| -rw-r--r-- | formal/zash_spec/ZashSpec/Patterns.lean | 327 | ||||
| -rw-r--r-- | formal/zash_spec/lake-manifest.json | 6 | ||||
| -rw-r--r-- | formal/zash_spec/lakefile.toml | 13 | ||||
| -rw-r--r-- | formal/zash_spec/lean-toolchain | 1 | ||||
| -rw-r--r-- | src/exec.c | 22 | ||||
| -rw-r--r-- | src/mvsfmt.c | 11 | ||||
| -rw-r--r-- | src/sys_zos.c | 238 | ||||
| -rw-r--r-- | src/util.c | 13 | ||||
| -rw-r--r-- | src/zos_csi.s | 99 | ||||
| -rw-r--r-- | tests/posix/expand-edge.sh | 4 | ||||
| -rw-r--r-- | tests/posix/glob-edge.sh | 2 | ||||
| -rw-r--r-- | tests/scripts/bigdata.sh | 4 | ||||
| -rw-r--r-- | tests/scripts/wordfreq.sh | 6 | ||||
| -rw-r--r-- | tests/tools/zos-shim/zos_shim.h | 9 | ||||
| -rw-r--r-- | tests/tools/zos-sleep.c | 35 | ||||
| -rw-r--r-- | tests/zos/fdmap.exp | 1 | ||||
| -rw-r--r-- | tests/zos/fdmap.sh | 5 | ||||
| -rw-r--r-- | tests/zos/tagging.sh | 2 |
28 files changed, 1427 insertions, 327 deletions
@@ -3,7 +3,7 @@ *.o compile_commands.json tests/out/ -doc/ +docs/ cov/ /fuzz-mvsfmt fuzz/corpus/ @@ -16,3 +16,4 @@ crash-* /zash.amblist /zos_csi.amblist __pycache__/ +/build/ @@ -1,9 +1,11 @@ <p align="center"> - <img src="packaging/zash-logo.svg" alt="zash" width="128"> + <img src="packaging/zash-logo.svg" alt="zash" width="220"> </p> # zash design +<p align="center">Sean Kurtz</p> + 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. @@ -88,7 +90,13 @@ creation and character encoding. (`/** @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. + `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. @@ -145,6 +153,41 @@ A forked child can never share the address space. So the rule is: > 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 | 4.2 ms | 0.10 ms | +| `fork()` + `wait()`, 64 MB touched | 28.2 ms | 27.7 ms | +| start a trivial program | 29.5 ms | 1.1 ms | + +So there are two independent costs, and only one of them is about +copying: + +- **A fixed penalty for being 64-bit**: about 4 ms per fork and 28 ms per + program start, whatever the program does or holds. This is what makes + `fork()` expensive here, and it is not storage-related, not program + load, and not the sticky bit. +- **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 — `spawn()` costs no more +than `fork()` and avoids the copy — but the reason usually given for it, +that z/OS `fork()` is inherently expensive, is true only of the copy, +and only above a few MB. And the three rows that zash used to lose on +z/OS (`( : ) &`, `( cd / ) &`, `( cd / )`) are lost to the address mode, +not to the plan: they would be won without changing the plan at all. + +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, the probe programs +and the method. + ### What each construct costs | Construct | Mechanism | @@ -372,6 +415,13 @@ 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. @@ -390,8 +440,8 @@ and backslash escapes are always interpreted. ## The z/OS layer -`sys_zos.c` is the only C file that knows about z/OS. `zos_csi.s` is its -one piece of assembler. It provides: +`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. @@ -411,7 +461,11 @@ build it with ibm-clang for both character sets (ASCII is `./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. What no +`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 @@ -511,36 +565,30 @@ 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 is AMODE 31 and takes three -addresses: reason area, selection criteria, work area. zash is AMODE 64, so -`zos_csi.s` (ZASHCSI) switches mode around a branch to the module. It -loads the module with LOAD on the first call, keeps the entry point in the -block, and branches to it from then on: 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 each time. +**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. zash is 31-bit XPLINK and IGGCSI00 is AMODE +31, so the two agree and the call is a plain call through a function +pointer: no mode switch 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. -Everything the glue touches is one `csi_block` from `__malloc31()`, taken -on the first Tab and held. It has to stay below 2 GB, because IGGCSI00 is -AMODE 31 and all three of its addresses have to fit in 31 bits: +Two details are load-bearing, and the second is not obvious: -| Offset | Field | | -| --- | --- | --- | -| +0 | parameter list | A(reason), A(criteria), A(work) with the VL bit | -| +12 | 72-byte save area | for IGGCSI00 | -| +84 | reason area | | -| +88 | 16 doublewords | the caller's R14-R13 | -| +216 | entry point | EPA LOAD returned, 0 until the first call | -| +220 | return code | | -| +224 | module name | CL8`IGGCSI00`, IBM-1047 | -| +232 | selection criteria | 162 bytes | -| +394 | work area | 64,000 bytes, as IBM recommends | - -The block is declared `packed`, so the compiler cannot add padding the -assembler's DSECT does not have, and `aligned(8)`, so the save area starts -on a doubleword and the `STMG` to it cannot fault. The glue keeps the -caller's registers in the block rather than in a save area reached through -R13, because under XPLINK-64 OS linkage the caller's R13 is not an OS save -area. The offsets are checked by `_Static_assert`, alignment included. +- The function type is declared with `#pragma linkage(iggcsi_fn, + OS_UPSTACK)`, **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.**`. +- 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: @@ -550,10 +598,10 @@ The searches are narrow on purpose: - 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 64,000 bytes, the size IBM recommends. The search - stops after two calls: one call returns about 1100 names at 58 bytes - an entry, so two cover two screens of an 80-column terminal. That is - more than the editor displays. +- 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. @@ -564,10 +612,26 @@ 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 block, one search at a time: a nested search is refused rather than -given a second block, because the block holds the resume name and the -return code of the search that is running. The loaded module is never -released; MVS drops it when the shell ends. +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 @@ -577,15 +641,19 @@ 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, both through the assembled glue, -and Tab in an interactive shell completes `//'SYS1.MA` to `//'SYS1.MACLIB'` -and lists that PDS's members. `make zos-amblist` maps the load module, so -the OS-linkage parameter list, the AMODE and RMODE 31 placement can be -read off the listing, and `make zos-heapcheck` runs the suite with the -catalog work under LE heap checking. A probe on the machine confirmed -the block is shared, not doubled: a second search straight after the -first succeeds, a search started from inside a completion callback is -refused, and both hold under `HEAPCHK(ON)` and `HEAPZONES`. +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. @@ -652,9 +720,11 @@ Policy: cannot drift. 4. The choice is made at build time. The default build is pure C. -The one piece of HLASM so far is not a speed-up but a necessity: -`zos_csi.s`, the AMODE switch for calling IGGCSI00 (see -[MVS names](#mvs-names-completion-and-the-catalog)). +**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 below +is the standing one for any future candidate: ## Testing @@ -691,11 +761,21 @@ Rules: - 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 - not been run. The first z/OS build must review them, not trust them. + 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 @@ -884,6 +964,10 @@ terminal that is the default (`jobs.c`). 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: the 64-bit address mode itself costs + about 4 ms per `fork()` and 28 ms per program start, which is the + whole of the remaining z/OS gap and cannot be tuned away through LE + options. See [the cost model](#the-cost-model). ## Open questions @@ -897,4 +981,11 @@ terminal that is the default (`jobs.c`). `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. - Worth doing once z/OS measurements say how much a fork costs. + The measurement says a 64-bit fork costs 4.2 ms and a 31-bit one + 0.10 ms (see [the cost model](#the-cost-model)), so the gain depends + on the address mode as much as on the plan. +- Should the z/OS build stay 31-bit? It is now the default: it removes + the 4 ms fork and the 28 ms start-up, and the catalog is reached from + C without the assembler that used to make the difference. What it + costs is the 2 GB address space, which no measurement here has come + close to needing. @@ -1,7 +1,7 @@ -# Doxygen configuration for zash. Run with `make doc`; output goes to doc/. +# Doxygen configuration for zash. Run with `make doc`; output goes to docs/. PROJECT_NAME = zash PROJECT_BRIEF = "A small, fast POSIX shell for z/OS UNIX" -OUTPUT_DIRECTORY = doc +OUTPUT_DIRECTORY = docs # The source reference only; README.md and DESIGN.md are read as they are. INPUT = src FILE_PATTERNS = *.c *.h @@ -14,11 +14,18 @@ EXTRACT_LOCAL_CLASSES = YES SOURCE_BROWSER = YES REFERENCED_BY_RELATION = YES GENERATE_HTML = YES -GENERATE_LATEX = NO +GENERATE_LATEX = YES +# Nonstop mode: `make doc` must not sit waiting for an answer on a missing file. +LATEX_BATCHMODE = YES QUIET = YES +GENERATE_TREEVIEW = YES +WARN_LOGFILE = docs/doxygen-warnings.txt WARN_IF_UNDOCUMENTED = YES WARN_NO_PARAMDOC = NO -# Two files each have an alternative that defines the same functions -# (the editor, the platform layer); only the default one is documented. -EXCLUDE = src/edit_libedit.c src/sys_zos.c +# Two files are alternative implementations of the same interface and +# would be documented twice over: edit_libedit.c (the editor, when libedit +# is used) and sys_posix.c (the platform layer on Linux). Their contract +# is in interact.h and sys.h; the files documented here are the ones with +# the explanations, edit_builtin.c and sys_zos.c. +EXCLUDE = src/edit_libedit.c src/sys_posix.c PREDEFINED = PRINTFLIKE(f,a)= NODISCARD= _Noreturn= @@ -1,15 +1,17 @@ -# shellcheck disable=SC2283,SC2068,SC1089 -# ^ cleaner lints this makefile as shell; `NAME = value` is make syntax, -# and $(OBJS)-style make expansions are not shell arrays or a syntax error. +# shellcheck disable=SC2283,SC2046,SC2068,SC1089 +# ^ cleaner lints this makefile as shell: `NAME = value`, `$(CFLAGS)` and a +# recipe that is not a script are make syntax, not shell. .POSIX: .SUFFIXES: .SUFFIXES: .c .o # zash - a small, fast POSIX shell for z/OS UNIX. # -# One flat makefile; nothing here invokes make again. +# One flat makefile; the only make it runs again is `all`'s one-line +# choice of build for the host. # -# make build ./zash (Linux: clang, posix_spawn) +# make build ./zash (Linux: clang, posix_spawn; +# z/OS: the ASCII z/OS build) # make check run the test suite against ./zash # make asan build ./zash-asan, run the suite under ASan + UBSan # make valgrind run the test suite under Valgrind @@ -27,6 +29,7 @@ # make spec typeset formal/zash-spec.pdf with typst # make doc the source reference, Doxygen into doc/ # make other-docs spec and doc: the documentation tools z/OS lacks +# make docs HTML and PDF of README.md and DESIGN.md, in docs/ # # make zos-ascii z/OS build, ASCII program (IBM Open XL C/C++) # make zos-ebcdic z/OS build, EBCDIC program @@ -54,8 +57,11 @@ SANFLAGS = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined \ -fno-omit-frame-pointer ZCC = ibm-clang -ZAS = as -ZCFLAGS = $(CSTD) $(WARN) -O2 -m64 +# 31-bit: a 64-bit fork() costs 4.2 ms and a 32-bit one 0.10 ms on z/OS, +# and a trivial program starts in 29.5 ms against 1.1 ms. bench/README.md +# has the measurements. Nothing in the sources needs 64 bits, so this is +# the whole fix for the fork-heavy benchmarks. +ZCFLAGS = $(CSTD) $(WARN) -O2 -m32 # _POSIX_C_SOURCE=200809L: z/OS exposes SUSv4 names only through it # (_XOPEN_SOURCE 700 is not accepted). _EXT: IBM extensions (fetch()). @@ -76,7 +82,7 @@ DBGFLAGS = -O0 -g3 -fno-omit-frame-pointer # make syntax, as everywhere else in this file; z/OS make rejects `?=`.) DBX = dbx # dbx needs -g and read/write load; no optimisation or inlining. -ZDBGFLAGS = -O0 -g3 -m64 -fno-omit-frame-pointer +ZDBGFLAGS = -O0 -g3 -m32 -fno-omit-frame-pointer ARGS = PID = DUMP = @@ -100,7 +106,11 @@ OBJS = src/alias.o src/arith.o src/builtin.o src/builtin_ext.o \ src/printf.o src/redir.o src/test.o src/trap.o src/unparse.o \ src/util.o src/var.o src/edit_$(EDIT).o src/sys_$(SYS).o -all: zash +# z/OS builds zash with IBM Open XL (ibm-clang, not clang) and without +# posix_spawn, so plain `make` builds the ASCII z/OS build there. z/OS make +# is POSIX make, with no $(shell) and no conditionals, so the shell picks. +all: + @uname -s | grep OS/390 >/dev/null && exec make zos-ascii; make zash zash: $(OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS) @@ -125,9 +135,9 @@ attach: # z/OS debug build: same sources, -O0 -g3, no inlining. zos-debug: zash-dbg -zash-dbg: $(COMMON) src/sys_zos.c src/zos_csi.o $(HDRS) +zash-dbg: $(COMMON) src/sys_zos.c $(HDRS) $(ZCC) $(ZCPPFLAGS) $(CSTD) $(WARN) $(ZDBGFLAGS) -fzos-le-char-mode=ascii \ - -o $@ $(COMMON) src/sys_zos.c src/zos_csi.o $(LDLIBS) + -o $@ $(COMMON) src/sys_zos.c $(LDLIBS) # make zos-dbx ARGS='-c "echo hi"' # @@ -151,23 +161,13 @@ zos-dump: zash-dbg @if [ -z "$(DUMP)" ]; then echo 'usage: make zos-dump DUMP=file' >&2; exit 2; fi $(DBX) -C $(DUMP) ./zash-dbg -# Map the CSECTs, AMODE/RMODE and entry points of the built program object, -# and of the HLASM routine's object module. amblist reads the control -# statement on stdin and needs a leading blank; the output is long, so it -# goes to a file. -zos-amblist: zos-ascii src/zos_csi.o +# Map the CSECTs, AMODE/RMODE and entry points of the built program object. +# amblist reads the control statement on stdin and needs a leading blank; +# the output is long, so it goes to a file. +zos-amblist: zos-ascii echo ' $(AMBLIST_STMT)' | amblist ./zash > zash.amblist - echo ' LISTOBJ' | amblist src/zos_csi.o > zos_csi.amblist -# HLASM reads its source as EBCDIC records split at X'15'; the file in git -# is ASCII (tagged UTF-8), so convert a copy first. -src/zos_csi.o: src/zos_csi.s - iconv -f UTF-8 -t IBM-1047 src/zos_csi.s > src/zos_csi.ebc.s - chtag -tc IBM-1047 src/zos_csi.ebc.s - $(ZAS) -mgoff -o src/zos_csi.o src/zos_csi.ebc.s - rm -f src/zos_csi.ebc.s - @@ -195,24 +195,37 @@ zash-asan: $(COMMON) src/sys_posix.c $(HDRS) # goes to its own name so the two never overwrite each other: make would # otherwise call a rebuild of the other mode "up to date" and leave the # old one in place. -zos-ascii: $(COMMON) src/sys_zos.c src/zos_csi.o $(HDRS) +zos-ascii: $(COMMON) src/sys_zos.c $(HDRS) $(ZCC) $(ZCPPFLAGS) $(ZCFLAGS) -fzos-le-char-mode=ascii -o zash \ - $(COMMON) src/sys_zos.c src/zos_csi.o $(LDLIBS) + $(COMMON) src/sys_zos.c $(LDLIBS) -zos-ebcdic: $(COMMON) src/sys_zos.c src/zos_csi.o $(HDRS) +zos-ebcdic: $(COMMON) src/sys_zos.c $(HDRS) $(ZCC) $(ZCPPFLAGS) $(ZCFLAGS) -fzos-le-char-mode=ebcdic -o zash-ebcdic \ - $(COMMON) src/sys_zos.c src/zos_csi.o $(LDLIBS) + $(COMMON) src/sys_zos.c $(LDLIBS) + +# /bin/sleep on z/OS takes whole seconds -- "0.3" is an error -- and the +# tests order background jobs with sub-second sleeps. The z/OS test runs +# put a sleep that takes fractions in front of PATH. +ZTOOLS = build/zos-tools -check: zash +$(ZTOOLS)/sleep: tests/tools/zos-sleep.c + @mkdir -p $(ZTOOLS) + $(ZCC) $(ZCPPFLAGS) $(CSTD) -O2 -m32 -Wall -Wextra \ + -fzos-le-char-mode=ascii -o $@ tests/tools/zos-sleep.c + +# On z/OS the `zash` build above wants clang and posix_spawn, so run the z/OS +# build and both its test passes instead. +check: + @uname -s | grep OS/390 >/dev/null && exec make zos-check || $(MAKE) zash sh tests/run.sh ./zash # z/OS has no ASan, but Language Environment can put a check zone after # every heap element and validate the heap on every request, which turns # an overlay into a U4042 abend. Meant for a run on the real system: # make zos-heapcheck -zos-heapcheck: +zos-heapcheck: $(ZTOOLS)/sleep _CEE_RUNOPTS='HEAPZONES(0,ABEND,32,ABEND) HEAPCHK(ON)' \ - sh tests/run.sh ./zash + PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash asan: zash-asan ASAN_OPTIONS=detect_leaks=1:abort_on_error=0 sh tests/run.sh ./zash-asan @@ -248,9 +261,9 @@ valgrind: zash # z/OS: behaviour only (no sanitizers or Valgrind there), against the # ./zash that zos-ascii or zos-ebcdic built. -zos-check: zos-ascii zos-ebcdic - sh tests/run.sh ./zash - sh tests/run.sh ./zash-ebcdic zos/ebcdic +zos-check: zos-ascii zos-ebcdic $(ZTOOLS)/sleep + PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash + PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash-ebcdic zos/ebcdic bench: zash sh bench/run.sh $$(pwd)/zash @@ -280,8 +293,67 @@ coverage: printf "%-24s %7s of %s\n", f, a[2], $$4; f=""}' gcov.log | tr -d "'"; \ tail -n 1 gcov.log +# The source reference. docs/html/ for browsing, and docs/zash-reference.pdf +# as one file to send: Doxygen's LaTeX output built with pdflatex, which needs +# its packages installed (Fedora: texlive-{amsfonts,wasysym,fancyhdr,cmap, +# tocbibind,etoolbox,float,varwidth,adjustbox,alphalph,caption,changepage, +# enumitem,etoc,fancyvrb,geometry,hanging,multirow,natbib,newunicodechar, +# stackengine,tabularray,tocloft,ulem,xltabular,ec,cm-super,metafont, +# collection-fontsrecommended}). Without pdflatex, docs/html is all you get. +# The LaTeX build is quiet unless it fails; its log is docs/latex.log. doc: + @rm -rf docs/html docs/latex docs/zash-reference.pdf doxygen Doxyfile + @if command -v pdflatex >/dev/null 2>&1; then \ + $(MAKE) -C docs/latex > docs/latex.log 2>&1 \ + && cp docs/latex/refman.pdf docs/zash-reference.pdf \ + && echo "docs/zash-reference.pdf"; \ + else \ + echo "doc: pdflatex not found, docs/html only"; \ + fi + +# HTML and PDF of the two documents, in docs/ (which is not committed). +# The PDF comes from the HTML through a headless browser, so no LaTeX +# installation is needed; without one, the HTML is still written. +# The colours are the ones formal/zash-spec.typ uses. +DOCS = README DESIGN +CHROME ?= $(shell command -v google-chrome || command -v chromium || \ + command -v chromium-browser) + +docs: doc + @mkdir -p docs + printf '%s\n' \ + 'body { max-width: 46em; margin: 2em auto; padding: 0 1em;' \ + ' font: 16px/1.55 Helvetica, Arial, sans-serif; color: #1b1f24;' \ + ' -webkit-print-color-adjust: exact; print-color-adjust: exact; }' \ + 'h1 { border-bottom: 2px solid #3fb950; padding-bottom: .2em; }' \ + 'a { color: #1f5fa8; }' \ + 'code { color: #7a3e9d; }' \ + 'pre { background: #f6f8fa; border: 1px solid #d0d7de; padding: .6em;' \ + ' white-space: pre-wrap; }' \ + 'th { background: #eef3fb; }' \ + 'tr:nth-child(even) td { background: #fafbfc; }' \ + 'blockquote { border-left: 4px solid #3fb950; margin-left: 0;' \ + ' padding-left: 1em; color: #57606a; }' \ + 'img { max-width: 100%; }' > docs/style.css + for d in $(DOCS); do \ + awk '/^<p align="center">$$/{print "<p align=\"center\"><img " \ + "src=\"packaging/zash-logo.svg\" alt=\"zash\" width=\"128\"></p>"; \ + skip=1; next} skip && /^<\/p>$$/{skip=0; next} !skip' \ + $$d.md > docs/$$d.md; \ + pandoc -s --embed-resources --resource-path=. \ + --metadata pagetitle="zash $$d" --css docs/style.css \ + -o docs/$$d.html docs/$$d.md || exit 1; \ + rm -f docs/$$d.md; \ + if [ -n "$(CHROME)" ]; then \ + $(CHROME) --headless --disable-gpu --no-sandbox \ + --no-pdf-header-footer --user-data-dir=docs/.chrome \ + --print-to-pdf="$$(pwd)/docs/$$d.pdf" \ + "file://$$(pwd)/docs/$$d.html" >/dev/null 2>&1 || exit 1; \ + else \ + echo "docs: no browser found, docs/$$d.html only"; \ + fi; \ + done # The language specification: formal/zash-spec.typ, typeset by typst. spec: @@ -301,10 +373,10 @@ install: zash clean: rm -f zash zash-asan zash-dbg zash-debug zash-mvslint fuzz-mvsfmt \ src/*.o compile_commands.json - rm -f zash.amblist zos_csi.amblist - rm -rf doc cov + rm -f zash.amblist + rm -rf docs cov $(ZTOOLS) .PHONY: fuzz zos-lint mvs-asan all check asan valgrind bench compdb format tidy \ - doc spec other-docs coverage install clean \ + doc docs spec other-docs coverage install clean \ zos-ascii zos-ebcdic zos-check zos-heapcheck zos-debug zos-dbx \ zos-attach zos-dump zos-amblist @@ -1,9 +1,11 @@ <p align="center"> - <img src="packaging/zash-logo.svg" alt="zash" width="128"> + <img src="packaging/zash-logo.svg" alt="zash" width="220"> </p> # zash +<p align="center">Sean Kurtz</p> + A small, fast POSIX shell for z/OS UNIX System Services, in the Almquist (ash) tradition. zash aims to be for z/OS what FreeBSD's `sh` is for FreeBSD: a lean, standards-following `/bin/sh` that is quick at running @@ -87,6 +89,12 @@ The code is plain C17. The few attributes it uses are behind macros. See [DESIGN.md](DESIGN.md#language-level) for the language level and the coding style. +The z/OS build is 31-bit (`-m32`), because a 31-bit `fork()` costs a +ten-th of a 64-bit one and the catalog can then be called from C. Open +XL also takes `-m64`, and the sources build either way unmodified; the +measured difference between the two is discussed in +[bench/README.md](bench/README.md). + Where the z/OS code generator leaves measurable performance on the table, a hot routine may be rewritten in HLASM. Any such routine keeps its C version. That stays the reference, and it is what Linux builds use. @@ -101,7 +109,9 @@ make asan # build zash-asan (ASan + UBSan) and run the tests make valgrind # run the tests under Valgrind make bench # CPU time against dash, bash, ksh, zsh, oksh (or /bin/sh) make compdb # write compile_commands.json for clangd -make format tidy doc # clang-format, clang-tidy, Doxygen +make format tidy # clang-format, clang-tidy +make doc # the source reference: docs/html, docs/zash-reference.pdf +make docs # that, plus HTML and PDF of this file and DESIGN.md make zos-ascii # z/OS, ibm-clang, ASCII mode (zopen convention) make zos-ebcdic # the same in EBCDIC (IBM-1047), as zash-ebcdic @@ -117,6 +127,12 @@ Makefile is one flat, plain `.POSIX` makefile: it works with any `make` and never invokes make recursively. Variant builds (sanitizers, the z/OS modes) are single compile-and-link commands over the source list. +`make doc` needs Doxygen, and for the PDF a working `pdflatex` with the +packages Doxygen's LaTeX output uses (the Fedora list is a comment above +the `doc` target in the Makefile); without `pdflatex` it builds +`docs/html` and says so. `make docs` also needs `pandoc` and a +Chrome/Chromium to turn the two Markdown documents into HTML and PDF. + ## Testing The project is tested at several levels: @@ -143,7 +159,12 @@ The project is tested at several levels: Language Environment can put a check zone after every heap element and validate the heap on every request, so an overlay becomes a U4042 abend: `make zos-heapcheck` runs the whole suite that way, and - `tests/zos/fuzz.sh` runs its own cases under it. + `tests/zos/fuzz.sh` runs its own cases under it. `zos-check` also puts a + bundled `sleep` first in `PATH`, because `/bin/sleep` rejects a + fractional interval and four tests of job ordering need one. Both + character modes pass `zos-check`; under the heap checker two signal + tests fail, as they do not in `zos-check` (see + [DESIGN.md](DESIGN.md#testing)). - **A debugger** is `lldb` on Linux (`make debug`, `make attach`) and `dbx` on z/OS (`make zos-debug`, `make zos-dbx`). `make zos-amblist` maps the CSECTs of the program object when a module-level question @@ -170,9 +191,10 @@ history and `fc`, libedit optional). It builds warning-free with Clang and GCC as C17 and passes its suite plain, under ASan/UBSan, and under Valgrind. -On z/OS it builds in both character modes with Open XL, passes its suite -(including the `zos/` group, run under the LE heap checker) and debugs -with `dbx`. `make zos-debug`, `zos-dbx`, `zos-heapcheck` and +On z/OS it builds in both character modes with Open XL, 31-bit, passes +its suite (including the `zos/` group) and debugs with `dbx`. The +LE heap-checker run is the one exception: two signal tests fail there and +pass in `zos-check`. `make zos-debug`, `zos-dbx`, `zos-heapcheck` and `zos-amblist` are the entry points. Data set redirection and `tso` are the parts still written from documentation. See [DESIGN.md](DESIGN.md#roadmap). @@ -267,6 +289,15 @@ subshell whose body is one output-only builtin now runs in the shell, like a pipeline stage already did, so the same 3000 cost 0.00 s here against ksh88's 0.79. +What is left of the gap in the `background jobs` row above is the price +of the address mode, not of the design: measured on this machine a +64-bit `fork()` costs 4.2 ms and a 31-bit one 0.10 ms, and the same +program starts in 29.5 ms at 64-bit against 1.1 ms at 31-bit. The z/OS +make targets therefore build `-m32`, and the table above is the last +64-bit run: at 31-bit `background jobs` is 0.08, `zz-bgsub` 0.11 (ksh88 +0.12) and `zz-bgcd` 0.08 (ksh88 0.14), with no other row moving. +[bench/README.md](bench/README.md) has the measurements. + The `port bug` entries are the third-party `oksh` port's, not zash's: on there `echo hi | cat` prints two bytes of garbage, so those rows measure nothing and the run reports a differing result. n/a means the diff --git a/bench/README.md b/bench/README.md new file mode 100644 index 0000000..bd53044 --- /dev/null +++ b/bench/README.md @@ -0,0 +1,297 @@ +# bench + +The benchmark scripts, and what the numbers cost on z/OS. + +Each script is also a test: `run.sh` compares every shell's output with +the reference shell's, so a wrong answer fails instead of merely being +timed. + +## Running + +On Linux, `make bench`. + +On z/OS (ASCII build), from the source directory: + +```sh +export PATH=/bin:/usr/bin TMPDIR=$HOME/tmp _BPXK_AUTOCVT=ON +sh bench/run.sh "$(pwd)/zash" /bin/sh bash zsh oksh +``` + +Three things about that line are not optional: + +- **Every shell is an absolute path.** `run.sh` changes to a work + directory before running anything, so a relative `./zash` prints `n/a` + in every row. +- **`_BPXK_AUTOCVT=ON`.** The scripts are tagged ISO8859-1. Without it, + ksh88 and the other shells cannot read them and fail with + `FSUM7332 syntax error: got ), expecting Newline`. zash is not + affected: it converts by tag itself. +- **`TMPDIR` on a writable filesystem.** That is where the work + directory goes. + +A full run takes about a minute and is best run detached +(`nohup ... > bench.txt 2>&1 </dev/null &`); otherwise an interrupted +`ssh` session takes the run with it. + +The times are **CPU seconds, user + sys, children included**, so they do +not include wall-clock start-up. See [Start-up is not in these +numbers](#start-up-is-not-in-these-numbers). + +## What a process costs on z/OS + +Measured on the CBT z/OS system with IBM Open XL C/C++ 2.1 (clang +18.1.8), the same compiler and the same source in both modes, so the +only variable is the address mode. + +| | `-m64` | `-m32` | ratio | +| --- | --- | --- | --- | +| `fork()` + `wait()`, empty parent | 4.20 ms | 0.10 ms | 42× | +| the same, 8 MB touched | 7.20 ms | 3.30 ms | 2× | +| the same, 64 MB touched | 28.2 ms | 27.7 ms | 1.0× | +| start a trivial program | 29.5 ms | 1.1 ms | 27× | + +Two separate costs, and they behave differently: + +- **A fixed penalty for being 64-bit.** About 4 ms per `fork()` and + about 28 ms per program start, paid whatever the program does and + whatever storage it holds. A ten-line program that returns 0 pays it. +- **A per-byte copy cost that both modes pay.** Roughly 0.4 ms per MB of + touched private storage, identical at `-m64` and `-m32`. At 64 MB it + dominates and the address mode stops mattering. + +The 28 ms is not program load: a 28 KB program and a 900 KB program cost +the same, and the sticky bit changes nothing (29.4 ms either way). It is +not I/O either — the process uses under 1 ms of CPU in that time and +simply waits. It is not XPLINK, and not C code: Open XL spells the three +modes `-m64` (64-bit XPLINK), `-m32` (32-bit XPLINK) and `-m32n` (32-bit +non-XPLINK), and the two 32-bit ones both start in 1.0 ms. Only the +64-bit address space is slow. Nor is it zash's own storage — LE reports +50 KB of user heap, 94 KB of library heap and 1 MB of stack for +`zash -c :`, so a fork has almost nothing to copy. + +What is left is Language Environment building the enclave. The +[LE Programming Guide for 64-bit](https://www.ibm.com/docs/en/zos) puts +it plainly — "the creation and termination of that HLL environment +multiple times is needlessly inefficient" — and offers PreInit +(`CELQPIPI`) to create it once and reuse it, which is no help to a shell +that starts, runs and exits. On this machine that creation costs 28 ms +of wall time, in both modes, and no option moves it. + +For scale, the same measurement on `/bin/sh` (ksh88, AMODE 31) is 2.1 ms +per start and 0.42 s for 200 of them, against 6.01 s for 200 starts of +zash at `-m64`. + +### Probing it yourself + +Two small programs, no shell involved. This one measures `fork()`: + +```c +/* fk3.c: fork() cost against the storage the parent holds. p[0] is read + after the loop so the allocation cannot be optimised away. */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <sys/wait.h> +#include <sys/times.h> + +int main(int argc, char **argv) { + long mb = argc > 1 ? atol(argv[1]) : 0; + int n = argc > 2 ? atoi(argv[2]) : 100; + char *p = NULL; + + if (mb > 0) { + p = malloc((size_t)mb * 1024 * 1024); + if (!p) { printf("malloc failed\n"); return 1; } + memset(p, 'x', (size_t)mb * 1024 * 1024); + } + + struct tms a, b; + times(&a); + for (int i = 0; i < n; i++) { + pid_t c = fork(); + if (c == 0) _exit(0); + int st; + waitpid(c, &st, 0); + } + times(&b); + + clock_t t = (b.tms_utime - a.tms_utime) + (b.tms_stime - a.tms_stime) + + (b.tms_cutime - a.tms_cutime) + (b.tms_cstime - a.tms_cstime); + printf(" %4ld MB: %6.2f s (%5.2f ms per fork)", mb, (double)t / 100.0, + (double)t / 100.0 * 1000.0 / n); + if (p) printf(" [p[0]=%c]", p[0]); + printf("\n"); + return 0; +} +``` + +```sh +ibm-clang -O2 -m64 -o fk_64 fk3.c && ibm-clang -O2 -m32 -o fk_32 fk3.c +for m in 0 8 64; do ./fk_64 $m 100; ./fk_32 $m 100; done +``` + +Start-up cost is measured by starting a program that does nothing, so +that nothing but the run-time matters: + +```sh +echo 'int main(void) { return 0; }' > tiny.c +ibm-clang -O2 -m64 -o t64 tiny.c && ibm-clang -O2 -m32 -o t32 tiny.c +time sh -c 'i=0; while [ $i -lt 100 ]; do ./t64; i=$((i+1)); done' +time sh -c 'i=0; while [ $i -lt 100 ]; do ./t32; i=$((i+1)); done' +``` + +Two traps in getting this right, both of which produced wrong answers +here first: + +- **Check the build, not the flag.** `-m31` is rejected; `-m32` is the + spelling that works, and `file` prints `amode=31` for the result. + `ibm-clang -print-targets` lists `systemz32` as a registered target. +- **Make sure the probe measures what you think.** `return p ? 0 : 0;` + lets the compiler delete the allocation, and the "8 MB" row then reads + the same as "0 MB". Touch the memory after the loop. + +## LE run-time options: no measurable effect + +The obvious suspect for a 4 ms `fork()` and a 28 ms start is LE's own +sizing — `HEAP64`, `HEAPPOOLS64`, `STACK64`. It is not. + +| `_CEE_RUNOPTS` | fork | start | +| --- | --- | --- | +| defaults | 4.4 ms | 29.4 ms | +| `HEAPPOOLS64(OFF)` | 4.2 ms | 29.4 ms | +| `HEAP64(256M,256M,KEEP,16M,16M,KEEP,4M,4M,FREE),HEAPPOOLS64(OFF)` | 4.4 ms | — | +| `STACK64(1M,1M,4M)` | — | 29.3 ms | +| `STACK64(1M,1M,64M)` | 4.2 ms | 29.7 ms | +| all of the small ones together | — | 29.4 ms | + +Everything lands inside the run-to-run spread. So there is nothing to +tune and nothing worth building into the program with a `CELQUOPT` +module: the cost is not in the sizes LE is asked for. + +`HEAP64` numbers are in megabytes and must carry an `M` +(`HEAP64(256K,...)` is rejected). To see the effective options and the +storage actually used, in case a future LE release behaves differently: + +```sh +_CEE_RUNOPTS='RPTOPTS(ON),RPTSTG(ON)' ./zash -c : 2>rpt.txt +``` + +The report lists each option, its value, and where it was set — +installation default, `CELQUOPT`, or the `_CEE_RUNOPTS` override. Both +reports go to the message file, stderr by default. `_CEE_RUNOPTS` is +inherited, so any LE child of the process prints its own report; `-c :` +keeps that to one. + +## Start-up is not in these numbers + +`run.sh` takes CPU time, so the ~28 ms of wall time a 64-bit program +spends starting is invisible to every row. That is why `subshell` and +`zz-fgsub` can read 0.00 for zash while `zash -c :` takes 30 ms of wall +time. Both statements are true, and the CPU table is the wrong place to +look for start-up cost. + +It matters for anything that starts zash often: a script with a `#!` +line, `zash -c`, a spawned subshell. It does not matter for a long +interactive session. Compare it with `time`, not with `make bench`. + +## Address mode and the 31-bit build + +zash is a 31-bit (AMODE 31) XPLINK program, which is what the z/OS +Makefile targets build. It used to be 64-bit; the costs above are what +that choice cost, and they were the whole of the remaining z/OS gap. + +The same sources build at either width with the same compiler: + +```sh +ibm-clang ... -O2 -m32 -fzos-le-char-mode=ascii -o zash $(COMMON) src/sys_zos.c +``` + +(`-m32` is 32-bit XPLINK, `-m32n` is 32-bit non-XPLINK, `-m64` is 64-bit +XPLINK. `-m31` does not exist and is rejected.) + +Measured against ksh88, CPU seconds, ASCII build, same box: + +| benchmark | zash `-m64` | zash `-m32` | ksh88 | +| --- | --- | --- | --- | +| `jobs` (200 `( : ) &`) | 0.90 | 0.07 | 0.12 | +| `zz-bgsub` (200 `( : ) &`) | 0.86 | 0.08 | 0.12 | +| `zz-bgcd` (200 `( cd / ) &`) | 0.85 | 0.08 | 0.12 | +| `zz-fgcd` (200 `( cd / )` fg) | 0.84 | 0.08 | 0.05 | +| `zz-fgsub` (200 `( : )` fg) | 0.00 | 0.00 | 0.04 | +| `zz-bgtrue` (200 `/bin/true &`) | 0.06 | 0.05 | 0.10 | +| `zz-bgsh` (200 `/bin/sh -c : &`) | 0.06 | 0.05 | 0.14 | + +The rows that fork improve by a factor of ten and stop being losses. +Nothing else moves: `report` 0.18 → 0.16, `deploy` 0.15 → 0.14, `spawn` +0.47 → 0.45, `cmdsub` 0.04 → 0.04, `strings` 0.28 → 0.25, `printf` +1.17 → 1.15. Every row is the same or slightly better, because a smaller +address space costs nothing. + +Two things had to be settled before 31-bit could ship, and both are: + +1. **The catalog search.** It used to need `zos_csi.s`, an `AMODE 64` + routine that switched modes with `SAM31`/`SAM64` around IGGCSI00 and + passed a `__malloc31` block. At 31-bit the C code calls IGGCSI00 + directly, with `fetch()` and `#pragma linkage(..., OS_UPSTACK)`, and + the assembler is gone. Two traps cost a day between them: under + `-m32` plain `OS` means `OS_NOSTACK` and the call takes a program + check (use `OS_UPSTACK`), and the name given to `fetch()` must be an + ordinary literal, because `__fetch_a` converts it and EBCDIC bytes + get converted twice. +2. **Address space.** A 31-bit shell is limited to storage below 2 GB. + Ample for a shell, not for `x=$(<hugefile)`, which now fails with + "out of memory" rather than growing past it. + +32-bit pointers also shrink the nodes, arenas and hash tables, which is +why no row got worse. + +## Diagnostics + +What to run when a number here is surprising. + +**Which address mode is this program, and does every CSECT agree?** + +```sh +file ./zash # amode=31 or amode=64 + echo ' LISTLOAD OUTPUT=BOTH' | amblist ./zash > zash.amblist # note the leading blank +grep -nE 'AMODE|RMODE|ENTRY POINT' zash.amblist +``` + +`make zos-amblist` does this for `./zash`. At 31-bit there is no +assembler CSECT left to check, so the listing should show one member and +`AMODE 31` throughout. + +**What storage does the program actually use?** This is the input to +fork cost, and the reason a big shell would fork more slowly than a +small one: + +```sh +_CEE_RUNOPTS='RPTSTG(ON)' ./zash -c : 2>rpt.txt +_CEE_RUNOPTS='RPTOPTS(ON)' ./zash -c : 2>opts.txt +``` + +RPTSTG reports heap and stack use per enclave; RPTOPTS reports every +run-time option, its value, and where it was set. Both go to the message +file, stderr by default. + +**Where is the shell spending CPU?** `dbx` works on z/OS and is the +target of `make zos-debug` and `make zos-dbx`. Note that the costs above +are not CPU — nearly all of the 28 ms is a wait — so a profile taken +inside zash will not show them. That is why the probes here are separate +programs rather than shell built-ins. + +**What did the compiler emit?** `ibm-clang -S` gives assembly, and +`-fsave-optimization-record` (or `-Rpass=`) gives clang's remarks about +what was and was not optimised. + +## Reading the two tables + +`n/a` means the shell lacks the feature the benchmark uses. `differs` +means it computed something else, and the run says so. `port bug` marks +the third-party oksh port's own breakage (`echo hi | cat` prints garbage +there), not anything zash did. + +Rows that create processes move by a few hundredths between runs, and +the fork-heavy ones move more, so treat a 0.01–0.02 difference as noise +and re-run before believing it. diff --git a/formal/zash_spec/.github/workflows/lean_action_ci.yml b/formal/zash_spec/.github/workflows/lean_action_ci.yml new file mode 100644 index 0000000..db27f03 --- /dev/null +++ b/formal/zash_spec/.github/workflows/lean_action_ci.yml @@ -0,0 +1,14 @@ +name: Lean Action CI + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + - uses: leanprover/lean-action@v1 diff --git a/formal/zash_spec/.gitignore b/formal/zash_spec/.gitignore new file mode 100644 index 0000000..bfb30ec --- /dev/null +++ b/formal/zash_spec/.gitignore @@ -0,0 +1 @@ +/.lake diff --git a/formal/zash_spec/Main.lean b/formal/zash_spec/Main.lean new file mode 100644 index 0000000..86636b5 --- /dev/null +++ b/formal/zash_spec/Main.lean @@ -0,0 +1,4 @@ +import ZashSpec + +def main : IO Unit := + IO.println "zash_spec" diff --git a/formal/zash_spec/ZashSpec.lean b/formal/zash_spec/ZashSpec.lean new file mode 100644 index 0000000..d153f0d --- /dev/null +++ b/formal/zash_spec/ZashSpec.lean @@ -0,0 +1,226 @@ +namespace ZashSpec.Patterns + +inductive PatElem where + | lit (b : UInt8) + | any + | star + deriving Repr, DecidableEq + +abbrev Pattern := List PatElem +abbrev Bytes := List UInt8 + +/-- Empty byte string `ε`. -/ +scoped notation:max "ε" => ([] : Bytes) + +/-- Formal language `Lang := Bytes → Prop` with set membership `w ∈ L`. -/ +abbrev Lang := Bytes → Prop + +instance : Membership Bytes Lang where + mem L w := L w + +/-- R-PAT-4: Inductive matching relation `Matches p s`. + s ∈ ℒ(ε) ⟺ s = ε + s ∈ ℒ(* p') ⟺ ∃ i, s[i..] ∈ ℒ(p') + c s' ∈ ℒ(e p') ⟺ (e matches c) ∧ s' ∈ ℒ(p') -/ +inductive Matches : Pattern → Bytes → Prop where + | nil : Matches [] ε + | lit (b : UInt8) (p : Pattern) (s : Bytes) : + Matches p s → Matches (.lit b :: p) (b :: s) + | any (c : UInt8) (p : Pattern) (s : Bytes) : + Matches p s → Matches (.any :: p) (c :: s) + | star_empty (p : Pattern) (s : Bytes) : + Matches p s → Matches (.star :: p) s + | star_cons (c : UInt8) (p : Pattern) (s : Bytes) : + Matches (.star :: p) s → Matches (.star :: p) (c :: s) + +/-- Language `ℒ(p) = { s | Matches p s }` recognised by pattern `p`. -/ +scoped notation:max "ℒ(" p ")" => (Matches p : Lang) + +/-- Executable matcher `⟦p⟧(s) ∈ Bool` for R-PAT-4. -/ +def matchBool : Pattern → Bytes → Bool + | [], [] => true + | [], _ :: _ => false + | .lit b :: p, c :: s => b == c && matchBool p s + | .lit _ :: _, [] => false + | .any :: p, _ :: s => matchBool p s + | .any :: _, [] => false + | .star :: p, [] => matchBool p [] + | .star :: p, c :: s => + matchBool p (c :: s) || matchBool (.star :: p) s + +scoped notation:max "⟦" p "⟧(" s ")" => matchBool p s + +/-- Soundness: ∀ p s, ⟦p⟧(s) = true → s ∈ ℒ(p) -/ +theorem matchBool_sound : + ∀ (p : Pattern) (s : Bytes), + ⟦p⟧(s) = true → s ∈ ℒ(p) := by + intro p s + induction p generalizing s with + | nil => + cases s with + | nil => intro _; exact .nil + | cons _ _ => simp [matchBool] + | cons e p ih => + cases e with + | lit b => + cases s with + | nil => simp [matchBool] + | cons c s => + simp [matchBool] + intro hbc hrec + subst hbc + exact .lit b p s (ih s hrec) + | any => + cases s with + | nil => simp [matchBool] + | cons c s => + simp [matchBool] + intro hrec + exact .any c p s (ih s hrec) + | star => + induction s with + | nil => + simp [matchBool] + intro hrec + exact .star_empty p ε (ih ε hrec) + | cons c s ihs => + simp [matchBool] + intro h + cases h with + | inl h₁ => + exact .star_empty p (c :: s) (ih (c :: s) h₁) + | inr h₂ => + exact .star_cons c p s (ihs h₂) + +/-- Completeness: ∀ p s, s ∈ ℒ(p) → ⟦p⟧(s) = true -/ +theorem matchBool_complete : + ∀ {p : Pattern} {s : Bytes}, + s ∈ ℒ(p) → ⟦p⟧(s) = true := by + intro p s h + induction h with + | nil => simp [matchBool] + | lit b p s _ ih => simp [matchBool, ih] + | any c p s _ ih => simp [matchBool, ih] + | star_empty p s _ ih => + cases s with + | nil => simp [matchBool, ih] + | cons c s => simp [matchBool, ih] + | star_cons c p s _ ih => simp [matchBool, ih] + +/-- Equivalence: ∀ p s, ⟦p⟧(s) = true ⟺ s ∈ ℒ(p) -/ +theorem matchBool_iff : + ∀ (p : Pattern) (s : Bytes), + ⟦p⟧(s) = true ↔ s ∈ ℒ(p) := + fun p s => ⟨matchBool_sound p s, matchBool_complete⟩ + + +/-- Search for the smallest `m ≥ k` such that `s[..m] ∈ ℒ(p)`. -/ +def findShortestFrom (p : Pattern) (s : Bytes) (k : Nat) : + Option Nat := + if _ : k ≤ s.length then + if ⟦p⟧(s.take k) then + some k + else + findShortestFrom p s (k + 1) + else + none +termination_by s.length + 1 - k + +/-- R-EXP-8 (`${x#p}`): remove the shortest prefix of `s` in `ℒ(p)`. -/ +def trimShortestPrefix (p : Pattern) (s : Bytes) : Bytes := + match findShortestFrom p s 0 with + | some k => s.drop k + | none => s + +/-- Soundness and minimality of `findShortestFrom`: + ∀ p s k m, findShortestFrom p s k = some m → + k ≤ m ≤ |s| ∧ s[..m] ∈ ℒ(p) ∧ + ∀ j ∈ [k, m), s[..j] ∉ ℒ(p) -/ +theorem findShortestFrom_spec (p : Pattern) (s : Bytes) (k m : Nat) : + findShortestFrom p s k = some m → + k ≤ m ∧ m ≤ s.length ∧ + s.take m ∈ ℒ(p) ∧ + ∀ j, k ≤ j → j < m → s.take j ∉ ℒ(p) := by + unfold findShortestFrom + split + · rename_i hle + split + · rename_i hm + intro heq + injection heq with hkm + subst hkm + refine ⟨Nat.le_refl _, hle, (matchBool_iff p _).mp hm, ?_⟩ + intro j hkj hjk + omega + · rename_i hnm + intro hrec + have ih := findShortestFrom_spec p s (k + 1) m hrec + refine ⟨by omega, ih.2.1, ih.2.2.1, ?_⟩ + intro j hkj hjm hmatch + by_cases hjk : j = k + · subst hjk + exact hnm ((matchBool_iff p _).mpr hmatch) + · exact ih.2.2.2 j (by omega) hjm hmatch + · intro h + contradiction +termination_by s.length + 1 - k + +/-- No-match completeness: + ∀ p s k, findShortestFrom p s k = none → + ∀ j ∈ [k, |s|], s[..j] ∉ ℒ(p) -/ +theorem findShortestFrom_none (p : Pattern) (s : Bytes) (k : Nat) : + findShortestFrom p s k = none → + ∀ j, k ≤ j → j ≤ s.length → s.take j ∉ ℒ(p) := by + unfold findShortestFrom + split + · rename_i hle + split + · intro h + contradiction + · rename_i hnm + intro hrec j hkj hjle hmatch + by_cases hjk : j = k + · subst hjk + exact hnm ((matchBool_iff p _).mpr hmatch) + · exact findShortestFrom_none p s (k + 1) hrec j (by omega) + hjle hmatch + · rename_i hgt + intro _ j hkj hjle + omega +termination_by s.length + 1 - k + +/-- R-EXP-8 (`${x#p}`): Either there exists a shortest matching prefix + `m ≤ |s|` with `s[..m] ∈ ℒ(p)` and `trimShortestPrefix p s = s[m..]`, + or `∀ j ∈ {0..|s|}, s[..j] ∉ ℒ(p)` and `s` is unchanged. -/ +theorem trimShortestPrefix_spec : + ∀ (p : Pattern) (s : Bytes), + (∃ m ≤ s.length, + s.take m ∈ ℒ(p) ∧ + (∀ j < m, s.take j ∉ ℒ(p)) ∧ + trimShortestPrefix p s = s.drop m) ∨ + ((∀ j ∈ List.range (s.length + 1), s.take j ∉ ℒ(p)) ∧ + trimShortestPrefix p s = s) := by + intro p s + unfold trimShortestPrefix + cases h : findShortestFrom p s 0 with + | some m => + left + have hspec := findShortestFrom_spec p s 0 m h + refine ⟨m, hspec.2.1, hspec.2.2.1, ?_, rfl⟩ + intro j hj + exact hspec.2.2.2 j (Nat.zero_le j) hj + | none => + right + refine ⟨?_, rfl⟩ + intro j hj + have hle : j ≤ s.length := by + simp [List.mem_range] at hj + omega + exact findShortestFrom_none p s 0 h j (Nat.zero_le j) hle + + + + + + +end ZashSpec.Patterns diff --git a/formal/zash_spec/ZashSpec/Patterns.lean b/formal/zash_spec/ZashSpec/Patterns.lean new file mode 100644 index 0000000..205c58d --- /dev/null +++ b/formal/zash_spec/ZashSpec/Patterns.lean @@ -0,0 +1,327 @@ +/- + zash specification, chapter Patterns (R-PAT-4) and trimming (R-EXP-9). + NOT YET COMPILED: written without a Lean toolchain at hand. +-/ +namespace ZashSpec.Patterns + +inductive PatElem where + | lit (b : UInt8) + | any + | star + deriving Repr, DecidableEq + +abbrev Pattern := List PatElem +abbrev Bytes := List UInt8 + +/-- Empty byte string `ε`. (Not `∈`: that would hijack membership.) -/ +scoped notation:max "ε" => ([] : Bytes) + +/-- Formal language `Lang := Bytes → Prop`, with `w ∈ L`. -/ +abbrev Lang := Bytes → Prop + +instance : Membership Bytes Lang where + mem L w := L w + +/-- R-PAT-4: the matching relation. -/ +inductive Matches : Pattern → Bytes → Prop where + | nil : Matches [] ε + | lit (b : UInt8) (p : Pattern) (s : Bytes) : + Matches p s → Matches (.lit b :: p) (b :: s) + | any (c : UInt8) (p : Pattern) (s : Bytes) : + Matches p s → Matches (.any :: p) (c :: s) + | star_empty (p : Pattern) (s : Bytes) : + Matches p s → Matches (.star :: p) s + | star_cons (c : UInt8) (p : Pattern) (s : Bytes) : + Matches (.star :: p) s → Matches (.star :: p) (c :: s) + +scoped notation:max "ℒ(" p ")" => (Matches p : Lang) + +/-- Executable matcher for R-PAT-4. -/ +def matchBool : Pattern → Bytes → Bool + | [], [] => true + | [], _ :: _ => false + | .lit b :: p, c :: s => b == c && matchBool p s + | .lit _ :: _, [] => false + | .any :: p, _ :: s => matchBool p s + | .any :: _, [] => false + | .star :: p, [] => matchBool p [] + | .star :: p, c :: s => matchBool p (c :: s) || matchBool (.star :: p) s + +scoped notation:max "⟦" p "⟧(" s ")" => matchBool p s + +/-! ## 1. The matcher agrees with the relation (unchanged from your file) -/ + +theorem matchBool_sound : + ∀ (p : Pattern) (s : Bytes), ⟦p⟧(s) = true → s ∈ ℒ(p) := by + intro p s + induction p generalizing s with + | nil => + cases s with + | nil => intro _; exact .nil + | cons _ _ => simp [matchBool] + | cons e p ih => + cases e with + | lit b => + cases s with + | nil => simp [matchBool] + | cons c s => + simp [matchBool] + intro hbc hrec + subst hbc + exact .lit b p s (ih s hrec) + | any => + cases s with + | nil => simp [matchBool] + | cons c s => + simp [matchBool] + intro hrec + exact .any c p s (ih s hrec) + | star => + induction s with + | nil => + simp [matchBool] + intro hrec + exact .star_empty p ε (ih ε hrec) + | cons c s ihs => + simp [matchBool] + intro h + cases h with + | inl h₁ => exact .star_empty p (c :: s) (ih (c :: s) h₁) + | inr h₂ => exact .star_cons c p s (ihs h₂) + +theorem matchBool_complete : + ∀ {p : Pattern} {s : Bytes}, s ∈ ℒ(p) → ⟦p⟧(s) = true := by + intro p s h + induction h with + | nil => simp [matchBool] + | lit b p s _ ih => simp [matchBool, ih] + | any c p s _ ih => simp [matchBool, ih] + | star_empty p s _ ih => + cases s with + | nil => simp [matchBool, ih] + | cons c s => simp [matchBool, ih] + | star_cons c p s _ ih => simp [matchBool, ih] + +theorem matchBool_iff (p : Pattern) (s : Bytes) : ⟦p⟧(s) = true ↔ s ∈ ℒ(p) := + ⟨matchBool_sound p s, matchBool_complete⟩ + +/-- The `false` side, which every "no shorter match" clause needs. -/ +theorem not_mem_of_false {p : Pattern} {s : Bytes} (h : ⟦p⟧(s) = false) : + s ∉ ℒ(p) := by + intro hm + rw [matchBool_complete hm] at h + contradiction + +/-! ## 2. Two generic searches over `0..n` + +All four trims are "find the least or the greatest index whose cut matches". +Proving that once, about an arbitrary `q : Nat → Bool`, means each trim's +spec is a few lines and never repeats an induction. -/ + +/-- Least `m` with `k ≤ m ≤ n` and `q m`. -/ +def firstFrom (q : Nat → Bool) (n k : Nat) : Option Nat := + if _ : k ≤ n then + if q k then some k else firstFrom q n (k + 1) + else none +termination_by n + 1 - k + +theorem firstFrom_some (q : Nat → Bool) (n k m : Nat) : + firstFrom q n k = some m → + k ≤ m ∧ m ≤ n ∧ q m = true ∧ ∀ j, k ≤ j → j < m → q j = false := by + unfold firstFrom + split + · rename_i hle + split + · rename_i hq + intro h + injection h with h + subst h + exact ⟨Nat.le_refl _, hle, hq, fun j h1 h2 => by omega⟩ + · rename_i hq + intro h + obtain ⟨h1, h2, h3, h4⟩ := firstFrom_some q n (k + 1) m h + refine ⟨by omega, h2, h3, ?_⟩ + intro j hkj hjm + by_cases hjk : j = k + · subst hjk; simpa using hq + · exact h4 j (by omega) hjm + · intro h; contradiction +termination_by n + 1 - k + +theorem firstFrom_none (q : Nat → Bool) (n k : Nat) : + firstFrom q n k = none → ∀ j, k ≤ j → j ≤ n → q j = false := by + unfold firstFrom + split + · rename_i hle + split + · intro h; contradiction + · rename_i hq + intro h j hkj hjn + by_cases hjk : j = k + · subst hjk; simpa using hq + · exact firstFrom_none q n (k + 1) h j (by omega) hjn + · intro _ j hkj hjn + omega +termination_by n + 1 - k + +/-- Greatest `m ≤ k` with `q m`. Structural recursion: no `termination_by`. -/ +def lastUpTo (q : Nat → Bool) : Nat → Option Nat + | 0 => if q 0 then some 0 else none + | k + 1 => if q (k + 1) then some (k + 1) else lastUpTo q k + +theorem lastUpTo_some (q : Nat → Bool) : + ∀ k m, lastUpTo q k = some m → + m ≤ k ∧ q m = true ∧ ∀ j, m < j → j ≤ k → q j = false := by + intro k + induction k with + | zero => + intro m h + simp only [lastUpTo] at h + split at h + · rename_i hq + injection h with h + subst h + exact ⟨Nat.le_refl _, hq, fun j h1 h2 => by omega⟩ + · contradiction + | succ k ih => + intro m h + simp only [lastUpTo] at h + split at h + · rename_i hq + injection h with h + subst h + exact ⟨Nat.le_refl _, hq, fun j h1 h2 => by omega⟩ + · rename_i hq + obtain ⟨h1, h2, h3⟩ := ih m h + refine ⟨by omega, h2, ?_⟩ + intro j hmj hjk + by_cases hj : j = k + 1 + · subst hj; simpa using hq + · exact h3 j hmj (by omega) + +theorem lastUpTo_none (q : Nat → Bool) : + ∀ k, lastUpTo q k = none → ∀ j, j ≤ k → q j = false := by + intro k + induction k with + | zero => + intro h j hj + simp only [lastUpTo] at h + split at h + · contradiction + · rename_i hq + have : j = 0 := by omega + subst this + simpa using hq + | succ k ih => + intro h j hj + simp only [lastUpTo] at h + split at h + · contradiction + · rename_i hq + by_cases hjk : j = k + 1 + · subst hjk; simpa using hq + · exact ih h j (by omega) + +/-! ## 3. R-EXP-9: the four trims + +For suffixes the index `m` is the length of the suffix removed, so the +candidate is `s.drop (s.length - m)` and the result `s.take (s.length - m)`. -/ + +/-- `${x#p}` -/ +def trimShortestPrefix (p : Pattern) (s : Bytes) : Bytes := + match firstFrom (fun m => ⟦p⟧(s.take m)) s.length 0 with + | some m => s.drop m + | none => s + +/-- `${x##p}` -/ +def trimLongestPrefix (p : Pattern) (s : Bytes) : Bytes := + match lastUpTo (fun m => ⟦p⟧(s.take m)) s.length with + | some m => s.drop m + | none => s + +/-- `${x%p}` -/ +def trimShortestSuffix (p : Pattern) (s : Bytes) : Bytes := + match firstFrom (fun m => ⟦p⟧(s.drop (s.length - m))) s.length 0 with + | some m => s.take (s.length - m) + | none => s + +/-- `${x%%p}` -/ +def trimLongestSuffix (p : Pattern) (s : Bytes) : Bytes := + match lastUpTo (fun m => ⟦p⟧(s.drop (s.length - m))) s.length with + | some m => s.take (s.length - m) + | none => s + +theorem trimShortestPrefix_spec (p : Pattern) (s : Bytes) : + (∃ m ≤ s.length, s.take m ∈ ℒ(p) ∧ + (∀ j < m, s.take j ∉ ℒ(p)) ∧ + trimShortestPrefix p s = s.drop m) ∨ + ((∀ j ≤ s.length, s.take j ∉ ℒ(p)) ∧ trimShortestPrefix p s = s) := by + unfold trimShortestPrefix + cases h : firstFrom (fun m => ⟦p⟧(s.take m)) s.length 0 with + | some m => + obtain ⟨_, hmn, hq, hmin⟩ := firstFrom_some _ _ _ _ h + exact Or.inl ⟨m, hmn, matchBool_sound p (s.take m) hq, + fun j hj => not_mem_of_false (hmin j (Nat.zero_le j) hj), rfl⟩ + | none => + exact Or.inr ⟨fun j hj => not_mem_of_false + (firstFrom_none _ _ _ h j (Nat.zero_le j) hj), rfl⟩ + +theorem trimLongestSuffix_spec (p : Pattern) (s : Bytes) : + (∃ m ≤ s.length, s.drop (s.length - m) ∈ ℒ(p) ∧ + (∀ j, m < j → j ≤ s.length → s.drop (s.length - j) ∉ ℒ(p)) ∧ + trimLongestSuffix p s = s.take (s.length - m)) ∨ + ((∀ j ≤ s.length, s.drop (s.length - j) ∉ ℒ(p)) ∧ + trimLongestSuffix p s = s) := by + unfold trimLongestSuffix + cases h : lastUpTo (fun m => ⟦p⟧(s.drop (s.length - m))) s.length with + | some m => + obtain ⟨hmn, hq, hmax⟩ := lastUpTo_some _ _ _ h + exact Or.inl ⟨m, hmn, matchBool_sound p (s.drop (s.length - m)) hq, + fun j hmj hjn => not_mem_of_false (hmax j hmj hjn), rfl⟩ + | none => + exact Or.inr ⟨fun j hj => not_mem_of_false (lastUpTo_none _ _ h j hj), rfl⟩ + +/-- Exercise 1: same shape as `trimLongestSuffix_spec`, with `take`/`drop` + swapped back. Use `lastUpTo_some` and `lastUpTo_none`. -/ +theorem trimLongestPrefix_spec (p : Pattern) (s : Bytes) : + (∃ m ≤ s.length, s.take m ∈ ℒ(p) ∧ + (∀ j, m < j → j ≤ s.length → s.take j ∉ ℒ(p)) ∧ + trimLongestPrefix p s = s.drop m) ∨ + ((∀ j ≤ s.length, s.take j ∉ ℒ(p)) ∧ trimLongestPrefix p s = s) := by + sorry + +/-- Exercise 2: same shape as `trimShortestPrefix_spec`, with suffixes. + Use `firstFrom_some` and `firstFrom_none`. -/ +theorem trimShortestSuffix_spec (p : Pattern) (s : Bytes) : + (∃ m ≤ s.length, s.drop (s.length - m) ∈ ℒ(p) ∧ + (∀ j < m, s.drop (s.length - j) ∉ ℒ(p)) ∧ + trimShortestSuffix p s = s.take (s.length - m)) ∨ + ((∀ j ≤ s.length, s.drop (s.length - j) ∉ ℒ(p)) ∧ + trimShortestSuffix p s = s) := by + sorry + +/-! ## 4. Toward the single-pass matcher: concatenation + +The bitmask algorithm keeps, after each byte, the set of pattern positions +`i` such that the input so far matches the first `i` elements. Its +invariant is stated with `p.take i`, and proving the step case needs +matching to split over `++`. These two lemmas are that tool. -/ + +theorem Matches.append {p q : Pattern} {s t : Bytes} + (hp : Matches p s) (hq : Matches q t) : Matches (p ++ q) (s ++ t) := by + induction hp with + | nil => simpa using hq + | lit b p s _ ih => exact .lit b (p ++ q) (s ++ t) ih + | any c p s _ ih => exact .any c (p ++ q) (s ++ t) ih + | star_empty p s _ ih => exact .star_empty (p ++ q) (s ++ t) ih + | star_cons c p s _ ih => exact .star_cons c (p ++ q) (s ++ t) ih + +/-- Exercise 3 (the hard direction). Hint: `induction p generalizing s`; + `nil` is `⟨[], s, rfl, .nil, h⟩`; for `lit` and `any` use `cases h` + and put the head byte on the front of the first part; for `star`, do + an inner `induction s` exactly as in `matchBool_sound`. -/ +theorem Matches.split {p q : Pattern} {s : Bytes} (h : Matches (p ++ q) s) : + ∃ s₁ s₂, s = s₁ ++ s₂ ∧ Matches p s₁ ∧ Matches q s₂ := by + sorry + +end ZashSpec.Patterns diff --git a/formal/zash_spec/lake-manifest.json b/formal/zash_spec/lake-manifest.json new file mode 100644 index 0000000..55880bc --- /dev/null +++ b/formal/zash_spec/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "zash_spec", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/formal/zash_spec/lakefile.toml b/formal/zash_spec/lakefile.toml new file mode 100644 index 0000000..e9fc41a --- /dev/null +++ b/formal/zash_spec/lakefile.toml @@ -0,0 +1,13 @@ +name = "zash_spec" +version = "0.1.0" +defaultTargets = ["zash_spec"] + +[[lean_lib]] +name = "ZashSpec" + +[[lean_exe]] +name = "zash_spec" +root = "Main" + +[leanOptions] +autoImplicit = false
\ No newline at end of file diff --git a/formal/zash_spec/lean-toolchain b/formal/zash_spec/lean-toolchain new file mode 100644 index 0000000..00f8483 --- /dev/null +++ b/formal/zash_spec/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 @@ -863,17 +863,6 @@ static void assign_temp(const simple_cmd *sc) { } /** - * @brief Run an external command. - * - * @param sc The prepared command. - * @param flags EV_EXIT allows replacing the shell with exec. - * @param in Descriptor for its stdin, or -1. - * @param out Descriptor for its stdout, or -1. - * @param async When not NULL, receives the pid and the command is not - * waited for (pipeline stages, `&`, command substitution). - * @return The exit status. 0 for an async launch. - */ -/** * @brief Apply `_TAG_REDIR_*` assignments given on an external command. * * Assignments before an external command go only into its environment, @@ -918,6 +907,17 @@ static void tag_prefix_end(const tag_mode saved[3], int in, int out) { memcpy(tag_redir, saved, sizeof tag_redir); } +/** + * @brief Run an external command. + * + * @param sc The prepared command. + * @param flags EV_EXIT allows replacing the shell with exec. + * @param in Descriptor for its stdin, or -1. + * @param out Descriptor for its stdout, or -1. + * @param async When not NULL, receives the pid and the command is not + * waited for (pipeline stages, `&`, command substitution). + * @return The exit status. 0 for an async launch. + */ static int run_external(simple_cmd *sc, unsigned flags, int in, int out, pid_t *async) { const node *n = sc->n; diff --git a/src/mvsfmt.c b/src/mvsfmt.c index 08494dc..8424ac8 100644 --- a/src/mvsfmt.c +++ b/src/mvsfmt.c @@ -292,11 +292,12 @@ bool csi_parse(const unsigned char *work, size_t worklen, mvs_name_fn *fn, /** * @brief Most IGGCSI00 calls for one search (resumes included). * - * One call fills the 64000-byte work area with roughly 1100 entries (about - * 58 bytes each for a name and its VOLSER), and a screen holds tens. The - * only caller is Tab completion, so two calls is already more names than - * anyone can look at -- and a broad filter on a big catalog is the one way - * this feature can put real work on catalog management. + * One call fills the 32K work area with roughly 560 entries (about + * 58 bytes each for a name and its VOLSER), so three calls are about + * 1700 names, and a screen holds tens. The only caller is Tab + * completion, so three calls is already more names than anyone can look + * at -- and a broad filter on a big catalog is the one way this feature + * can put real work on catalog management. */ #define CSI_MAX_CALLS 3 diff --git a/src/sys_zos.c b/src/sys_zos.c index 9041edd..48c1315 100644 --- a/src/sys_zos.c +++ b/src/sys_zos.c @@ -15,6 +15,7 @@ #include <_Nascii.h> #include <errno.h> #include <fcntl.h> +#include <setjmp.h> #include <spawn.h> #include <stddef.h> #include <stdint.h> @@ -29,6 +30,12 @@ #include "charset.h" #include "sys.h" +/* IGGCSI00 is AMODE 31 and is called through a plain function pointer: + * that only works because this program is 31-bit too (bench/README.md). */ +#ifndef ZASH_ZOS_SHIM +_Static_assert(sizeof(void *) == 4, "the z/OS build must be -m32"); +#endif + /** * @brief Describe a signal. * @@ -89,6 +96,8 @@ const char *sys_strsignal(int sig) { */ pid_t sys_spawn(const spawn_req *rq) { int fd_map[SYS_NFD + 16]; + int dups[SYS_NFD]; + int ndups = 0; const int map_max = (int)(sizeof fd_map / sizeof fd_map[0]); int fd_count = 1; /* 0 would mean "inherit everything" */ struct inheritance inh = {0}; @@ -100,10 +109,31 @@ pid_t sys_spawn(const spawn_req *rq) { src = FD_CLOSED; if (src == FD_CLOSED) { fd_map[i] = SPAWN_FDCLOSED; - } else { - fd_map[i] = src; - fd_count = i + 1; + continue; + } + if (src != i) { + /* + * The shell keeps its pipe ends close-on-exec (sys_pipe()). A + * mapping onto the child's 0..2 has to clear that flag: the child + * is the one that execs the command, and close-on-exec would take + * its standard output with it -- ps and a #!/bin/sh shim both + * failed this way. dup2() clears the flag, but spawn()'s map + * gives the child the parent's descriptor as it is, so pass a + * plain duplicate, which F_DUPFD makes without the flag. + */ + src = fcntl(src, F_DUPFD, SYS_NFD); + if (src < 0) { + int saved; + saved = errno; + while (ndups) + close(dups[--ndups]); + errno = saved; + return -1; + } + dups[ndups++] = src; } + fd_map[i] = src; + fd_count = i + 1; } if (rq->sigdfl) { inh.flags |= SPAWN_SETSIGDEF; @@ -138,8 +168,14 @@ pid_t sys_spawn(const spawn_req *rq) { * runtime converts path, argv and envp, and that _BPX_SHAREAS, * _BPX_SPAWN_SCRIPT and STEPLIB are honoured from `envp`. */ - return spawn(rq->path, fd_count, fd_map, &inh, (const char **)rq->argv, - (const char **)rq->envp); + pid_t pid = spawn(rq->path, fd_count, fd_map, &inh, (const char **)rq->argv, + (const char **)rq->envp); + int saved; + saved = errno; + while (ndups) + close(dups[--ndups]); + errno = saved; + return pid; } /** @@ -541,70 +577,79 @@ const char *sys_info(sys_info_kind kind) { /* ---- the catalog ------------------------------------------------------- */ /* - * IGGCSI00 is AMODE 31 and takes a standard three-word parameter list. - * zash is AMODE 64, so the call goes through zos_csi.s, which switches - * addressing mode around a branch to the module. Everything the routine - * or the glue touches is in one csi_block in 31-bit storage, below 2 GB. - * The glue keeps the caller's registers there too, so it depends on - * nothing about the caller's save area or stack, and it writes the entry - * point of IGGCSI00 back there so later calls skip the directory search. + * IGGCSI00 is AMODE 31 and takes a standard OS parameter list of three + * addresses: reason area, selection criteria, work area, with the VL bit + * on the last. zash is 31-bit XPLINK too, so it is called directly: + * fetch() loads it once, and the OS linkage makes the compiler build the + * parameter list and give the module a save area. No mode switch, and + * no assembler. + * + * The linkage has to be OS_UPSTACK, not plain OS. Under -m32 (XPLINK), + * OS means OS_NOSTACK: no standard save area, so IGGCSI00 -- a + * traditional upward-stack OS routine -- takes a program check on the + * first call. OS_UPSTACK is what the compiler reference names for + * exactly this case; measured on z/OS, OS abends and OS_UPSTACK returns + * rc=0 with the work area filled. */ -/** @brief Size of the CSI return work area (IBM recommends 64000). */ -#define CSI_WORK 64000 - -/** @brief Returned when IGGCSI00 cannot be loaded (CSI uses 0-16). */ -#define CSI_NOLOAD 16 - -/** - * @brief 31-bit storage for CSI calls. The layout up to `rc` is shared - * with zos_csi.s (the offsets are checked below). +/** @brief Size of the CSI return work area. * - * Packed, so the compiler cannot insert padding the DSECT does not have, - * and aligned(8), so the block and its save area start on a doubleword. - * The name is kept as EBCDIC bytes and not as a C string, so that both - * character modes spell it the same way. + * IBM recommends 64000; 32K already holds more names than a completion + * screen shows, and it is taken per search rather than held. */ -typedef struct __attribute__((packed, aligned(8))) csi_block { - unsigned char *__ptr32 parm[3]; /**< +0: A(reason), A(field), - A(work) with the VL bit */ - uint32_t save[18]; /**< +12: save area for IGGCSI00 */ - unsigned char reason[4]; /**< +84 */ - uint64_t regs[16]; /**< +88: caller's R14-R13 */ - uint32_t ep; /**< +216: EPA from LOAD */ - int32_t rc; /**< +220: R15 from IGGCSI00 */ - unsigned char epname[8]; /**< +224: "IGGCSI00", IBM-1047 */ - unsigned char field[CSI_FIELD_LEN]; /**< +232: selection criteria */ - unsigned char work[CSI_WORK]; /**< return work area */ -} csi_block; +#define CSI_WORK 32768 + +/** @brief One search's storage: taken per search, freed before return. */ +typedef struct csi_req { + unsigned char reason[4]; + unsigned char field[CSI_FIELD_LEN]; + unsigned char work[CSI_WORK] __attribute__((aligned(8))); +} csi_req; + +typedef int iggcsi_fn(void *reason, void *field, void *work); +#pragma linkage(iggcsi_fn, OS_UPSTACK) + +static iggcsi_fn *csi_ep; /**< from fetch(), NULL until loaded */ +static bool csi_dead; /**< fetch failed or a call abended */ +static bool csi_in_flight; /**< one search at a time */ -_Static_assert(offsetof(csi_block, save) == 12, "zos_csi.s SAVE"); -_Static_assert(offsetof(csi_block, reason) == 84, "zos_csi.s REASON"); -_Static_assert(offsetof(csi_block, regs) == 88, "zos_csi.s REGS"); -_Static_assert(offsetof(csi_block, ep) == 216, "zos_csi.s EP"); -_Static_assert(offsetof(csi_block, rc) == 220, "zos_csi.s RC"); -_Static_assert(_Alignof(csi_block) == 8, "csi_block alignment"); -/* Held for the life of the shell: keep it small. */ -_Static_assert(sizeof(csi_block) <= 64 * 1024 + 512, "csi_block size"); +/** @brief Returned by csi_call() after an abend: > 4, so the search stops. */ +#define CSI_ABENDED 20 -#pragma linkage(ZASHCSI, OS) -int ZASHCSI(csi_block *block); +static sigjmp_buf csi_jb; + +static void csi_trap(int sig) { + (void)sig; + siglongjmp(csi_jb, 1); +} /** * @brief One IGGCSI00 call (a csi_call_fn). * - * The parameter list is rebuilt each time: IGGCSI00 is entitled to - * assume nothing else in the block survives a call. + * A program check or abend inside IGGCSI00 comes back as a signal. It is + * caught only for the length of the call, and the call then reports + * failure; the caller frees the block and retires the catalog. */ static int csi_call(csi_area *a, void *ctx) { - csi_block *b = ctx; - (void)a; - /* 64-bit to __ptr32 is an explicit cast; the block is below 2 GB, - * so nothing is lost. The VL bit goes on the last entry. */ - b->parm[0] = (unsigned char *__ptr32)b->reason; - b->parm[1] = (unsigned char *__ptr32)b->field; - b->parm[2] = (unsigned char *__ptr32)((uintptr_t)b->work | 0x80000000u); - return ZASHCSI(b); + bool *abended = ctx; + static const int sigs[] = {SIGABND, SIGSEGV, SIGILL, SIGFPE, SIGBUS}; + enum { NSIG_CSI = sizeof sigs / sizeof sigs[0] }; + struct sigaction sa = {.sa_handler = csi_trap}, old[NSIG_CSI]; + sigemptyset(&sa.sa_mask); + for (int i = 0; i < NSIG_CSI; i++) + sigaction(sigs[i], &sa, &old[i]); + volatile int rc; + if (sigsetjmp(csi_jb, 1) == 0) { + /* VL bit on the last address; harmless if the compiler sets it. */ + void *work = (void *)((uintptr_t)a->work | 0x80000000u); + rc = csi_ep(a->reason, a->field, work); + } else { + *abended = true; + rc = CSI_ABENDED; + } + for (int i = 0; i < NSIG_CSI; i++) + sigaction(sigs[i], &old[i], NULL); + return rc; } /** @@ -615,45 +660,40 @@ bool sys_has_catalog(void) { } /** - * @brief The one CSI block, in 31-bit storage, allocated on the first - * search and held for the life of the shell. - */ -static csi_block *csi_blk; - -/** @brief True while a search is using the block. */ -static bool csi_in_flight; - -/** * @brief List cataloged names that match a CSI filter key. * - * The block is 64 KB of 31-bit storage: IGGCSI00 is AMODE 31, so all - * three of its addresses have to be below 2 GB. Allocating one for - * the first Tab and keeping it is better than taking a fresh one per - * Tab, which is what the shell used to do. A nested search is - * refused rather than given a second block: the block holds the - * resume token of the search that is running. The module zash loads - * is never DELETEd; MVS drops it when the shell ends. + * The module is loaded once and, unless a call abends, stays loaded for + * the life of the shell: MVS drops it when the shell ends. A nested + * search is refused rather than given a second block, because the work + * area holds the resume token of the search that is running. * * @return false if the catalog could not be searched. */ bool sys_catalog_list(const char *filter, mvs_name_fn *fn, void *arg) { - if (csi_in_flight) + if (csi_dead || csi_in_flight) return false; - if (!csi_blk) { - /* Spelled in IBM-1047 whatever this program's own character - * mode is: LOAD takes the name as the system spells it. */ - static const unsigned char name[8] = {0xC9, 0xC7, 0xC7, 0xC3, - 0xE2, 0xC9, 0xF0, 0xF0}; - csi_blk = __malloc31(sizeof *csi_blk); - if (!csi_blk) + if (!csi_ep) { + csi_ep = (iggcsi_fn *)(void (*)(void))fetch("IGGCSI00"); + if (!csi_ep) { + csi_dead = true; /* never asked for again */ return false; - memset(csi_blk, 0, offsetof(csi_block, epname)); - memcpy(csi_blk->epname, name, sizeof name); + } } - csi_area a = {csi_blk->reason, csi_blk->field, csi_blk->work, CSI_WORK}; + csi_req *r = malloc(sizeof *r); + if (!r) + return false; /* not sticky: storage may come back */ + csi_area a = {r->reason, r->field, r->work, CSI_WORK}; + bool abended = false; csi_in_flight = true; - bool ok = csi_search(filter, &a, csi_call, csi_blk, fn, arg); + bool ok = csi_search(filter, &a, csi_call, &abended, fn, arg); csi_in_flight = false; + free(r); + if (abended) { + (void)release((void (*)(void))csi_ep); + csi_ep = NULL; + csi_dead = true; + ok = false; + } return ok; } @@ -668,6 +708,9 @@ bool sys_catalog_list(const char *filter, mvs_name_fn *fn, void *arg) { * PDS under BSAM. A PDSE directory is simulated). * * @param dsn Data set name, without quotes. + * @param fn Called for each member name. + * @param arg Passed to `fn`. + * @return false if the directory could not be read or was malformed. */ bool sys_pds_members(const char *dsn, mvs_name_fn *fn, void *arg) { char path[64]; @@ -708,7 +751,7 @@ bool sys_dd_names(mvs_name_fn *fn, void *arg) { /* ---- dynamic allocation ------------------------------------------------ */ typedef int bpxwdyn_fn(char *); -#pragma linkage(bpxwdyn_fn, OS) +#pragma linkage(bpxwdyn_fn, OS_UPSTACK) /** * @brief Issue a BPXWDYN request, such as `alloc dd(in) da(x.y) shr`. @@ -717,9 +760,6 @@ typedef int bpxwdyn_fn(char *); * names allocated this way belong to the address space, so a command * spawned with `_BPX_SHAREAS=YES` can open them as `//DD:NAME`. * - * VERIFY: calling BPXWDY2 from an AMODE 64 program through fetch(). It - * may need the same kind of glue as the catalog search. - * * @param request The request text. * @param msg Receives an explanation on failure. * @param msglen Size of `msg`. @@ -728,16 +768,19 @@ typedef int bpxwdyn_fn(char *); */ int sys_dynalloc(const char *request, char *msg, size_t msglen) { static bpxwdyn_fn *bpxwdyn; - if (!bpxwdyn) + static bool tried; + if (!bpxwdyn && !tried) { + tried = true; bpxwdyn = (bpxwdyn_fn *)(void (*)(void))fetch("BPXWDY2 "); + } if (!bpxwdyn) { snprintf(msg, msglen, "cannot load BPXWDYN"); return -1; } size_t len = strlen(request); - char *text = __malloc31(len + 1); + char *text = malloc(len + 1); if (!text) { - snprintf(msg, msglen, "out of storage below 2 GB"); + snprintf(msg, msglen, "out of storage"); return -1; } memcpy(text, request, len + 1); @@ -775,7 +818,8 @@ int sys_pipe(int fd[2]) { } int high = sys_dupfd(fd[i], SYS_NFD); if (high < 0) { - int err = errno; + int err; + err = errno; close(fd[0]); close(fd[1]); errno = err; @@ -826,6 +870,14 @@ int sys_open(const char *path, int flags, mode_t mode) { unsigned sys_init(void) { unsigned mask = 0; /* + * LE prints "CEE5208S The signal SIGxxx was received." on stderr when a + * process dies of a signal with the default action -- noise in a script's + * output, and /bin/sh does not do it. IBM's zoslib sets this too. The + * runtime reads it lazily, so this covers this shell and the children it + * forks; "0": a value the user set wins. + */ + (void)setenv("_EDC_SIG_DFLT", "1", 0); + /* * An ASCII build converts to and from tagged files and pipes itself; * it must not depend on the user having set _BPXK_AUTOCVT. An EBCDIC * build leaves the process setting alone, like /bin/sh. @@ -531,12 +531,6 @@ void exc_raise(int exc) { } /** - * @brief Print a message on standard error, prefixed with the shell's name and, - * in a script, the current line number. - * @param fmt printf() format. - * @param ap Arguments. - */ -/** * @brief Derive a message number from a message's format string. * * `set -o msgid` puts an identifier such as `ZSH4711E` in front of every @@ -561,6 +555,13 @@ static unsigned message_number(const char *fmt) { return 1000 + h % 9000; } +/** + * @brief Print a message on standard error, prefixed with the shell's name and, + * in a script, the current line number. + * @param fmt printf() format. + * @param ap Arguments. + * @param severity 'W' for a warning, 'E' for an error. + */ static void vwarn(const char *fmt, va_list ap, char severity) { out_flush(&out1); if (opt.msgid) diff --git a/src/zos_csi.s b/src/zos_csi.s deleted file mode 100644 index aa77826..0000000 --- a/src/zos_csi.s +++ /dev/null @@ -1,99 +0,0 @@ -*********************************************************************** -* ZASHCSI - call IGGCSI00 (Catalog Search Interface) from AMODE 64 -* -* int ZASHCSI(csi_block *block); #pragma linkage(ZASHCSI, OS) -* -* IGGCSI00 runs AMODE 31 and takes a standard three-word parameter -* list. zash is 64-bit XPLINK, so sys_zos.c keeps everything the -* routine needs in one csi_block in 31-bit storage, below 2 GB, with -* that parameter list at its head: -* -* +0 A(reason), A(field), A(work) with the VL bit -* +12 72-byte save area handed to IGGCSI00 -* +84 reason area -* +88 16 doublewords: the caller's R14-R13 -* +216 the entry point LOAD gave, 0 until the first call -* +220 return code from IGGCSI00 -* +224 CL8'IGGCSI00' in IBM-1047, for LOAD -* -* Entry (OS linkage from 64-bit C, no stack): -* R1 -> parameter list of doublewords; the first is the block -* R14 = return address (64-bit) -* Exit: -* R15 = IGGCSI00's return code, sign-extended -* R0-R14 as on entry -* -* The glue stores nothing through the caller's R13: under XPLINK the -* caller's save area is not one the routine may use, so the caller's -* registers are kept in the block instead. IGGCSI00 saves and restores -* the low halves of R2-R14 and never touches a high half, so the -* registers come back whole and the return code is the only thing left -* to keep: it is stored in the block because the exit path needs R15 to -* reach the block. -* -* The CSECT is RMODE 31 because SAM31 branches to the next instruction -* with the address cut to 31 bits: that only works below 2 GB. -* -* Assemble: as -mgoff -o src/zos_csi.o src/zos_csi.s -*********************************************************************** -PARM EQU 0 three-word CSI parameter list -SAVE EQU 12 save area for IGGCSI00 -REGS EQU 88 the caller's R14..R13 -EP EQU 216 EPA from LOAD, 0 until loaded -RC EQU 220 return code from IGGCSI00 -NAME EQU 224 CL8'IGGCSI00' in IBM-1047 -NOLOAD EQU 16 the failure code (sys_zos.c) -ZASHCSI CSECT -ZASHCSI AMODE 64 -ZASHCSI RMODE 31 - SYSSTATE AMODE64=YES - LG R8,0(R1) R8 = block (below 2 GB) - STMG R14,R13,REGS(R8) save R14,R15,R0..R13 in the block - LA R13,SAVE(R8) save area for IGGCSI00 -* Load IGGCSI00 once; the entry point stays in the block, so -* only the first search pays for the directory search. It is -* never DELETEd: MVS drops it when the shell ends. - LLGT R2,EP(R8) - LTR R2,R2 - JNZ ZCSICALL - LA R3,NAME(R8) - SAM31 - SYSSTATE AMODE64=NO - LOAD EPLOC=(R3),ERRET=ZCSIFAIL - SYSSTATE AMODE64=YES - SAM64 - ST R0,EP-SAVE(R13) R13 = block+SAVE - LLGT R2,EP-SAVE(R13) - LTR R2,R2 - JZ ZCSIFAIL -ZCSICALL DS 0H - LA R1,PARM(R8) R1 -> parameter list at block+0 - SAM31 - BASR R14,R2 - SAM64 - ST R15,RC-SAVE(R13) keep the return code -ZCSIRET DS 0H - LGR R15,R13 - AGHI R15,-SAVE R15 = block - LG R14,REGS(R15) caller's R14 - LMG R0,R13,REGS+16(R15) caller's R0..R13 - LGF R15,RC(R15) return code, sign-extended - BR R14 -ZCSIFAIL DS 0H - LGHI R15,NOLOAD - ST R15,RC-SAVE(R13) - J ZCSIRET - LTORG - -*********************************************************************** -* Register equates -*********************************************************************** -R0 EQU 0 -R1 EQU 1 -R2 EQU 2 -R3 EQU 3 -R8 EQU 8 -R13 EQU 13 -R14 EQU 14 -R15 EQU 15 - END ZASHCSI diff --git a/tests/posix/expand-edge.sh b/tests/posix/expand-edge.sh index d8d1e7c..230578e 100644 --- a/tests/posix/expand-edge.sh +++ b/tests/posix/expand-edge.sh @@ -25,7 +25,7 @@ x=abcabc; echo "${x#*b}" "${x##*b}" "${x%b*}" "${x%%b*}" "${#x}" x='a*b'; echo "${x#a\*}" "${x#"a*"}" "${x%'*b'}" x=/usr/local/bin/sh; echo "${x##*/}" "${x%/*}" echo "${#}" "${#@}" 2>/dev/null -echo ${x:+"quoted alt"} | wc -w +echo ${x:+"quoted alt"} | wc -w | tr -d ' ' a=1; b='$a'; echo "$b" ${b} echo "$(echo "nested $(echo "deeper")")" echo `echo \`echo inner\`` @@ -37,6 +37,6 @@ y=a:~:b; echo "$y" | sed "s|$HOME|HOME|g" echo $((1+2))$((3)) "$((4*5))" echo ${x+$(echo sub)} echo "${u-$(echo default)}" -unset u; echo "${u-"a b"}" | wc -w +unset u; echo "${u-"a b"}" | wc -w | tr -d ' ' f() { echo "$#"; }; f "$@"; f $u; f "$u"; f '' set -- 1 2 3 4 5 6 7 8 9 10 11; echo "$10" "${10}" "${11}" diff --git a/tests/posix/glob-edge.sh b/tests/posix/glob-edge.sh index ea3f0ee..006e948 100644 --- a/tests/posix/glob-edge.sh +++ b/tests/posix/glob-edge.sh @@ -18,7 +18,7 @@ echo q? x='a*'; echo $x "$x" for f in sp*; do echo "<$f>"; done echo [a-b]1 -echo [[:digit:]]* | wc -w +echo [[:digit:]]* | wc -w | tr -d ' ' echo [[:alpha:]]1 echo a[ echo sub/../a1 diff --git a/tests/scripts/bigdata.sh b/tests/scripts/bigdata.sh index 0b012d9..58410e1 100644 --- a/tests/scripts/bigdata.sh +++ b/tests/scripts/bigdata.sh @@ -10,8 +10,8 @@ printf '%s\n' "$big" | cksum | cut -d' ' -f1 >sum3 cmp -s sum1 sum3 && echo "command substitution intact" n=0; while read -r a b c; do n=$((n + c)); done <data; echo "sum: $n" printf '%s\n' "$big" | while read -r a b c; do :; done; echo "read loop: $a" -x=$(printf '%070000d' 0 | wc -c); echo "70000 bytes: $x" | tr -s ' ' -y=$(printf '%070000d' 0 | tr 0 x | tr x y | wc -c); echo "through tr: $y" | tr -s ' ' +x=$(printf '%070000d' 0 | wc -c | tr -d ' '); echo "70000 bytes: $x" | tr -s ' ' +y=$(printf '%070000d' 0 | tr 0 x | tr x y | wc -c | tr -d ' '); echo "through tr: $y" | tr -s ' ' printf '%0100000d\n' 0 | { read -r l; echo "${#l}"; } cat <<EOF2 | wc -c | tr -d ' ' $big diff --git a/tests/scripts/wordfreq.sh b/tests/scripts/wordfreq.sh index 31c5eb0..5637c0e 100644 --- a/tests/scripts/wordfreq.sh +++ b/tests/scripts/wordfreq.sh @@ -4,7 +4,11 @@ The quick brown fox jumps over the lazy dog. The dog barks; the fox runs. A quick, quick fox! TXT normalize() { - tr 'A-Z' 'a-z' | tr -c 'a-z\n' ' ' | tr -s ' ' '\n' | sed '/^$/d' + # tr's ranges and -c follow the code page's collating order, which on + # z/OS (EBCDIC) makes 'A-Z' 'a-z' a mapping into punctuation and + # leaves ';' alone. sed and the [:upper:]/[:lower:] classes do not. + sed 's/[^a-zA-Z]/ /g' | tr '[:upper:]' '[:lower:]' | tr -s ' ' '\n' | + sed '/^$/d' } total=0 while read -r w; do diff --git a/tests/tools/zos-shim/zos_shim.h b/tests/tools/zos-shim/zos_shim.h index 5c4bac3..54f5fe9 100644 --- a/tests/tools/zos-shim/zos_shim.h +++ b/tests/tools/zos-shim/zos_shim.h @@ -11,6 +11,9 @@ */ #ifndef ZOS_SHIM_H #define ZOS_SHIM_H +/* Tell the sources they are being checked, not built: this is 64-bit + * Linux, and sys_zos.c asserts the real build is 31-bit. */ +#define ZASH_ZOS_SHIM 1 #include <fcntl.h> #include <signal.h> #include <spawn.h> @@ -85,6 +88,12 @@ int __osname(struct utsname *); /* <stdlib.h> fetch() */ typedef int (*__fetch_t)(void); __fetch_t fetch(const char *); +int release(void (*)(void)); + +/* <signal.h>: LE's abend signal. The value is from EDC4H023. */ +#ifndef SIGABND +#define SIGABND 18 +#endif /* <spawn.h> (z/OS spawn(), not posix_spawn) */ struct inheritance { diff --git a/tests/tools/zos-sleep.c b/tests/tools/zos-sleep.c new file mode 100644 index 0000000..f6272ab --- /dev/null +++ b/tests/tools/zos-sleep.c @@ -0,0 +1,35 @@ +/** + * @file zos-sleep.c + * @brief A `sleep` that takes fractions, for the z/OS test runs. + * + * /bin/sleep on z/OS rejects "0.3" ("Improper sleep interval + * specification"), and tests/zash/jobs.sh and tests/scripts/parallel.sh + * order background jobs with sub-second sleeps. `make zos-check` builds + * this and puts its directory in front of PATH; Linux never builds it, + * because its own sleep is already fine. + */ +#include <errno.h> +#include <stdlib.h> +#include <time.h> + +int main(int argc, char **argv) { + struct timespec ts = {0, 0}; + if (argc < 2) + return 1; + for (int i = 1; i < argc; i++) { + char *end = NULL; + double seconds = strtod(argv[i], &end); + if (end == argv[i] || *end != '\0' || seconds < 0) + return 1; + long whole = (long)seconds; + ts.tv_sec += (time_t)whole; + ts.tv_nsec += (long)((seconds - (double)whole) * 1e9); + } + ts.tv_sec += (time_t)(ts.tv_nsec / 1000000000L); + ts.tv_nsec %= 1000000000L; + while (nanosleep(&ts, &ts) < 0) { + if (errno != EINTR) + return 1; + } + return 0; +} diff --git a/tests/zos/fdmap.exp b/tests/zos/fdmap.exp index cd47308..62f83ce 100644 --- a/tests/zos/fdmap.exp +++ b/tests/zos/fdmap.exp @@ -7,4 +7,5 @@ piped captured script descriptors ok and closed again +survives exec [status 0] diff --git a/tests/zos/fdmap.sh b/tests/zos/fdmap.sh index c4f1679..b63a199 100644 --- a/tests/zos/fdmap.sh +++ b/tests/zos/fdmap.sh @@ -26,3 +26,8 @@ while [ $i -le 9 ]; do i=$((i + 1)) done /bin/sh -c 'echo "and closed again"' +# The map hands the child the shell's own pipe descriptors. They are +# close-on-exec (sys_pipe()), and spawn() keeps the flag, so a grandchild +# that execs would lose the pipe -- ps printed EDC5113I Bad file +# descriptor. The map must pass a duplicate without the flag. +/bin/sh -c 'exec /bin/echo survives exec' | /bin/cat diff --git a/tests/zos/tagging.sh b/tests/zos/tagging.sh index 5f3c3bb..5ef4a3d 100644 --- a/tests/zos/tagging.sh +++ b/tests/zos/tagging.sh @@ -69,7 +69,7 @@ _TAG_REDIR_OUT=BIN printf 'hello\n' >in819 # ASCII bytes in an ASCII build [ "$self" = IBM-1047 ] && _TAG_REDIR_OUT=BIN printf '\150\145\154\154\157\012' >in819 chtag -tc ISO8859-1 in819 _TAG_REDIR_IN=TXT cat <in819 -_TAG_REDIR_IN=BIN od -An -tx1 <in819 | tr -d ' \n' +_TAG_REDIR_IN=BIN od -An -tx1 <in819 | tr -d ' \n' | tr '[:upper:]' '[:lower:]' echo echo "-- pipeline stage tagged by _TAG_REDIR_OUT" |
