Python

 View Only

Working With Control Blocks Using Python with CBXP and ctypes

By Austin Wells posted 09/30/26 03:11 PM

  

Introduction

On z/OS, many system resources are represented by data structures known as control blocks. Jobs, address spaces, devices, tasks, subsystems, and even the operating system itself are described by one or more control blocks residing in memory.

System programmers frequently inspect these structures when analyzing dumps, troubleshooting problems, or obtaining information that is not exposed through higher-level APIs.

Traditionally, working with control blocks required detailed knowledge of storage layouts, offsets, pointer structures, and EBCDIC-encoded fields. With the IBM Open Enterprise SDK for Python, however, control blocks can be accessed directly from Python using either the standard ctypes library or the open-source Control Block EXPlorer (CBXP) package.

The ctypes approach provides direct access to memory and offers maximum flexibility, but it requires developers to manually locate control blocks, follow pointer chains, decode EBCDIC fields, and understand the layout of each structure being examined. CBXP builds on these same concepts by encapsulating control-block definitions and navigation logic behind a Python API. Rather than working with raw memory addresses and offsets, developers can retrieve control-block information as native Python dictionaries that can be inspected, filtered, serialized to JSON, and integrated into automation workflows, at the cost that only certain control blocks are currently supported.

More About Control Blocks

Control blocks rarely exist in isolation. Instead, z/OS organizes them into a hierarchy of structures linked through pointers. By following these links, programs can navigate from one system structure to another and locate information about specific resources.

The major categories of control blocks include:

  • PSA (Prefixed Save Area) — one per logical CPU, at real address 0x000; contains pointers to most other system structures
  • CVT (Communications Vector Table) — the master directory of z/OS, pointed to by the PSA
  • ASCB (Address Space Control Block) — one per active address space
  • TCB (Task Control Block) — one per active task within an address space

Locating a particular structure typically involves following a sequence of pointers from a known starting point, a process commonly referred to as walking the control-block chain. Each control block contains addresses of related structures, allowing software to traverse the hierarchy until the desired information is reached.

A common entry point is the PSA (Prefixed Save Area), which resides at absolute real-storage address 0x0000. From the PSA, a program can locate key system structures such as the CVT, ASCB, and TCB, which in turn provide access to many other areas of z/OS system information.

For example, the following walks give access to a rich amount of system information:

PSA (address 0x000 — one per logical CPU)
  └─ CVT at PSA+16          — root of all system control blocks
       └─ ECVT at CVT+140   — extended system information
       └─ XCVT at CVT+...   — further extensions
  └─ ASCB at PSA+548        — current address space
       └─ ASSB              — address-space secondary block (job names, etc.)
Note: More information regarding the location and the fields provided in the control blocks for this demo can be found in the IBM documentation: PSA, CVT and ECVT.

Working With Control Blocks Using ctypes

Control blocks can be accessed directly from Python using the ctypes library. ctypes is a standard Python library that provides access to C data types and allows Python code to interact with memory and native libraries. When working with z/OS control blocks, it can be used to dereference pointers and read fields from memory in a manner similar to C.

While this approach is not as Pythonic as using CBXP, it provides a foundation into how control blocks are structured and how they are traversed. Understanding these fundamentals makes it easier to appreciate and reason with the abstractions provided by higher-level tooling.

A previous blog post, Walking Control Blocks with Python, demonstrates how control block chains can be navigated manually from Python. The article includes examples that start at the PSA and follow pointers through structures such as the CVT and ECVT to retrieve system information directly from memory. One example, reproduced below, walks the chain PSA → CVT → ECVT to determine the active z/OS version and release.

Another example follows PSA → ASCB to retrieve the current job name.

import ctypes

if __name__ == '__main__':
    PSA = 0  # PSA is always located at memory address 0
    CVT = ctypes.c_int.from_address(PSA + 16)       # CVT is located at PSA + 16
    ECVT = ctypes.c_int.from_address(CVT.value + 140)  # ECVT is located at CVT + 140

    # Both version and release are two bytes, encoded in EBCDIC
    product_version = ctypes.string_at(ECVT.value + 512, 2).decode('cp1047')
    product_release = ctypes.string_at(ECVT.value + 514, 2).decode('cp1047')

    print('z/OS Version {} Release {}'.format(product_version, product_release))

In this example, the variable PSA represents the address of the PSA control block. Since the PSA is always located at virtual address 0, to access the CVT we read the pointer stored at offset 16 within the PSA using ctypes.c_int.from_address().

Next, the address of the ECVT is obtained by reading the pointer stored at offset 140 within the CVT. Again, ctypes.c_int.from_address() is used to retrieve the value directly from memory.

The z/OS version and release information are stored within the ECVT as two-byte EBCDIC-encoded fields. The ctypes.string_at() function reads these values from memory, after which they are converted to Python strings by decoding them with the 'cp1047' EBCDIC code page.

