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
|
/**
* @file sys_zos.c
* @brief Platform layer for z/OS UNIX, built on spawn().
*
* spawn() is the reason this shell exists: unlike fork() it does not copy
* the address space, and with `_BPX_SHAREAS=YES` in the child's
* environment the child runs in the shell's own address space. The fd
* map the rest of the shell builds is exactly spawn()'s fd_map argument.
*
* This file is compiled and run on z/OS: `make zos-ascii` and `make
* zos-ebcdic` build it there, and the tests under `tests/zos` exercise it
* on the machine. Lines marked VERIFY are the parts no test has reached.
*/
#include <_Ccsid.h>
#include <_Nascii.h>
#include <errno.h>
#include <fcntl.h>
#include <setjmp.h>
#include <spawn.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <signal.h>
#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.
*
* The z/OS C library has no strsignal(), so the common signals are
* described here in glibc's words, which is what dash prints and what the
* tests expect.
*
* @return Static text. For an unlisted signal, a buffer overwritten by the
* next such call.
*/
const char *sys_strsignal(int sig) {
static const struct {
int sig;
const char *text;
} table[] = {
{SIGHUP, "Hangup"},
{SIGINT, "Interrupt"},
{SIGQUIT, "Quit"},
{SIGILL, "Illegal instruction"},
{SIGTRAP, "Trace/breakpoint trap"},
{SIGABRT, "Aborted"},
{SIGBUS, "Bus error"},
{SIGFPE, "Floating point exception"},
{SIGKILL, "Killed"},
{SIGUSR1, "User defined signal 1"},
{SIGSEGV, "Segmentation fault"},
{SIGUSR2, "User defined signal 2"},
{SIGPIPE, "Broken pipe"},
{SIGALRM, "Alarm clock"},
{SIGTERM, "Terminated"},
{SIGCHLD, "Child exited"},
{SIGCONT, "Continued"},
{SIGSTOP, "Stopped (signal)"},
{SIGTSTP, "Stopped"},
{SIGTTIN, "Stopped (tty input)"},
{SIGTTOU, "Stopped (tty output)"},
{SIGURG, "Urgent I/O condition"},
{SIGXCPU, "CPU time limit exceeded"},
{SIGXFSZ, "File size limit exceeded"},
{SIGVTALRM, "Virtual timer expired"},
{SIGPROF, "Profiling timer expired"},
{SIGPOLL, "I/O possible"},
{SIGSYS, "Bad system call"},
};
for (size_t i = 0; i < sizeof table / sizeof table[0]; i++) {
if (table[i].sig == sig)
return table[i].text;
}
static char other[sizeof "Signal -2147483648"];
snprintf(other, sizeof other, "Signal %d", sig);
return other;
}
/**
* @brief Create a process running a program, with z/OS spawn().
* @param rq What to run and how to set it up.
* @return The child's pid, or -1 with errno set.
*/
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};
for (int i = 0; i < SYS_NFD; i++) {
int src = rq->fdmap[i];
/* spawn() rejects a map entry naming a descriptor that is closed. */
if (src == i && !(rq->open_mask & (1u << i)))
src = FD_CLOSED;
if (src == FD_CLOSED) {
fd_map[i] = SPAWN_FDCLOSED;
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;
inh.sigdefault = *rq->sigdfl;
}
/* VERIFY: job control through the inheritance structure. */
if (rq->pgroup >= 0) {
inh.flags |= SPAWN_SETGROUP;
inh.pgroup = rq->pgroup == 0 ? SPAWN_NEWPGROUP : rq->pgroup;
}
/*
* spawn() sets the terminal's foreground process group in the child,
* after it has closed every descriptor from fd_count up (zos-c-runtime-
* library, "fd_count ... The files from fd_count through OPEN_MAX are
* closed in the child process"). A terminal descriptor living above the
* script's, as ours does, is therefore EBADF by the time spawn() uses it,
* and spawn() fails the command with EDC5113I. Carrying it in the map
* keeps it open in the child for exactly that call.
*
* shortcut: SYS_NFD+16 covers a script's own descriptors (0..SYS_NFD-1)
* and the shell's. Widen the map if the shell ever holds more.
*/
if (rq->tty_fd >= 0 && rq->tty_fd < map_max) {
while (fd_count <= rq->tty_fd)
fd_map[fd_count++] = SPAWN_FDCLOSED;
fd_map[rq->tty_fd] = rq->tty_fd;
inh.flags |= SPAWN_SETTCPGRP;
inh.ctlttyfd = rq->tty_fd;
}
/*
* VERIFY: in an ASCII-mode build (-fzos-le-char-mode=ascii), that the
* runtime converts path, argv and envp, and that _BPX_SHAREAS,
* _BPX_SPAWN_SCRIPT and STEPLIB are honoured from `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;
}
/**
* @brief Can sys_spawn() hand the terminal to the child's process group?
* (VERIFY: SPAWN_SETTCPGRP is assumed to work as documented.)
*/
bool sys_spawn_gives_tty(void) {
return true;
}
/* ---- helpers ---------------------------------------------------------- */
/** @brief CCSID of this program's own text: 819 if built ASCII, else 1047. */
#define PROGRAM_CCSID (ZASH_ASCII ? 819 : 1047)
/** @brief CCSID that marks a file as binary. */
#define CCSID_BINARY 65535
/**
* @brief Follow a 31-bit pointer stored in 31-bit storage.
* @param addr Address of the fullword.
* @return The address it holds, with the AMODE bit removed.
*/
static const unsigned char *ptr31(uintptr_t addr) {
uint32_t v;
memcpy(&v, (const void *)addr, sizeof v);
return (const unsigned char *)(uintptr_t)(v & 0x7fffffffu);
}
/* ---- file tags and automatic conversion ------------------------------- */
/**
* @brief Cached `_TAG_REDIR_IN`, `_OUT`, `_ERR`. See sys.h.
*/
tag_mode tag_redir[3];
/**
* @brief Does this platform have file tags? Yes.
*/
bool sys_has_tags(void) {
return true;
}
/**
* @brief Set a deferred tag: the CCSID is filled in by the system from
* the program that does the first write.
* @param fd An untagged file or pipe.
* @param text Whether to set the text flag.
*/
static void tag_deferred(int fd, bool text) {
struct file_tag t;
memset(&t, 0, sizeof t);
t.ft_ccsid = 0;
t.ft_txtflag = text;
t.ft_deferred = 1;
fcntl(fd, F_SETTAG, &t);
}
/**
* @brief Tag a descriptor with a definite CCSID, as text.
*/
static void tag_text(int fd, int ccsid) {
struct file_tag t;
memset(&t, 0, sizeof t);
t.ft_ccsid = (unsigned short)ccsid;
t.ft_txtflag = 1;
fcntl(fd, F_SETTAG, &t);
}
/**
* @brief Convert this process's I/O on `fd` between its own CCSID and
* IBM-1047.
*
* Automatic conversion for a descriptor is decided when it is opened, from
* the tag then in force. A pipe, a here-document file the shell tags
* after creating it, and a standard stream inherited untagged all miss
* that, so an ASCII zash would write ASCII bytes where EBCDIC readers
* (and EBCDIC writers on the same file) expect IBM-1047. The first z/OS
* run of the suite showed exactly that: `echo x | wc -l` counted 0 lines.
*
* pccsid 0 means "the CCSID of the program doing the I/O", so the setting
* is harmless if it is shared with a child through the open file: an
* EBCDIC child converts 1047 to 1047.
*
* VERIFY: pccsid 0 is resolved per process, as described above.
*/
static void cvt_1047(int fd) {
struct f_cnvrt cv;
memset(&cv, 0, sizeof cv);
cv.cvtcmd = SETCVTON;
cv.pccsid = 0;
cv.fccsid = 1047;
fcntl(fd, F_CONTROL_CVT, &cv);
}
/**
* @brief Apply tagging or conversion control to a file a redirection has
* just opened.
*
* This is what the `_TAG_REDIR_IN`, `_TAG_REDIR_OUT` and `_TAG_REDIR_ERR`
* variables of the z/OS shell do (z/OS UNIX Command Reference, `sh`,
* "Shell variables for automatic conversion"):
*
* - **Input, TXT:** the file is treated as text in its tagged CCSID
* (conversion is switched on for the descriptor). No effect on an
* untagged file.
* - **Input, BIN:** conversion is switched off for the descriptor.
* - **Output or error, TXT or BIN:** an untagged, empty target gets a
* deferred tag: text flag on or off, CCSID that of the program that
* first writes to it. A file that is already tagged is left alone.
*
* With the variable unset an EBCDIC build does nothing, exactly like
* `/bin/sh`. An ASCII build tags new output as deferred text, because
* otherwise everything an ASCII shell or tool writes through `>` would
* be untagged ISO8859-1 that EBCDIC tools misread. (An EBCDIC tool
* writing through the same redirection tags the file IBM-1047: the tag
* follows the writer.)
*
* The settings live on the open file, so they hold for a spawned child
* as well as for a builtin.
*
* VERIFY: that a deferred tag is applied by a writer that has automatic
* conversion off, and that SETCVTON with pccsid 0 follows the reading
* program's CCSID after spawn().
*
* @param fd The descriptor just opened.
* @param stream Which standard stream it will become.
* @param mode Value of that stream's `_TAG_REDIR_*` variable.
* @param created The redirection creates or truncates (`>`, `>|`, `>>`).
*/
void sys_redir_tag(int fd, tag_stream stream, tag_mode mode, bool created) {
struct stat st;
if (stream == TAG_IN) {
if (mode == TAG_UNSET || fstat(fd, &st) < 0)
return;
struct f_cnvrt cv;
memset(&cv, 0, sizeof cv);
if (mode == TAG_BIN) {
cv.cvtcmd = SETCVTOFF;
} else {
if (st.st_tag.ft_ccsid == 0 || st.st_tag.ft_ccsid == CCSID_BINARY)
return;
cv.cvtcmd = SETCVTON;
cv.fccsid = (short)st.st_tag.ft_ccsid;
}
fcntl(fd, F_CONTROL_CVT, &cv);
return;
}
if (mode == TAG_UNSET) {
if (!ZASH_ASCII)
return;
/*
* No _TAG_REDIR_* setting in an ASCII build: the file holds
* IBM-1047 text, as under /bin/sh. A deferred tag would go to
* whichever program writes first, and a later writer in the other
* character set (zash and an EBCDIC tool in one `{ ...; } >f`)
* would then put unconverted bytes into it. Untagged data
* already in the file is taken to be EBCDIC too.
*/
if (fstat(fd, &st) < 0 || st.st_tag.ft_ccsid != 0 ||
(!S_ISREG(st.st_mode) && !S_ISFIFO(st.st_mode)))
return;
if (S_ISFIFO(st.st_mode) || st.st_size == 0)
tag_text(fd, 1047);
cvt_1047(fd);
return;
}
if (!created || fstat(fd, &st) < 0 || st.st_tag.ft_ccsid != 0)
return;
if (S_ISREG(st.st_mode) ? st.st_size != 0 : !S_ISFIFO(st.st_mode))
return; /* existing untagged data, or a device: leave it alone */
tag_deferred(fd, mode == TAG_TXT);
}
/**
* @brief Tag a pipe the shell has just created.
*
* - `_TAG_REDIR_OUT` set: the pipe gets a deferred tag in that mode, so
* the output of each command writing to a pipeline is tagged with the
* writer's CCSID (documented `/bin/sh` behaviour).
* - Otherwise, in an ASCII build with `set -o pipetag` (the default
* there): the pipe is tagged IBM-1047 text. ASCII programs, zash
* included, then have their writes converted to EBCDIC and their reads
* converted back, and EBCDIC programs see EBCDIC. Without this an
* EBCDIC reader would get the ASCII bytes of an ASCII writer.
* `set +o pipetag` turns it off, for pipelines that carry binary data
* from an EBCDIC program to an ASCII one.
* - EBCDIC build, variable unset: nothing, as `/bin/sh`.
*
* @param fd Both ends of the pipe.
*/
static void pipe_tag(int fd[2]) {
if (tag_redir[TAG_OUT] != TAG_UNSET)
tag_deferred(fd[1], tag_redir[TAG_OUT] == TAG_TXT);
else if (ZASH_ASCII && opt.pipetag) {
tag_text(fd[1], 1047);
cvt_1047(fd[0]); /* $( ) and `read` get EBCDIC writers' text */
cvt_1047(fd[1]); /* builtins write ASCII */
}
}
/**
* @brief Tag a temporary file that will carry a here-document.
*
* In an ASCII build the file is tagged IBM-1047 text, and the shell's own
* writes and reads are converted, so the text is EBCDIC on disk and any
* reader gets its own character set. Nothing to do in an EBCDIC build.
*/
void sys_tmp_tag(int fd) {
if (ZASH_ASCII) {
tag_text(fd, 1047);
cvt_1047(fd);
}
}
/**
* @brief Guess the character set of untagged text from its first block.
*
* A newline is 0x15 in EBCDIC and 0x0A in ASCII, and neither code is
* common in the other character set's text.
*
* @return 1047, 819, or 0 if there is no telling.
*/
static int sniff_ccsid(int fd) {
unsigned char buf[512];
ssize_t n = pread(fd, buf, sizeof buf, 0);
int nl_e = 0;
int nl_a = 0;
for (ssize_t i = 0; i < n; i++) {
nl_e += buf[i] == 0x15;
nl_a += buf[i] == 0x0a;
}
if (nl_e && !nl_a)
return 1047;
if (nl_a && !nl_e)
return 819;
return 0;
}
/**
* @brief Make a script (or `.` file, profile, `ENV` file) readable
* whatever character set it is in.
*
* - Tagged as text in a CCSID other than the program's: conversion is
* switched on for the descriptor.
* - Untagged regular file: the first block is examined. If it is plainly
* in the other character set (an IBM-1047 script under an ASCII build,
* or an ISO8859-1 script under an EBCDIC build) it is converted.
* - Otherwise the bytes are read as they are.
*
* One fstat() per script, plus one pread() for an untagged one. Both
* conversions are single-byte, so file offsets are unchanged and the
* shell's lseek() on a shared stdin stays correct.
*
* VERIFY: SETCVTON with an explicit fccsid on an untagged file.
*/
void sys_input_cvt(int fd) {
struct stat st;
if (fstat(fd, &st) < 0)
return;
int ccsid = st.st_tag.ft_ccsid;
if (ccsid == CCSID_BINARY || (ccsid && !st.st_tag.ft_txtflag))
return;
if (!ccsid && S_ISREG(st.st_mode))
ccsid = sniff_ccsid(fd);
if (!ccsid || ccsid == PROGRAM_CCSID)
return;
struct f_cnvrt cv;
memset(&cv, 0, sizeof cv);
cv.cvtcmd = SETCVTON;
cv.pccsid = PROGRAM_CCSID;
cv.fccsid = (short)ccsid;
fcntl(fd, F_CONTROL_CVT, &cv);
}
/**
* @brief Read a file's tag.
* @param path The file.
* @param tag Receives the CCSID, text flag and code set name.
* @return 0, or -1 with errno set.
*/
int sys_tag_get(const char *path, sys_tag *tag) {
struct stat st;
if (stat(path, &st) < 0)
return -1;
tag->ccsid = st.st_tag.ft_ccsid;
tag->text = st.st_tag.ft_txtflag;
tag->codeset[0] = '\0';
if (tag->ccsid && tag->ccsid != CCSID_BINARY) {
char name[_CSNAME_LEN_MAX + 1] = "";
if (__toCSName((__ccsid_t)tag->ccsid, name) == 0)
snprintf(tag->codeset, sizeof tag->codeset, "%s", name);
}
return 0;
}
/**
* @brief Change a file's tag.
* @param path The file.
* @param codeset A code set name or CCSID number. NULL removes the tag;
* "BINARY" tags the file as binary.
* @param text 1 text, 0 not text, -1 keep the current flag.
* @return 0, or -1 with errno set (EINVAL for an unknown code set).
*/
int sys_tag_set(const char *path, const char *codeset, int text) {
attrib_t attr;
struct stat st;
memset(&attr, 0, sizeof attr);
attr.att_filetagchg = 1;
if (stat(path, &st) < 0)
return -1;
attr.att_filetag = st.st_tag;
if (!codeset) {
attr.att_filetag.ft_ccsid = 0;
attr.att_filetag.ft_txtflag = 0;
} else if (!strcmp(codeset, "BINARY")) {
attr.att_filetag.ft_ccsid = CCSID_BINARY;
attr.att_filetag.ft_txtflag = 0;
} else if (*codeset) {
char *end;
long n = strtol(codeset, &end, 10);
if (*end || n <= 0 || n > 65535) {
char name[_CSNAME_LEN_MAX + 1];
snprintf(name, sizeof name, "%s", codeset);
n = __toCcsid(name);
if (n <= 0) {
errno = EINVAL;
return -1;
}
}
attr.att_filetag.ft_ccsid = (unsigned short)n;
}
if (text >= 0 && codeset && strcmp(codeset, "BINARY"))
attr.att_filetag.ft_txtflag = text != 0;
return __chattr((char *)path, &attr, sizeof attr);
}
/* ---- system facts ------------------------------------------------------ */
/**
* @brief Facts about the system, read from MVS control blocks.
*
* | Kind | Source |
* |------------|-----------------------------------------------------|
* | SI_SYSNAME | CVTSNAME (CVT + X'154') |
* | SI_SYSPLEX | ECVTSPLX (ECVT + 8. ECVT from CVT + X'8C') |
* | SI_RELEASE | __osname(): version "." release |
* | SI_ASID | ASCBASID (ASCB + X'24'. ASCB from PSAAOLD, X'224') |
* | SI_JOBNAME | ASCBJBNI (+X'AC') or, if zero, ASCBJBNS (+X'B0') |
*
* These fields are part of the programming interface and have been at
* these offsets for decades, but the code has not been run: VERIFY.
*
* @param kind Which fact.
* @return A string in static storage (overwritten by the next call).
*/
const char *sys_info(sys_info_kind kind) {
static char buf[32];
const unsigned char *cvt = ptr31(0x10);
const unsigned char *ascb = ptr31(0x224);
/* Both are always there under TSO and batch, but a bad address here
* would be an S0C4 in the most visible place a shell has. */
if (!cvt || !ascb)
return "";
switch (kind) {
case SI_SYSNAME:
mvs_name(cvt + 0x154, 8, buf);
break;
case SI_SYSPLEX: {
const unsigned char *ecvt = ptr31((uintptr_t)(cvt + 0x8c));
if (!ecvt)
return "";
mvs_name(ecvt + 8, 8, buf);
break;
}
case SI_RELEASE: {
struct utsname u;
if (__osname(&u) < 0)
return "";
snprintf(buf, sizeof buf, "%.8s.%.8s", u.version, u.release);
break;
}
case SI_ASID:
snprintf(buf, sizeof buf, "%04X",
(unsigned)(ascb[0x24] << 8 | ascb[0x25]));
break;
case SI_JOBNAME: {
const unsigned char *name = ptr31((uintptr_t)(ascb + 0xac));
if (!name)
name = ptr31((uintptr_t)(ascb + 0xb0));
if (!name)
return "";
mvs_name(name, 8, buf);
break;
}
}
return buf;
}
/* ---- the catalog ------------------------------------------------------- */
/*
* 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; 32K already holds more names than a completion
* screen shows, and it is taken per search rather than held.
*/
#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 */
/** @brief Returned by csi_call() after an abend: > 4, so the search stops. */
#define CSI_ABENDED 20
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).
*
* 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) {
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;
}
/**
* @brief Is there a catalog to complete data set names from? Always.
*/
bool sys_has_catalog(void) {
return true;
}
/**
* @brief List cataloged names that match a CSI filter key.
*
* 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_dead || csi_in_flight)
return false;
if (!csi_ep) {
csi_ep = (iggcsi_fn *)(void (*)(void))fetch("IGGCSI00");
if (!csi_ep) {
csi_dead = true; /* never asked for again */
return false;
}
}
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, &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;
}
/**
* @brief List the members of a partitioned data set.
*
* The directory is read as 256-byte blocks through the C library and
* decoded with pds_parse_block().
*
* VERIFY: that fopen() of a PDS or PDSE without a member name, with
* `recfm=u,blksize=256`, delivers the directory blocks (it does for a
* 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];
if (strlen(dsn) > MVS_DSN_MAX)
return false;
snprintf(path, sizeof path, "//'%s'", dsn);
FILE *f = fopen(path, "rb,recfm=u,blksize=256");
if (!f)
return false;
unsigned char blk[PDS_DIRBLK];
bool end = false;
bool ok = true;
while (ok && !end && fread(blk, 1, sizeof blk, f) == sizeof blk)
ok = pds_parse_block(blk, fn, arg, &end);
fclose(f);
return ok && end;
}
/** @brief Most bytes of TIOT entries read (the TIOT is at most 64 KB). */
#define TIOT_MAX 65536
/**
* @brief List the DD names allocated to this address space.
*
* TCB from PSATOLD (X'21C'), TIOT from TCBTIO (TCB + X'0C'), entries
* from TIOT + 24, decoded by tiot_parse().
*
* VERIFY: not yet run.
*/
bool sys_dd_names(mvs_name_fn *fn, void *arg) {
const unsigned char *tcb = ptr31(0x21c);
const unsigned char *tiot = tcb ? ptr31((uintptr_t)(tcb + 0xc)) : NULL;
if (!tiot)
return false;
return tiot_parse(tiot + 24, TIOT_MAX, fn, arg);
}
/* ---- dynamic allocation ------------------------------------------------ */
typedef int bpxwdyn_fn(char *);
#pragma linkage(bpxwdyn_fn, OS_UPSTACK)
/**
* @brief Issue a BPXWDYN request, such as `alloc dd(in) da(x.y) shr`.
*
* BPXWDY2 is the entry point that takes one NUL-terminated string. DD
* names allocated this way belong to the address space, so a command
* spawned with `_BPX_SHAREAS=YES` can open them as `//DD:NAME`.
*
* @param request The request text.
* @param msg Receives an explanation on failure.
* @param msglen Size of `msg`.
* @return BPXWDYN's return code (0 is success), or -1 if it could not be
* called.
*/
int sys_dynalloc(const char *request, char *msg, size_t msglen) {
static bpxwdyn_fn *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 = malloc(len + 1);
if (!text) {
snprintf(msg, msglen, "out of storage");
return -1;
}
memcpy(text, request, len + 1);
mvs_to_ebcdic(text, len);
int rc = bpxwdyn(text);
free(text);
if (rc)
snprintf(msg, msglen, "BPXWDYN return code %d (X'%08X')", rc,
(unsigned)rc);
return rc;
}
/* VERIFY: whether pipe2(), O_CLOEXEC and F_DUPFD_CLOEXEC exist on the
* target release. The fallbacks below cost one extra fcntl() each. */
/**
* @brief Mark a descriptor close-on-exec.
*/
static int set_cloexec(int fd) {
return fcntl(fd, F_SETFD, FD_CLOEXEC);
}
int sys_dupfd(int fd, int min);
/**
* @brief Create a pipe with both ends above descriptor 9. See sys_posix.c.
*/
int sys_pipe(int fd[2]) {
if (pipe(fd) < 0)
return -1;
for (int i = 0; i < 2; i++) {
if (fd[i] >= SYS_NFD) {
set_cloexec(fd[i]);
continue;
}
int high = sys_dupfd(fd[i], SYS_NFD);
if (high < 0) {
int err;
err = errno;
close(fd[0]);
close(fd[1]);
errno = err;
return -1;
}
close(fd[i]);
fd[i] = high;
}
pipe_tag(fd);
return 0;
}
/**
* @brief Duplicate a descriptor to the lowest free number >= `min`,
* close-on-exec.
*/
int sys_dupfd(int fd, int min) {
#ifdef F_DUPFD_CLOEXEC
return fcntl(fd, F_DUPFD_CLOEXEC, min);
#else
int copy = fcntl(fd, F_DUPFD, min);
if (copy >= 0)
set_cloexec(copy);
return copy;
#endif
}
/**
* @brief open(), close-on-exec where the system has O_CLOEXEC.
*/
int sys_open(const char *path, int flags, mode_t mode) {
#ifdef O_CLOEXEC
return open(path, flags | O_CLOEXEC, mode);
#else
/*
* Not close-on-exec, which is harmless here: spawn() passes on only
* the descriptors in fd_map, and the shell closes redirection
* descriptors itself before any exec().
*/
return open(path, flags, mode);
#endif
}
/**
* @brief Platform start-up.
* @return Mask of descriptors 0..9 that are open at startup.
*/
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.
* VERIFY: __ae_autoconvert_state() and its constants (<_Nascii.h>).
*/
if (ZASH_ASCII) {
if (__ae_autoconvert_state(_CVTSTATE_QUERY) == _CVTSTATE_OFF)
__ae_autoconvert_state(_CVTSTATE_ON);
opt.pipetag = true;
/*
* An untagged standard output or error that is not a terminal is
* EBCDIC text by z/OS convention (and the EBCDIC tools the shell
* runs will write EBCDIC into it). Convert to it, and tag it if
* nothing has been written yet, so that LE's AUTOTAG does not tag
* it ISO8859-1 on the shell's first write and mislabel what the
* tools write after.
*/
for (int fd = 1; fd <= 2; fd++) {
struct stat st;
if (isatty(fd) || fstat(fd, &st) < 0 || st.st_tag.ft_ccsid != 0)
continue;
if (!S_ISREG(st.st_mode) && !S_ISFIFO(st.st_mode))
continue;
if (S_ISFIFO(st.st_mode) || st.st_size == 0)
tag_text(fd, 1047);
cvt_1047(fd);
}
}
for (int i = 0; i < SYS_NFD; i++) {
if (fcntl(i, F_GETFD) != -1)
mask |= 1u << i;
}
return mask;
}
|