1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
|
<p align="center">
<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.
## 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
- C17, compiled with `-std=c17` and no compiler extensions beyond a
few attributes that are wrapped in macros. C23 was tried first and
dropped: it cannot be relied on for the z/OS toolchain.
- Clang on Linux, IBM Open XL C/C++ (Clang-based) on z/OS. The tree
also builds cleanly with GCC (`-std=c17 -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 C11 and C99: `_Noreturn`, `_Static_assert`,
`_Alignas`, `<stdbool.h>`, designated initialisers, compound literals,
flexible array members, `static` array parameters.
- Four attributes are used through macros in `shell.h`: `NODISCARD`,
`FALLTHROUGH`, `UNREACHABLE()` and `PRINTFLIKE` for format checking.
They expand to nothing on a compiler that lacks them.
- Constants are `#define`s with a typed value, or anonymous `enum`s for
sets of related integer constants.
- 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 | 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 |
Two independent costs, and only one of them is about copying.
- A fixed penalty for Language Environment at 64 bits: about 4 ms per
fork and 28 ms per program start, whatever the program does or holds.
The address mode itself is free (an assembler program with no C
run-time starts in 0.8 ms at 31 bits and at 64), so the cost is LE
building the 64-bit enclave. 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, since `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. The three rows zash used to lose on z/OS
(`( : ) &`, `( cd / ) &`, `( cd / )`) are lost to the 64-bit C
run-time, 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 and the method;
[notes/investigation.md](notes/investigation.md) has the probe programs
and what they leave open.
### 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 |
| `$(<file)` | none: the file is read directly |
| `$(a \| b)`, all external | one `spawn()` each, no forks: the shell reads the last stage's pipe itself |
| `$(echo "$x" \| sed ...)` | one `spawn()`: the builtin's output is written into the pipe by the shell |
| a command that is not found, in any of the positions above | none: only the message is printed |
| `cmd &` (external) | one `spawn()` |
| `sh -c 'cmd'`, last command of a script | `exec` in place, no new process |
| `( list )` | `fork()` |
| `{ list; } &`, `$( compound )` | `fork()` |
| compound command or function as a non-last pipeline stage | `fork()` |
| a script with no `#!` line | `spawn()` of zash itself on the script |
Everything `spawn()` needs is computed in the parent: arguments are
expanded, the command is looked up, redirections are opened, and the
child's file descriptors are described by an *fd plan* (see
[Redirection](#redirection)) that maps directly onto `spawn()`'s `fd_map`
argument, so nothing has to run "in the child before exec", and nothing
forces a `fork()`.
### Running builtins without a subshell
POSIX says each pipeline stage and each command substitution runs in a
subshell environment. For an external command that is free. For a builtin
it would normally mean a `fork()`.
zash avoids it for *output-only* builtins (`echo`, `printf`, `pwd`,
`test`, `true`, `false`, `type`): builtins whose only effect is writing
to stdout/stderr. Two things make that safe:
1. Builtins write through `out1`/`out2`, never to fd 1 directly. The
output object is pointed at a pipe, or at a memory buffer, for the
duration of the builtin. The real fd table is untouched.
2. Expansion side effects are undone. Expanding the builtin's
arguments can assign variables (`${x=1}`, `$((i++))`). The expansion
runs inside a *capture scope* that records every variable change and
reverts it afterwards, so the visible behaviour matches a subshell.
The same capture scope wraps argument expansion for any command the
parent prepares on behalf of a child (pipeline stages, `&`, `$( )`).
The check runs the other way too, so a subshell can sometimes avoid a
process. `( : )` is a subshell whose body is one output-only builtin with
no redirections and no assignments. Nothing outside it can change, so it
runs in the shell. A `fork()` copies the address space on z/OS, where a
`spawn()` shares it. Measured there, 3000 empty subshells fell from
14.16 s to 0.01 s, against 0.80 s for ksh88, which never forks for
them.
While a builtin writes into a pipe in-process, `SIGPIPE` is ignored and a
failed write ends the builtin, as it would end a subshell.
**The shell must never block on its own pipe.** A builtin writing into a
pipe in-process is only safe if something else is draining it:
- If the reader is already a running process (and the far end of the
pipeline is not the shell), the builtin streams straight into the pipe.
- If the reader is the shell itself (the last stage running in-shell,
another in-shell builtin, or the collector of a command substitution),
the output is gathered in memory first. Up to `PIPE_BUF` bytes are
guaranteed to fit in an empty pipe and are written with no process at
all. Anything larger is handed to a forked writer.
- An external last stage is started *before* any in-shell writer runs.
`echo "$line" | read a b` and `x=$(echo "$v" | tr a-z A-Z)` are therefore
free of forks, and `printf '%s' "$megabyte" | while read ...` cannot
deadlock.
Pipes the shell creates are moved above descriptor 9, so they can never
collide with, or be mistaken for, a descriptor the script names.
### `_BPX_SHAREAS`
zash does not invent a policy. `spawn()` reads the variable from the
child's environment, so `export _BPX_SHAREAS=YES` in `/etc/profile`
behaves as it does with `/bin/sh`. A one-off `_BPX_SHAREAS=NO daemon &`
works through ordinary assignment syntax.
zash's job is to create as many children as possible with `spawn()`, so
the setting applies to them.
The same holds for `STEPLIB` and `_BPX_SPAWN_SCRIPT`.
zash applies no default of its own. `set -o shareas` is the opt-in: it
adds `_BPX_SHAREAS=YES` for foreground commands only (see
[Per-command z/OS options](#per-command-zos-options)).
### Accounting
The shell counts `spawn()` and `fork()` calls. With `ZASH_PROCSTAT=1` in
the environment it prints the counts at exit. The test suite uses this to
assert that constructs cost what the table above says.
## Character sets
zash builds in ASCII mode (`-fzos-le-char-mode=ascii`, the zopen
convention) or in EBCDIC (IBM-1047), chosen at compile time. The source
never assumes either:
- No in-band marker bytes. A classic ash encodes quoting inside the
word as control bytes in the 0x81+ range. In IBM-1047 those are
ordinary letters (`0x81` is `a`). zash keeps words as a typed list of
parts (literal, parameter, command substitution, arithmetic), each
flagged quoted or not. There are no reserved byte values.
- No arithmetic on letters. `a`..`z` are not contiguous in EBCDIC.
Character tests go through `<ctype.h>`. 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. 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.
Two details matter, and the second is not obvious:
- 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:
- `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 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 comes
from dropping the 64-bit C run-time, not from 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.
|