To access additional control blocks, the same pattern applies: find a known control block and walk along the chains until the desired structure is reached. This approach is sufficient for most cases, however manually remembering and parsing control blocks can be error-prone, hard to debug, and cumbersome. Next we will examine using CBXP to more comfortably navigate control blocks.

Introducing CBXP

CBXP (Control Block EXPlorer) is an open-source Python package for z/OS that encapsulates all the offset knowledge, manual memory management, and EBCDIC decoding that the manual approach requires. CBXP greatly simplifies working with control blocks via Python and lowers the barrier to entry for new developers on z/OS.

Before using CBXP, the package must be installed into either a Python virtual environment or the system-wide Python installation on z/OS. Instructions for installation are provided below.

Prerequisites and Installation

Requirements

  • IBM Open Enterprise SDK for Python 3.13.x or higher on z/OS
  • Network access to PyPI, or a local copy of the CBXP wheel
  • No special SAF authorisation is required: CBXP runs in problem state and reads only fetch-unprotected storage

Installation

  1. Verify your Python version:

    python3 --version
  2. Install CBXP from PyPI:

    pip3 install cbxp
  3. Verify the installation:

    python -m pip show cbxp

    Expected output:

    Name: cbxp
    Version: 0.0.4
    Summary: A unified and standardized interface for extracting and formatting z/OS control block data.
    Home-page: https://ambitus.github.io/cbxp/
    ...

Working with CBXP

CBXP exposes a single primary API, cbxp.extract(), which is used to locate, read, and format control-block data from live z/OS storage. Below is the method signature:

def extract(
    control_block: str,
    includes: list[str] = None,
    filters: list[CBXPFilter] = None,
    debug: bool = False,
) -> dict:

cbxp.extract accepts up to four arguments:

  1. The name of the control block to extract (e.g. "psa", "cvt")
  2. A list of Include Patterns describing additional control blocks to include that are accessible from the root control block being extracted
  3. A list of Filters used to filter entries returned in repeated control-block data
  4. A boolean — if True, debug messages are printed; if False, they are suppressed

On success, cbxp.extract returns a dictionary representation of the control blocks. On error, a CBXPError is raised.

Below is a table comparing the manual ctypes approach with CBXP:

Concern Manual ctypes approach CBXP
Navigation Caller adds offsets and dereferences each pointer explicitly Caller names the root block; CBXP walks the chain internally
Field layout Caller must know every offset, length, and pointer width CBXP contains the supported field mappings
EBCDIC decoding Caller reads raw bytes and calls .decode('cp1047') manually Character fields are returned as Python strings automatically
Output Individual integers and byte strings A Python dictionary, ready to inspect or serialise as JSON
Flexibility Can access any readable, documented storage location Limited to the blocks CBXP currently supports
Note: For a list of supported control blocks, please see https://ambitus.github.io/cbxp/supported_control_blocks/

Demo 1.) Reading the PSA

The PSA (Prefixed Save Area) is the most natural starting point. It lives at real address 0x000, one per logical CPU, and contains pointers to most other important system structures. With CBXP you read it in two lines:

from cbxp import cbxp

psa_data = cbxp.extract('psa')
print(psa_data)

The above code will print the following:

{
  'flcarch': '00000001',
  'flccvt': '0x00fd5a40',
  'flccvt64': '0x0000000000fd5a40',
  'flcfacl': '11111011111111111111111111111011...',
  'flcfacle': '11111111001101101110111111011000...',
  'flcrnpsw_bitstring': '00000000000000000000000000000000',
  'flcrnpsw_hex': '0x00000000',
  'flcsopsw': '01111111111111111111000000000000 | 0x7ffff000',
  'flcsvilc': 2,
  'psaaold': '0xc1e2c3c2',
  'psaecvt': '0x0000000001debb18',
  'psaflags': '00001100',
  'psafpfl': '00011000',
  'psalaa': '0xd3c1c140',
  'psalccav': '0x0227e500',
  'psapsa': 'PSA',
  'psatold': '0x005fb500',
  'psatrvt': '0xe3d9e5e3',
  'psaval': '0000010100100000',
  'psaxcvt': '0x00000000016f0cd8'
}

Key fields to note in this output:

  • psapsa: the eyecatcher string confirming this is a real PSA
  • flcarch = '00000001': last bit set means the CPU is in z/Architecture (64-bit) mode
  • flccvt / flccvt64: 31-bit and 64-bit addresses of the CVT, the root of all system control structures
  • flcfacl / flcfacle: 128-bit facility lists, each 1 bit means a hardware or software facility is installed
  • psaaold: address of the current address space's ASCB
  • psaecvt: direct pointer to the ECVT (extended CVT)

