Files
nvdriver/tools/check_drm_ioctl_abi.py

993 lines
37 KiB
Python
Executable File

#!/usr/bin/env python3
"""Compiler-exact C/Rust ABI conformance verifier for NVIDIA DRM & NVKMS ioctls.
Verifies 100% binary ABI parity across three boundaries:
1. `kernel-open/nvidia-drm/nvidia_rs_drm.c` vs stock
`/usr/src/nvidia-580.178.04/nvidia-drm/nvidia-drm-ioctl.h`:
- Compiles two independent C probes with `gcc` against kernel UAPI `<drm/drm.h>`:
one including stock `nvidia-drm-ioctl.h` (`-DNV_LINUX`) and one compiling
the exact UAPI block extracted from `kernel-open/nvidia-drm/nvidia_rs_drm.c`.
- Verifies all 24 `DRM_IOCTL_NVIDIA_*` ioctls (command indices `0x00`..`0x18`,
encoded `unsigned long` `_IO`/`_IOW`/`_IOWR` ioctl numbers, `sizeof`,
`_Alignof`, and `offsetof` + field `sizeof` for every field of every struct,
including nested helper structs and shared constants/enums), plus completeness
against stock headers and `nv_rs_drm_ioctls[]` registration.
2. `kernel-open/nvidia-modeset/nv_rs_kms_abi.h` vs stock
`/usr/src/nvidia-580.178.04/nvidia-modeset/nvkms-ioctl.h`:
- Verifies `NV_RS_NVKMS_IOCTL_MAGIC == NVKMS_IOCTL_MAGIC`,
`NV_RS_NVKMS_IOCTL_CMD == NVKMS_IOCTL_CMD`,
`NV_RS_NVKMS_IOCTL_IOWR == NVKMS_IOCTL_IOWR`,
`sizeof(struct nv_rs_nvkms_ioctl_params) == sizeof(struct NvKmsIoctlParams)`,
`_Alignof`, and `offsetof` + `sizeof` for `cmd`, `size`, and `address`.
3. `kernel-open/nvidia-modeset/nv_rs_kms_abi.h` `struct nv_rs_kms_gpu_caps` vs
`src/nvidia/kernel/modeset_ffi.rs` `#[repr(C)] pub struct NvRsKmsGpuCaps`:
- Compiles both a C probe (`gcc`) including `nv_rs_kms_abi.h` and a Rust probe
(`rustc`) embedding the exact `NvRsKmsGpuCaps` definition extracted from
`src/nvidia/kernel/modeset_ffi.rs`.
- Verifies identical field list/order, `sizeof`, `alignof`, and every field's
exact `offsetof` and `sizeof`.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
STOCK_NVIDIA_SRC = Path(os.environ.get("STOCK_NVIDIA_SRC", "/usr/src/nvidia-580.178.04"))
STOCK_DRM_IOCTL_H = STOCK_NVIDIA_SRC / "nvidia-drm" / "nvidia-drm-ioctl.h"
STOCK_NVKMS_IOCTL_H = STOCK_NVIDIA_SRC / "nvidia-modeset" / "nvkms-ioctl.h"
STOCK_COMMON_INC = STOCK_NVIDIA_SRC / "common" / "inc"
RS_DRM_C = ROOT / "kernel-open" / "nvidia-drm" / "nvidia_rs_drm.c"
RS_KMS_ABI_H = ROOT / "kernel-open" / "nvidia-modeset" / "nv_rs_kms_abi.h"
RS_MODESET_FFI_RS = ROOT / "src" / "nvidia" / "kernel" / "modeset_ffi.rs"
# All 24 NVIDIA 580.178.04 DRM ioctls:
# (suffix, expected_cmd_index, struct_name_or_None, tuple_of_field_names)
DRM_IOCTL_SPECS: tuple[tuple[str, int, str | None, tuple[str, ...]], ...] = (
(
"GET_CRTC_CRC32",
0x00,
"drm_nvidia_get_crtc_crc32_params",
("crtc_id", "crc32"),
),
(
"GEM_IMPORT_NVKMS_MEMORY",
0x01,
"drm_nvidia_gem_import_nvkms_memory_params",
("mem_size", "nvkms_params_ptr", "nvkms_params_size", "handle", "__pad"),
),
(
"GEM_IMPORT_USERSPACE_MEMORY",
0x02,
"drm_nvidia_gem_import_userspace_memory_params",
("size", "address", "handle"),
),
(
"GET_DEV_INFO",
0x03,
"drm_nvidia_get_dev_info_params",
(
"gpu_id",
"mig_device",
"primary_index",
"supports_alloc",
"generic_page_kind",
"page_kind_generation",
"sector_layout",
"supports_sync_fd",
"supports_semsurf",
),
),
(
"FENCE_SUPPORTED",
0x04,
None,
(),
),
(
"PRIME_FENCE_CONTEXT_CREATE",
0x05,
"drm_nvidia_prime_fence_context_create_params",
(
"handle",
"index",
"size",
"import_mem_nvkms_params_ptr",
"import_mem_nvkms_params_size",
"event_nvkms_params_ptr",
"event_nvkms_params_size",
),
),
(
"GEM_PRIME_FENCE_ATTACH",
0x06,
"drm_nvidia_gem_prime_fence_attach_params",
("handle", "fence_context_handle", "sem_thresh", "__pad"),
),
(
"GET_CLIENT_CAPABILITY",
0x08,
"drm_nvidia_get_client_capability_params",
("capability", "value"),
),
(
"GEM_EXPORT_NVKMS_MEMORY",
0x09,
"drm_nvidia_gem_export_nvkms_memory_params",
("handle", "__pad", "nvkms_params_ptr", "nvkms_params_size"),
),
(
"GEM_MAP_OFFSET",
0x0A,
"drm_nvidia_gem_map_offset_params",
("handle", "__pad", "offset"),
),
(
"GEM_ALLOC_NVKMS_MEMORY",
0x0B,
"drm_nvidia_gem_alloc_nvkms_memory_params",
("handle", "block_linear", "compressible", "__pad0", "memory_size", "flags", "__pad1"),
),
(
"GET_CRTC_CRC32_V2",
0x0C,
"drm_nvidia_get_crtc_crc32_v2_params",
("crtc_id", "crc32"),
),
(
"GEM_EXPORT_DMABUF_MEMORY",
0x0D,
"drm_nvidia_gem_export_dmabuf_memory_params",
("handle", "__pad", "nvkms_params_ptr", "nvkms_params_size"),
),
(
"GEM_IDENTIFY_OBJECT",
0x0E,
"drm_nvidia_gem_identify_object_params",
("handle", "object_type"),
),
(
"DMABUF_SUPPORTED",
0x0F,
None,
(),
),
(
"GET_DPY_ID_FOR_CONNECTOR_ID",
0x10,
"drm_nvidia_get_dpy_id_for_connector_id_params",
("connectorId", "dpyId"),
),
(
"GET_CONNECTOR_ID_FOR_DPY_ID",
0x11,
"drm_nvidia_get_connector_id_for_dpy_id_params",
("dpyId", "connectorId"),
),
(
"GRANT_PERMISSIONS",
0x12,
"drm_nvidia_grant_permissions_params",
("fd", "dpyId", "type"),
),
(
"REVOKE_PERMISSIONS",
0x13,
"drm_nvidia_revoke_permissions_params",
("dpyId", "type"),
),
(
"SEMSURF_FENCE_CTX_CREATE",
0x14,
"drm_nvidia_semsurf_fence_ctx_create_params",
("index", "nvkms_params_ptr", "nvkms_params_size", "handle", "__pad"),
),
(
"SEMSURF_FENCE_CREATE",
0x15,
"drm_nvidia_semsurf_fence_create_params",
("fence_context_handle", "timeout_value_ms", "wait_value", "fd", "__pad"),
),
(
"SEMSURF_FENCE_WAIT",
0x16,
"drm_nvidia_semsurf_fence_wait_params",
("fence_context_handle", "fd", "pre_wait_value", "post_wait_value"),
),
(
"SEMSURF_FENCE_ATTACH",
0x17,
"drm_nvidia_semsurf_fence_attach_params",
("handle", "fence_context_handle", "timeout_value_ms", "shared", "wait_value"),
),
(
"GET_DRM_FILE_UNIQUE_ID",
0x18,
"drm_nvidia_get_drm_file_unique_id_params",
("id",),
),
)
DRM_HELPER_STRUCTS: tuple[tuple[str, tuple[str, ...]], ...] = (
("drm_nvidia_crtc_crc32", ("value", "supported", "__pad0", "__pad1")),
(
"drm_nvidia_crtc_crc32_v2_out",
("compositorCrc32", "rasterGeneratorCrc32", "outputCrc32"),
),
)
DRM_CONSTANTS: tuple[str, ...] = (
"NV_GEM_ALLOC_NO_SCANOUT",
"NV_GEM_OBJECT_NVKMS",
"NV_GEM_OBJECT_DMABUF",
"NV_GEM_OBJECT_USERMEMORY",
"NV_GEM_OBJECT_UNKNOWN",
)
NVKMS_IOCTL_FIELDS: tuple[str, ...] = ("cmd", "size", "address")
def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def extract_rs_drm_uapi_section(source_text: str) -> str:
"""Extract the exact UAPI defines/structs/enums/ioctls block from nvidia_rs_drm.c."""
lines = source_text.splitlines()
start_idx = None
for idx, line in enumerate(lines):
if re.match(r"^\s*#\s*define\s+DRM_NVIDIA_", line):
start_idx = idx
break
if start_idx is None:
raise ValueError("Could not find '#define DRM_NVIDIA_' in nvidia_rs_drm.c")
# End after the last '#define DRM_IOCTL_NVIDIA_*' macro (following line continuations).
last_ioctl_idx = None
for idx in range(start_idx, len(lines)):
if re.match(r"^\s*#\s*define\s+DRM_IOCTL_NVIDIA_", lines[idx]):
last_ioctl_idx = idx
if last_ioctl_idx is None:
raise ValueError("Could not find '#define DRM_IOCTL_NVIDIA_' in nvidia_rs_drm.c")
end_idx = last_ioctl_idx
while end_idx < len(lines) and lines[end_idx].rstrip().endswith("\\"):
end_idx += 1
return "\n".join(lines[start_idx : end_idx + 1]) + "\n"
def extract_c_struct_fields(source_text: str, struct_name: str) -> list[str]:
"""Parse ordered field names of a flat C struct definition."""
m = re.search(
rf"\bstruct\s+{re.escape(struct_name)}\s*\{{(.*?)\}}\s*;",
source_text,
re.DOTALL,
)
if m is None:
raise ValueError(f"Could not find 'struct {struct_name}' definition")
body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.DOTALL)
body = re.sub(r"//.*", "", body)
fields: list[str] = []
for raw_stmt in body.split(";"):
stmt = raw_stmt.strip()
if not stmt:
continue
# Strip trailing attributes such as __aligned(8) or NV_ALIGN_BYTES(8).
stmt = re.sub(r"\b(?:__aligned|NV_ALIGN_BYTES)\s*\([^)]*\)", "", stmt).strip()
# Handle array declarators if any (e.g., pad[2]).
stmt = re.sub(r"\[[^\]]*\]", "", stmt).strip()
ident_match = re.search(r"([A-Za-z_][A-Za-z0-9_]*)\s*$", stmt)
if ident_match is None:
raise ValueError(f"Cannot parse field name from '{raw_stmt.strip()}' in struct {struct_name}")
fields.append(ident_match.group(1))
return fields
def extract_rust_struct_block(source_text: str, struct_name: str) -> tuple[str, list[str]]:
"""Extract a `#[repr(C)] pub struct <Name> { ... }` block and its ordered field names."""
pattern = re.compile(
rf"((?:#\[[^\]]+\]\s*)+)pub\s+struct\s+{re.escape(struct_name)}\s*\{{(.*?)\}}",
re.DOTALL,
)
m = pattern.search(source_text)
if m is None:
raise ValueError(f"Could not find 'pub struct {struct_name}' in modeset_ffi.rs")
attrs = m.group(1)
if not re.search(r"#\[\s*repr\s*\(\s*C\s*\)\s*\]", attrs):
raise ValueError(f"Rust struct {struct_name} is missing #[repr(C)]")
body = re.sub(r"//.*", "", m.group(2))
fields: list[str] = []
for raw_line in body.split(","):
line = raw_line.strip()
if not line:
continue
fm = re.match(r"^(?:pub(?:\([^)]*\))?\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*:", line)
if fm is None:
raise ValueError(f"Cannot parse Rust field '{line}' in {struct_name}")
fields.append(fm.group(1))
return m.group(0), fields
def build_drm_probe_body() -> str:
"""Emit C main() printing JSON for all 24 DRM ioctls, helper structs, and constants."""
lines = [
"int main(void) {",
' printf("{\\n");',
' printf(" \\"ioctls\\": {\\n");',
]
for i, (suffix, _idx, struct_name, fields) in enumerate(DRM_IOCTL_SPECS):
comma = "," if i + 1 < len(DRM_IOCTL_SPECS) else ""
cmd_macro = f"DRM_NVIDIA_{suffix}"
ioctl_macro = f"DRM_IOCTL_NVIDIA_{suffix}"
lines.append(f' printf(" \\"{suffix}\\": {{\\n");')
lines.append(
f' printf(" \\"cmd_index\\": %lu,\\n", (unsigned long)({cmd_macro}));'
)
lines.append(
f' printf(" \\"ioctl_nr\\": %lu,\\n", (unsigned long)({ioctl_macro}));'
)
if struct_name is None:
lines.append(' printf(" \\"struct_name\\": null,\\n");')
lines.append(' printf(" \\"struct_size\\": 0,\\n");')
lines.append(' printf(" \\"struct_align\\": 0,\\n");')
lines.append(' printf(" \\"fields\\": {}\\n");')
else:
lines.append(f' printf(" \\"struct_name\\": \\"{struct_name}\\",\\n");')
lines.append(
f' printf(" \\"struct_size\\": %zu,\\n", sizeof(struct {struct_name}));'
)
lines.append(
f' printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct {struct_name}));'
)
lines.append(' printf(" \\"fields\\": {\\n");')
for j, field in enumerate(fields):
fcomma = "," if j + 1 < len(fields) else ""
lines.append(
f' printf(" \\"{field}\\": {{\\"offset\\": %zu, \\"size\\": %zu}}{fcomma}\\n", '
f"offsetof(struct {struct_name}, {field}), "
f"sizeof(((struct {struct_name} *)0)->{field}));"
)
lines.append(' printf(" }\\n");')
lines.append(f' printf(" }}{comma}\\n");')
lines.append(' printf(" },\\n");')
lines.append(' printf(" \\"helper_structs\\": {\\n");')
for i, (struct_name, fields) in enumerate(DRM_HELPER_STRUCTS):
comma = "," if i + 1 < len(DRM_HELPER_STRUCTS) else ""
lines.append(f' printf(" \\"{struct_name}\\": {{\\n");')
lines.append(
f' printf(" \\"struct_size\\": %zu,\\n", sizeof(struct {struct_name}));'
)
lines.append(
f' printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct {struct_name}));'
)
lines.append(' printf(" \\"fields\\": {\\n");')
for j, field in enumerate(fields):
fcomma = "," if j + 1 < len(fields) else ""
lines.append(
f' printf(" \\"{field}\\": {{\\"offset\\": %zu, \\"size\\": %zu}}{fcomma}\\n", '
f"offsetof(struct {struct_name}, {field}), "
f"sizeof(((struct {struct_name} *)0)->{field}));"
)
lines.append(' printf(" }\\n");')
lines.append(f' printf(" }}{comma}\\n");')
lines.append(' printf(" },\\n");')
lines.append(' printf(" \\"constants\\": {\\n");')
for i, const in enumerate(DRM_CONSTANTS):
comma = "," if i + 1 < len(DRM_CONSTANTS) else ""
lines.append(
f' printf(" \\"{const}\\": %lu{comma}\\n", (unsigned long)({const}));'
)
lines.append(' printf(" }\\n");')
lines.append(' printf("}\\n");')
lines.append(" return 0;")
lines.append("}")
return "\n".join(lines) + "\n"
def compile_and_run_c(source: str, extra_args: list[str], label: str) -> dict:
with tempfile.TemporaryDirectory(prefix=f"nvrs-abi-{label}-") as td:
src_path = Path(td) / f"{label}.c"
exe_path = Path(td) / label
src_path.write_text(source, encoding="utf-8")
cmd = ["gcc", "-O2", "-Wall", "-Wextra", *extra_args, str(src_path), "-o", str(exe_path)]
res = subprocess.run(cmd, capture_output=True, text=True)
if res.returncode != 0:
raise RuntimeError(
f"C probe '{label}' failed to compile:\nCMD: {' '.join(cmd)}\nSTDERR:\n{res.stderr}"
)
out = subprocess.check_output([str(exe_path)], text=True)
return json.loads(out)
def compile_and_run_rust(source: str, label: str) -> dict:
with tempfile.TemporaryDirectory(prefix=f"nvrs-abi-{label}-") as td:
src_path = Path(td) / f"{label}.rs"
exe_path = Path(td) / label
src_path.write_text(source, encoding="utf-8")
cmd = ["rustc", "-O", "--edition=2021", str(src_path), "-o", str(exe_path)]
res = subprocess.run(cmd, capture_output=True, text=True)
if res.returncode != 0:
raise RuntimeError(
f"Rust probe '{label}' failed to compile:\nCMD: {' '.join(cmd)}\nSTDERR:\n{res.stderr}"
)
out = subprocess.check_output([str(exe_path)], text=True)
return json.loads(out)
def verify_drm_ioctl_abi() -> dict:
stock_text = STOCK_DRM_IOCTL_H.read_text(encoding="utf-8")
rs_text = RS_DRM_C.read_text(encoding="utf-8")
rs_uapi_snippet = extract_rs_drm_uapi_section(rs_text)
# Completeness checks against stock header & nvidia_rs_drm.c ioctl dispatch table.
spec_suffixes = {s for s, _, _, _ in DRM_IOCTL_SPECS}
stock_cmd_suffixes = set(re.findall(r"^\s*#\s*define\s+DRM_NVIDIA_([A-Z0-9_]+)\b", stock_text, re.M))
stock_ioctl_suffixes = set(
re.findall(r"^\s*#\s*define\s+DRM_IOCTL_NVIDIA_([A-Z0-9_]+)\b", stock_text, re.M)
)
stock_structs = set(re.findall(r"\bstruct\s+(drm_nvidia_[a-z0-9_]+)\s*\{", stock_text))
spec_structs = {st for _, _, st, _ in DRM_IOCTL_SPECS if st is not None} | {
st for st, _ in DRM_HELPER_STRUCTS
}
rs_table_suffixes = set(
re.findall(r"\bDRM_IOCTL_DEF_DRV\s*\(\s*NVIDIA_([A-Z0-9_]+)\s*,", rs_text)
)
completeness_diffs: list[dict] = []
if stock_cmd_suffixes != spec_suffixes:
completeness_diffs.append(
{
"check": "stock_cmd_macro_set",
"missing_in_spec": sorted(stock_cmd_suffixes - spec_suffixes),
"extra_in_spec": sorted(spec_suffixes - stock_cmd_suffixes),
}
)
if stock_ioctl_suffixes != spec_suffixes:
completeness_diffs.append(
{
"check": "stock_ioctl_macro_set",
"missing_in_spec": sorted(stock_ioctl_suffixes - spec_suffixes),
"extra_in_spec": sorted(spec_suffixes - stock_ioctl_suffixes),
}
)
if stock_structs != spec_structs:
completeness_diffs.append(
{
"check": "stock_struct_set",
"missing_in_spec": sorted(stock_structs - spec_structs),
"extra_in_spec": sorted(spec_structs - stock_structs),
}
)
if rs_table_suffixes != spec_suffixes:
completeness_diffs.append(
{
"check": "nvidia_rs_drm_ioctl_table_registration",
"missing_in_table": sorted(spec_suffixes - rs_table_suffixes),
"extra_in_table": sorted(rs_table_suffixes - spec_suffixes),
}
)
# Verify every field present in both stock header and nvidia_rs_drm.c matches our spec.
for _suffix, _idx, st_name, fields in DRM_IOCTL_SPECS:
if st_name is None:
continue
parsed_stock_fields = extract_c_struct_fields(stock_text, st_name)
if tuple(parsed_stock_fields) != fields:
completeness_diffs.append(
{
"check": f"stock_fields:{st_name}",
"stock_header_fields": parsed_stock_fields,
"spec_fields": list(fields),
}
)
parsed_rs_fields = extract_c_struct_fields(rs_uapi_snippet, st_name)
if tuple(parsed_rs_fields) != fields:
completeness_diffs.append(
{
"check": f"rs_fields:{st_name}",
"rs_fields": parsed_rs_fields,
"spec_fields": list(fields),
}
)
for st_name, fields in DRM_HELPER_STRUCTS:
parsed_stock_fields = extract_c_struct_fields(stock_text, st_name)
if tuple(parsed_stock_fields) != fields:
completeness_diffs.append(
{
"check": f"stock_fields:{st_name}",
"stock_header_fields": parsed_stock_fields,
"spec_fields": list(fields),
}
)
parsed_rs_fields = extract_c_struct_fields(rs_uapi_snippet, st_name)
if tuple(parsed_rs_fields) != fields:
completeness_diffs.append(
{
"check": f"rs_fields:{st_name}",
"rs_fields": parsed_rs_fields,
"spec_fields": list(fields),
}
)
probe_body = build_drm_probe_body()
stock_probe_src = (
"#include <stdio.h>\n"
"#include <stdint.h>\n"
"#include <stddef.h>\n"
'#include "nvidia-drm-ioctl.h"\n\n'
+ probe_body
)
rs_probe_src = (
"#include <stdio.h>\n"
"#include <stdint.h>\n"
"#include <stddef.h>\n"
"#include <drm/drm.h>\n\n"
"typedef uint8_t u8;\n"
"typedef uint16_t u16;\n"
"typedef uint32_t u32;\n"
"typedef uint64_t u64;\n"
"typedef int32_t s32;\n\n"
+ rs_uapi_snippet
+ "\n"
+ probe_body
)
stock_data = compile_and_run_c(
stock_probe_src,
["-DNV_LINUX", f"-I{STOCK_DRM_IOCTL_H.parent}"],
"stock_drm_ioctl",
)
rs_data = compile_and_run_c(rs_probe_src, [], "rs_drm_ioctl")
diffs: list[dict] = list(completeness_diffs)
ioctl_results: list[dict] = []
for suffix, expected_idx, struct_name, fields in DRM_IOCTL_SPECS:
s_entry = stock_data["ioctls"][suffix]
r_entry = rs_data["ioctls"][suffix]
entry_diffs: list[dict] = []
if s_entry["cmd_index"] != expected_idx or r_entry["cmd_index"] != expected_idx:
entry_diffs.append(
{
"item": f"DRM_NVIDIA_{suffix}.cmd_index",
"expected": expected_idx,
"stock": s_entry["cmd_index"],
"rs": r_entry["cmd_index"],
}
)
if s_entry["ioctl_nr"] != r_entry["ioctl_nr"]:
entry_diffs.append(
{
"item": f"DRM_IOCTL_NVIDIA_{suffix}.ioctl_nr",
"stock": hex(s_entry["ioctl_nr"]),
"rs": hex(r_entry["ioctl_nr"]),
}
)
if s_entry["struct_size"] != r_entry["struct_size"]:
entry_diffs.append(
{
"item": f"sizeof(struct {struct_name})",
"stock": s_entry["struct_size"],
"rs": r_entry["struct_size"],
}
)
if s_entry["struct_align"] != r_entry["struct_align"]:
entry_diffs.append(
{
"item": f"_Alignof(struct {struct_name})",
"stock": s_entry["struct_align"],
"rs": r_entry["struct_align"],
}
)
for field in fields:
sf = s_entry["fields"][field]
rf = r_entry["fields"][field]
if sf != rf:
entry_diffs.append(
{
"item": f"struct {struct_name}.{field}",
"stock": sf,
"rs": rf,
}
)
diffs.extend(entry_diffs)
ioctl_results.append(
{
"name": f"DRM_IOCTL_NVIDIA_{suffix}",
"cmd_index": r_entry["cmd_index"],
"ioctl_nr": r_entry["ioctl_nr"],
"struct_name": struct_name,
"struct_size": r_entry["struct_size"],
"field_count": len(fields),
"passed": len(entry_diffs) == 0,
"diffs": entry_diffs,
}
)
helper_results: list[dict] = []
for struct_name, fields in DRM_HELPER_STRUCTS:
s_entry = stock_data["helper_structs"][struct_name]
r_entry = rs_data["helper_structs"][struct_name]
h_diffs: list[dict] = []
if s_entry["struct_size"] != r_entry["struct_size"]:
h_diffs.append(
{
"item": f"sizeof(struct {struct_name})",
"stock": s_entry["struct_size"],
"rs": r_entry["struct_size"],
}
)
if s_entry["struct_align"] != r_entry["struct_align"]:
h_diffs.append(
{
"item": f"_Alignof(struct {struct_name})",
"stock": s_entry["struct_align"],
"rs": r_entry["struct_align"],
}
)
for field in fields:
if s_entry["fields"][field] != r_entry["fields"][field]:
h_diffs.append(
{
"item": f"struct {struct_name}.{field}",
"stock": s_entry["fields"][field],
"rs": r_entry["fields"][field],
}
)
diffs.extend(h_diffs)
helper_results.append(
{
"struct_name": struct_name,
"struct_size": r_entry["struct_size"],
"field_count": len(fields),
"passed": len(h_diffs) == 0,
"diffs": h_diffs,
}
)
const_results: list[dict] = []
for const in DRM_CONSTANTS:
sv = stock_data["constants"][const]
rv = rs_data["constants"][const]
ok = sv == rv
if not ok:
diffs.append({"item": const, "stock": sv, "rs": rv})
const_results.append({"name": const, "value": rv, "passed": ok})
return {
"passed": len(diffs) == 0,
"ioctl_count": len(ioctl_results),
"ioctls": ioctl_results,
"helper_structs": helper_results,
"constants": const_results,
"diffs": diffs,
}
def verify_nvkms_ioctl_abi() -> dict:
stock_fields = extract_c_struct_fields(
STOCK_NVKMS_IOCTL_H.read_text(encoding="utf-8"), "NvKmsIoctlParams"
)
rs_fields = extract_c_struct_fields(
RS_KMS_ABI_H.read_text(encoding="utf-8"), "nv_rs_nvkms_ioctl_params"
)
diffs: list[dict] = []
if tuple(stock_fields) != NVKMS_IOCTL_FIELDS or tuple(rs_fields) != NVKMS_IOCTL_FIELDS:
diffs.append(
{
"item": "NvKmsIoctlParams.field_list",
"stock": stock_fields,
"rs": rs_fields,
"expected": list(NVKMS_IOCTL_FIELDS),
}
)
stock_probe_src = """
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <linux/ioctl.h>
#include "nvkms-ioctl.h"
int main(void) {
printf("{\\n");
printf(" \\"magic\\": %lu,\\n", (unsigned long)(NVKMS_IOCTL_MAGIC));
printf(" \\"cmd\\": %lu,\\n", (unsigned long)(NVKMS_IOCTL_CMD));
printf(" \\"ioctl_iowr\\": %lu,\\n", (unsigned long)(NVKMS_IOCTL_IOWR));
printf(" \\"struct_size\\": %zu,\\n", sizeof(struct NvKmsIoctlParams));
printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct NvKmsIoctlParams));
printf(" \\"fields\\": {\\n");
printf(" \\"cmd\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n",
offsetof(struct NvKmsIoctlParams, cmd), sizeof(((struct NvKmsIoctlParams *)0)->cmd));
printf(" \\"size\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n",
offsetof(struct NvKmsIoctlParams, size), sizeof(((struct NvKmsIoctlParams *)0)->size));
printf(" \\"address\\": {\\"offset\\": %zu, \\"size\\": %zu}\\n",
offsetof(struct NvKmsIoctlParams, address), sizeof(((struct NvKmsIoctlParams *)0)->address));
printf(" }\\n");
printf("}\\n");
return 0;
}
"""
rs_probe_src = """
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int32_t s32;
#ifndef __aligned
#define __aligned(x) __attribute__((__aligned__(x)))
#endif
struct page;
#include "nv_rs_kms_abi.h"
int main(void) {
printf("{\\n");
printf(" \\"magic\\": %lu,\\n", (unsigned long)(NV_RS_NVKMS_IOCTL_MAGIC));
printf(" \\"cmd\\": %lu,\\n", (unsigned long)(NV_RS_NVKMS_IOCTL_CMD));
printf(" \\"ioctl_iowr\\": %lu,\\n", (unsigned long)(NV_RS_NVKMS_IOCTL_IOWR));
printf(" \\"struct_size\\": %zu,\\n", sizeof(struct nv_rs_nvkms_ioctl_params));
printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct nv_rs_nvkms_ioctl_params));
printf(" \\"fields\\": {\\n");
printf(" \\"cmd\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n",
offsetof(struct nv_rs_nvkms_ioctl_params, cmd), sizeof(((struct nv_rs_nvkms_ioctl_params *)0)->cmd));
printf(" \\"size\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n",
offsetof(struct nv_rs_nvkms_ioctl_params, size), sizeof(((struct nv_rs_nvkms_ioctl_params *)0)->size));
printf(" \\"address\\": {\\"offset\\": %zu, \\"size\\": %zu}\\n",
offsetof(struct nv_rs_nvkms_ioctl_params, address), sizeof(((struct nv_rs_nvkms_ioctl_params *)0)->address));
printf(" }\\n");
printf("}\\n");
return 0;
}
"""
stock_data = compile_and_run_c(
stock_probe_src,
[f"-I{STOCK_NVKMS_IOCTL_H.parent}", f"-I{STOCK_COMMON_INC}"],
"stock_nvkms_ioctl",
)
rs_data = compile_and_run_c(
rs_probe_src,
[f"-I{RS_KMS_ABI_H.parent}"],
"rs_nvkms_ioctl",
)
for key in ("magic", "cmd", "ioctl_iowr", "struct_size", "struct_align"):
if stock_data[key] != rs_data[key]:
diffs.append({"item": key, "stock": stock_data[key], "rs": rs_data[key]})
for field in NVKMS_IOCTL_FIELDS:
if stock_data["fields"][field] != rs_data["fields"][field]:
diffs.append(
{
"item": f"NvKmsIoctlParams.{field}",
"stock": stock_data["fields"][field],
"rs": rs_data["fields"][field],
}
)
return {
"passed": len(diffs) == 0,
"ioctl_iowr": rs_data["ioctl_iowr"],
"struct_size": rs_data["struct_size"],
"struct_align": rs_data["struct_align"],
"fields": rs_data["fields"],
"diffs": diffs,
}
def verify_kms_gpu_caps_abi() -> dict:
c_header_text = RS_KMS_ABI_H.read_text(encoding="utf-8")
rust_src_text = RS_MODESET_FFI_RS.read_text(encoding="utf-8")
c_fields = extract_c_struct_fields(c_header_text, "nv_rs_kms_gpu_caps")
rust_struct_def, rust_fields = extract_rust_struct_block(rust_src_text, "NvRsKmsGpuCaps")
diffs: list[dict] = []
if c_fields != rust_fields:
diffs.append(
{
"item": "field_list_and_order",
"c_fields": c_fields,
"rust_fields": rust_fields,
}
)
# Build C probe against kernel-open/nvidia-modeset/nv_rs_kms_abi.h
c_lines = [
"#include <stdio.h>",
"#include <stdint.h>",
"#include <stddef.h>",
"typedef uint8_t u8;",
"typedef uint16_t u16;",
"typedef uint32_t u32;",
"typedef uint64_t u64;",
"typedef int32_t s32;",
"#ifndef __aligned",
"#define __aligned(x) __attribute__((__aligned__(x)))",
"#endif",
"struct page;",
'#include "nv_rs_kms_abi.h"',
"int main(void) {",
' printf("{\\n");',
' printf(" \\"struct_size\\": %zu,\\n", sizeof(struct nv_rs_kms_gpu_caps));',
' printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct nv_rs_kms_gpu_caps));',
' printf(" \\"fields\\": {\\n");',
]
for i, field in enumerate(c_fields):
comma = "," if i + 1 < len(c_fields) else ""
c_lines.append(
f' printf(" \\"{field}\\": {{\\"offset\\": %zu, \\"size\\": %zu}}{comma}\\n", '
f"offsetof(struct nv_rs_kms_gpu_caps, {field}), "
f"sizeof(((struct nv_rs_kms_gpu_caps *)0)->{field}));"
)
c_lines.extend([' printf(" }\\n");', ' printf("}\\n");', " return 0;", "}"])
c_data = compile_and_run_c("\n".join(c_lines) + "\n", [f"-I{RS_KMS_ABI_H.parent}"], "c_gpu_caps")
# Build Rust probe embedding the exact struct extracted from src/nvidia/kernel/modeset_ffi.rs
r_lines = [
"#![allow(dead_code)]",
"use core::mem::{align_of, offset_of, size_of, size_of_val};",
rust_struct_def,
"fn main() {",
" let sample = NvRsKmsGpuCaps::default();",
' println!("{{");',
' println!(" \\"struct_size\\": {},", size_of::<NvRsKmsGpuCaps>());',
' println!(" \\"struct_align\\": {},", align_of::<NvRsKmsGpuCaps>());',
' println!(" \\"fields\\": {{");',
]
for i, field in enumerate(rust_fields):
comma = "," if i + 1 < len(rust_fields) else ""
r_lines.append(
f' println!(" \\"{field}\\": {{{{\\"offset\\": {{}}, \\"size\\": {{}}}}}}{comma}", '
f"offset_of!(NvRsKmsGpuCaps, {field}), size_of_val(&sample.{field}));"
)
r_lines.extend([' println!(" }}");', ' println!("}}");', "}"])
rust_data = compile_and_run_rust("\n".join(r_lines) + "\n", "rust_gpu_caps")
for key in ("struct_size", "struct_align"):
if c_data[key] != rust_data[key]:
diffs.append({"item": key, "c": c_data[key], "rust": rust_data[key]})
common_fields = [f for f in c_fields if f in rust_data["fields"]]
for field in common_fields:
if c_data["fields"][field] != rust_data["fields"][field]:
diffs.append(
{
"item": f"NvRsKmsGpuCaps.{field}",
"c": c_data["fields"][field],
"rust": rust_data["fields"][field],
}
)
return {
"passed": len(diffs) == 0,
"struct_size": c_data["struct_size"],
"struct_align": c_data["struct_align"],
"field_count": len(c_fields),
"c_fields": c_data["fields"],
"rust_fields": rust_data["fields"],
"diffs": diffs,
}
def main() -> int:
parser = argparse.ArgumentParser(description="Verify DRM & NVKMS C/Rust ABI parity against 580.178.04.")
parser.add_argument("--json", action="store_true", help="Emit full machine-readable JSON report only")
args = parser.parse_args()
required_files = (
STOCK_DRM_IOCTL_H,
STOCK_NVKMS_IOCTL_H,
STOCK_COMMON_INC / "nvtypes.h",
RS_DRM_C,
RS_KMS_ABI_H,
RS_MODESET_FFI_RS,
)
missing = [str(p) for p in required_files if not p.is_file()]
if missing:
err = {"status": "error", "passed": False, "missing_files": missing}
print(json.dumps(err, indent=2), file=sys.stderr)
return 2
drm_res = verify_drm_ioctl_abi()
nvkms_res = verify_nvkms_ioctl_abi()
caps_res = verify_kms_gpu_caps_abi()
overall_passed = drm_res["passed"] and nvkms_res["passed"] and caps_res["passed"]
report = {
"name": "nvidia_580_178_04_drm_nvkms_abi_parity",
"status": "PASS" if overall_passed else "FAIL",
"passed": overall_passed,
"files_sha256": {
str(STOCK_DRM_IOCTL_H): sha256_file(STOCK_DRM_IOCTL_H),
str(STOCK_NVKMS_IOCTL_H): sha256_file(STOCK_NVKMS_IOCTL_H),
str(RS_DRM_C.relative_to(ROOT)): sha256_file(RS_DRM_C),
str(RS_KMS_ABI_H.relative_to(ROOT)): sha256_file(RS_KMS_ABI_H),
str(RS_MODESET_FFI_RS.relative_to(ROOT)): sha256_file(RS_MODESET_FFI_RS),
},
"drm_ioctls": drm_res,
"nvkms_ioctl": nvkms_res,
"kms_gpu_caps": caps_res,
}
if args.json:
print(json.dumps(report, indent=2))
return 0 if overall_passed else 1
print("[1/3] DRM UAPI: kernel-open/nvidia-drm/nvidia_rs_drm.c vs stock nvidia-drm-ioctl.h")
for entry in drm_res["ioctls"]:
tag = "PASS" if entry["passed"] else "FAIL"
st_desc = (
f"sizeof({entry['struct_name']})={entry['struct_size']} ({entry['field_count']} fields)"
if entry["struct_name"]
else "DRM_IO (no payload struct)"
)
print(
f" [{tag}] {entry['name']:<44} cmd=0x{entry['cmd_index']:02x} "
f"ioctl=0x{entry['ioctl_nr']:08x} {st_desc}"
)
for helper in drm_res["helper_structs"]:
tag = "PASS" if helper["passed"] else "FAIL"
print(
f" [{tag}] helper struct {helper['struct_name']:<30} "
f"sizeof={helper['struct_size']} ({helper['field_count']} fields)"
)
for const in drm_res["constants"]:
tag = "PASS" if const["passed"] else "FAIL"
print(f" [{tag}] constant {const['name']:<35} value=0x{const['value']:x}")
if drm_res["diffs"]:
print(" DIFFS:", json.dumps(drm_res["diffs"], indent=2))
print("\n[2/3] NVKMS ioctl ABI: kernel-open/nvidia-modeset/nv_rs_kms_abi.h vs stock nvkms-ioctl.h")
tag = "PASS" if nvkms_res["passed"] else "FAIL"
field_summary = ", ".join(
f"{k}@{nvkms_res['fields'][k]['offset']}(sz={nvkms_res['fields'][k]['size']})"
for k in NVKMS_IOCTL_FIELDS
)
print(
f" [{tag}] NV_RS_NVKMS_IOCTL_IOWR == NVKMS_IOCTL_IOWR "
f"(0x{nvkms_res['ioctl_iowr']:08x}) sizeof={nvkms_res['struct_size']} "
f"align={nvkms_res['struct_align']} [{field_summary}]"
)
if nvkms_res["diffs"]:
print(" DIFFS:", json.dumps(nvkms_res["diffs"], indent=2))
print("\n[3/3] KAPI C/Rust ABI: nv_rs_kms_abi.h struct nv_rs_kms_gpu_caps vs modeset_ffi.rs NvRsKmsGpuCaps")
tag = "PASS" if caps_res["passed"] else "FAIL"
print(
f" [{tag}] struct nv_rs_kms_gpu_caps == #[repr(C)] NvRsKmsGpuCaps "
f"sizeof={caps_res['struct_size']} align={caps_res['struct_align']} "
f"({caps_res['field_count']} fields exact offset & size parity)"
)
if caps_res["diffs"]:
print(" DIFFS:", json.dumps(caps_res["diffs"], indent=2))
total_drm_fields = sum(e["field_count"] for e in drm_res["ioctls"]) + sum(
h["field_count"] for h in drm_res["helper_structs"]
)
print(
f"\nSUMMARY: {'PASS' if overall_passed else 'FAIL'} "
f"(24/24 DRM ioctls, {total_drm_fields} DRM fields, "
f"NVKMS ioctl + 3 fields, NvRsKmsGpuCaps + {caps_res['field_count']} C/Rust fields)"
)
return 0 if overall_passed else 1
if __name__ == "__main__":
sys.exit(main())