diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-28 18:58:16 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-28 18:58:16 -0600 |
| commit | d51ac5247e9b0393e9d05cd34f0e1b5e87f82c68 (patch) | |
| tree | 582a776ea6445a69aa2a9524244e567a86a60c6a | |
| parent | 5028adbb065ba243a8cff351e308bb454f159813 (diff) | |
| parent | 7ecdc5efc90cd0f983764997fb17da6928b908fa (diff) | |
| download | whoson-d51ac5247e9b0393e9d05cd34f0e1b5e87f82c68.tar.gz | |
Merge pull request #26 from skurtz97/fix/c-programming-standards
Follow C-PROGRAMMING-STANDARDS.md, and stop the EBCDIC report after make check
| -rw-r--r-- | .clang-tidy | 5 | ||||
| -rw-r--r-- | .clangd | 12 | ||||
| -rw-r--r-- | CHANGELOG.md | 19 | ||||
| -rw-r--r-- | CONTRIBUTING.md | 29 | ||||
| -rw-r--r-- | Makefile | 17 | ||||
| -rw-r--r-- | README.md | 9 | ||||
| -rw-r--r-- | buildenv | 12 | ||||
| -rw-r--r-- | patches/LICENSE | 19 | ||||
| -rw-r--r-- | whoson.c | 600 |
9 files changed, 536 insertions, 186 deletions
diff --git a/.clang-tidy b/.clang-tidy index 27098ce..8519493 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -30,6 +30,7 @@ Checks: > -readability-function-cognitive-complexity, -readability-identifier-length, -readability-magic-numbers, + -readability-implicit-bool-conversion, -readability-else-after-return, -readability-isolate-declaration, -readability-non-const-parameter, @@ -70,6 +71,10 @@ Checks: > # (`!strcmp(a, b)` is the house idiom for equality) # readability-magic-numbers, readability-identifier-length # (noise in a text parser) +# readability-implicit-bool-conversion +# (the tree tests bools directly and returns +# `flag ? 1 : 0` from main; the 0/1 conversion is the +# intent, not an accident) WarningsAsErrors: '' FormatStyle: file @@ -2,9 +2,10 @@ # compilation database, so the editor is told the same language level and # macros here. CompileFlags: - Add: [-std=c17, -D_XOPEN_SOURCE=600, -D_POSIX_C_SOURCE=200809L, - -D_ALL_SOURCE, -D_EXT, -D_OPEN_SYS, -D_OPEN_SYS_FILE_EXT, - -Wall, -Wextra, -Wshadow, -Wconversion] + Add: [-std=c23, -D_XOPEN_SOURCE=600, -D_POSIX_C_SOURCE=200809L, + -D_ALL_SOURCE, -D_EXT, -D_OPEN_SYS, -D_OPEN_SYS_FILE_EXT=1, + -Wall, -Wextra, -Wshadow, -Wconversion, -Wstrict-prototypes, + -Wmissing-prototypes] # IBM Open XL only: the editor is not that compiler. Remove: [-fzos-le-char-mode=*, -m64] @@ -32,8 +33,9 @@ Diagnostics: FastCheckFilter: Strict # Two checks .clang-tidy already switches off or allows. clangd applies # its CheckOptions unevenly between clang-tidy versions, so name them - # here too. The tree writes `if (ptr)` and spells C11 keywords such as - # _Static_assert, which are the implementation's namespace to define. + # here too. The tree writes `if (ptr)` and depends on compiler-only + # spellings such as `__attribute__`, which is the implementation's + # namespace to define. Remove: - readability-implicit-bool-conversion - bugprone-reserved-identifier diff --git a/CHANGELOG.md b/CHANGELOG.md index ef0b3df..0890415 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## Unreleased + +- The CPU column prints a compact duration (`2.34s`, `12m31s`, `1h02m`, + `3d04h`) instead of `hours:minutes:seconds`, so a long session no longer + reads `1947:50:11`. +- The ASCB, CSCB and ASSB overlays are packed C23 structs with every offset + the walk reads pinned by `static_assert`; hand-written padding arrays are + gone. +- The CSCB is validated by its eye-catcher and `CHASID`, and the ASSB by its + eye-catcher, before either supplies a userid, logon procedure or CPU time. +- The runtime's own diagnostics, and the `ps` child's storage report, are + written as text instead of EBCDIC: an untagged stdout or stderr is tagged + ISO8859-1 at startup, so `make check` no longer fills an ASCII terminal or + log with undecodable bytes. +- The source follows `C-PROGRAMMING-STANDARDS.md`: C23 (`nullptr`, + `constexpr` widths, `static_assert`), a Doxygen block on every function, + type and global, `-Wstrict-prototypes -Wmissing-prototypes`, and + `make format` / `make tidy` targets. + ## 1.1.0 Rewritten to read the system directly, and packaged as a zopen port. This is diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12b56ff..d754f73 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,12 +4,14 @@ Small tool, small rules. ## Building -whoson is a single C17 file with no external library, so it builds on z/OS +whoson is a single C23 file with no external library, so it builds on z/OS and nowhere else: ```sh make # -> ./whoson make check # under the CEE heap checker and storage report +make format # clang-format -i whoson.c +make tidy # clang-tidy, which needs the z/OS headers make install # -> ~/.local/bin/whoson ``` @@ -34,17 +36,28 @@ syntax (`?=` is out), and let `make -n` stay free of side effects. ## Style +`C-PROGRAMMING-STANDARDS.md` is the authority for language level, types, +comments and the Makefile targets; this list is only what a change here has to +remember. + - Warnings are bugs. The tree builds with `-Wall -Wextra -Wpedantic -Wshadow - -Wconversion`; a warning from any of them, or from `clang-tidy` with - `.clang-tidy`, gets fixed rather than silenced. `.clang-tidy` needs the z/OS - headers (`<sys/ps.h>`), so only a z/OS build environment can run it; the - Ubuntu CI job enforces clang-format, not clang-tidy. + -Wconversion -Wstrict-prototypes -Wmissing-prototypes`; a warning from any + of them, or from `clang-tidy` with `.clang-tidy`, gets fixed rather than + silenced. `.clang-tidy` needs the z/OS headers (`<sys/ps.h>`), so only a z/OS + build environment can run it, and IBM Open XL ships no clang-tidy: the only + one on the host is zopen's LLVM, which cannot compile z/OS `va_list` + (`__builtin_zos_va_start`). `make tidy` therefore reports those compiler + errors and nothing else; the Ubuntu CI job enforces clang-format. +- C23: `nullptr` rather than `NULL`, `static_assert`, and `constexpr` for the + buffer and column widths. Compiler-only attributes go through a macro + (`PRINTFLIKE`). - Types are `typedef struct name { ... } name;`, and no variable, function or field reuses a type name. -- `clang-format -i whoson.c` before committing; `.clang-format` is the - authority, and CI checks the result against clang-format 23.1.5. +- `make format` before committing; `.clang-format` is the authority, and CI + checks the result against clang-format 23.1.5. - Comments say why, not what, and the file header says what the control-block - walk and the process table give and what they do not. + walk and the process table give and what they do not. Functions, types and + globals carry a Doxygen `@brief`; struct members carry `/**< */`. ## Changes @@ -38,13 +38,14 @@ VERSION = 1.1.0 CCDIR = /usr/lpp/IBM/cnw/v2r2/openxl/bin CC = $(CCDIR)/ibm-clang CPPFLAGS = -D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200809L -D_ALL_SOURCE \ - -D_EXT -D_OPEN_SYS -D_OPEN_SYS_FILE_EXT \ + -D_EXT -D_OPEN_SYS -D_OPEN_SYS_FILE_EXT=1 \ -DWHOSON_VERSION=\"$(VERSION)\" -CFLAGS = -std=c17 -O3 -m64 -mzos-target=zosv2r5 -fzos-le-char-mode=ascii \ - -Wall -Wextra -Wpedantic -Wshadow -Wconversion +CFLAGS = -std=c23 -O3 -m64 -mzos-target=zosv2r5 -fzos-le-char-mode=ascii \ + -Wall -Wextra -Wpedantic -Wshadow -Wconversion \ + -Wstrict-prototypes -Wmissing-prototypes CEEOPTS = HEAPCHK(ON,1,32),RPTSTG(ON),FILETAG(AUTOCVT,AUTOTAG),POSIX(ON) -.PHONY: all install check list clean +.PHONY: all install check list format tidy clean all: whoson @@ -66,6 +67,14 @@ install: whoson cp whoson $(BINDIR)/whoson chmod 755 $(BINDIR)/whoson +# The two gates that run off-platform, named as the standards document asks. +# tidy needs the z/OS headers, so it only runs on z/OS. +format: + clang-format -i whoson.c + +tidy: + clang-tidy whoson.c -- $(CPPFLAGS) -std=c23 + check: whoson _CEE_RUNOPTS="$(CEEOPTS)" ./whoson @@ -10,9 +10,9 @@ with the address space, the job name, the logon procedure and its CPU time. ```text $ whoson USER TYPE ASID JOBNAME LOGONPROC PID CPU -CBT002 TSO/E 0046 CBT002 CBT002 - 0:12:31 -SKURTZ z/OSMF 003D SKURTZ IZUFPROC - 0:03:41 -SKURTZ SSH 004C SKURTZ - 33555303 0:00:02 +CBT002 TSO/E 0046 CBT002 CBT002 - 12m31s +SKURTZ z/OSMF 003D SKURTZ IZUFPROC - 3m41s +SKURTZ SSH 004C SKURTZ - 33555303 2.00s ``` Three types of session are listed, and nothing else: @@ -47,7 +47,8 @@ CSCB key (`CHKEY`), the userid for a TSO/E session, and the POSIX effective uid for an SSH session. `ASID` is the address space id, `PID` the POSIX process id where one exists (`-` for a session that has none), and `CPU` is TCB time (`ASCBEJST`) plus SRB time (`ASCBSRBT`) plus additional preemptable -SRB time (`ASSBASST`) as `hours:minutes:seconds`. All three are TOD-clock +SRB time (`ASSBASST`) as a compact duration (`2.34s`, `12m31s`, `1h02m`, +`3d04h`). All three are TOD-clock accumulators, so the low 12 bits are the fraction, not 1024-microsecond units. @@ -3,14 +3,22 @@ # The stable source is the release tarball, so the port builds exactly what # the GitHub release ships. Bump WHOSON_VERSION together with Makefile's # VERSION and the release tag; the CI job checks the first two agree. -# `zopen build -b DEV` uses the git tree instead. - +# `zopen build --build DEV` uses the git tree instead. +# +# The bump workflow reads this line and opens a pull request when a new +# release tag appears. It watches the git tags; ZOPEN_STABLE_URL stays the +# release tarball so a build ships exactly the released archive. +# bump: whoson-version /WHOSON_VERSION="(.*)"/ https://github.com/skurtz97/whoson.git|semver:* WHOSON_VERSION="1.1.0" export ZOPEN_PROJECT_NAME="whoson" export ZOPEN_NAME="whoson" export ZOPEN_BUILD_LINE="STABLE" export ZOPEN_CATEGORIES="utilities monitoring" +# whoson is a single executable linked against libc; it needs no zopen +# package at run time (ZOPEN_DONT_ADD_ZOSLIB_DEP below says the same for +# zoslib). +export ZOPEN_RUNTIME_DEPS="" export ZOPEN_STABLE_URL="https://github.com/skurtz97/whoson/releases/download/v${WHOSON_VERSION}/whoson-${WHOSON_VERSION}.tar.gz" export ZOPEN_STABLE_DEPS="make" export ZOPEN_DEV_URL="https://github.com/skurtz97/whoson.git" diff --git a/patches/LICENSE b/patches/LICENSE new file mode 100644 index 0000000..bbaf078 --- /dev/null +++ b/patches/LICENSE @@ -0,0 +1,19 @@ +MIT License + +Copyright (c) 2026 Sean Kurtz + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + @@ -1,13 +1,14 @@ -/* +/** + * @file whoson.c + * @brief Who is logged on to this z/OS system, and how: TSO/E, z/OSMF, SSH. + * * SPDX-License-Identifier: MIT OR Apache-2.0 OR BSD-2-Clause * SPDX-FileCopyrightText: 2026 Sean Kurtz * - * whoson - who is logged on to this z/OS system, and how (TSO/E, z/OSMF, SSH). - * - * Sessions come from the address space control blocks, not from a subsystem - * or a console command: CVT (PSA+X'10') -> ASVT -> every allocated ASCB. That - * walk reads only common storage, which is mapped into every address space, - * so it needs no APF authorization, no supervisor state and no key zero. + * @details Sessions come from the address space control blocks, not from a + * subsystem or a console command: CVT (PSA+X'10') -> ASVT -> every allocated + * ASCB. That walk reads only common storage, which is mapped into every address + * space, so it needs no APF authorization, no supervisor state and no key zero. * ASCBJBNI holds the job name; the logon procedure comes from the session's * CSCB (CHCLS), not from ASCBJBNS, which only names how the address space was * started. A non-zero ASCBTSB, or a CSCB track id of X'01', marks TSO/E. @@ -59,110 +60,170 @@ #include <sys/wait.h> #include <unistd.h> -#define MSG_LEN 512 -#define NAME_LEN 16 -#define JOB_LEN 9 -#define ASID_LEN 8 -#define PID_LEN 12 -#define CPU_LEN 16 -#define PATH_LEN 64 -#define OUT_LEN 8192 -#define CMD_BUF 2048 -#define TTY_BUF 2048 +/* Attributes without C23 spelling wrap here, so call sites stay readable. */ +#ifdef __clang__ +/** @brief printf-format checking for a wrapper that forwards a va_list. */ +#define PRINTFLIKE(fmt_index, va_index) \ + __attribute__((format(printf, fmt_index, va_index))) +#else +#define PRINTFLIKE(fmt_index, va_index) +#endif + +/* Buffer and column widths. */ +static constexpr size_t msg_len = + 512; /**< one formatted message or table line */ +static constexpr size_t name_len = 16; /**< a userid from CHKEY or getpwuid */ +static constexpr size_t job_len = 9; /**< an 8-byte job name, plus the nul */ +static constexpr size_t asid_len = 8; /**< "%04X" of an ASID, plus the nul */ +static constexpr size_t pid_len = + 12; /**< a 32-bit pid in decimal, plus the nul */ +static constexpr size_t cpu_len = 16; /**< a formatted CPU duration */ +static constexpr size_t path_len = 64; /**< basename of a process path */ +static constexpr size_t out_len = 8192; /**< the whole table, then one write */ +static constexpr size_t cmd_buf = 2048; /**< W_PSPROC command buffer */ +static constexpr size_t tty_buf = 2048; /**< W_PSPROC controlling-TTY buffer */ #ifdef PS_PATHBLEN -#define PS_PATH_BUF PS_PATHBLEN +/** @brief W_PSPROC path buffer: the header's own limit when it has one. */ +static constexpr size_t ps_path_buf = PS_PATHBLEN; #else -#define PS_PATH_BUF 1027 +/** @brief W_PSPROC path buffer, for headers that do not name a limit. */ +static constexpr size_t ps_path_buf = 1027; #endif /* CVTASVT. The ASVT's own head, then ASVTENTY, the array of ASCB addresses; * a set high bit marks an ASID that is free or non-reusable. */ +/** @brief CVT field holding the ASVT address (CVTASVT). */ #define CVT_ASVT_OFF 0x22Cu +/** @brief ASVT field: the eye-catcher "ASVT". */ #define ASVT_ACRONYM_OFF 0x200u +/** @brief ASVT field: highest ASID in use (ASVTMXU). */ #define ASVT_MAXU_OFF 0x204u +/** @brief ASVT field: first entry of ASVTENTY, four bytes each. */ #define ASVT_ENTY_OFF 0x210u -#define ASVT_ACRONYM 0xC1E2E5E3u /* "ASVT" in EBCDIC */ -#define ASCB_ACRONYM 0xC1E2C3C2u /* "ASCB" in EBCDIC */ -/* Field offsets are checked against these overlays (static_assert below). +/* An eye-catcher is a four-byte word that spells its block name in EBCDIC, + * and these blocks are filled in while the system runs in EBCDIC, even when + * whoson is built in ASCII mode. The value therefore cannot be a character + * literal: 'ASCB' would be the ASCII bytes B0 09 34 7E. */ +/** @brief "ASVT" as it appears in the ASVT. */ +#define ASVT_ACRONYM 0xC1E2E5E3u +/** @brief "ASCB" as it appears in the ASCB. */ +#define ASCB_ACRONYM 0xC1E2C3C2u +/** @brief "CSCB" as it appears in the CSCB. */ +#define CSCB_ACRONYM 0xC3E2C3C2u +/** @brief "ASSB" as it appears in the ASSB. */ +#define ASSB_ACRONYM 0xC1E2E2C2u + +/** @brief CSCB CHTRKID value that marks a TSO/E session. */ +enum { CSCB_TRKID_TSO = 0x01 }; + +/* Packed so the compiler adds no padding of its own: every offset is the sum + * of the field widths, and the static asserts pin the fields the walk reads. * The overlays describe layout only; every read goes through the accessors, * so the compiler never assumes the block is stable. */ -typedef struct ascb { - uint32_t ascbascb; - unsigned char pad0[0x24 - 0x04]; - uint16_t ascbasid; - unsigned char pad1[0x38 - 0x26]; - uint32_t ascbcscb; - uint32_t ascbtsb; - uint64_t ascbejst; - unsigned char pad2[0xAC - 0x48]; - uint32_t ascbjbni; - uint32_t ascbjbns; - unsigned char pad3[0xC8 - 0xB4]; - uint64_t ascbsrbt; - unsigned char pad4[0x150 - 0xD0]; - uint32_t ascbassb; +/** + * @brief Address space control block, as far as the walk needs it (ASCB). + */ +typedef struct __attribute__((packed)) ascb { + uint32_t ascbascb; /**< X'00' eye-catcher */ + unsigned char ascbresv0[0x24 - 0x04]; /**< X'04' unused here */ + uint16_t ascbasid; /**< X'24' address space id */ + unsigned char ascbresv1[0x38 - 0x26]; /**< X'26' unused here */ + uint32_t ascbcscb; /**< X'38' CSCB address */ + uint32_t ascbtsb; /**< X'3C' TSB address, zero if none */ + uint64_t ascbejst; /**< X'40' TCB CPU in TOD units */ + unsigned char ascbresv2[0xAC - 0x48]; /**< X'48' unused here */ + uint32_t ascbjbni; /**< X'AC' job name, for a batch job */ + uint32_t ascbjbns; /**< X'B0' procedure name, or job */ + unsigned char ascbresv3[0xC8 - 0xB4]; /**< X'B4' unused here */ + uint64_t ascbsrbt; /**< X'C8' SRB CPU in TOD units */ + unsigned char ascbresv4[0x150 - 0xD0]; /**< X'D0' unused here */ + uint32_t ascbassb; /**< X'150' ASSB address */ } ascb; -typedef struct cscb { - unsigned char pad0[0x08]; - char chkey[8]; - char chcls[8]; - unsigned char pad1[0x1C - 0x18]; - unsigned char chtrkid; +/** @brief Command scheduling control block (CSCB), the session's identity. */ +typedef struct __attribute__((packed)) cscb { + uint32_t chptr; /**< X'00' chain pointer */ + unsigned char chvcd; /**< X'04' VCD */ + unsigned char chsze; /**< X'05' block size */ + unsigned char chresv0[0x08 - 0x06]; /**< X'06' unused here */ + char chkey[8]; /**< X'08' userid */ + char chcls[8]; /**< X'10' logon procedure name */ + uint32_t chunit; /**< X'18' unit */ + unsigned char chtrkid; /**< X'1C' X'01' is a TSO/E session */ + unsigned char chresv1; /**< X'1D' unused here */ + uint16_t chasid; /**< X'1E' address space id */ + unsigned char chresv2[0xD8 - 0x20]; /**< X'20' unused here */ + char chcscbid[4]; /**< X'D8' eye-catcher */ } cscb; -typedef struct assb { - unsigned char pad[0x160]; - uint64_t assbasst; +/** @brief Address space secondary block: preemptible SRB time (ASSB). */ +typedef struct __attribute__((packed)) assb { + char assbassb[4]; /**< X'000' eye-catcher */ + unsigned char assbresv[0x160 - 0x04]; /**< X'004' unused here */ + uint64_t assbasst; /**< X'160' SRB CPU in TOD units */ } assb; -_Static_assert(offsetof(ascb, ascbasid) == 0x24, "ASCBASID"); -_Static_assert(offsetof(ascb, ascbcscb) == 0x38, "ASCBCSCB"); -_Static_assert(offsetof(ascb, ascbtsb) == 0x3C, "ASCBTSB"); -_Static_assert(offsetof(ascb, ascbejst) == 0x40, "ASCBEJST"); -_Static_assert(offsetof(ascb, ascbjbni) == 0xAC, "ASCBJBNI"); -_Static_assert(offsetof(ascb, ascbjbns) == 0xB0, "ASCBJBNS"); -_Static_assert(offsetof(ascb, ascbsrbt) == 0xC8, "ASCBSRBT"); -_Static_assert(offsetof(ascb, ascbassb) == 0x150, "ASCBASSB"); -_Static_assert(offsetof(cscb, chkey) == 0x08, "CHKEY"); -_Static_assert(offsetof(cscb, chcls) == 0x10, "CHCLS"); -_Static_assert(offsetof(cscb, chtrkid) == 0x1C, "CHTRKID"); -_Static_assert(offsetof(assb, assbasst) == 0x160, "ASSBASST"); +static_assert(alignof(ascb) == 1); +static_assert(alignof(cscb) == 1); +static_assert(alignof(assb) == 1); +static_assert(sizeof(ascb) == 0x154); +static_assert(sizeof(cscb) == 0xDC); +static_assert(sizeof(assb) == 0x168); +static_assert(offsetof(ascb, ascbasid) == 0x24, "ASCBASID"); +static_assert(offsetof(ascb, ascbcscb) == 0x38, "ASCBCSCB"); +static_assert(offsetof(ascb, ascbtsb) == 0x3C, "ASCBTSB"); +static_assert(offsetof(ascb, ascbejst) == 0x40, "ASCBEJST"); +static_assert(offsetof(ascb, ascbjbni) == 0xAC, "ASCBJBNI"); +static_assert(offsetof(ascb, ascbjbns) == 0xB0, "ASCBJBNS"); +static_assert(offsetof(ascb, ascbsrbt) == 0xC8, "ASCBSRBT"); +static_assert(offsetof(ascb, ascbassb) == 0x150, "ASCBASSB"); +static_assert(offsetof(cscb, chkey) == 0x08, "CHKEY"); +static_assert(offsetof(cscb, chcls) == 0x10, "CHCLS"); +static_assert(offsetof(cscb, chtrkid) == 0x1C, "CHTRKID"); +static_assert(offsetof(cscb, chasid) == 0x1E, "CHASID"); +static_assert(offsetof(cscb, chcscbid) == 0xD8, "CHCSCBID"); +static_assert(offsetof(assb, assbasst) == 0x160, "ASSBASST"); -/* One address space, as read from its ASCB, indexed by ASID - 1. */ +/** @brief What the ASCB walk keeps per address space, indexed by ASID - 1. */ typedef struct space { - bool tso; - uint64_t us; /* microseconds of CPU */ - char job[JOB_LEN]; - char user[NAME_LEN]; - char logon[JOB_LEN]; + bool tso; /**< the session is TSO/E */ + uint64_t us; /**< microseconds of CPU */ + char job[job_len]; /**< job name, or the procedure name */ + char user[name_len]; /**< CHKEY userid, else the job name */ + char logon[job_len]; /**< CHCLS procedure, else empty */ } space; -/* One output row. TSO rows are built from a space; SSH rows from a process. */ +/** @brief One line of the table, before it is sorted and formatted: a TSO/E + * row comes from a space, an SSH row from a process. */ typedef struct row { - unsigned asid; - uint64_t us; - pid_t pid; - const char *type; - char job[JOB_LEN]; - char logon[JOB_LEN]; - char user[NAME_LEN]; + unsigned asid; /**< ASID, or 0 when no address space is known */ + uint64_t us; /**< microseconds of CPU */ + pid_t pid; /**< POSIX pid, or 0 for a TSO/E session */ + const char *type; /**< "TSO/E", "z/OSMF" or "SSH" */ + char job[job_len]; /**< job name, or "-" */ + char logon[job_len]; /**< logon procedure, or "-" */ + char user[name_len]; /**< userid */ } row; +/** @brief One process from the table, reduced to what the SSH rule needs. */ typedef struct proc { - pid_t pid; - pid_t ppid; - uid_t euid; - char name[PATH_LEN]; + pid_t pid; /**< process id */ + pid_t ppid; /**< parent process id */ + uid_t euid; /**< effective uid, the userid for SSH */ + char name[path_len]; /**< basename of the executable */ } proc; +/** @brief One pid-to-ASID pair, as printed by ps -o pid,xasid. */ typedef struct pid_asid { - pid_t pid; - unsigned asid; + pid_t pid; /**< process id */ + unsigned asid; /**< address space id from the xasid column */ } pid_asid; +/** @brief The --help text, kept as a plain array: Open XL 2.2 generates + * bad code for a string-literal `constexpr` (negative character + * representation). */ static const char usage_text[] = "usage: whoson [--help | --version]\n" "\n" @@ -179,18 +240,27 @@ static const char usage_text[] = "(default: IZUFPROC).\n"; /* Set by the Makefile from its VERSION, so the binary and the tag agree. */ +/** @brief Version string, or "unknown" when the Makefile did not set one. */ #ifndef WHOSON_VERSION #define WHOSON_VERSION "unknown" #endif -/* A control-block read that faults is caught here and turned into a skipped - * row. */ +/** @brief Where a faulting control-block read resumes: set by scan_one() and + * read_asvt(), and only valid while a guarded read is in progress. */ static sigjmp_buf fault_env; +/** @brief Non-zero while a guarded read is in progress. */ static volatile sig_atomic_t fault_armed; -/* Only fcntl(), which is safe in a signal handler. */ +/** @brief Put back the descriptor's conversion setting, from a signal handler. + */ static void restore_cvt(void); +static void vmessage(bool usage, const char *fmt, va_list ap) PRINTFLIKE(2, 0); +static void error_msg(const char *fmt, ...) PRINTFLIKE(1, 2); +static void usage_error(const char *fmt, ...) PRINTFLIKE(1, 2); + +/** @brief Turn a faulting read of an address space that went away into a + * skipped row; otherwise restore the conversion setting and die. */ static void on_fault(int sig) { if (fault_armed) siglongjmp(fault_env, 1); @@ -198,18 +268,21 @@ static void on_fault(int sig) { _exit(128 + sig); } +/** @brief Catch SIGSEGV and SIGBUS: a read of an ended address space must + * skip one row, not abend the program. */ static void guard(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = on_fault; sigemptyset(&sa.sa_mask); - sigaction(SIGSEGV, &sa, NULL); + sigaction(SIGSEGV, &sa, nullptr); #ifdef SIGBUS - sigaction(SIGBUS, &sa, NULL); + sigaction(SIGBUS, &sa, nullptr); #endif } +/** @brief Put the default fault handling back once the walk is over. */ static void unguard(void) { signal(SIGSEGV, SIG_DFL); #ifdef SIGBUS @@ -217,25 +290,39 @@ static void unguard(void) { #endif } +/* The accessors below read a live control block. volatile is load-bearing: + * the compiler may not fold two reads of a block the system is changing, and + * it may not assume the value it read once still holds. The pointer cast is + * the MVS control-block interface: the address came out of another block. */ +/** @brief Read one byte of common storage at addr. */ static uint8_t read_u8(uint32_t addr) { return *(const volatile uint8_t *)(uintptr_t)addr; } +/** @brief Read a big-endian 16-bit field of common storage at addr. */ static uint16_t read_u16(uint32_t addr) { return *(const volatile uint16_t *)(uintptr_t)addr; } +/** @brief Read a big-endian 32-bit field of common storage at addr. */ static uint32_t read_u32(uint32_t addr) { return *(const volatile uint32_t *)(uintptr_t)addr; } +/** @brief Read a big-endian 64-bit field of common storage at addr. */ static uint64_t read_u64(uint32_t addr) { return *(const volatile uint64_t *)(uintptr_t)addr; } -/* Set by a failed write, so main can exit nonzero on truncated output. */ +/** @brief Set by a failed write, so main can exit nonzero on truncated + * output. */ static bool output_failed; +/** @brief Write the whole buffer, retrying short writes and EINTR. + * @param fd descriptor + * @param buf bytes to write + * @param len byte count + * @return 0 on success, -1 with output_failed set on failure. */ static int write_all(int fd, const char *buf, size_t len) { while (len > 0) { ssize_t n = write(fd, buf, len); @@ -252,8 +339,12 @@ static int write_all(int fd, const char *buf, size_t len) { return 0; } -/* Tag fd with ccsid as text. zopen's setccsid(): an untagged file created by - * the shell becomes ISO8859-1 rather than an anonymous EBCDIC file. */ +/** + * @brief Tag fd as text in ccsid; zopen's setccsid(), through __fchattr(). + * @param fd descriptor to tag + * @param ccsid CCSID to record, 819 for ASCII + * @return 0 on success, -1 with errno set + */ static int tag_fd(int fd, unsigned ccsid) { attrib_t a; @@ -264,6 +355,13 @@ static int tag_fd(int fd, unsigned ccsid) { return __fchattr(fd, &a, sizeof(a)); } +/** @brief Set the descriptor's character conversion (F_CONTROL_CVT). + * @param fd descriptor + * @param cmd SETCVTON, SETCVTOFF or QUERYCVT + * @param pccsid source CCSID of a write + * @param fccsid destination CCSID of a write + * @return what fcntl() returns + */ static int set_cvt(int fd, int cmd, int pccsid, int fccsid) { struct f_cnvrt c; @@ -273,17 +371,25 @@ static int set_cvt(int fd, int cmd, int pccsid, int fccsid) { return fcntl(fd, F_CONTROL_CVT, &c); } -/* The conversion setting belongs to the open file description, which the - * calling shell keeps after whoson exits. Save it and put it back, or the - * shell's own output would inherit ours. */ +/** @brief A descriptor's starting conversion setting, kept for restore_cvt(). + */ typedef struct cvt_saved { - int fd; - struct f_cnvrt v; + int fd; /**< descriptor */ + struct f_cnvrt v; /**< the setting to put back */ } cvt_saved; +/** @brief Conversion settings saved before whoson changed them. */ static cvt_saved saved_cvt[2]; +/** @brief How many entries of saved_cvt are in use (stdout and stderr). */ static size_t nsaved; +/** + * @brief Put back every saved conversion setting. + * + * The setting belongs to the open file description, which the calling shell + * keeps after whoson exits, so leaving ours behind would change the shell's + * own output. Only fcntl(), which is async-signal-safe, is used here. + */ static void restore_cvt(void) { size_t i; @@ -291,6 +397,7 @@ static void restore_cvt(void) { (void)fcntl(saved_cvt[i].fd, F_CONTROL_CVT, &saved_cvt[i].v); } +/** @brief Save fd's conversion setting for restore_cvt(). */ static void save_cvt(int fd) { struct f_cnvrt q; @@ -305,16 +412,25 @@ static void save_cvt(int fd) { nsaved++; } +/** @brief Whether a stat structure says the file is EBCDIC text. */ static bool ebcdic_tag(const struct stat *st) { return st->st_tag.ft_txtflag && (st->st_tag.ft_ccsid == 37 || st->st_tag.ft_ccsid == 1047); } -/* Write buf in the character set fd expects. Files are the ASCII half of the - * zopen rule; terminals, pipes and EBCDIC-tagged files are IBM-1047. Only a - * file's tag is changed (an untagged file becomes ISO8859-1); a pipe or pty - * keeps its tag and just gets the conversion, so the runtime's own output to - * the same descriptor is not relabelled. */ +/** + * @brief Write buf in the character set fd expects. + * + * Files are the ASCII half of the zopen rule; terminals, pipes and + * EBCDIC-tagged files are IBM-1047. Only a file's tag is changed (an untagged + * file becomes ISO8859-1); a pipe or pty keeps its tag and just gets the + * conversion, so the runtime's own output to the same descriptor is not + * relabelled. + * @param fd descriptor + * @param buf ASCII bytes; converted in place when the destination wants + * EBCDIC + * @param len byte count + */ static void emit(int fd, char *buf, size_t len) { struct stat st; bool ascii = false; @@ -349,8 +465,9 @@ static void emit(int fd, char *buf, size_t len) { write_all(fd, buf, len); } +/** @brief emit() a nul-terminated string, copied into a bounded buffer. */ static void emit_str(int fd, const char *text) { - char buf[MSG_LEN]; + char buf[msg_len]; size_t len = strlen(text); if (len >= sizeof(buf)) @@ -359,8 +476,10 @@ static void emit_str(int fd, const char *text) { emit(fd, buf, len); } +/** @brief Format into a bounded buffer and emit() it, with the usage text + * when the message is a usage error. */ static void vmessage(bool usage, const char *fmt, va_list ap) { - char text[MSG_LEN]; + char text[msg_len]; vsnprintf(text, sizeof(text), fmt, ap); emit_str(STDERR_FILENO, text); @@ -370,6 +489,7 @@ static void vmessage(bool usage, const char *fmt, va_list ap) { } } +/** @brief Report an error on stderr, in the destination's character set. */ static void error_msg(const char *fmt, ...) { va_list ap; @@ -378,6 +498,7 @@ static void error_msg(const char *fmt, ...) { va_end(ap); } +/** @brief Report a usage error on stderr, followed by the usage text. */ static void usage_error(const char *fmt, ...) { va_list ap; @@ -386,8 +507,16 @@ static void usage_error(const char *fmt, ...) { va_end(ap); } -/* Copy the 8-byte EBCDIC name a control block points at. These pointers - * address common storage, so no cross-memory services are needed. */ +/** + * @brief Copy the 8-byte EBCDIC name a control block points at, as ASCII. + * + * These pointers address common storage, so no cross-memory services are + * needed, and the name is decoded with __e2a_l() because the block holds + * EBCDIC even in an ASCII build. + * @param ptr address of the name in common storage, 0 for none + * @param dst output buffer, always nul-terminated + * @param dstlen size of dst + */ static void read_name(uint32_t ptr, char *dst, size_t dstlen) { unsigned char raw[8]; size_t i; @@ -411,7 +540,18 @@ static void read_name(uint32_t ptr, char *dst, size_t dstlen) { dst[n] = '\0'; } -/* Read one ASCB. Returns 0 and fills *out on success; -1 skips it. */ +/** + * @brief Read one ASCB into *out, with its CSCB and ASSB. + * + * Every read is guarded: the address space can end between the ASVT read and + * the ASCB read, and the block can be reused while it is being read, so the + * ASVT entry is re-checked at the end. + * @param idx index into ASVTENTY, so the ASID must be idx + 1 + * @param entry the raw ASVT entry, high bit included + * @param entries address of ASVTENTY + * @param out receives the address space on success + * @return 0 on success, -1 when the address space is gone or unreadable + */ static int scan_one(unsigned idx, uint32_t entry, uint32_t entries, space *out) { space tmp = {0}; @@ -420,8 +560,8 @@ static int scan_one(unsigned idx, uint32_t entry, uint32_t entries, uint32_t cscb_addr; uint64_t tod; bool tso; - char key[NAME_LEN] = {0}; - char cls[JOB_LEN] = {0}; + char key[name_len] = {0}; + char cls[job_len] = {0}; fault_armed = 1; if (sigsetjmp(fault_env, 1) != 0) { @@ -441,15 +581,22 @@ static int scan_one(unsigned idx, uint32_t entry, uint32_t entries, uint32_t assb_addr = read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbassb)); - if (assb_addr != 0) + if (assb_addr != 0 && read_u32(assb_addr) == ASSB_ACRONYM) tod += read_u64(assb_addr + (uint32_t)offsetof(assb, assbasst)); } - if (cscb_addr != 0) { + /* A CSCB that has already been released can still be reachable through a + * stale ASCB pointer; its eye-catcher and CHASID say whether the block + * still belongs to this address space. */ + if (cscb_addr != 0 && + read_u32(cscb_addr + (uint32_t)offsetof(cscb, chcscbid)) == + CSCB_ACRONYM && + read_u16(cscb_addr + (uint32_t)offsetof(cscb, chasid)) == asid) { read_name(cscb_addr + (uint32_t)offsetof(cscb, chkey), key, sizeof(key)); read_name(cscb_addr + (uint32_t)offsetof(cscb, chcls), cls, sizeof(cls)); - if (read_u8(cscb_addr + (uint32_t)offsetof(cscb, chtrkid)) == 0x01) + if (read_u8(cscb_addr + (uint32_t)offsetof(cscb, chtrkid)) == + CSCB_TRKID_TSO) tso = true; } read_name(read_u32(ascb_addr + (uint32_t)offsetof(ascb, ascbjbni)), tmp.job, @@ -480,6 +627,12 @@ fail: return -1; } +/** + * @brief Find the ASVT through the CVT and validate it. + * @param maxu receives ASVTMXU, the highest ASID in use + * @param entries receives the address of ASVTENTY + * @return 0 on success, -1 when the PSA, CVT or ASVT cannot be used + */ static int read_asvt(unsigned *maxu, uint32_t *entries) { uint32_t cvt; uint32_t asvt; @@ -508,6 +661,13 @@ fail: return -1; } +/** + * @brief Walk ASVTENTY and fill one space per live address space. + * @param entries address of ASVTENTY + * @param maxu number of entries to examine + * @param snap output array, indexed by ASID - 1 + * @param found receives the number of address spaces that were read + */ static void ascb_scan(uint32_t entries, unsigned maxu, space *snap, unsigned *found) { unsigned i; @@ -523,16 +683,42 @@ static void ascb_scan(uint32_t entries, unsigned maxu, space *snap, } } +/** @brief Tag an untagged pipe or file ISO8859-1 before anything writes. + * + * The runtime prints its own diagnostics -- and the ps child prints its + * storage report -- as EBCDIC text, which reaches an ASCII terminal or log + * as a wall of undecodable bytes unless the descriptor says it is text. + * A terminal carries its own tag and is left alone. + * @param fd descriptor to tag when it has no text tag yet + */ +static void tag_untagged(int fd) { + struct stat st; + + if (fstat(fd, &st) != 0 || S_ISCHR(st.st_mode)) + return; + if (st.st_tag.ft_txtflag && st.st_tag.ft_ccsid != 0) + return; + (void)tag_fd(fd, 819); +} + +/** @brief Start ps, which supplies the ASID the process table lacks. */ static FILE *ps_open(void) { + /* NOLINTNEXTLINE(cert-env33-c): ps is the only source of pid-to-ASID. */ return popen("/bin/ps -A -o pid,xasid", "r"); } +/** @brief Read a whole descriptor into a growing buffer. + * @param fd descriptor + * @param out receives the malloc'd, nul-terminated buffer + * @param outlen receives the byte count + * @return 0 on success, -1 on error or out of memory + */ static int read_all(int fd, char **out, size_t *outlen) { size_t cap = 16384; size_t len = 0; char *buf = malloc(cap + 1); - if (buf == NULL) + if (buf == nullptr) return -1; for (;;) { ssize_t n; @@ -546,7 +732,7 @@ static int read_all(int fd, char **out, size_t *outlen) { return -1; } grown = realloc(buf, cap * 2 + 1); - if (grown == NULL) { + if (grown == nullptr) { free(buf); return -1; } @@ -570,9 +756,13 @@ static int read_all(int fd, char **out, size_t *outlen) { return 0; } -/* ps on a pipe is ASCII when the pipe is tagged ASCII and EBCDIC when it is - * not; the content decides, not the environment. A line ends at LF, NL or - * the EBCDIC 0x25/0x15 code points. */ +/** + * @brief Convert a buffer of untagged ps output to ASCII, in place. + * + * ps writes ASCII when its pipe is tagged ASCII and EBCDIC when it is not; + * the content decides, not the environment. A line ends at LF, NL or the + * EBCDIC 0x25/0x15 code points, which __e2a_l() turns into '\n'. + */ static void text_to_ascii(char *buf, size_t len) { size_t i; @@ -584,9 +774,11 @@ static void text_to_ascii(char *buf, size_t len) { } } -/* Tell read() what the pipe carries, using its tag: 1 = valid ASCII, 2 = - * the runtime was told to convert (read returns ASCII), 0 = untagged, so the - * bytes must be sniffed after the read. */ +/** + * @brief Tell read() what the pipe carries, using its tag. + * @return 1 = valid ASCII, 2 = the runtime converts (read returns ASCII), + * 0 = untagged, so the bytes must be sniffed after the read + */ static int read_setup(int fd) { struct stat st; @@ -605,13 +797,14 @@ static int read_setup(int fd) { return 0; } +/** @brief Append one pid-to-ASID pair, growing the map when it is full. */ static int add_pid_asid(pid_asid **map, size_t *n, size_t *cap, pid_t pid, unsigned asid) { if (*n == *cap) { size_t ncap = *cap ? *cap * 2 : 64; pid_asid *grown = realloc(*map, ncap * sizeof(**map)); - if (grown == NULL) + if (grown == nullptr) return -1; *map = grown; *cap = ncap; @@ -622,19 +815,29 @@ static int add_pid_asid(pid_asid **map, size_t *n, size_t *cap, pid_t pid, return 0; } -/* ps prints one header line ("PID ASID" on current releases); anything else - * that does not parse is an error, not a line to drop. */ +/** + * @brief Whether a ps line is the header rather than a process. + * + * ps prints one header line ("PID ASID" on current releases); anything else + * that does not parse is an error, not a line to drop. + */ static bool is_header(const char *s) { while (isspace((unsigned char)*s)) s++; return strncmp(s, "PID", 3) == 0 && (s[3] == '\0' || isspace((unsigned char)s[3])) && - strstr(s, "ASID") != NULL; + strstr(s, "ASID") != nullptr; } +/** + * @brief Read /bin/ps -A -o pid,xasid into a sorted pid-to-ASID map. + * @param map receives the malloc'd array + * @param count receives the number of pairs + * @return 0 on success, -1 when ps cannot run or its output does not parse + */ static int ps_scan(pid_asid **map, size_t *count) { FILE *fp; - char *buf = NULL; + char *buf = nullptr; size_t len = 0; size_t n = 0; size_t cap = 0; @@ -643,10 +846,10 @@ static int ps_scan(pid_asid **map, size_t *count) { int status; int mode; - *map = NULL; + *map = nullptr; *count = 0; fp = ps_open(); - if (fp == NULL) { + if (fp == nullptr) { error_msg("whoson: cannot run /bin/ps: %s\n", strerror(errno)); return -1; } @@ -685,7 +888,7 @@ static int ps_scan(pid_asid **map, size_t *count) { } else if (!is_header(&buf[start])) { error_msg("whoson: cannot parse ps line: %s\n", &buf[start]); free(*map); - *map = NULL; + *map = nullptr; free(buf); return -1; } @@ -696,13 +899,14 @@ static int ps_scan(pid_asid **map, size_t *count) { if (n == 0) { error_msg("whoson: ps returned no processes\n"); free(*map); - *map = NULL; + *map = nullptr; return -1; } *count = n; return 0; } +/** @brief qsort() order for pid_asid: by pid, then ASID. */ static int cmp_pid_asid(const void *a, const void *b) { const pid_asid *x = a; const pid_asid *y = b; @@ -712,6 +916,7 @@ static int cmp_pid_asid(const void *a, const void *b) { return 0; } +/** @brief Binary-search a sorted pid_asid map for pid; 0 copies use ASID 0. */ static const pid_asid *find_asid(const pid_asid *map, size_t n, pid_t pid) { pid_asid key; @@ -720,6 +925,7 @@ static const pid_asid *find_asid(const pid_asid *map, size_t n, pid_t pid) { return bsearch(&key, map, n, sizeof(*map), cmp_pid_asid); } +/** @brief qsort() order for proc: by pid. */ static int cmp_proc(const void *a, const void *b) { const proc *x = a; const proc *y = b; @@ -729,26 +935,33 @@ static int cmp_proc(const void *a, const void *b) { return 0; } +/** @brief Binary-search a sorted process list for pid. */ static const proc *find_proc(const proc *procs, size_t n, pid_t pid) { proc key = {.pid = pid}; return bsearch(&key, procs, n, sizeof(*procs), cmp_proc); } +/** @brief Whether a process path is sshd or sshd-session. */ static bool is_sshd(const char *path) { const char *base = strrchr(path, '/'); - base = base != NULL ? base + 1 : path; + base = base != nullptr ? base + 1 : path; return strcmp(base, "sshd") == 0 || strcmp(base, "sshd-session") == 0; } -/* The sftp subsystem also runs as a child of sshd-session, but it is a file - * transfer, not a login. */ +/** + * @brief Whether a process is the sftp subsystem. + * + * It also runs as a child of sshd-session, but it is a file transfer, not a + * login. + */ static bool is_sftp_server(const char *name) { return strcmp(name, "sftp-server") == 0 || strcmp(name, "internal-sftp") == 0; } +/** @brief Append one process, keeping only the basename of its path. */ static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps, const char *path) { const char *base; @@ -758,13 +971,13 @@ static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps, size_t ncap = *cap ? *cap * 2 : 64; proc *grown = realloc(*procs, ncap * sizeof(**procs)); - if (grown == NULL) + if (grown == nullptr) return -1; *procs = grown; *cap = ncap; } base = strrchr(path, '/'); - base = base != NULL ? base + 1 : path; + base = base != nullptr ? base + 1 : path; len = strlen(base); if (len >= sizeof((*procs)[*n].name)) len = sizeof((*procs)[*n].name) - 1; @@ -777,6 +990,12 @@ static int append_proc(proc **procs, size_t *n, size_t *cap, const W_PSPROC *ps, return 0; } +/** + * @brief Read the process table with w_getpsent into a sorted list. + * @param procs receives the malloc'd array + * @param count receives the number of processes + * @return 0 on success, -1 on a table that cannot be read + */ static int proc_scan(proc **procs, size_t *count) { W_PSPROC ps; char *path; @@ -786,12 +1005,12 @@ static int proc_scan(proc **procs, size_t *count) { size_t cap = 0; int token = 0; - *procs = NULL; + *procs = nullptr; *count = 0; - path = malloc(PS_PATH_BUF); - cmd = malloc(CMD_BUF); - tty = malloc(TTY_BUF); - if (path == NULL || cmd == NULL || tty == NULL) { + path = malloc(ps_path_buf); + cmd = malloc(cmd_buf); + tty = malloc(tty_buf); + if (path == nullptr || cmd == nullptr || tty == nullptr) { error_msg("whoson: out of memory\n"); free(path); free(cmd); @@ -802,18 +1021,18 @@ static int proc_scan(proc **procs, size_t *count) { int next; memset(&ps, 0, sizeof(ps)); - ps.ps_pathlen = PS_PATH_BUF; + ps.ps_pathlen = (int)ps_path_buf; ps.ps_pathptr = path; - ps.ps_cmdlen = CMD_BUF; + ps.ps_cmdlen = (int)cmd_buf; ps.ps_cmdptr = cmd; - ps.ps_conttylen = TTY_BUF; + ps.ps_conttylen = (int)tty_buf; ps.ps_conttyptr = tty; next = w_getpsent(token, &ps, sizeof(ps)); if (next < 0) { error_msg("whoson: cannot read the process table: %s\n", strerror(errno)); free(*procs); - *procs = NULL; + *procs = nullptr; free(path); free(cmd); free(tty); @@ -822,11 +1041,11 @@ static int proc_scan(proc **procs, size_t *count) { if (next == 0) break; token = next; - path[PS_PATH_BUF - 1] = '\0'; + path[ps_path_buf - 1] = '\0'; if (append_proc(procs, &n, &cap, &ps, path) != 0) { error_msg("whoson: out of memory\n"); free(*procs); - *procs = NULL; + *procs = nullptr; free(path); free(cmd); free(tty); @@ -839,7 +1058,7 @@ static int proc_scan(proc **procs, size_t *count) { if (n == 0) { error_msg("whoson: the process table is empty\n"); free(*procs); - *procs = NULL; + *procs = nullptr; return -1; } qsort(*procs, n, sizeof(**procs), cmp_proc); @@ -847,18 +1066,24 @@ static int proc_scan(proc **procs, size_t *count) { return 0; } -/* A logon procedure name from WHOSON_ZOSMF_PROCS; z/OSMF passes the procedure - * it was started with, so the name is the only clue common storage has. */ +/** + * @brief Whether a logon procedure is one z/OSMF uses. + * + * A logon procedure name from WHOSON_ZOSMF_PROCS; z/OSMF passes the + * procedure it was started with, so the name is the only clue common storage + * has. An unset or empty variable means IZUFPROC, the default in the z/OSMF + * configuration. + */ static bool logon_is_zosmf(const char *logon) { const char *list = getenv("WHOSON_ZOSMF_PROCS"); const char *p; - if (logon == NULL || logon[0] == '\0') + if (logon == nullptr || logon[0] == '\0') return false; - p = list != NULL && list[0] != '\0' ? list : "IZUFPROC"; + p = list != nullptr && list[0] != '\0' ? list : "IZUFPROC"; for (;;) { const char *comma = strchr(p, ','); - const char *end = comma != NULL ? comma : p + strlen(p); + const char *end = comma != nullptr ? comma : p + strlen(p); const char *s = p; size_t len; @@ -869,17 +1094,22 @@ static bool logon_is_zosmf(const char *logon) { len = (size_t)(end - s); if (len != 0 && len == strlen(logon) && strncmp(s, logon, len) == 0) return true; - if (comma == NULL) + if (comma == nullptr) break; p = comma + 1; } return false; } +/** @brief Map a uid to a userid, caching getpwuid() for the rows. + * @param uid effective uid of an SSH process + * @param out output buffer + * @param outlen size of out + */ static void user_name(uid_t uid, char *out, size_t outlen) { static struct { - uid_t uid; - char name[NAME_LEN]; + uid_t uid; /**< cached uid */ + char name[name_len]; /**< its userid */ } cache[16]; static size_t used; size_t i; @@ -892,7 +1122,7 @@ static void user_name(uid_t uid, char *out, size_t outlen) { } } pw = getpwuid(uid); - if (pw != NULL) + if (pw != nullptr) snprintf(cache[used].name, sizeof(cache[used].name), "%s", pw->pw_name); else snprintf(cache[used].name, sizeof(cache[used].name), "%u", @@ -903,6 +1133,7 @@ static void user_name(uid_t uid, char *out, size_t outlen) { used++; } +/** @brief qsort() order for the table: userid, then ASID, then pid. */ static int cmp_rows(const void *a, const void *b) { const row *x = a; const row *y = b; @@ -917,27 +1148,52 @@ static int cmp_rows(const void *a, const void *b) { return 0; } -/* TOD units are 2^-12 microseconds; print the total as h:mm:ss. */ +/** + * @brief Format a CPU time as a compact duration. + * + * TOD units are 2^-12 microseconds. The largest unit that keeps it short + * wins: hundredths of a second under a minute, then whole minutes, hours and + * days. A long session could otherwise read 1947:50:11. + * @param us microseconds of CPU + * @param out output buffer + * @param outlen size of out + */ static void fmt_cpu(uint64_t us, char *out, size_t outlen) { - uint64_t secs = (us + 500000u) / 1000000u; + uint64_t hundredths = (us + 5000u) / 10000u; + uint64_t secs = hundredths / 100u; - snprintf(out, outlen, "%" PRIu64 ":%02" PRIu64 ":%02" PRIu64, secs / 3600u, - secs % 3600u / 60u, secs % 60u); + if (secs < 60u) + snprintf(out, outlen, "%" PRIu64 ".%02" PRIu64 "s", secs, + hundredths % 100u); + else if (secs < 3600u) + snprintf(out, outlen, "%" PRIu64 "m%02" PRIu64 "s", secs / 60u, + secs % 60u); + else if (secs < 86400u) + snprintf(out, outlen, "%" PRIu64 "h%02" PRIu64 "m", secs / 3600u, + secs % 3600u / 60u); + else + snprintf(out, outlen, "%" PRIu64 "d%02" PRIu64 "h", secs / 86400u, + secs % 86400u / 3600u); } +/** @brief The table as it is built, so one write carries every row. */ typedef struct outbuf { - char buf[OUT_LEN]; - size_t len; + char buf[out_len]; /**< formatted rows, not yet written */ + size_t len; /**< bytes in buf */ } outbuf; +static void out_add(outbuf *o, const char *fmt, ...) PRINTFLIKE(2, 3); + +/** @brief emit() whatever the table has accumulated and reset it. */ static void out_flush(outbuf *o) { if (o->len != 0) emit(STDOUT_FILENO, o->buf, o->len); o->len = 0; } +/** @brief Append one formatted line to the table, flushing it when full. */ static void out_add(outbuf *o, const char *fmt, ...) { - char line[MSG_LEN]; + char line[msg_len]; va_list ap; int n; @@ -954,11 +1210,12 @@ static void out_add(outbuf *o, const char *fmt, ...) { o->len += (size_t)n; } +/** @brief Format the header and the rows, one row at a time, and write them. */ static void print_rows(row *rows, size_t n) { outbuf out; - char cpu[CPU_LEN]; - char asid[ASID_LEN]; - char pid[PID_LEN]; + char cpu[cpu_len]; + char asid[asid_len]; + char pid[pid_len]; size_t i; out.len = 0; @@ -981,6 +1238,18 @@ static void print_rows(row *rows, size_t n) { out_flush(&out); } +/** + * @brief Build the table: one row per TSO/E space, then one per SSH login. + * @param rows output array + * @param maxrows capacity of rows + * @param snap per-ASID state from the ASCB walk + * @param maxu number of entries in snap + * @param procs the process table, sorted by pid + * @param nprocs number of processes + * @param map pid-to-ASID map, sorted by pid + * @param nmap number of pairs + * @return the number of rows written + */ static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu, const proc *procs, size_t nprocs, const pid_asid *map, size_t nmap) { @@ -1010,11 +1279,11 @@ static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu, const char *job = "-"; parent = find_proc(procs, nprocs, procs[k].ppid); - if (parent == NULL || !is_sshd(parent->name) || + if (parent == nullptr || !is_sshd(parent->name) || is_sshd(procs[k].name) || is_sftp_server(procs[k].name)) continue; pa = find_asid(map, nmap, procs[k].pid); - if (pa != NULL && pa->asid >= 1 && pa->asid <= maxu) { + if (pa != nullptr && pa->asid >= 1 && pa->asid <= maxu) { asid = pa->asid; us = snap[asid - 1].us; if (snap[asid - 1].job[0] != '\0') @@ -1032,6 +1301,9 @@ static int collect(row *rows, size_t maxrows, const space *snap, unsigned maxu, return (int)n; } +/** @brief Walk common storage and the process table, and print the sessions. + * @return 0 on success, 1 on a read, memory or output failure + */ int main(int argc, char **argv) { space *snap; row *rows; @@ -1045,6 +1317,8 @@ int main(int argc, char **argv) { int nrows; int arg; + tag_untagged(STDOUT_FILENO); + tag_untagged(STDERR_FILENO); save_cvt(STDOUT_FILENO); save_cvt(STDERR_FILENO); (void)atexit(restore_cvt); @@ -1068,7 +1342,7 @@ int main(int argc, char **argv) { return 1; } snap = calloc((size_t)maxu, sizeof(*snap)); - if (snap == NULL) { + if (snap == nullptr) { unguard(); error_msg("whoson: out of memory for %u address spaces\n", maxu); return 1; @@ -1094,7 +1368,7 @@ int main(int argc, char **argv) { * the table can hold both lists; maxu alone would drop SSH sessions on a * system that shares address spaces (_BPX_SHAREAS). */ rows = calloc((size_t)maxu + nprocs, sizeof(*rows)); - if (rows == NULL) { + if (rows == nullptr) { error_msg("whoson: out of memory for the session table\n"); free(procs); free(map); |
