Files
nvdriver/tools/generate_trace_fixtures.py

114 lines
4.7 KiB
Python

#!/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 shutil
import subprocess
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ANALYSIS_ROOT = Path.home() / '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()