tools: add stdlib ELF64 fallback for check_native_shader and make ABI/RAMIN oracles portable

This commit is contained in:
morebrackets
2026-12-02 04:31:35 -08:00
parent db720ba4a6
commit 9c8f10b63c
6 changed files with 643 additions and 121 deletions

View File

@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Offline tests for check_native_shader, check_system_memory_abi,
check_ramin_oracle, check_root_migration_oracle, and generate_abi.
"""
import contextlib
import importlib.util
import io
import os
from pathlib import Path
import shutil
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
def _load(name: str, rel: str):
spec = importlib.util.spec_from_file_location(name, ROOT / rel)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
return mod
class NativeShaderAndAbiToolsTest(unittest.TestCase):
def test_native_shader_fallback_elf_parser_detects_tampered_embedded_binary(self):
mod = _load("check_native_shader", "tools/check_native_shader.py")
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
checkpoint = Path("reports/checkpoints/native-hello-baseline-2da2fe783377")
for rel in (
checkpoint / "reports/native-hello-original-580/validation.json",
checkpoint / "target/hardware-hello/native_hello.sm70.cubin",
Path("tests/hardware/native_hello.cu"),
Path("src/nvidia/src/compute/native_hello_sm70.bin"),
):
dst = root / rel
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / rel, dst)
with (
mock.patch.object(mod, "ROOT", root),
mock.patch.object(mod, "BASELINE", root / checkpoint),
contextlib.redirect_stdout(io.StringIO()),
):
# Real cubin passes via stdlib ELF64 fallback even under python3 -O.
mod.main()
# Corrupting the embedded binary must fail even under python3 -O.
emb = root / "src/nvidia/src/compute/native_hello_sm70.bin"
data = bytearray(emb.read_bytes())
data[0] ^= 0xFF
emb.write_bytes(bytes(data))
with self.assertRaisesRegex(SystemExit, "differs from baseline cubin"):
mod.main()
def test_system_memory_abi_portable_discovery(self):
mod = _load("check_system_memory_abi", "tools/check_system_memory_abi.py")
with tempfile.TemporaryDirectory() as tmp:
sdk_inc = Path(tmp) / "src/common/sdk/nvidia/inc"
sdk_inc.mkdir(parents=True)
(sdk_inc / "nvos.h").write_text("/* stub */\n", encoding="utf-8")
with mock.patch.dict(os.environ, {"NV_RS_OPEN_GPU_SRC": tmp}, clear=True):
self.assertEqual(mod.find_sdk_include_dir(), sdk_inc)
missing = str(Path(tmp) / "missing")
with mock.patch.dict(
os.environ,
{"NV_RS_OPEN_GPU_SRC": missing, "NV_RS_ANALYSIS_ROOT": missing},
clear=True,
):
with self.assertRaisesRegex(SystemExit, "nvos.h"):
mod.find_sdk_include_dir()
def test_ramin_and_root_migration_portable_discovery(self):
ramin = _load("check_ramin_oracle", "tools/check_ramin_oracle.py")
root_mig = _load("check_root_migration_oracle", "tools/check_root_migration_oracle.py")
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "src"
for rel in list(ramin.REQUIRED_REL) + [root_mig.VASPACE_REL]:
p = src / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("", encoding="utf-8")
with mock.patch.dict(os.environ, {"NV_RS_OPEN_GPU_SRC": tmp}, clear=True):
self.assertEqual(ramin.find_open_gpu_src(), src)
self.assertEqual(root_mig.find_gpu_vaspace_source(), src / root_mig.VASPACE_REL)
missing = str(Path(tmp) / "missing")
with mock.patch.dict(
os.environ,
{"NV_RS_OPEN_GPU_SRC": missing, "NV_RS_ANALYSIS_ROOT": missing},
clear=True,
):
with self.assertRaisesRegex(SystemExit, "RAMIN sources"):
ramin.find_open_gpu_src()
with self.assertRaisesRegex(SystemExit, "gpu_vaspace.c"):
root_mig.find_gpu_vaspace_source()
def test_generate_abi_portable_rustfmt_resolution(self):
mod = _load("generate_abi", "tools/generate_abi.py")
with mock.patch.dict(os.environ, {"RUSTFMT": "/custom/rustfmt"}, clear=True):
self.assertEqual(mod.find_rustfmt(), "/custom/rustfmt")
with tempfile.TemporaryDirectory() as tmp:
fake = Path(tmp) / "bin/rustfmt"
fake.parent.mkdir(parents=True)
fake.write_text("", encoding="utf-8")
with (
mock.patch.dict(os.environ, {"CARGO_HOME": tmp}, clear=True),
mock.patch.object(shutil, "which", return_value=None),
):
self.assertEqual(mod.find_rustfmt(), str(fake))
if __name__ == "__main__":
unittest.main()

View File

@ -3,24 +3,93 @@
import hashlib
import json
from pathlib import Path, PurePosixPath
from elftools.elf.elffile import ELFFile
import struct
ROOT = Path(__file__).resolve().parents[1]
BASELINE = ROOT / 'reports/checkpoints/native-hello-baseline-2da2fe783377'
cubin = BASELINE / 'target/hardware-hello/native_hello.sm70.cubin'
expected = '2da2fe78337788e5c8103837255d3dd79fe248ae26a3d4f51b5f3e6e05ccb7ac'
assert hashlib.sha256(cubin.read_bytes()).hexdigest() == expected
record = json.loads((BASELINE / 'reports/native-hello-original-580/validation.json').read_text())
if record['passed'] is not True or record['pci_driver_before'] != 'nvidia':
raise SystemExit('archived original-driver validation did not pass')
if not record['runs'] or any(
run['observed']['passed'] is not True or run['observed']['verified_words'] != 64
for run in record['runs']
):
raise SystemExit('archived original-driver runs are missing or incomplete')
EXPECTED_CUBIN_SHA256 = '2da2fe78337788e5c8103837255d3dd79fe248ae26a3d4f51b5f3e6e05ccb7ac'
def recorded_digest(relative_path):
class _FallbackSection(dict):
def __init__(self, name, data_bytes, **fields):
super().__init__(**fields)
self.name = name
self._data = data_bytes
def data(self):
return self._data
class _FallbackELFFile:
"""Minimal stdlib ELF64 little-endian section reader used when pyelftools is absent."""
def __init__(self, stream):
raw = stream.read()
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
raise SystemExit('cubin is not a valid 64-bit little-endian ELF file')
e_shoff, = struct.unpack_from('<Q', raw, 40)
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
if e_shoff == 0 or e_shentsize < 64 or e_shnum == 0 or e_shstrndx >= e_shnum:
raise SystemExit('cubin ELF section header table is missing or malformed')
table_end = e_shoff + e_shentsize * e_shnum
if table_end > len(raw):
raise SystemExit('cubin ELF section header table exceeds file size')
headers = []
for idx in range(e_shnum):
off = e_shoff + idx * e_shentsize
sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize = (
struct.unpack_from('<IIQQQQIIQQ', raw, off)
)
headers.append((sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize))
str_hdr = headers[e_shstrndx]
str_off, str_size = str_hdr[4], str_hdr[5]
if str_off + str_size > len(raw):
raise SystemExit('cubin ELF section string table exceeds file size')
shstrtab = raw[str_off:str_off + str_size]
self._sections = []
self._by_name = {}
for sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize in headers:
nul = shstrtab.find(b'\x00', sh_name)
name = shstrtab[sh_name:nul if nul != -1 else len(shstrtab)].decode('utf-8', errors='replace')
if sh_type != 8 and sh_offset + sh_size > len(raw):
raise SystemExit(f'cubin ELF section {name!r} exceeds file size')
payload = b'' if sh_type == 8 else raw[sh_offset:sh_offset + sh_size]
sec = _FallbackSection(
name,
payload,
sh_name=sh_name,
sh_type=sh_type,
sh_flags=sh_flags,
sh_addr=sh_addr,
sh_offset=sh_offset,
sh_size=sh_size,
sh_link=sh_link,
sh_info=sh_info,
sh_addralign=sh_addralign,
sh_entsize=sh_entsize,
)
self._sections.append(sec)
self._by_name[name] = sec
def get_section_by_name(self, name):
return self._by_name.get(name)
def iter_sections(self):
return iter(self._sections)
def _open_elf(stream):
try:
from elftools.elf.elffile import ELFFile
except ImportError:
return _FallbackELFFile(stream)
return ELFFile(stream)
def recorded_digest(record, relative_path):
# The original archive stored absolute paths on its evidence host.
expected_suffix = PurePosixPath(relative_path).parts
matches = [
@ -32,27 +101,68 @@ def recorded_digest(relative_path):
return matches[0]
cubin_path = cubin.relative_to(BASELINE).as_posix()
if recorded_digest(cubin_path) != expected:
raise SystemExit('archived validation identifies a different cubin')
source_path = 'tests/hardware/native_hello.cu'
source = ROOT / source_path
if hashlib.sha256(source.read_bytes()).hexdigest() != recorded_digest(source_path):
raise SystemExit('native shader source differs from archived validation')
with cubin.open('rb') as stream:
elf = ELFFile(stream)
text = elf.get_section_by_name('.text.native_hello')
code = text.data()
assert len(code) == 256 and text['sh_addralign'] == 128
assert text['sh_info'] >> 24 == 8
constant = elf.get_section_by_name('.nv.constant0.native_hello').data()
assert len(constant) == 368 and not any(constant)
assert not any(section.name.startswith(('.rel.text.native_hello', '.rela.text.native_hello')) for section in elf.iter_sections())
embedded = ROOT / 'src/nvidia/src/compute/native_hello_sm70.bin'
assert embedded.read_bytes() == code
result = {'passed': True, 'baseline_cubin_sha256': expected,
'code_sha256': hashlib.sha256(code).hexdigest(),
'code_bytes': len(code), 'constant0_bytes': len(constant), 'registers': 8,
'scope': 'Exact shader bytes from recorded original-driver execution. No replacement QMD, firmware, initialization or physical GPU execution is established by this check.'}
(ROOT / 'reports/native-shader-baseline-check.json').write_text(json.dumps(result, indent=2) + '\n')
print(json.dumps(result))
def main():
cubin = BASELINE / 'target/hardware-hello/native_hello.sm70.cubin'
expected = EXPECTED_CUBIN_SHA256
actual_cubin_sha = hashlib.sha256(cubin.read_bytes()).hexdigest()
if actual_cubin_sha != expected:
raise SystemExit(f'baseline cubin sha256 mismatch: {actual_cubin_sha} != {expected}')
record = json.loads((BASELINE / 'reports/native-hello-original-580/validation.json').read_text(encoding='utf-8'))
if record['passed'] is not True or record['pci_driver_before'] != 'nvidia':
raise SystemExit('archived original-driver validation did not pass')
if not record['runs'] or any(
run['observed']['passed'] is not True or run['observed']['verified_words'] != 64
for run in record['runs']
):
raise SystemExit('archived original-driver runs are missing or incomplete')
cubin_path = cubin.relative_to(BASELINE).as_posix()
if recorded_digest(record, cubin_path) != expected:
raise SystemExit('archived validation identifies a different cubin')
source_path = 'tests/hardware/native_hello.cu'
source = ROOT / source_path
if hashlib.sha256(source.read_bytes()).hexdigest() != recorded_digest(record, source_path):
raise SystemExit('native shader source differs from archived validation')
with cubin.open('rb') as stream:
elf = _open_elf(stream)
text = elf.get_section_by_name('.text.native_hello')
if text is None:
raise SystemExit('missing .text.native_hello section in baseline cubin')
code = text.data()
if len(code) != 256 or text['sh_addralign'] != 128:
raise SystemExit(
f'unexpected .text.native_hello size/alignment: len={len(code)} align={text["sh_addralign"]}'
)
if (text['sh_info'] >> 24) != 8:
raise SystemExit(f'unexpected .text.native_hello register count: {text["sh_info"] >> 24}')
const_sec = elf.get_section_by_name('.nv.constant0.native_hello')
if const_sec is None:
raise SystemExit('missing .nv.constant0.native_hello section in baseline cubin')
constant = const_sec.data()
if len(constant) != 368 or any(constant):
raise SystemExit(f'unexpected .nv.constant0.native_hello contents (len={len(constant)})')
if any(section.name.startswith(('.rel.text.native_hello', '.rela.text.native_hello')) for section in elf.iter_sections()):
raise SystemExit('unexpected relocation sections for .text.native_hello')
embedded = ROOT / 'src/nvidia/src/compute/native_hello_sm70.bin'
if embedded.read_bytes() != code:
raise SystemExit('embedded native_hello_sm70.bin differs from baseline cubin .text.native_hello')
result = {
'passed': True,
'baseline_cubin_sha256': expected,
'code_sha256': hashlib.sha256(code).hexdigest(),
'code_bytes': len(code),
'constant0_bytes': len(constant),
'registers': 8,
'scope': 'Exact shader bytes from recorded original-driver execution. No replacement QMD, firmware, initialization or physical GPU execution is established by this check.',
}
out = ROOT / 'reports/native-shader-baseline-check.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
print(json.dumps(result))
if __name__ == '__main__':
main()

View File

@ -1,14 +1,54 @@
#!/usr/bin/env python3
"""Compile exact GP100/GV100 PDB HAL functions against their published RAMIN headers."""
import hashlib,json,subprocess,tempfile
import hashlib
import json
import os
from pathlib import Path
R=Path(__file__).resolve().parents[1];S=Path('/home/geodd/nvidia-driver/analysis-580.178.04/reference/open-gpu-kernel-modules-580.178.04/src')
GP=S/'nvidia/src/kernel/gpu/mmu/arch/pascal/kern_gmmu_gp100.c';GV=S/'nvidia/src/kernel/gpu/mmu/arch/volta/kern_gmmu_gv100.c';HP=S/'common/inc/swref/published/pascal/gp100/dev_ram.h';HV=S/'common/inc/swref/published/volta/gv100/dev_ram.h'
def function(path,name):
text=path.read_text();start=text.rfind('NV_STATUS',0,text.index(name+'\n'));pos=text.index('{',start);level=1;end=pos+1
while level:level+=(text[end]=='{')-(text[end]=='}');end+=1
return text[start:end]
prefix=r'''
import subprocess
import tempfile
R = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
REQUIRED_REL = (
'nvidia/src/kernel/gpu/mmu/arch/pascal/kern_gmmu_gp100.c',
'nvidia/src/kernel/gpu/mmu/arch/volta/kern_gmmu_gv100.c',
'common/inc/swref/published/pascal/gp100/dev_ram.h',
'common/inc/swref/published/volta/gv100/dev_ram.h',
)
def find_open_gpu_src() -> Path:
candidates: list[Path] = []
for env_name in ('NV_RS_OPEN_GPU_SRC', 'OPEN_GPU_ROOT'):
val = os.environ.get(env_name)
if val:
base = Path(val)
candidates.extend([base / 'src', base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / 'reference/open-gpu-kernel-modules-580.178.04/src')
for candidate in candidates:
if all((candidate / rel).is_file() for rel in REQUIRED_REL):
return candidate
raise SystemExit(
'Cannot find open-gpu-kernel-modules-580.178.04 RAMIN sources. '
'Set NV_RS_OPEN_GPU_SRC (or OPEN_GPU_ROOT / NV_RS_ANALYSIS_ROOT).'
)
def function(path: Path, name: str) -> str:
text = path.read_text(encoding='utf-8')
start = text.rfind('NV_STATUS', 0, text.index(name + '\n'))
pos = text.index('{', start)
level = 1
end = pos + 1
while level:
level += (text[end] == '{') - (text[end] == '}')
end += 1
return text[start:end]
PREFIX_TEMPLATE = r'''
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
@ -53,13 +93,65 @@ static NvU64 memdescGetPhysAddr(MEMORY_DESCRIPTOR*m,int a,int b){(void)a;(void)b
static NvU32 kgmmuGetHwPteApertureFromMemdesc(KernelGmmu*g,MEMORY_DESCRIPTOR*m){(void)g;return m->aperture;}
static NvU32 memdescGetVolatility(MEMORY_DESCRIPTOR*m){return m->vol;}
static MEMORY_DESCRIPTOR*kfifoGetDummyPageMemDesc(KernelFifo*f){(void)f;return 0;}
'''.replace('GPHEADER',str(HP)).replace('GVHEADER',str(HV))
main=r'''
int main(void){NvU64 addresses[]={0,0x12345000ULL,0x12345678000ULL,0xfffffffffffff000ULL};NvU32 targets[]={UINT32_MAX,0,63};for(unsigned a=0;a<4;a++)for(unsigned ap=0;ap<4;ap++){if(ap==1)continue;for(unsigned vol=0;vol<2;vol++)for(unsigned replay=0;replay<2;replay++)for(unsigned ver=0;ver<2;ver++)for(unsigned big=0;big<2;big++)for(unsigned t=0;t<3;t++){MEMORY_DESCRIPTOR root={addresses[a],ap,vol};GMMU_FMT fmt={ver?2:1};OBJVASPACE v={&root,&fmt,big?65536:131072};OBJGPU gpu={0};KernelGmmu k={0};INST_BLK_INIT_PARAMS p={0,replay,0};NvU32 lo,lv,hi,hv;assert(kgmmuInstBlkPageDirBaseGet_GV100(&gpu,&k,&v,&p,targets[t],&lo,&lv,&hi,&hv)==0);printf("%llu %u %u %u %u %u %u %u %u %u %u\n",(unsigned long long)addresses[a],ap,vol,replay,ver,big,targets[t],lo,lv,hi,hv);}}}
'''
with tempfile.TemporaryDirectory() as t:
p=Path(t);(p/'oracle.c').write_text(prefix+function(GP,'kgmmuInstBlkPageDirBaseGet_GP100')+function(GV,'kgmmuInstBlkPageDirBaseGet_GV100')+main);subprocess.run(['cc','-std=c11','-Wall','-Werror','-O2',str(p/'oracle.c'),'-o',str(p/'oracle')],check=True);rows=subprocess.check_output([str(p/'oracle')],text=True).splitlines()
lines=['// Original exact580 GP100 base + GV100 subcontext HAL outputs.','pub type Vector = (u64,u8,bool,bool,bool,bool,u32,u32,u32,u32,u32);','#[rustfmt::skip]','pub const VECTORS: &[Vector] = &[']
for row in rows:
a,ap,vol,replay,ver,big,target,lo,lv,hi,hv=map(int,row.split());lines.append(f'({a},{ap},{str(bool(vol)).lower()},{str(bool(replay)).lower()},{str(bool(ver)).lower()},{str(bool(big)).lower()},{target},{lo},{lv},{hi},{hv}),')
lines.append('];');(R/'src/nvidia/src/mmu/ramin_oracle_vectors.rs').write_text('\n'.join(lines)+'\n');(R/'reports/ramin-oracle.json').write_text(json.dumps({'passed':True,'vectors':len(rows),'source_hashes':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [GP,GV,HP,HV]},'executed':'Original PDB HAL functions with descriptor/property lookup mocks; no driver/GPU execution'},indent=2)+'\n');print(len(rows),'original C RAMIN vectors')
MAIN_C = r'''
int main(void){NvU64 addresses[]={0,0x12345000ULL,0x12345678000ULL,0xfffffffffffff000ULL};NvU32 targets[]={UINT32_MAX,0,63};for(unsigned a=0;a<4;a++)for(unsigned ap=0;ap<4;ap++){if(ap==1)continue;for(unsigned vol=0;vol<2;vol++)for(unsigned replay=0;replay<2;replay++)for(unsigned ver=0;ver<2;ver++)for(unsigned big=0;big<2;big++)for(unsigned t=0;t<3;t++){MEMORY_DESCRIPTOR root={addresses[a],ap,vol};GMMU_FMT fmt={ver?2:1};OBJVASPACE v={&root,&fmt,big?65536:131072};OBJGPU gpu={0};KernelGmmu k={0};INST_BLK_INIT_PARAMS p={0,replay,0};NvU32 lo,lv,hi,hv;if(kgmmuInstBlkPageDirBaseGet_GV100(&gpu,&k,&v,&p,targets[t],&lo,&lv,&hi,&hv)!=0)return 1;printf("%llu %u %u %u %u %u %u %u %u %u %u\n",(unsigned long long)addresses[a],ap,vol,replay,ver,big,targets[t],lo,lv,hi,hv);}}return 0;}
'''
def main() -> None:
src = find_open_gpu_src()
gp = src / REQUIRED_REL[0]
gv = src / REQUIRED_REL[1]
hp = src / REQUIRED_REL[2]
hv = src / REQUIRED_REL[3]
prefix = PREFIX_TEMPLATE.replace('GPHEADER', str(hp)).replace('GVHEADER', str(hv))
with tempfile.TemporaryDirectory() as t:
p = Path(t)
(p / 'oracle.c').write_text(
prefix
+ function(gp, 'kgmmuInstBlkPageDirBaseGet_GP100')
+ function(gv, 'kgmmuInstBlkPageDirBaseGet_GV100')
+ MAIN_C,
encoding='utf-8',
)
subprocess.run(
['cc', '-std=c11', '-UNDEBUG', '-Wall', '-Werror', '-O2', str(p / 'oracle.c'), '-o', str(p / 'oracle')],
check=True,
)
rows = subprocess.check_output([str(p / 'oracle')], text=True).splitlines()
lines = [
'// Original exact580 GP100 base + GV100 subcontext HAL outputs.',
'pub type Vector = (u64,u8,bool,bool,bool,bool,u32,u32,u32,u32,u32);',
'#[rustfmt::skip]',
'pub const VECTORS: &[Vector] = &[',
]
for row in rows:
a, ap, vol, replay, ver, big, target, lo, lv, hi, hv_val = map(int, row.split())
lines.append(
f'({a},{ap},{str(bool(vol)).lower()},{str(bool(replay)).lower()},'
f'{str(bool(ver)).lower()},{str(bool(big)).lower()},{target},{lo},{lv},{hi},{hv_val}),'
)
lines.append('];')
(R / 'src/nvidia/src/mmu/ramin_oracle_vectors.rs').write_text('\n'.join(lines) + '\n', encoding='utf-8')
report = R / 'reports/ramin-oracle.json'
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(
json.dumps(
{
'passed': True,
'vectors': len(rows),
'source_hashes': {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in [gp, gv, hp, hv]},
'executed': 'Original PDB HAL functions with descriptor/property lookup mocks; no driver/GPU execution',
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
print(len(rows), 'original C RAMIN vectors')
if __name__ == '__main__':
main()

View File

@ -1,15 +1,47 @@
#!/usr/bin/env python3
"""Execute exact580 shared-root clipping callbacks with memory-only callback mocks."""
import hashlib,json,subprocess,tempfile
import hashlib
import json
import os
from pathlib import Path
R=Path(__file__).resolve().parents[1]
S=Path('/home/geodd/nvidia-driver/analysis-580.178.04/reference/open-gpu-kernel-modules-580.178.04/src/nvidia/src/kernel/mem_mgr/gpu_vaspace.c')
s=S.read_text()
def function(name):
start=s.rfind('static void',0,s.index(name+'\n'));pos=s.index('{',start);level=1;end=pos+1
while level:level+=(s[end]=='{')-(s[end]=='}');end+=1
return s[start:end]
prefix=r'''
import subprocess
import tempfile
R = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
VASPACE_REL = 'nvidia/src/kernel/mem_mgr/gpu_vaspace.c'
def find_gpu_vaspace_source() -> Path:
candidates: list[Path] = []
for env_name in ('NV_RS_OPEN_GPU_SRC', 'OPEN_GPU_ROOT'):
val = os.environ.get(env_name)
if val:
base = Path(val)
candidates.extend([base / 'src' / VASPACE_REL, base / VASPACE_REL, base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / 'reference/open-gpu-kernel-modules-580.178.04/src' / VASPACE_REL)
for candidate in candidates:
if candidate.is_file() and candidate.name == 'gpu_vaspace.c':
return candidate
raise SystemExit(
'Cannot find open-gpu-kernel-modules-580.178.04 gpu_vaspace.c. '
'Set NV_RS_OPEN_GPU_SRC (or OPEN_GPU_ROOT / NV_RS_ANALYSIS_ROOT).'
)
def function(text: str, name: str) -> str:
start = text.rfind('static void', 0, text.index(name + '\n'))
pos = text.index('{', start)
level = 1
end = pos + 1
while level:
level += (text[end] == '{') - (text[end] == '}')
end += 1
return text[start:end]
PREFIX = r'''
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
@ -28,13 +60,58 @@ static void fill(MMU_WALK_USER_CTX*c,const MMU_FMT_LEVEL*f,const MMU_WALK_MEMDES
static void copy(MMU_WALK_USER_CTX*c,const MMU_FMT_LEVEL*f,const MMU_WALK_MEMDESC*s,const MMU_WALK_MEMDESC*d,NvU32 lo,NvU32 hi,NvU32*p){(void)c;(void)f;for(unsigned i=lo;i<=hi;i++)((MMU_WALK_MEMDESC*)d)->data[i]=s->data[i];*p=hi-lo+1;}
static struct {void(*FillEntries)(MMU_WALK_USER_CTX*,const MMU_FMT_LEVEL*,const MMU_WALK_MEMDESC*,NvU32,NvU32,MMU_WALK_FILL_STATE,NvU32*);void(*CopyEntries)(MMU_WALK_USER_CTX*,const MMU_FMT_LEVEL*,const MMU_WALK_MEMDESC*,const MMU_WALK_MEMDESC*,NvU32,NvU32,NvU32*);}g_gmmuWalkCallbacks={fill,copy};
'''
main=r'''
int main(void){for(unsigned old=1;old<=4;old++)for(unsigned new=1;new<=4;new++)for(unsigned lo=0;lo<6;lo++)for(unsigned hi=lo;hi<6;hi++){OBJGVASPACE v={lo,hi};MMU_WALK_USER_CTX c={&v};MMU_FMT_LEVEL f={0};MMU_WALK_MEMDESC src={{11,12,13,14}},dst={{99,99,99,99}};NvU32 p=0;_gmmuWalkCBCopyEntries_SkipExternal(&c,&f,&src,&dst,0,(old<new?old:new)-1,&p);assert(p==(old<new?old:new));if(new>old){_gmmuWalkCBFillEntries_SkipExternal(&c,&f,&dst,old,new-1,0,&p);assert(p==new-old);}printf("%u %u %u %u",old,new,lo,hi);for(unsigned i=0;i<new;i++)printf(" %llu",(unsigned long long)dst.data[i]);puts("");}}
MAIN_C = r'''
int main(void){for(unsigned old=1;old<=4;old++)for(unsigned new=1;new<=4;new++)for(unsigned lo=0;lo<6;lo++)for(unsigned hi=lo;hi<6;hi++){OBJGVASPACE v={lo,hi};MMU_WALK_USER_CTX c={&v};MMU_FMT_LEVEL f={0};MMU_WALK_MEMDESC src={{11,12,13,14}},dst={{99,99,99,99}};NvU32 p=0;_gmmuWalkCBCopyEntries_SkipExternal(&c,&f,&src,&dst,0,(old<new?old:new)-1,&p);if(p!=(old<new?old:new))return 1;if(new>old){_gmmuWalkCBFillEntries_SkipExternal(&c,&f,&dst,old,new-1,0,&p);if(p!=new-old)return 1;}printf("%u %u %u %u",old,new,lo,hi);for(unsigned i=0;i<new;i++)printf(" %llu",(unsigned long long)dst.data[i]);puts("");}return 0;}
'''
with tempfile.TemporaryDirectory() as t:
p=Path(t);(p/'oracle.c').write_text(prefix+function('_gmmuWalkCBFillEntries_SkipExternal')+function('_gmmuWalkCBCopyEntries_SkipExternal')+main);subprocess.run(['cc','-std=c11','-Wall','-Werror','-O2',str(p/'oracle.c'),'-o',str(p/'oracle')],check=True);rows=subprocess.check_output([str(p/'oracle')],text=True).splitlines()
lines=['// Exact580 original shared-root callback clipping with memory-only normal callbacks.','pub type Vector = (u32,u32,u32,u32,&\'static [u64]);','#[rustfmt::skip]','pub const VECTORS: &[Vector] = &[']
for row in rows:
old,new,lo,hi,*data=map(int,row.split());lines.append(f'({old},{new},{lo},{hi},&{data}),')
lines.append('];');(R/'src/nvidia/src/mmu/root_migration_oracle_vectors.rs').write_text('\n'.join(lines)+'\n')
(R/'reports/root-migration-oracle.json').write_text(json.dumps({'passed':True,'vectors':len(rows),'source':str(S),'sha256':hashlib.sha256(S.read_bytes()).hexdigest(),'executed':'Original two SkipExternal callbacks with normal memory-only copy/fill callback mocks; no driver/GPU execution'},indent=2)+'\n');print(len(rows),'actual C root-copy vectors')
def main() -> None:
source_path = find_gpu_vaspace_source()
s = source_path.read_text(encoding='utf-8')
with tempfile.TemporaryDirectory() as t:
p = Path(t)
(p / 'oracle.c').write_text(
PREFIX
+ function(s, '_gmmuWalkCBFillEntries_SkipExternal')
+ function(s, '_gmmuWalkCBCopyEntries_SkipExternal')
+ MAIN_C,
encoding='utf-8',
)
subprocess.run(
['cc', '-std=c11', '-UNDEBUG', '-Wall', '-Werror', '-O2', str(p / 'oracle.c'), '-o', str(p / 'oracle')],
check=True,
)
rows = subprocess.check_output([str(p / 'oracle')], text=True).splitlines()
lines = [
'// Exact580 original shared-root callback clipping with memory-only normal callbacks.',
'pub type Vector = (u32,u32,u32,u32,&\'static [u64]);',
'#[rustfmt::skip]',
'pub const VECTORS: &[Vector] = &[',
]
for row in rows:
old, new, lo, hi, *data = map(int, row.split())
lines.append(f'({old},{new},{lo},{hi},&{data}),')
lines.append('];')
(R / 'src/nvidia/src/mmu/root_migration_oracle_vectors.rs').write_text('\n'.join(lines) + '\n', encoding='utf-8')
report = R / 'reports/root-migration-oracle.json'
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(
json.dumps(
{
'passed': True,
'vectors': len(rows),
'source': str(source_path),
'sha256': hashlib.sha256(source_path.read_bytes()).hexdigest(),
'executed': 'Original two SkipExternal callbacks with normal memory-only copy/fill callback mocks; no driver/GPU execution',
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
print(len(rows), 'actual C root-copy vectors')
if __name__ == '__main__':
main()

View File

@ -1,29 +1,69 @@
#!/usr/bin/env python3
"""Compile exact shipped NV_MEMORY_ALLOCATION_PARAMS ABI assertions."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
INC = Path('/home/geodd/nvidia-driver/analysis-580.178.04/reference/open-gpu-kernel-modules-580.178.04/src/common/sdk/nvidia/inc')
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
FIELDS = {'owner': 0, 'type': 4, 'flags': 8, 'width': 12, 'height': 16,
'pitch': 20, 'attr': 24, 'attr2': 28, 'format': 32, 'comprCovg': 36,
'zcullCovg': 40, 'rangeLo': 48, 'rangeHi': 56, 'size': 64,
'alignment': 72, 'offset': 80, 'limit': 88, 'address': 96,
'ctagOffset': 104, 'hVASpace': 108, 'internalflags': 112,
'tag': 116, 'numaNode': 120}
source = '#include <stddef.h>\n#include "nvos.h"\n'
source += '_Static_assert(sizeof(NV_MEMORY_ALLOCATION_PARAMS)==128,"size");\n'
source += ''.join(f'_Static_assert(offsetof(NV_MEMORY_ALLOCATION_PARAMS,{field})=={offset},"{field}");\n' for field, offset in FIELDS.items())
results = []
with tempfile.TemporaryDirectory(prefix='nv-rs-sysmem-abi-') as directory:
cfile = Path(directory) / 'layout.c'
cfile.write_text(source)
for abi, flag in [('x86_64', '-m64'), ('i386', '-m32')]:
command = ['cc', flag, '-std=c11', '-Wall', '-Wextra', '-Werror', '-I', str(INC), '-c', str(cfile), '-o', str(Path(directory) / (abi + '.o'))]
subprocess.run(command, check=True, capture_output=True, text=True)
results.append({'abi': abi, 'status': 'passed'})
report = {'header': str(INC / 'nvos.h'), 'size': 128, 'offsets': FIELDS, 'compiler_checks': results}
(ROOT / 'reports/system-memory-abi.json').write_text(json.dumps(report, indent=2) + '\n')
print('NV_MEMORY_ALLOCATION_PARAMS: native and i386 layouts passed')
def find_sdk_include_dir() -> Path:
candidates: list[Path] = []
for env_name in ('NV_RS_OPEN_GPU_SRC', 'OPEN_GPU_ROOT'):
val = os.environ.get(env_name)
if val:
base = Path(val)
candidates.extend([
base / 'src/common/sdk/nvidia/inc',
base / 'common/sdk/nvidia/inc',
base,
])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / 'reference/open-gpu-kernel-modules-580.178.04/src/common/sdk/nvidia/inc')
for candidate in candidates:
if (candidate / 'nvos.h').is_file():
return candidate
raise SystemExit(
'Cannot find 580.178.04 SDK header nvos.h. '
'Set NV_RS_OPEN_GPU_SRC (or OPEN_GPU_ROOT / NV_RS_ANALYSIS_ROOT) to an '
'open-gpu-kernel-modules-580.178.04 checkout.'
)
def main() -> None:
inc = find_sdk_include_dir()
source = '#include <stddef.h>\n#include "nvos.h"\n'
source += '_Static_assert(sizeof(NV_MEMORY_ALLOCATION_PARAMS)==128,"size");\n'
source += ''.join(
f'_Static_assert(offsetof(NV_MEMORY_ALLOCATION_PARAMS,{field})=={offset},"{field}");\n'
for field, offset in FIELDS.items()
)
results = []
with tempfile.TemporaryDirectory(prefix='nv-rs-sysmem-abi-') as directory:
cfile = Path(directory) / 'layout.c'
cfile.write_text(source, encoding='utf-8')
for abi, flag in [('x86_64', '-m64'), ('i386', '-m32')]:
command = [
'cc', flag, '-std=c11', '-Wall', '-Wextra', '-Werror',
'-I', str(inc), '-c', str(cfile), '-o', str(Path(directory) / (abi + '.o')),
]
subprocess.run(command, check=True, capture_output=True, text=True)
results.append({'abi': abi, 'status': 'passed'})
report = {'header': str(inc / 'nvos.h'), 'size': 128, 'offsets': FIELDS, 'compiler_checks': results}
out = ROOT / 'reports/system-memory-abi.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('NV_MEMORY_ALLOCATION_PARAMS: native and i386 layouts passed')
if __name__ == '__main__':
main()