Notice there is no need to call .decode('cp1047'), or to compute or remember offsets, CBXP handles this internally.

Demo 2.) Walking From the CVT to the ECVT

Contained within the PSA is the location of the CVT. The CVT is the master directory of z/OS, it points to hundreds of subsystem and service tables. The ECVT (Extended CVT), reached from the CVT, contains fields such as ecvtpver and ecvtprel which identify the z/OS product version and release, as well as the system name (ecvthdnm), sysplex name (ecvtsplx), and product name (ecvtpnam).

With CBXP we can use the includes parameter to walk the control block and retrieve the ECVT directly from the CVT. We use the same cbxp.extract method as before, this time passing includes=['ecvt'] to indicate that CBXP should walk the CVT and return the ECVT as a dictionary nested within the CVT dictionary.

from cbxp import cbxp

cbdata = cbxp.extract('cvt', includes=['ecvt'])

# The ECVT is nested under "cvtecvt" inside the CVT dictionary
ecvt = cbdata.get('cvtecvt', {})

version = ecvt.get('ecvtpver', 'unknown')
release = ecvt.get('ecvtprel', 'unknown')
product = ecvt.get('ecvtpnam', 'unknown')
system  = ecvt.get('ecvthdnm', 'unknown')
sysplex = ecvt.get('ecvtsplx', 'unknown')

print('{} Version {} Release {}'.format(product, version, release))
print('System: {}  Sysplex: {}'.format(system, sysplex))

Sample output:

z/OS Version 02 Release 05
System: HSSSYS11  Sysplex: PLEX1

The ECVT is rich with system-level information. A few other notable fields available in the returned cvtecvt dictionary:

  • ecvtpidn: product identifier string (e.g. "5650-ZOS")
  • ecvtpown: product owner (e.g. "IBM CORP")
  • ecvt_installed_cpu_at_ipl: number of CPUs installed at IPL time
  • ecvtlpnm: LPAR name (e.g. "MYMAINFRAME")
  • ecvtsname: system name, also available directly on the CVT as cvtsname

Demo 3.) Enumerating Address Spaces and Filtering Results

Every active address space on z/OS has an associated ASSB (Address Space Secondary Block). The ASSB contains accounting, timing, and identification fields for the address space, including assbjbni (the initiator job name) and assbjbns (the job name from the started task or batch initiator).

To find the ASSB, we can use the following walk starting from the PSA:

PSA → ASCB (current address space) → ASSB
  assbjbni — initiator job name (e.g. "KIARASH7")
  assbjbns — started task / batch job name (e.g. "BPXAS")

Listing all active address spaces

Calling cbxp.extract('assb') without any filters returns a list with one entry per active address space on the system:

import json
from cbxp import cbxp

all_assb = cbxp.extract('assb')
print(json.dumps(all_assb, indent=2))

Each entry in the returned list is a dictionary of ASSB fields. A selection of the most useful ones:

  • assbjbni: initiator job name (8 characters, space-padded)
  • assbjbns: started task or batch job name
  • assb_task_time_on_cp: accumulated task CPU time on general-purpose CPs
  • assb_srb_time_on_cp: accumulated SRB CPU time on general-purpose CPs
  • assb_time_on_ziip: time dispatched on zIIP processors
  • assbisqn: address space sequence number

However, often we are not interested in every single address space on the machine, this is where the filters parameter is useful.

Using Filters

The filters parameter lets you narrow results to a specific address space. To create a filter, construct a list of CBXPFilter objects. The CBXPFilter constructor accepts three parameters:

  • key — the dictionary key to filter against
  • operation — a CBXPFilterOperation value, e.g. CBXPFilterOperation.EQUAL or CBXPFilterOperation.LESS_THAN
  • value — the value to compare against

In the next example, we filter all ASSB control blocks with an assbjbni (initiator job name) of KIARASH7:

import json
from cbxp import CBXPFilter, CBXPFilterOperation, cbxp

cbdata = cbxp.extract(
    'assb',
    filters=[
        CBXPFilter(
            'assbjbni',
            CBXPFilterOperation.EQUAL,
            'KIARASH7'     # exactly 8 characters — pad with spaces if shorter
        )
    ]
)

print(json.dumps(cbdata, indent=2))

Sample output:

"assb_asst_time_on_cp": 0,
"assb_asst_time_on_zcbp": 0,
...
"assbjbni": "KIARASH7",
"assbjbns": "BPXAS",
"assbldax": "0x000001ef80a3f400",
...
Note: Because job name fields in z/OS control blocks are fixed 8-byte EBCDIC strings, the filter value must be padded to exactly 8 characters with trailing spaces to match. This is true of many fields, consult the IBM documentation for the fields you are working with to ensure adequate padding.

Printing a job inventory

