tools: make trace, resource, policy, and class-db generators portable and -O-safe

This commit is contained in:
morebrackets
2026-12-02 04:48:56 -08:00
parent db720ba4a6
commit 32ed551507
7 changed files with 566 additions and 67 deletions

View File

@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Offline tests for generate_private_policy, generate_resources,
generate_rmapi_class_db, generate_software_control_replay,
generate_trace_fixtures, and generate_transport_trace.
"""
import contextlib
import importlib.util
import io
import json
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 TraceAndResourceGeneratorsTest(unittest.TestCase):
def test_all_six_generators_are_import_safe(self):
for rel in (
"tools/generate_private_policy.py",
"tools/generate_resources.py",
"tools/generate_rmapi_class_db.py",
"tools/generate_software_control_replay.py",
"tools/generate_trace_fixtures.py",
"tools/generate_transport_trace.py",
):
mod = _load(Path(rel).stem, rel)
self.assertTrue(callable(mod.main))
def test_rmapi_class_db_check_fails_under_O_and_rejects_bad_cli(self):
mod = _load("generate_rmapi_class_db", "tools/generate_rmapi_class_db.py")
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as ctx:
mod.main(["--bogus"])
self.assertEqual(ctx.exception.code, 2)
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp)
rec = t / "record.txt"
rec.write_text("header only\n", encoding="utf-8")
with self.assertRaisesRegex(SystemExit, "no 'descriptors ' line"):
mod.main(["--record", str(rec), "--check"])
rec.write_text("descriptors f:7ef3cb00 c3c0:d334df00\n", encoding="utf-8")
target = t / "class_db_gv100.rs"
target.write_text("// stale\n", encoding="utf-8")
with mock.patch.object(mod, "TARGET", target):
with self.assertRaisesRegex(SystemExit, "differs from the oracle record"):
mod.main(["--record", str(rec), "--check"])
with contextlib.redirect_stdout(io.StringIO()):
mod.main(["--record", str(rec)])
with contextlib.redirect_stdout(io.StringIO()):
mod.main(["--record", str(rec), "--check"])
def test_transport_trace_rejects_mismatched_lengths_under_O(self):
mod = _load("generate_transport_trace", "tools/generate_transport_trace.py")
with tempfile.TemporaryDirectory() as tmp:
bad = Path(tmp) / "bad.jsonl"
bad.write_text(
json.dumps({
"request": "0xc020462a",
"before": "0000",
"after": "00000000",
"params_before": "",
"params_after": "",
}) + "\n",
encoding="utf-8",
)
with self.assertRaisesRegex(SystemExit, "mismatched before/after lengths"):
mod.main(["--input", str(bad)])
def test_resources_rejects_wrong_count_under_O(self):
mod = _load("generate_resources", "tools/generate_resources.py")
with tempfile.TemporaryDirectory() as tmp:
bad = Path(tmp) / "res.json"
bad.write_text(json.dumps({"input_sha256": "0" * 64, "scope": "test", "resources": []}), encoding="utf-8")
with self.assertRaisesRegex(SystemExit, "expected 279"):
mod.main(["--input", str(bad)])
def test_portable_rustfmt_resolution(self):
for rel in (
"tools/generate_private_policy.py",
"tools/generate_resources.py",
"tools/generate_trace_fixtures.py",
):
mod = _load(Path(rel).stem, rel)
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

@ -1,9 +1,72 @@
#!/usr/bin/env python3
from pathlib import Path
"""Generate src/nvidia/src/controls/policy_data.rs from private-controls contracts."""
import argparse
import json
root=Path(__file__).resolve().parents[1];p=Path('/home/geodd/nvidia-driver/analysis-580.178.04/reports/deep-private-controls-contracts.json');j=json.loads(p.read_text())['control_20808159'];out=['// Original RM .data+0x40760:146 records. No runtime hardware coverage implied.','pub const POLICIES: [(u16,[u8;6]);146] = [']
for r in j['packed_policy_table']:out.append('('+r['pci_device_id']+',['+','.join(str(v)for v in bytes.fromhex(r['packed_policy_bytes']))+']),')
out+= ['];','pub const SELECTOR_BITS: [(usize,usize,u8);33] = [','(0,5,0),']+[f"({r['selector']},{r['packed_byte']},{r['bit']}),"for r in j['selector_map_partially_automated']]+['];'];(root/'src/nvidia/src/controls/policy_data.rs').write_text('\n'.join(out)+'\n')
import os
from pathlib import Path
import shutil
import subprocess
subprocess.run([str(Path.home()/".cargo/bin/rustfmt"),"--edition","2024",str(Path(__file__).resolve().parents[1]/"src/nvidia/src/controls/policy_data.rs")],check=True)
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
REPORT_REL = 'reports/deep-private-controls-contracts.json'
def find_input(explicit: Path | None = None) -> Path:
if explicit is not None:
if not explicit.is_file():
raise SystemExit(f'input file not found: {explicit}')
return explicit
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidate = analysis / REPORT_REL
if candidate.is_file():
return candidate
raise SystemExit(f'input file not found at {candidate}; pass --input or set NV_RS_ANALYSIS_ROOT')
def find_rustfmt() -> str:
if os.environ.get('RUSTFMT'):
return os.environ['RUSTFMT']
which = shutil.which('rustfmt')
if which:
return which
candidates = []
if os.environ.get('CARGO_HOME'):
candidates.append(Path(os.environ['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 main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', type=Path, default=None)
args = parser.parse_args(argv)
p = find_input(args.input)
j = json.loads(p.read_text(encoding='utf-8'))['control_20808159']
out = [
'// Original RM .data+0x40760:146 records. No runtime hardware coverage implied.',
'pub const POLICIES: [(u16,[u8;6]);146] = [',
]
for r in j['packed_policy_table']:
out.append('(' + r['pci_device_id'] + ',[' + ','.join(str(v) for v in bytes.fromhex(r['packed_policy_bytes'])) + ']),')
out += [
'];',
'pub const SELECTOR_BITS: [(usize,usize,u8);33] = [',
'(0,5,0),',
] + [
f"({r['selector']},{r['packed_byte']},{r['bit']}),"
for r in j['selector_map_partially_automated']
] + ['];']
target = ROOT / 'src/nvidia/src/controls/policy_data.rs'
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text('\n'.join(out) + '\n', encoding='utf-8')
subprocess.run([find_rustfmt(), '--edition', '2024', str(target)], check=True)
if __name__ == '__main__':
main()

View File

@ -1,13 +1,108 @@
#!/usr/bin/env python3
"""Export exact shipped resource descriptors; never infer live device support."""
import json,argparse
import argparse
import json
import os
from pathlib import Path
root=Path(__file__).resolve().parents[1];p=argparse.ArgumentParser();p.add_argument('--input',type=Path,default=Path('/home/geodd/nvidia-driver/analysis-580.178.04/reports/proprietary-all-resource-descriptors.json'));args=p.parse_args();j=json.loads(args.input.read_text());rows=j['resources'];assert len(rows)==279==len({r['external_class']for r in rows})
out=['// Generated by tools/generate_resources.py from exact 580.178.04 proprietary metadata.','// Input RM SHA256: '+j['input_sha256'],'use nv_rs_abi::NvStatus;','#[derive(Clone, Copy, Debug, PartialEq, Eq)]','pub struct ResourceDescriptor { pub class: u32, pub internal_class: u32, pub parameter_size: u32, pub required: bool, pub multi_instance: bool, pub any_parent: bool, pub flags: u32, pub free_priority: u32, pub required_rights_count: u32, pub parents: &\'static [u32], pub class_info_symbol: &\'static str }','pub static RESOURCES: [ResourceDescriptor; 279] = [']
for r in rows:
out.append('ResourceDescriptor {class:'+r['external_class']+', internal_class:'+r['internal_class']+', parameter_size:'+str(r['allocation_parameter_size'])+', required:'+str(r['required']).lower()+', multi_instance:'+str(r['multi_instance']).lower()+', any_parent:'+str(r['any_parent']).lower()+', flags:'+r['flags']+', free_priority:'+str(r['free_priority'])+', required_rights_count:'+str(r['required_rights_length'])+', parents:&['+','.join(r['parent_internal_classes'])+'], class_info_symbol:"'+r['class_info']['symbol']+'"},')
out+= ['];','pub fn lookup(class: u32) -> Option<&\'static ResourceDescriptor> { RESOURCES.iter().find(|r|r.class==class) }','/// Implicit allocation size, including the recovered optional-pointer policy.','pub fn parameter_size(class: u32, pointer_nonnull: bool) -> Result<u32,NvStatus> { let desc=lookup(class).ok_or(NvStatus::INVALID_CLASS)?; if desc.required && !pointer_nonnull {return Err(NvStatus::INVALID_ARGUMENT);} Ok(if desc.required || pointer_nonnull {desc.parameter_size} else {0}) }','#[cfg(test)] mod tests {use super::*;','#[test] fn known_legacy_sizes_and_null_policy() {assert_eq!(parameter_size(0xc3b5,true),Ok(8));assert_eq!(parameter_size(0xc3c0,true),Ok(16));assert_eq!(parameter_size(0xc3c0,false),Ok(0));assert_eq!(parameter_size(0xc36f,true),Ok(368));assert_eq!(parameter_size(0xc36f,false),Err(NvStatus::INVALID_ARGUMENT));assert_eq!(parameter_size(0xffffffff,true),Err(NvStatus::INVALID_CLASS));}','#[test] fn all_classes_unique() {for(i,a)in RESOURCES.iter().enumerate(){for b in &RESOURCES[i+1..]{assert_ne!(a.class,b.class);}}}','}']
(root/'src/nvidia/src/resources.rs').write_text('\n'.join(out)+'\n');(root/'reports/resource-metadata-provenance.json').write_text(json.dumps({'source':str(args.input),'source_sha256':j['input_sha256'],'record_count':len(rows),'scope':j['scope']},indent=2)+'\n')
import shutil
import subprocess
subprocess.run([str(Path.home()/".cargo/bin/rustfmt"),"--edition","2024",str(Path(__file__).resolve().parents[1]/"src/nvidia/src/resources.rs")],check=True)
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
REPORT_REL = 'reports/proprietary-all-resource-descriptors.json'
def find_input(explicit: Path | None = None) -> Path:
if explicit is not None:
if not explicit.is_file():
raise SystemExit(f'input file not found: {explicit}')
return explicit
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidate = analysis / REPORT_REL
if candidate.is_file():
return candidate
raise SystemExit(f'input file not found at {candidate}; pass --input or set NV_RS_ANALYSIS_ROOT')
def find_rustfmt() -> str:
if os.environ.get('RUSTFMT'):
return os.environ['RUSTFMT']
which = shutil.which('rustfmt')
if which:
return which
candidates = []
if os.environ.get('CARGO_HOME'):
candidates.append(Path(os.environ['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 main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', type=Path, default=None)
args = parser.parse_args(argv)
inp = find_input(args.input)
j = json.loads(inp.read_text(encoding='utf-8'))
rows = j['resources']
if len(rows) != 279 or len({r['external_class'] for r in rows}) != 279:
raise SystemExit(f'expected 279 unique resource descriptors, found {len(rows)}')
out = [
'// Generated by tools/generate_resources.py from exact 580.178.04 proprietary metadata.',
'// Input RM SHA256: ' + j['input_sha256'],
'use nv_rs_abi::NvStatus;',
'#[derive(Clone, Copy, Debug, PartialEq, Eq)]',
"pub struct ResourceDescriptor { pub class: u32, pub internal_class: u32, pub parameter_size: u32, pub required: bool, pub multi_instance: bool, pub any_parent: bool, pub flags: u32, pub free_priority: u32, pub required_rights_count: u32, pub parents: &'static [u32], pub class_info_symbol: &'static str }",
'pub static RESOURCES: [ResourceDescriptor; 279] = [',
]
for r in rows:
out.append(
'ResourceDescriptor {class:' + r['external_class']
+ ', internal_class:' + r['internal_class']
+ ', parameter_size:' + str(r['allocation_parameter_size'])
+ ', required:' + str(r['required']).lower()
+ ', multi_instance:' + str(r['multi_instance']).lower()
+ ', any_parent:' + str(r['any_parent']).lower()
+ ', flags:' + r['flags']
+ ', free_priority:' + str(r['free_priority'])
+ ', required_rights_count:' + str(r['required_rights_length'])
+ ', parents:&[' + ','.join(r['parent_internal_classes'])
+ '], class_info_symbol:"' + r['class_info']['symbol'] + '"},'
)
out += [
'];',
"pub fn lookup(class: u32) -> Option<&'static ResourceDescriptor> { RESOURCES.iter().find(|r|r.class==class) }",
'/// Implicit allocation size, including the recovered optional-pointer policy.',
'pub fn parameter_size(class: u32, pointer_nonnull: bool) -> Result<u32,NvStatus> { let desc=lookup(class).ok_or(NvStatus::INVALID_CLASS)?; if desc.required && !pointer_nonnull {return Err(NvStatus::INVALID_ARGUMENT);} Ok(if desc.required || pointer_nonnull {desc.parameter_size} else {0}) }',
'#[cfg(test)] mod tests {use super::*;',
'#[test] fn known_legacy_sizes_and_null_policy() {assert_eq!(parameter_size(0xc3b5,true),Ok(8));assert_eq!(parameter_size(0xc3c0,true),Ok(16));assert_eq!(parameter_size(0xc3c0,false),Ok(0));assert_eq!(parameter_size(0xc36f,true),Ok(368));assert_eq!(parameter_size(0xc36f,false),Err(NvStatus::INVALID_ARGUMENT));assert_eq!(parameter_size(0xffffffff,true),Err(NvStatus::INVALID_CLASS));}',
'#[test] fn all_classes_unique() {for(i,a)in RESOURCES.iter().enumerate(){for b in &RESOURCES[i+1..]{assert_ne!(a.class,b.class);}}}',
'}',
]
target = ROOT / 'src/nvidia/src/resources.rs'
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text('\n'.join(out) + '\n', encoding='utf-8')
report = ROOT / 'reports/resource-metadata-provenance.json'
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(
json.dumps(
{
'source': str(inp),
'source_sha256': j['input_sha256'],
'record_count': len(rows),
'scope': j['scope'],
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
subprocess.run([find_rustfmt(), '--edition', '2024', str(target)], check=True)
if __name__ == '__main__':
main()

View File

@ -7,28 +7,49 @@ attach: the class descriptor list its engine-table constructor built for a GV100
count GPU+0xd98; public gpuConstructEngineTable: generic classes, the chip's engine-less
classes, then the chip's class-to-engine list). `--check` verifies the checked-in file.
"""
import argparse
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
RECORD = ROOT / "target/rmapi/original-rmapi-gpu.txt"
TARGET = ROOT / "src/nvidia/src/rmapi/providers/class_db_gv100.rs"
line = next(line for line in RECORD.read_text().splitlines() if line.startswith("descriptors "))
records = [tuple(int(part, 16) for part in field.split(":")) for field in line.split()[1:]]
lines = [
"//! Class descriptor list of a GV100: (external class, engine descriptor) in the order of",
"//! the original's engine-table constructor (GPU+0xd90 after `gpumgrAttachGpu`).",
"//! Generated by tools/generate_rmapi_class_db.py from the oracle record; do not edit.",
"",
"#[rustfmt::skip]",
f"pub static DESCRIPTORS: [(u32, u32); {len(records)}] = [",
]
lines += [f" ({klass:#x}, {engine:#x})," for klass, engine in records]
lines += ["];", ""]
text = "\n".join(lines)
if "--check" in sys.argv:
assert TARGET.read_text() == text, "class descriptor table differs from the oracle record"
else:
TARGET.write_text(text)
print(f"{len(records)} class descriptors")
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true", help="fail if class_db_gv100.rs differs")
parser.add_argument("--record", type=Path, default=None, help="path to original-rmapi-gpu.txt")
args = parser.parse_args(argv)
record_path = args.record or RECORD
if not record_path.is_file():
raise SystemExit(f"oracle record not found: {record_path}")
line = next(
(ln for ln in record_path.read_text(encoding="utf-8").splitlines() if ln.startswith("descriptors ")),
None,
)
if line is None:
raise SystemExit(f"no 'descriptors ' line found in {record_path}")
records = [tuple(int(part, 16) for part in field.split(":")) for field in line.split()[1:]]
lines = [
"//! Class descriptor list of a GV100: (external class, engine descriptor) in the order of",
"//! the original's engine-table constructor (GPU+0xd90 after `gpumgrAttachGpu`).",
"//! Generated by tools/generate_rmapi_class_db.py from the oracle record; do not edit.",
"",
"#[rustfmt::skip]",
f"pub static DESCRIPTORS: [(u32, u32); {len(records)}] = [",
]
lines += [f" ({klass:#x}, {engine:#x})," for klass, engine in records]
lines += ["];", ""]
text = "\n".join(lines)
if args.check:
if not TARGET.is_file() or TARGET.read_text(encoding="utf-8") != text:
raise SystemExit("class descriptor table differs from the oracle record")
else:
TARGET.parent.mkdir(parents=True, exist_ok=True)
TARGET.write_text(text, encoding="utf-8")
print(f"{len(records)} class descriptors")
if __name__ == "__main__":
main()