View File

@ -1,11 +1,34 @@
#!/usr/bin/env python3
"""Generate safe byte codecs; layout oracle remains independent C evidence."""
import os
from pathlib import Path
p=Path(__file__).resolve().parents[1]/'src/common/abi/src/lib.rs'
import re
import shutil
import subprocess
ROOT = Path(__file__).resolve().parents[1]
TARGET = ROOT / 'src/common/abi/src/lib.rs'
# field name, Rust type, wire offset. u8 flags deliberately preserve unknown values.
S=[('PciInfo',12,[('domain','u32',0),('bus','u8',4),('slot','u8',5),('function','u8',6),('vendor_id','u16',8),('device_id','u16',10)]),('IoctlXfer',16,[('cmd','u32',0),('size','u32',4),('ptr','u64',8)]),('CardInfo',72,[('valid','u8',0),('pci_info','PciInfo',4),('gpu_id','u32',16),('interrupt_line','u16',20),('reg_address','u64',24),('reg_size','u64',32),('fb_address','u64',40),('fb_size','u64',48),('minor_number','u32',56),('dev_name','[u8; 10]',60)]),('AllocOsEvent',16,[('h_client','u32',0),('h_device','u32',4),('fd','u32',8),('status','u32',12)]),('FreeOsEvent',16,[('h_client','u32',0),('h_device','u32',4),('fd','u32',8),('status','u32',12)]),('StatusCode',12,[('domain','u32',0),('bus','u8',4),('slot','u8',5),('status','u32',8)]),('RmApiVersion',72,[('cmd','u32',0),('reply','u32',4),('version_string','[u8; 64]',8)]),('QueryDeviceIntr',8,[('intr_status','u32',0),('status','u32',4)]),('SysParams',8,[('memblock_size','u64',0)]),('RegisterFd',4,[('ctl_fd','i32',0)]),('ExportDmaBuf',2608,[('fd','i32',0),('h_client','u32',4),('total_objects','u32',8),('num_objects','u32',12),('index','u32',16),('total_size','u64',24),('mapping_type','u8',32),('allow_mmap','u8',33),('handles','[u32; 128]',36),('offsets','[u64; 128]',552),('sizes','[u64; 128]',1576),('status','u32',2600)]),('WaitOpenComplete',8,[('rc','i32',0),('adapter_status','u32',4)]),('RmControl',32,[('h_client','u32',0),('h_object','u32',4),('cmd','u32',8),('flags','u32',12),('params','u64',16),('params_size','u32',24),('status','u32',28)]),('RmAlloc',48,[('h_root','u32',0),('h_parent','u32',4),('h_new','u32',8),('class','u32',12),('params','u64',16),('rights','u64',24),('params_size','u32',32),('flags','u32',36),('status','u32',40)])]
S.append(('RmFree',16,[('h_root','u32',0),('h_parent','u32',4),('h_object','u32',8),('status','u32',12)]))
head='''//! NVIDIA 580.178.04 native x86_64 wire layouts. Generated by tools/generate_abi.py.
S = [
('PciInfo', 12, [('domain', 'u32', 0), ('bus', 'u8', 4), ('slot', 'u8', 5), ('function', 'u8', 6), ('vendor_id', 'u16', 8), ('device_id', 'u16', 10)]),
('IoctlXfer', 16, [('cmd', 'u32', 0), ('size', 'u32', 4), ('ptr', 'u64', 8)]),
('CardInfo', 72, [('valid', 'u8', 0), ('pci_info', 'PciInfo', 4), ('gpu_id', 'u32', 16), ('interrupt_line', 'u16', 20), ('reg_address', 'u64', 24), ('reg_size', 'u64', 32), ('fb_address', 'u64', 40), ('fb_size', 'u64', 48), ('minor_number', 'u32', 56), ('dev_name', '[u8; 10]', 60)]),
('AllocOsEvent', 16, [('h_client', 'u32', 0), ('h_device', 'u32', 4), ('fd', 'u32', 8), ('status', 'u32', 12)]),
('FreeOsEvent', 16, [('h_client', 'u32', 0), ('h_device', 'u32', 4), ('fd', 'u32', 8), ('status', 'u32', 12)]),
('StatusCode', 12, [('domain', 'u32', 0), ('bus', 'u8', 4), ('slot', 'u8', 5), ('status', 'u32', 8)]),
('RmApiVersion', 72, [('cmd', 'u32', 0), ('reply', 'u32', 4), ('version_string', '[u8; 64]', 8)]),
('QueryDeviceIntr', 8, [('intr_status', 'u32', 0), ('status', 'u32', 4)]),
('SysParams', 8, [('memblock_size', 'u64', 0)]),
('RegisterFd', 4, [('ctl_fd', 'i32', 0)]),
('ExportDmaBuf', 2608, [('fd', 'i32', 0), ('h_client', 'u32', 4), ('total_objects', 'u32', 8), ('num_objects', 'u32', 12), ('index', 'u32', 16), ('total_size', 'u64', 24), ('mapping_type', 'u8', 32), ('allow_mmap', 'u8', 33), ('handles', '[u32; 128]', 36), ('offsets', '[u64; 128]', 552), ('sizes', '[u64; 128]', 1576), ('status', 'u32', 2600)]),
('WaitOpenComplete', 8, [('rc', 'i32', 0), ('adapter_status', 'u32', 4)]),
('RmControl', 32, [('h_client', 'u32', 0), ('h_object', 'u32', 4), ('cmd', 'u32', 8), ('flags', 'u32', 12), ('params', 'u64', 16), ('params_size', 'u32', 24), ('status', 'u32', 28)]),
('RmAlloc', 48, [('h_root', 'u32', 0), ('h_parent', 'u32', 4), ('h_new', 'u32', 8), ('class', 'u32', 12), ('params', 'u64', 16), ('rights', 'u64', 24), ('params_size', 'u32', 32), ('flags', 'u32', 36), ('status', 'u32', 40)]),
('RmFree', 16, [('h_root', 'u32', 0), ('h_parent', 'u32', 4), ('h_object', 'u32', 8), ('status', 'u32', 12)]),
]
HEAD = '''//! NVIDIA 580.178.04 native x86_64 wire layouts. Generated by tools/generate_abi.py.
//! Pointer-shaped fields are opaque integers. Codecs never access caller addresses.
#![no_std]
#![forbid(unsafe_code)]
@ -22,34 +45,99 @@ pub const RM_ALLOC_IOCTL: u32 = 0xc030462b;
pub const RM_FREE_IOCTL: u32 = 0xc0104629;
pub const DRIVER_VERSION: &[u8] = b"580.178.04";
'''
import re
size={'u8':1,'u16':2,'u32':4,'i32':4,'u64':8,'PciInfo':12}
code=[head]
for name,n,fields in S:
code+=['#[derive(Clone, Copy, Debug, PartialEq, Eq)]','#[repr(C)]',f'pub struct {name} {{']+[f' pub {f}: {t},'for f,t,o in fields]+['}',f'impl Wire for {name} {{',f'const SIZE: usize = {n};','fn decode(bytes: &[u8]) -> Result<Self, WireError> { check(bytes, Self::SIZE)?;']
for f,t,o in fields:
a=re.fullmatch(r'\[(\w+); (\d+)\]',t)
if a:
base,count=a[1],int(a[2]);w=size[base];code.append(f'let mut {f} = [0; {count}]; for (i, value) in {f}.iter_mut().enumerate() {{ *value = {base}::from_le_bytes(bytes[{o}+i*{w}..{o}+(i+1)*{w}].try_into().unwrap()); }}')
elif t=='PciInfo':code.append(f'let {f} = PciInfo::decode(&bytes[{o}..{o+12}])?;')
else:code.append(f'let {f} = {t}::from_le_bytes(bytes[{o}..{o+size[t]}].try_into().unwrap());')
code+=['Ok(Self {'+','.join(f for f,t,o in fields)+'})','}','fn encode(&self, bytes: &mut [u8]) -> Result<(), WireError> { check(bytes, Self::SIZE)?; bytes.fill(0);']
for f,t,o in fields:
a=re.fullmatch(r'\[(\w+); (\d+)\]',t)
if a:
w=size[a[1]];code.append(f'for (i,value) in self.{f}.iter().enumerate() {{ bytes[{o}+i*{w}..{o}+(i+1)*{w}].copy_from_slice(&value.to_le_bytes()); }}')
elif t=='PciInfo':code.append(f'self.{f}.encode(&mut bytes[{o}..{o+12}])?;')
else:code.append(f'bytes[{o}..{o+size[t]}].copy_from_slice(&self.{f}.to_le_bytes());')
code+=['Ok(())','}','}']
# Verify every C field offset independently fixed above, not merely total size.
code+=['#[cfg(test)] mod tests { use super::*; use core::mem::{size_of,align_of,offset_of};','#[test] fn native_layouts() {']
for name,n,fields in S:
code.append(f'assert_eq!(size_of::<{name}>(),{n});'); code.append(f'assert_eq!(align_of::<{name}>(),{8 if any(t=="u64" or t.startswith("[u64") for f,t,o in fields) else 4});')
for f,t,o in fields:code.append(f'assert_eq!(offset_of!({name},{f}),{o});')
code+=['}','#[test] fn malformed_lengths_and_roundtrip() {']
for name,n,fields in S:
code.append(f'assert!({name}::decode(&[0; {n-1}]).is_err()); let value={name}::decode(&[0xa5; {n}]).unwrap(); let mut out=[0;{n}]; value.encode(&mut out).unwrap(); assert_eq!({name}::decode(&out).unwrap(),value);')
code+=['}','}'];p.write_text(re.sub(r'\*1(?!\d)', '', '\n'.join(code))+'\n')
import subprocess
subprocess.run([str(Path.home()/".cargo/bin/rustfmt"),"--edition","2024",str(Path(__file__).resolve().parents[1]/"src/common/abi/src/lib.rs")],check=True)
SIZE = {'u8': 1, 'u16': 2, 'u32': 4, 'i32': 4, 'u64': 8, 'PciInfo': 12}
def find_rustfmt() -> str:
env_rustfmt = os.environ.get('RUSTFMT')
if env_rustfmt:
return env_rustfmt
which = shutil.which('rustfmt')
if which:
return which
candidates = []
cargo_home = os.environ.get('CARGO_HOME')
if cargo_home:
candidates.append(Path(cargo_home) / 'bin/rustfmt')
candidates.append(Path.home() / '.cargo/bin/rustfmt')
for candidate in candidates:
if candidate.is_file():
return str(candidate)
raise SystemExit('rustfmt not found; set RUSTFMT or add rustfmt to PATH')
def render_source() -> str:
code = [HEAD]
for name, n, fields in S:
code += [
'#[derive(Clone, Copy, Debug, PartialEq, Eq)]',
'#[repr(C)]',
f'pub struct {name} {{',
] + [f' pub {f}: {t},' for f, t, o in fields] + [
'}',
f'impl Wire for {name} {{',
f'const SIZE: usize = {n};',
'fn decode(bytes: &[u8]) -> Result<Self, WireError> { check(bytes, Self::SIZE)?;',
]
for f, t, o in fields:
a = re.fullmatch(r'\[(\w+); (\d+)\]', t)
if a:
base, count = a[1], int(a[2])
w = SIZE[base]
code.append(
f'let mut {f} = [0; {count}]; for (i, value) in {f}.iter_mut().enumerate() '
f'{{ *value = {base}::from_le_bytes(bytes[{o}+i*{w}..{o}+(i+1)*{w}].try_into().unwrap()); }}'
)
elif t == 'PciInfo':
code.append(f'let {f} = PciInfo::decode(&bytes[{o}..{o+12}])?;')
else:
code.append(f'let {f} = {t}::from_le_bytes(bytes[{o}..{o+SIZE[t]}].try_into().unwrap());')
code += [
'Ok(Self {' + ','.join(f for f, t, o in fields) + '})',
'}',
'fn encode(&self, bytes: &mut [u8]) -> Result<(), WireError> { check(bytes, Self::SIZE)?; bytes.fill(0);',
]
for f, t, o in fields:
a = re.fullmatch(r'\[(\w+); (\d+)\]', t)
if a:
w = SIZE[a[1]]
code.append(
f'for (i,value) in self.{f}.iter().enumerate() '
f'{{ bytes[{o}+i*{w}..{o}+(i+1)*{w}].copy_from_slice(&value.to_le_bytes()); }}'
)
elif t == 'PciInfo':
code.append(f'self.{f}.encode(&mut bytes[{o}..{o+12}])?;')
else:
code.append(f'bytes[{o}..{o+SIZE[t]}].copy_from_slice(&self.{f}.to_le_bytes());')
code += ['Ok(())', '}', '}']
# Verify every C field offset independently fixed above, not merely total size.
code += [
'#[cfg(test)] mod tests { use super::*; use core::mem::{size_of,align_of,offset_of};',
'#[test] fn native_layouts() {',
]
for name, n, fields in S:
code.append(f'assert_eq!(size_of::<{name}>(),{n});')
align = 8 if any(t == 'u64' or t.startswith('[u64') for f, t, o in fields) else 4
code.append(f'assert_eq!(align_of::<{name}>(),{align});')
for f, t, o in fields:
code.append(f'assert_eq!(offset_of!({name},{f}),{o});')
code += ['}', '#[test] fn malformed_lengths_and_roundtrip() {']
for name, n, fields in S:
code.append(
f'assert!({name}::decode(&[0; {n-1}]).is_err()); '
f'let value={name}::decode(&[0xa5; {n}]).unwrap(); '
f'let mut out=[0;{n}]; value.encode(&mut out).unwrap(); '
f'assert_eq!({name}::decode(&out).unwrap(),value);'
)
code += ['}', '}']
return re.sub(r'\*1(?!\d)', '', '\n'.join(code)) + '\n'
def main() -> None:
TARGET.write_text(render_source(), encoding='utf-8')
subprocess.run([find_rustfmt(), '--edition', '2024', str(TARGET)], check=True)
if __name__ == '__main__':
main()