/** * @file sys_posix.c * @brief Platform layer for Linux and other POSIX systems, built on * posix_spawn(). */ #define _GNU_SOURCE /* posix_spawn_file_actions_addtcsetpgrp_np() */ #include #include #include #include #include #include #include #include #include "sys.h" /* * glibc 2.35 added a file action that hands the terminal to the child's * process group. Without it the parent does the hand-over after the * fact (see sys_spawn_gives_tty()). */ #if defined(__GLIBC__) && defined(__GLIBC_PREREQ) #if __GLIBC_PREREQ(2, 35) #define HAVE_SPAWN_TCSETPGRP 1 #endif #endif #ifndef HAVE_SPAWN_TCSETPGRP #define HAVE_SPAWN_TCSETPGRP 0 #endif /** * @brief Can sys_spawn() itself make the child's group the terminal's * foreground group? * * When it cannot, the shell does so from the parent just after the spawn * and then sends SIGCONT, in case the child touched the terminal first * and was stopped. */ bool sys_spawn_gives_tty(void) { return HAVE_SPAWN_TCSETPGRP; } /** * @brief Describe a signal. * @return strsignal()'s text. Valid until the next call. */ const char *sys_strsignal(int sig) { return strsignal(sig); } /** * @brief Translate an fd map into posix_spawn file actions. * * The map is "parallel" (every entry names a descriptor as it is in the * parent) but file actions run one after another in the child, so a * source that an earlier action overwrites is first copied to a scratch * descriptor. * * @param fa File actions to add to. * @param map Child descriptor i is to be the parent's map[i]. * @return 0, or an errno value. */ static int add_fd_actions(posix_spawn_file_actions_t *fa, const int *map) { int scratch_fd[SYS_NFD]; int next_scratch = SYS_NFD; int rc = 0; for (int i = 0; i < SYS_NFD; i++) { int src = map[i]; scratch_fd[i] = -1; bool clobbered = src >= 0 && src < i && map[src] != src; if (!clobbered) continue; for (int j = 0; j < SYS_NFD; j++) { /* pick one no entry uses */ if (map[j] == next_scratch) { next_scratch++; j = -1; } } scratch_fd[i] = next_scratch++; rc = posix_spawn_file_actions_adddup2(fa, src, scratch_fd[i]); if (rc) return rc; } for (int i = 0; i < SYS_NFD; i++) { int src = map[i]; if (src == i) continue; if (src == FD_CLOSED) { rc = posix_spawn_file_actions_addclose(fa, i); } else if (scratch_fd[i] >= 0) { rc = posix_spawn_file_actions_adddup2(fa, scratch_fd[i], i); if (!rc) rc = posix_spawn_file_actions_addclose(fa, scratch_fd[i]); } else { rc = posix_spawn_file_actions_adddup2(fa, src, i); } if (rc) return rc; } return 0; } /** * @brief Create a process running a program. * @param rq What to run and how its descriptors, signals and process * group are to be set up. * @return The child's pid, or -1 with errno set. */ pid_t sys_spawn(const spawn_req *rq) { posix_spawn_file_actions_t fa; posix_spawnattr_t attr; bool need_fa = false; pid_t pid; int rc; for (int i = 0; i < SYS_NFD && !need_fa; i++) need_fa = rq->fdmap[i] != i; #if HAVE_SPAWN_TCSETPGRP if (rq->tty_fd >= 0) need_fa = true; #endif if (need_fa) { rc = posix_spawn_file_actions_init(&fa); if (rc) { errno = rc; return -1; } #if HAVE_SPAWN_TCSETPGRP /* * Runs in the child after it has joined its process group and * while every signal is still blocked, so the child owns the * terminal before its first instruction and cannot be stopped by * SIGTTOU for asking. */ if (rq->tty_fd >= 0) rc = posix_spawn_file_actions_addtcsetpgrp_np(&fa, rq->tty_fd); #endif if (!rc) rc = add_fd_actions(&fa, rq->fdmap); if (rc) { posix_spawn_file_actions_destroy(&fa); errno = rc; return -1; } } bool need_attr = rq->sigdfl || rq->pgroup >= 0; if (need_attr) { short flags = 0; posix_spawnattr_init(&attr); if (rq->sigdfl) { posix_spawnattr_setsigdefault(&attr, rq->sigdfl); flags |= POSIX_SPAWN_SETSIGDEF; } if (rq->pgroup >= 0) { posix_spawnattr_setpgroup(&attr, rq->pgroup); flags |= POSIX_SPAWN_SETPGROUP; } posix_spawnattr_setflags(&attr, flags); } rc = posix_spawn(&pid, rq->path, need_fa ? &fa : nullptr, need_attr ? &attr : nullptr, rq->argv, rq->envp); if (need_fa) posix_spawn_file_actions_destroy(&fa); if (need_attr) posix_spawnattr_destroy(&attr); if (rc) { errno = rc; return -1; } return pid; } /** * @brief Create a pipe with both ends close-on-exec and above descriptor 9. * * A pipe the shell holds must never be mistaken for, or collide with, a * descriptor the script names in a redirection. */ int sys_pipe(int fd[2]) { /* pipe2() is not on every POSIX platform (macOS lacks it), so the ends * are made close-on-exec here instead. */ if (pipe(fd) < 0) return -1; for (int i = 0; i < 2; i++) { if (fd[i] < SYS_NFD) { int high = fcntl(fd[i], F_DUPFD_CLOEXEC, SYS_NFD); if (high < 0) { int perr = errno; close(fd[0]); close(fd[1]); errno = perr; return -1; } close(fd[i]); fd[i] = high; } else if (fcntl(fd[i], F_SETFD, FD_CLOEXEC) < 0) { int perr = errno; close(fd[0]); close(fd[1]); errno = perr; return -1; } } return 0; } /** * @brief Duplicate a descriptor to the lowest free number >= `min`, * close-on-exec. */ int sys_dupfd(int fd, int min) { return fcntl(fd, F_DUPFD_CLOEXEC, min); } /** * @brief open() with close-on-exec. */ int sys_open(const char *path, int flags, mode_t mode) { return open(path, flags | O_CLOEXEC, mode); } /** * @brief Platform start-up. * @return Mask of descriptors 0..9 that are open (posix_spawn inherits by * default, so here the mask is never consulted). */ unsigned sys_init(void) { /* posix_spawn inherits by default, so the mask is never consulted. */ return (1u << SYS_NFD) - 1; } /* ---- file tags: there are none here ----------------------------------- */ /** * @brief Cached `_TAG_REDIR_IN`, `_OUT`, `_ERR`. See sys.h. */ tag_mode tag_redir[3]; /** * @brief Does this platform have file tags? Not this one. */ bool sys_has_tags(void) { return false; } /** * @brief No file tags here: nothing to do. */ void sys_redir_tag(int fd, tag_stream stream, tag_mode mode, bool created) { (void)fd; (void)stream; (void)mode; (void)created; } /** * @brief No file tags here: nothing to do. */ void sys_tmp_tag(int fd) { (void)fd; } /** * @brief No conversion here: nothing to do. */ void sys_input_cvt(int fd) { (void)fd; } /** * @brief Query a file tag. Unsupported here. * @return -1 with errno ENOSYS. */ int sys_tag_get(const char *path, sys_tag *tag) { (void)path; (void)tag; errno = ENOSYS; return -1; } /** * @brief Set a file tag. Unsupported here. * @return -1 with errno ENOSYS. */ int sys_tag_set(const char *path, const char *codeset, int text) { (void)path; (void)codeset; (void)text; errno = ENOSYS; return -1; } /* ---- MVS services: stand-ins ------------------------------------------ */ /** * @brief System facts. None of the z/OS ones exist here. * @return nullptr: the ZOS_* variables are not defined on this platform. */ const char *sys_info(sys_info_kind kind) { (void)kind; return nullptr; } /* * There is no catalog here. So that data set completion runs end to end * on Linux (and under the sanitizers), the file named by * `ZASH_TEST_CATALOG` stands in for one: one entry per line, * * SYS1.MACLIB a data set (type A) * SYS1.MACLIB(GETMAIN) a member of it * X SYS1 an entry of another type (here an alias) * DD:SYSIN an allocated DD name * * The stand-ins do not hand the names over directly. They build the * bytes IGGCSI00, a PDS directory and the TIOT would hold, in EBCDIC, * with small work areas that force the resume protocol and blocks * that split across directory entries, and decode them with the same * mvsfmt.c code the z/OS build uses. */ /** @brief One line of the test catalog, split up. */ typedef struct test_entry { char type; /**< CSI type letter, or 'M' member, 'D' DD name */ char name[64]; /**< data set name (for a member: its data set) */ char member[9]; } test_entry; /** * @brief Read the next entry of the test catalog. * @return false at end of file. */ static bool test_next(FILE *f, test_entry *e) { char line[128]; while (fgets(line, sizeof line, f)) { line[strcspn(line, "\n")] = '\0'; const char *p = line; e->type = 'A'; e->member[0] = '\0'; if (!strncmp(p, "DD:", 3)) { e->type = 'D'; p += 3; } else if (p[0] && p[1] == ' ') { e->type = p[0]; p += 2; } size_t len = strlen(p); if (!len || len >= sizeof e->name) continue; memcpy(e->name, p, len + 1); char *paren = strchr(e->name, '('); if (paren && e->type == 'A') { *paren = '\0'; paren[strcspn(paren + 1, ")") + 1] = '\0'; snprintf(e->member, sizeof e->member, "%.8s", paren + 1); e->type = 'M'; } return true; } return false; } /** * @brief Does a data set name match a CSI filter key? * * `%` is one character, `*` any run within a qualifier, `**` any run of * qualifiers. A trailing `.**` also matches no qualifier at all. */ static bool filter_match(const char *f, const char *s) { for (; *f; f++) { if (*f == '*') { bool deep = f[1] == '*'; const char *rest = f + (deep ? 2 : 1); for (;; s++) { if (filter_match(rest, s)) return true; if (!*s || (!deep && *s == '.')) return false; } } if (*f == '.' && f[1] == '*' && f[2] == '*' && !f[3] && !*s) return true; /* "A.**" matches "A" */ if (!*s || (*f != '%' && *f != *s) || (*f == '%' && *s == '.')) return false; s++; } return !*s; } /** @brief Store a big-endian halfword. */ static void put16(unsigned char *p, size_t v) { p[0] = (unsigned char)(v >> 8); p[1] = (unsigned char)v; } /** @brief Store a big-endian fullword. */ static void put32(unsigned char *p, size_t v) { put16(p, v >> 16); put16(p + 2, v & 0xffff); } /** @brief Store a name, blank-padded, in EBCDIC. */ static void put_name(unsigned char *p, const char *name, size_t n) { size_t len = strlen(name); if (len > n) len = n; memset(p, ' ', n); memcpy(p, name, len); // NOLINT(bugprone-not-null-terminated-result): // fixed-width MVS field mvs_to_ebcdic((char *)p, n); } /** * @brief Behave like IGGCSI00 over the test catalog. * * Fills the work area with a catalog entry and as many matching entries * as fit, each with a VOLSER field. If any are left, sets CSIRESUM to * 'Y' and CSIRESNM to the last name returned, and continues after that * name on the next call, as the real interface does. */ static int stub_iggcsi00(csi_area *a, void *ctx) { FILE *f = ctx; char filter[45]; char resume[45]; mvs_name(a->field, 44, filter); bool resuming = a->field[149] == mvs_a2e['Y']; mvs_name(a->field + 88, 44, resume); if (fseek(f, 0, SEEK_SET) != 0) return 12; /* as the CSI does for an I/O error */ size_t off = 14; unsigned char *w = a->work; uint32_t len = a->worklen; w[off] = 0; /* catalog entry: flags 0, type '0' */ w[off + 1] = mvs_a2e['0']; put_name(w + off + 2, "CATALOG.TEST.MASTER", 44); memset(w + off + 46, 0, 4); off += 50; a->field[149] = mvs_a2e[' ']; test_entry e; char last[64] = ""; while (test_next(f, &e)) { if (e.type == 'M' || e.type == 'D' || !filter_match(filter, e.name)) continue; if (resuming && strcmp(e.name, resume) <= 0) continue; if (!strcmp(e.name, last)) continue; if (off + 46 + 12 > len) { a->field[149] = mvs_a2e['Y']; put_name(a->field + 88, last, 44); break; } unsigned char *p = w + off; p[0] = 0x80; /* CSIPMENT: a primary entry */ p[1] = mvs_a2e[(unsigned char)e.type]; put_name(p + 2, e.name, 44); put16(p + 46, 12); /* CSITOTLN: 2 + 2 + 2 + 6 */ put16(p + 48, 0); put16(p + 50, 6); put_name(p + 52, "TEST01", 6); off += 58; snprintf(last, sizeof last, "%s", e.name); } put32(w + 4, 64); put32(w + 8, off); put16(w + 12, 2); return 0; } /** * @brief Open the test catalog. * @return The file, or nullptr if there is none. */ static FILE *test_catalog(void) { const char *path = getenv("ZASH_TEST_CATALOG"); return path ? fopen(path, "r") : nullptr; } /** * @brief Is there a catalog to complete data set names from? * @return true if a test catalog is named. */ bool sys_has_catalog(void) { return getenv("ZASH_TEST_CATALOG") != nullptr; } /** @brief Work area size for the stand-in: small, to force resumes. */ #define TEST_WORK 1024 /** * @brief List cataloged names that match a CSI filter key. * @return false if no catalog is available or the search failed. */ bool sys_catalog_list(const char *filter, mvs_name_fn *fn, void *arg) { FILE *f = test_catalog(); if (!f) return false; unsigned char reason[4]; unsigned char field[CSI_FIELD_LEN]; unsigned char *work = malloc(TEST_WORK); bool ok = false; if (work) { csi_area a = {reason, field, work, TEST_WORK}; ok = csi_search(filter, &a, stub_iggcsi00, f, fn, arg); free(work); } fclose(f); return ok; } /** * @brief List the members of a partitioned data set. * * Builds directory blocks the way a PDS holds them (members in * collating order, user data of varying length so that entries do not * line up with block boundaries) and decodes them block by block. * * @return false if there is no catalog or the directory was malformed. */ bool sys_pds_members(const char *dsn, mvs_name_fn *fn, void *arg) { FILE *f = test_catalog(); if (!f) return false; unsigned char blk[PDS_DIRBLK]; size_t used = 2; bool ok = true; bool end = false; test_entry e; unsigned userdata = 0; for (bool more = true; ok && !end;) { more = more && test_next(f, &e); if (more && (e.type != 'M' || strcmp(e.name, dsn))) continue; size_t len = more ? 12 + (size_t)(userdata % 32) * 2 : 8; if (used + len > PDS_DIRBLK) { /* block full: decode it */ put16(blk, used); ok = pds_parse_block(blk, fn, arg, &end); used = 2; } unsigned char *p = blk + used; if (more) { put_name(p, e.member, 8); memset(p + 8, 0, len - 8); p[11] = (unsigned char)(userdata++ % 32); } else { memset(p, 0xff, 8); } used += len; if (!more) { put16(blk, used); ok = ok && pds_parse_block(blk, fn, arg, &end); break; } } fclose(f); return ok; } /** * @brief List the DD names allocated to this address space. * * Builds TIOT entries (with a concatenation entry after each, which has * a blank name) and decodes them with tiot_parse(). */ bool sys_dd_names(mvs_name_fn *fn, void *arg) { FILE *f = test_catalog(); if (!f) return false; unsigned char tiot[4096]; size_t off = 0; test_entry e; while (test_next(f, &e) && off + 2 * 20 + 1 < sizeof tiot) { if (e.type != 'D') continue; for (int concat = 0; concat < 2; concat++) { unsigned char *p = tiot + off; memset(p, 0, 20); p[0] = 20; put_name(p + 4, concat ? "" : e.name, 8); off += 20; } } tiot[off] = 0; fclose(f); return tiot_parse(tiot, off + 1, fn, arg); } /** * @brief Dynamic allocation (BPXWDYN). Z/OS only. * @return -1: not available on this platform. */ int sys_dynalloc(const char *request, char *msg, size_t msglen) { (void)request; snprintf(msg, msglen, "dynamic allocation needs z/OS"); return -1; }