View File

@ -1,12 +1,61 @@
from pathlib import Path
#!/usr/bin/env python3
"""Generate software_controls.rs fixture and replay JSON from recorded REA evidence."""
import argparse
import json
R=Path(__file__).resolve().parent.parent
E=json.loads((R/'reports/software-controls-replay-original-rea.json').read_text())
d=json.loads(''.join(f['data'] for f in E['normalized_result']['frames']).replace('\r',''))
(R/'reports/software-controls-replay-original.json').write_text(json.dumps(d,indent=2)+'\n')
def arr(h):return '&['+','.join('0x'+h[i:i+2] for i in range(0,len(h),2))+']'
rows=[]
for row in d['records']:
rows.append(' ('+json.dumps(row['label'])+','+row['request']+','+arr(row['input_top'])+','+arr(row['input_payload'] or '')+','+arr(row['response'])+','+arr(row.get('payload',''))+'),')
out=R/'src/nvidia/tests/fixtures/software_controls.rs';out.write_text('// Original REA Evidence '+E['evidence_id']+'\n[\n'+'\n'.join(rows)+'\n]\n')
print('Generated',len(rows),'original control records')
from pathlib import Path
R = Path(__file__).resolve().parent.parent
def _arr(h: str) -> str:
return '&[' + ','.join('0x' + h[i:i + 2] for i in range(0, len(h), 2)) + ']'
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true', help='verify checked-in fixture and replay JSON')
args = parser.parse_args(argv)
ev_path = R / 'reports/software-controls-replay-original-rea.json'
if not ev_path.is_file():
raise SystemExit(f'evidence file not found: {ev_path}')
evidence = json.loads(ev_path.read_text(encoding='utf-8'))
d = json.loads(''.join(f['data'] for f in evidence['normalized_result']['frames']).replace('\r', ''))
replay_json = json.dumps(d, indent=2) + '\n'
rows = []
for row in d['records']:
rows.append(
' ('
+ json.dumps(row['label'])
+ ','
+ row['request']
+ ','
+ _arr(row['input_top'])
+ ','
+ _arr(row['input_payload'] or '')
+ ','
+ _arr(row['response'])
+ ','
+ _arr(row.get('payload', ''))
+ '),'
)
fixture_text = '// Original REA Evidence ' + evidence['evidence_id'] + '\n[\n' + '\n'.join(rows) + '\n]\n'
replay_path = R / 'reports/software-controls-replay-original.json'
fixture_path = R / 'src/nvidia/tests/fixtures/software_controls.rs'
if args.check:
if not replay_path.is_file() or replay_path.read_text(encoding='utf-8') != replay_json:
raise SystemExit(f'stale {replay_path}')
if not fixture_path.is_file() or fixture_path.read_text(encoding='utf-8') != fixture_text:
raise SystemExit(f'stale {fixture_path}')
else:
replay_path.parent.mkdir(parents=True, exist_ok=True)
fixture_path.parent.mkdir(parents=True, exist_ok=True)
replay_path.write_text(replay_json, encoding='utf-8')
fixture_path.write_text(fixture_text, encoding='utf-8')
print('Generated', len(rows), 'original control records')
if __name__ == '__main__':
main()