A practical example is to extract all ASSB entries and print just the job names, giving you a live inventory of every address space on the system:

from cbxp import cbxp

all_assb = cbxp.extract('assb')

print('{:<10} {:<10}'.format('JOBNAME', 'STC/BATCH'))
print('-' * 22)
for entry in all_assb:
    jbni = entry.get('assbjbni', '').strip()
    jbns = entry.get('assbjbns', '').strip()
    if jbni:
        print('{:<10} {:<10}'.format(jbni, jbns))

Output:

JOBNAME    STC/BATCH
----------------------
KIARASH7   BPXAS
IBMUSER    OMVS
SDSFAUX    SDSFAUX
...

Demo 4.) Converting Output to JSON

CBXP returns standard Python dictionaries and lists, so converting any extracted control-block data to JSON is a single call. This makes it straightforward to feed z/OS system state into log collectors, dashboards, or REST APIs.

To serialize cbxp.extract output into a JSON string, call json.dumps on the result. Using the indent parameter produces pretty-printed output for easy reading and examination:

import json
from cbxp import cbxp

psa_data = cbxp.extract('psa')

# Pretty-print as JSON
print(json.dumps(psa_data, indent=2))

Output:

{
  "flcarch": "00000001",
  "flccvt": "0x00fd5a40",
  "flccvt64": "0x0000000000fd5a40",
  "psapsa": "PSA",
  "psaecvt": "0x0000000001debb18",
  ...
}

You can also write the output to a file for archiving or offline analysis:

import json
from cbxp import cbxp

psa_data = cbxp.extract('psa')

with open('psa_snapshot.json', 'w') as f:
    json.dump(psa_data, f, indent=2)

print('PSA snapshot written.')
Tip: Because control-block reads are not serialised (see section below), a single extract() call gives you the most consistent snapshot. Avoid calling extract() multiple times and comparing fields across calls for time-sensitive data.

CBXP's Current Support and Restrictions

Supported control blocks (CBXP 0.0.4)

  • PSA: Prefixed Save Area
  • CVT: Communications Vector Table
  • ECVT: Extended CVT
  • ASVT: Address Space Vector Table
  • ASCB: Address Space Control Block
  • ASSB: Address Space Secondary Block
  • OUCB: Operator Unit Control Block
  • LDAX: Linkage Data Area Extension

Control blocks outside this list may still be accessed manually using ctypes if desired.

Problem-state restriction

CBXP runs in problem state, the same execution mode as ordinary user programs. It can only read storage that is not fetch-protected. Supervisor-state or key-zero-protected areas are not accessible. This is by design, it means CBXP cannot accidentally damage system storage.

No serialisation, data may be inconsistent

Control-block reads in CBXP are not serialised. A control block can be modified by the operating system while CBXP is reading it. This means field values returned in a single extract() call may occasionally be inconsistent, malformed, or reflect a mid-update state. Do not use CBXP output for security decisions or to drive critical automated actions without accounting for this.

Version compatibility

The supported block list, returned key names, and output structure may change between CBXP releases. Always verify examples against the installed version on your target z/OS system. Check the CBXP GitHub repository and documentation for updates.

Some Example Applications

CBXP automation can be used for the following tasks and more:

  • Operational monitoring scripts: periodically snapshot PSA or ASSB data and alert when specific fields change
  • System inventory tools: enumerate all active address spaces and their job names without SDSF
  • z/OS version detection: programmatically read ecvtpver/ecvtprel to adapt script behaviour to the running OS release
  • Facility-list interrogation: check flcfacl bits to determine whether a specific hardware facility is available before using it
  • Diagnostics and troubleshooting: capture a JSON snapshot of control-block state at the time of a problem for offline analysis
  • Integration with Python dashboards: feed z/OS system-state data into monitoring tools, web interfaces, or alerting systems

Summary

  1. Control blocks are the live internal data structures of z/OS, organised as pointer chains starting from the PSA at address 0x000.
  2. The manual ctypes approach (covered in Walking Control Blocks with Python) gives full flexibility but requires precise knowledge of every offset, pointer width, and field encoding.
  3. CBXP encapsulates that knowledge and returns Python dictionaries, eliminating offset arithmetic from application code.
  4. The core API is cbxp.extract(control_block, includes, filters).
  5. When using includes=['ecvt'], the ECVT data is returned nested under the key "cvtecvt" inside the CVT dictionary.
  6. Use filters with CBXPFilter and CBXPFilterOperation to narrow ASSB results to a specific job. Job name filter values must be exactly 8 characters, padded with trailing spaces if needed.
  7. Any CBXP dictionary can be serialised with json.dumps() for storage, logging, or API integration.
  8. CBXP runs in problem state, reads are not serialised, and only the eight documented block types are currently supported.

Additional Resources

0 comments
0 views

Permalink