/** * @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 #include #include #include #include #include #include #include #include #include #include #include #include #include "charset.h" #include "sys.h" /* IGGCSI00 and BPXWDY2 are AMODE 31, and are called through plain * function pointers: under -m64 the OS linkage glue switches the address * mode for the call. On this system neither module loads, so that path * is unverified (notes/investigation.md). */ /** * @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. nullptr 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. 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 of our own, and no assembler. * * At -m32 the linkage has to be OS_UPSTACK, not plain OS: there OS means * OS_NOSTACK (no standard save area), so IGGCSI00 -- a traditional * upward-stack OS routine -- takes a program check on the first call; * measured on z/OS, OS abended and OS_UPSTACK returned rc=0 with the work * area filled. OS_UPSTACK is unsupported at -m64, so plain OS is used * there. If that abends the way it did at -m32, csi_call() catches the * program check and the catalog is retired: completion falls back to file * names instead of the shell going down. */ /** @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. */ constexpr unsigned CSI_WORK = 32768; /**< work area for one IGGCSI00 search */ /** @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) static iggcsi_fn *csi_ep; /**< from fetch(), nullptr 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 | ((uintptr_t)1 << (sizeof(uintptr_t) * 8 - 1))); 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], nullptr); 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 = nullptr; 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)) : nullptr; 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) /** * @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; }