View File

@ -1,18 +1,113 @@
#!/usr/bin/env python3
"""Generate recorded V100 trace fixtures from captured ioctl payloads."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import json,hashlib
root=Path(__file__).resolve().parents[1];analysis=Path('/home/geodd/nvidia-driver/analysis-580.178.04/reports');p=analysis/'cuda-compute-exact-allocation-ioctl-payloads.jsonl';rows=[json.loads(x)for x in p.read_text().splitlines()]
def arr(h):return '['+','.join('0x'+h[i:i+2]for i in range(0,len(h),2))+']'
code=['// Generated immutable actual V100 trace fixtures. See reports/trace-fixture-provenance.json.','use nv_rs_abi::{RmAlloc,RmControl,Wire,NvStatus};','use nv_rs_core::{resources,controls};','#[test] fn recorded_allocation_wrappers_and_nested_lengths() {','let cases: &[([u8;48],[u8;48],usize,usize)] = &[']
aa=[x for x in rows if int(x['request'],16)&65535==0x462b]
for x in aa:code.append('('+arr(x['before'])+','+arr(x['after'])+','+str(len(bytes.fromhex(x['params_before'])))+','+str(len(bytes.fromhex(x['params_after'])))+'),')
code+= ['];let mut nonnull=0; for(before,after,nb,na) in cases { let b=RmAlloc::decode(before).unwrap();let a=RmAlloc::decode(after).unwrap(); assert_eq!(b.params_size,0);assert_eq!(a.status,0);let n=resources::parameter_size(b.class,b.params!=0).unwrap() as usize;assert_eq!(n,*nb);assert_eq!(n,*na); if b.params!=0 {nonnull+=1;} }assert_eq!(cases.len(),221);assert_eq!(nonnull,203);}','#[test] fn recorded_policy_queries() {']
cc=[]
for x in rows:
if int(x['request'],16)&65535!=0x462a:continue
if int.from_bytes(bytes.fromhex(x['before'])[8:12],'little')!=0x20808159:continue
cc.append(x);code+=['{let wrapper=RmControl::decode(&'+arr(x['after'])+').unwrap();assert_eq!(wrapper.params_size,332);assert_eq!(wrapper.status,0);let mut payload='+arr(x['params_before'])+';let expected='+arr(x['params_after'])+';assert_eq!(controls::fill_policy_query(&mut payload,&[controls::TriState::Zero;41]),NvStatus::OK);assert_eq!(payload,expected);}']
code+=['}'];assert len(cc)==8;(root/'src/nvidia/tests/recorded_trace.rs').write_text('\n'.join(code)+'\n');(root/'reports/trace-fixture-provenance.json').write_text(json.dumps({'source':str(p),'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'scope':'Actual bounded GPU7 CUDA41->42trace.221allocation wrappers,203nested length observations,8actual policy query inputs/outputs. Test uses zero state only for observed selectors12/37; does not establish zero policy globally or execute driver.','allocation_cases':len(aa),'policy_cases':len(cc)},indent=2)+'\n')
import shutil
import subprocess
subprocess.run([str(Path.home()/".cargo/bin/rustfmt"),"--edition","2024",str(Path(__file__).resolve().parents[1]/"src/nvidia/tests/recorded_trace.rs")],check=True)
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
CAPTURE_REL = 'reports/cuda-compute-exact-allocation-ioctl-payloads.jsonl'
def find_input(explicit: Path | None = None) -> Path:
if explicit is not None:
if not explicit.is_file():
raise SystemExit(f'input capture not found: {explicit}')
return explicit
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidate = analysis / CAPTURE_REL
if candidate.is_file():
return candidate
raise SystemExit(f'input capture not found at {candidate}; pass --input or set NV_RS_ANALYSIS_ROOT')
def find_rustfmt() -> str:
if os.environ.get('RUSTFMT'):
return os.environ['RUSTFMT']
which = shutil.which('rustfmt')
if which:
return which
candidates = []
if os.environ.get('CARGO_HOME'):
candidates.append(Path(os.environ['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 _arr(h: str) -> str:
return '[' + ','.join('0x' + h[i:i + 2] for i in range(0, len(h), 2)) + ']'
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', type=Path, default=None)
args = parser.parse_args(argv)
p = find_input(args.input)
rows = [json.loads(x) for x in p.read_text(encoding='utf-8').splitlines() if x.strip()]
code = [
'// Generated immutable actual V100 trace fixtures. See reports/trace-fixture-provenance.json.',
'use nv_rs_abi::{RmAlloc,RmControl,Wire,NvStatus};',
'use nv_rs_core::{resources,controls};',
'#[test] fn recorded_allocation_wrappers_and_nested_lengths() {',
'let cases: &[([u8;48],[u8;48],usize,usize)] = &[',
]
aa = [x for x in rows if int(x['request'], 16) & 65535 == 0x462B]
for x in aa:
code.append(
'(' + _arr(x['before']) + ',' + _arr(x['after'])
+ ',' + str(len(bytes.fromhex(x['params_before'])))
+ ',' + str(len(bytes.fromhex(x['params_after']))) + '),'
)
code += [
'];let mut nonnull=0; for(before,after,nb,na) in cases { let b=RmAlloc::decode(before).unwrap();let a=RmAlloc::decode(after).unwrap(); assert_eq!(b.params_size,0);assert_eq!(a.status,0);let n=resources::parameter_size(b.class,b.params!=0).unwrap() as usize;assert_eq!(n,*nb);assert_eq!(n,*na); if b.params!=0 {nonnull+=1;} }assert_eq!(cases.len(),221);assert_eq!(nonnull,203);}',
'#[test] fn recorded_policy_queries() {',
]
cc = []
for x in rows:
if int(x['request'], 16) & 65535 != 0x462A:
continue
if int.from_bytes(bytes.fromhex(x['before'])[8:12], 'little') != 0x20808159:
continue
cc.append(x)
code += [
'{let wrapper=RmControl::decode(&' + _arr(x['after'])
+ ').unwrap();assert_eq!(wrapper.params_size,332);assert_eq!(wrapper.status,0);let mut payload='
+ _arr(x['params_before']) + ';let expected=' + _arr(x['params_after'])
+ ';assert_eq!(controls::fill_policy_query(&mut payload,&[controls::TriState::Zero;41]),NvStatus::OK);assert_eq!(payload,expected);}'
]
code += ['}']
if len(cc) != 8:
raise SystemExit(f'expected 8 policy query records (0x20808159), found {len(cc)}')
target = ROOT / 'src/nvidia/tests/recorded_trace.rs'
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text('\n'.join(code) + '\n', encoding='utf-8')
report = ROOT / 'reports/trace-fixture-provenance.json'
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(
json.dumps(
{
'source': str(p),
'sha256': hashlib.sha256(p.read_bytes()).hexdigest(),
'scope': 'Actual bounded GPU7 CUDA41->42trace.221allocation wrappers,203nested length observations,8actual policy query inputs/outputs. Test uses zero state only for observed selectors12/37; does not establish zero policy globally or execute driver.',
'allocation_cases': len(aa),
'policy_cases': len(cc),
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
subprocess.run([find_rustfmt(), '--edition', '2024', str(target)], check=True)
if __name__ == '__main__':
main()

View File

@ -1,10 +1,74 @@
#!/usr/bin/env python3
"""Pack immutable original trace buffers for a recorded-only backend test."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import json,struct,hashlib
root=Path(__file__).resolve().parents[1];source=Path('/home/geodd/nvidia-driver/analysis-580.178.04/reports/cuda-compute-exact-allocation-ioctl-payloads.jsonl');rows=[json.loads(x)for x in source.read_text().splitlines()];out=bytearray();known=0
for row in rows:
req=int(row['request'],16);a=bytes.fromhex(row['before']);b=bytes.fromhex(row['after']);p=bytes.fromhex(row['params_before']);q=bytes.fromhex(row['params_after']);assert len(a)==len(b) and len(p)==len(q)
out+=struct.pack('<III',req,len(a),len(p))+a+b+p+q
known+=req in [0xc020462a,0xc030462b,0xc0104629]
(root/'src/nvidia/tests/fixtures/transport-trace.bin').write_bytes(out);(root/'reports/transport-trace-provenance.json').write_text(json.dumps({'source':str(source),'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'fixture_sha256':hashlib.sha256(out).hexdigest(),'total_records':len(rows),'implemented_transport_records':known,'other_request_records':len(rows)-known,'scope':'Test-only recorded backend injects historical outputs; this is not new driver execution or live conformance.'},indent=2)+'\n');print(len(rows),'records',known,'implemented transports',len(out),'bytes')
import struct
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
CAPTURE_REL = 'reports/cuda-compute-exact-allocation-ioctl-payloads.jsonl'
def find_input(explicit: Path | None = None) -> Path:
if explicit is not None:
if not explicit.is_file():
raise SystemExit(f'input capture not found: {explicit}')
return explicit
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidate = analysis / CAPTURE_REL
if candidate.is_file():
return candidate
raise SystemExit(f'input capture not found at {candidate}; pass --input or set NV_RS_ANALYSIS_ROOT')
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', type=Path, default=None)
args = parser.parse_args(argv)
source = find_input(args.input)
rows = [json.loads(x) for x in source.read_text(encoding='utf-8').splitlines() if x.strip()]
out = bytearray()
known = 0
for idx, row in enumerate(rows):
req = int(row['request'], 16)
a = bytes.fromhex(row['before'])
b = bytes.fromhex(row['after'])
p = bytes.fromhex(row['params_before'])
q = bytes.fromhex(row['params_after'])
if len(a) != len(b) or len(p) != len(q):
raise SystemExit(
f'record {idx}: mismatched before/after lengths ({len(a)} vs {len(b)}, {len(p)} vs {len(q)})'
)
out += struct.pack('<III', req, len(a), len(p)) + a + b + p + q
known += req in (0xC020462A, 0xC030462B, 0xC0104629)
fixture = ROOT / 'src/nvidia/tests/fixtures/transport-trace.bin'
fixture.parent.mkdir(parents=True, exist_ok=True)
fixture.write_bytes(out)
report = ROOT / 'reports/transport-trace-provenance.json'
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(
json.dumps(
{
'source': str(source),
'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
'fixture_sha256': hashlib.sha256(out).hexdigest(),
'total_records': len(rows),
'implemented_transport_records': known,
'other_request_records': len(rows) - known,
'scope': 'Test-only recorded backend injects historical outputs; this is not new driver execution or live conformance.',
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
print(len(rows), 'records', known, 'implemented transports', len(out), 'bytes')
if __name__ == '__main__':
main()