# z/OS C and HLASM Programming Standards This document defines the engineering standards, language dialect, type conventions, memory safety rules, z/OS system interface patterns, and assembler integration guidelines across all C and HLASM projects on z/OS. It is written to serve as an authoritative, machine-actionable specification for automated agents and human developers. ## 1. Toolchain and Language Standard ### 1.1 Language Level * Standard: Pure C23 (`-std=c23`). * Compilers: * Linux (cross-development and sanitizers): Clang with `-std=c23`. * z/OS (native compilation): IBM Open XL C/C++ 2.2+ (`ibm-clang`) with `-std=c23`. * Forbidden: Classic IBM XL C/C++ (`xlc`). The legacy compiler does not support modern C standards and must not be targeted. * Standard C23 Features: * Keywords and constants: `nullptr` (never `NULL`), `bool`, `true`, `false`, `static_assert`, `alignas`. * Attributes: `[[noreturn]]`, `[[nodiscard]]`, `[[fallthrough]]`. * Macro-wrapped attributes: Compiler-specific attributes without standardized C23 syntax must be wrapped in macros (for example, `PRINTFLIKE(fmt, args)` and `UNREACHABLE()`). * Typed constants: Scalar typed constants must use `constexpr` (for example, `constexpr size_t mvs_dsn_max = 44;`). * Limitation with IBM Open XL C/C++ 2.2: String literals cannot be initialized as `static constexpr char[]` due to an open compiler bug regarding negative character representation; string constants must remain `static const char[]`. * Feature test macros: Constants evaluated by preprocessor `#if` directives cannot use `constexpr` and must remain macros or anonymous enums. * Standard library constraint: Do not rely on newer C23 library headers not yet supported across target libcs (such as `` or ``). ### 1.2 Compiler Flags and Warnings Warnings are treated as fatal defects. Code must compile warning-free under both Clang on Linux and `ibm-clang` on z/OS. Required compiler warning flags: ```text -Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wconversion -Wpedantic ``` Required platform and feature macros on z/OS: ```text -D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200809L -D_ALL_SOURCE -D_EXT -D_OPEN_SYS_FILE_EXT=1 ``` Note: z/OS exposes SUSv4 and POSIX 2008 symbols through `-D_POSIX_C_SOURCE=200809L`; setting `_XOPEN_SOURCE=700` is rejected by z/OS system headers. ### 1.3 Addressing Mode Architecture * Programs are built 64-bit (`-m64`) XPLINK or 31-bit (`-m32`) XPLINK depending on architectural requirements. * If 64-bit mode is selected, ensure the 64-bit Language Environment runtime libraries (`CEE.SCEERUN2`, including `CELQLIB`, etc.) are placed in the dynamic LPA (`SETPROG LPA,ADD...`) to eliminate per-process DLL relocation overhead. * 24-bit and 31-bit system routines (such as AMODE 31 system macros or catalog services) called from 64-bit code must be bridged through dedicated thunk layers and separate assembler stubs. ## 2. Type Definitions and Naming Conventions ### 2.1 Struct and Enum Declarations All structures and enumerations that represent concrete types must be defined using the symmetrical typedef pattern: ```c typedef struct name { /* members */ } name; typedef enum name { /* enumerators */ } name; ``` References to the type must always use the bare typedef identifier `name`, never `struct name`. When a struct contains a pointer to its own type, use `struct name *` inside the body: ```c typedef struct node { struct node *next; void *data; } node; ``` Enumerations used strictly to group integer constants, flag bits, or key codes without creating a distinct type must remain anonymous and omit typedefs: ```c enum { tui_max_w = 500, tui_max_h = 200 }; ``` ### 2.2 Namespace Collision Prevention In C, typedef names and variable/function/field identifiers share the same ordinary identifier namespace. To prevent shadowing and syntax errors: * A typedef name must never collide with or match the name of any variable, function, global, or struct member. * Disambiguation patterns from codebase: * When a global or parameter is named `input`, name the typedef `input_src`. * When a state variable is named `tok`, name the typedef `tok_kind`. * When an operation function is named `arena_mark()`, name the type `arena_marker`. * When an object variable is named `tui`, name the type `tui_context` or `tui_term`. ### 2.3 Identifier Casing Rules Naming must adhere to the house `.clang-tidy` rules: * `lower_case` (snake_case): * Typedefs: `typedef_name` * Structs, unions, enums: `struct_name`, `enum_name` * Functions: `parse_tokens()`, `sys_open()` * Variables, parameters, local variables: `arg_count`, `buffer_ptr` * Struct and union members: `next`, `len`, `item_count` * Global and local scalar constants: `constexpr size_t buffer_limit = 4096;` * `UPPER_CASE`: * Macro definitions: `#define MVS_DSN_MAX 44` * Enum constants: `ENUM_VALUE_ONE`, `STATUS_OK` * Header guards: `PROJECT_MODULE_H` * Macro-style constants replaced by `constexpr`: `constexpr size_t CSI_WORK = 4096;` is permitted when mimicking MVS macro constants. ## 3. Formatting, Linting, and Documentation ### 3.1 Clang-Format Specification Formatting is strictly enforced via `.clang-format` based on LLVM style: * Indentation: 4 spaces (no tabs). * Column limit: 80 characters. * Braces: Attached (`BreakBeforeBraces: Attach`). * Single-line statements: * `AllowShortFunctionsOnASingleLine: None` * `AllowShortIfStatementsOnASingleLine: Never` (every `if` body must be on its own line). * Switch statements: `IndentCaseLabels: false`. * Includes: `SortIncludes: false` (order of z/OS system headers is semantically significant). ### 3.2 Clang-Tidy Policy * `.clang-tidy` is an absolute project gate. Run `make tidy` before committing. * Clean ratchet rule: A patch or pull request must introduce zero new clang-tidy findings. * Suppressions: A false positive must be suppressed locally with `// NOLINT(check-name): reason` explaining why the suppression is necessary. Check-level disabling in `.clang-tidy` requires documented justification. ### 3.3 Documentation Standards * Header comments: Every file must begin with a description of its responsibility, system assumptions, and MVS interfaces. * Doxygen markup: * Every function, type, global variable, and public macro must have a `/** @brief ... */` block at its point of definition. * Struct members and enum values must have inline Doxygen comments `/**< ... */`. * Header prototypes do not duplicate docblocks present at the function definition. * Focus on Intent: Comments must explain *why* an operation is performed, which MVS control blocks are affected, or why specific error handling is in place, rather than restating the C syntax. ## 4. Memory Safety and Allocation Model ### 4.1 Zero Undefined Behavior Policy * Absolute prohibition of uninitialized reads, signed integer overflows, and out-of-bounds array access. * Banned functions: `strcpy`, `strcat`, `sprintf`, `vsprintf`, `gets`. Use bounded string builders, `snprintf`, or explicit length-tracked memory copies. * Integer conversions: Avoid casting pointers to integers or integers to pointers unless interfacing with low-level MVS control blocks (e.g., PSA offset pointers). ### 4.2 Allocation Architecture * Minimizing Dynamic Allocation: Prefer stack allocation, fixed-size structures, or caller-provided output buffers for predictable performance. * Bump Arenas for Dynamic Work: When dynamic lifetime is required (e.g., AST construction, command expansion, token lists), use chunked bump arenas: * Allocate memory sequentially from pre-allocated blocks. * Release entire arenas or roll back to an `arena_marker` in one operation. * Disallow scattered individual `malloc`/`free` calls across data structures. * Recursive Functions: Must be bounded by an explicit stack-depth guard or runtime stack-limit check, never unconstrained. ## 5. z/OS Platform and Character Set Rules ### 5.1 Dual-Encoding Awareness (ASCII and EBCDIC) Projects build in ASCII mode (`-fzos-le-char-mode=ascii`, CCSID 819 / ISO8859-1) or native EBCDIC mode (CCSID 1047): * No in-band control markers: Never use byte values in the `0x80`-`0xFF` range as internal state flags; in IBM-1047, `0x81` represents the letter `'a'`. * Non-contiguous alphabet safety: In EBCDIC, letters `a`-`z` and `A`-`Z` are not contiguous. Never perform pointer or integer arithmetic assuming sequential alphabetic values. Character classification must always use standard `` functions (`isalpha`, `isdigit`, `isspace`). * Character literals: Always write character literals (`'a'`, `'\n'`), never hexadecimal ASCII numeric literals. * Control codes: Where terminal or protocol escapes are required, abstract the values (e.g., via `charset.h`) so appropriate ASCII (`0x1B`) or EBCDIC sequences are selected at compile time. ### 5.2 File Tagging and Automatic Conversion * Tagging: On z/OS UNIX, source code and text files are tagged ISO8859-1 (`chtag -t -c ISO8859-1`). * Runtime Conversion: Use `fcntl(fd, F_CONTROL_CVT, ...)` to manage programmatic conversion. * ASCII Build Tagging Rule: In ASCII builds, newly created text files, pipes, and inherited stdout must be explicitly tagged IBM-1047 with programmatic conversion enabled so standard z/OS tools read them correctly. * zopen conventions: Wherever possible, character conversion follows the zopen community's guidance -- a file created in ASCII mode is tagged ISO8859-1 (CCSID 819) at open time via `setccsid()`/`__fchattr()`, the call is double-guarded with `#ifdef __MVS__` and `#if (__CHARSET_LIB == 1)`, and the same tagging is applied from the shell with `chtag -tc819`. See [zopen community -- C pipe, C open do not tag newly created file descriptors](https://zopen.community/Guides/CommonSolutions#c-pipe-c-open-do-not-tag-newly-created-file-descriptors). ### 5.3 System Data Areas and Control Blocks * Reading MVS Control Blocks: * Read control blocks (PSA, CVT, ASVT, ASCB, CSCB) using explicit `memcpy` into packed structures. * Never cast raw memory stream offsets directly to structs. * Offsets must be pinned by `static_assert` matching IBM macro specifications. * Multi-byte Fields: All multi-byte integers stored in MVS data areas are big-endian. Read them explicitly using big-endian byte reconstruction or validated `memcpy`. ## 6. Assembler (HLASM) Integration Standards ### 6.1 Policy on Assembler Usage * Assembler routines are strictly restricted to leaf functions requiring capabilities not accessible from C (such as MVS system macros without callable APIs, or hardware instructions like `TRTE` / `CLST` where performance benchmarks justify them). * Every assembler routine must have an equivalent C reference implementation used for testing and off-platform Linux verification. * Assembler files must use the `.S` suffix so they can be assembled directly via the compiler pipeline. ### 6.2 Register Equates Placement and Format Register equates must be placed at the very bottom of the assembler source file. Every register equate must be explicitly defined from `R0` through `R15`: ```hlasm * ==================================================================== * Register Equates (Mandatory at bottom of source) * ==================================================================== R0 EQU 0 R1 EQU 1 R2 EQU 2 R3 EQU 3 R4 EQU 4 R5 EQU 5 R6 EQU 6 R7 EQU 7 R8 EQU 8 R9 EQU 9 R10 EQU 10 R11 EQU 11 R12 EQU 12 R13 EQU 13 R14 EQU 14 R15 EQU 15 END ``` Instructions and macro operands must always refer to registers using their equate names (such as `R3`, `R11`, `R15`, or `MCSOPER NAME=(R5)`). Bare numeric register references (e.g., `LR 15,1` or `L 1,0(2)`) are forbidden so registers cannot be confused with lengths, displacements, or immediate constants. ### 6.3 Field and Offset Equates Data area offsets and structure field offsets used in assembler routines must each have an explicit equate defined alongside comments: ```hlasm ZR_RC EQU 20 Return code offset in request block ZR_WORK EQU 24 Work area pointer offset ``` The C caller must verify these identical offsets using `static_assert`: ```c static_assert(offsetof(zreq, rc) == 20, "zreq.rc offset mismatch with ZR_RC"); ``` ### 6.4 XPLINK Assembler Rules and Caveats When interfacing assembler with XPLINK C modules: * Read-Only CSECTs: In an XPLINK environment, assembler CSECTs are loaded into read-only storage. Attempting to write into a local data word within the CSECT causes an `0C4` abend. All dynamic work areas, save areas, and return buffers must reside in caller-supplied storage passed by address. * Base Register Setup: Do not use address constants like `=A(csect_name)` to initialize base registers; the XPLINK binder resolves address constants to function descriptors rather than code entry points. Use `BALR 12,0` and `USING *,12`. * Register Pairs in System Macros: When passing register pairs to MVS macros (e.g., `WKAREA`), use doubled parentheses: `WKAREA=((R4),(R5))`. Single parentheses like `WKAREA=(4,5)` are interpreted by HLASM as literal address constants rather than register specifications. * Linkage Pragmas: Use `#pragma linkage(routine, OS)` in C headers. Entry points exported by HLASM are uppercase; bind them in C with `__asm__("ENTRYNAME")`. ## 7. Build System (Makefiles) ### 7.1 POSIX Makefile Compliance Makefiles must conform strictly to standard POSIX make specifications. They must execute correctly under both z/OS native `make` and GNU `make`. Prohibited non-standard constructs: * Do not use GNU extensions such as `:=`, `?=`, `ifeq`, `endif`, or `$(shell ...)`. * Do not use pattern rules (such as `%.o: %.c`). Use standard inference rules: ```makefile .c.o: $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ ``` Target naming conventions: * `all`: Default build. * `check`: Run the test suite. * `format`: Run `clang-format -i` across all C headers and source files. * `tidy`: Run `clang-tidy` using `.clang-tidy`. * `clean`: Remove binaries and intermediate build artifacts.