diff --git a/tests/offline/test_firmware_unpack_and_vgx_helpers.py b/tests/offline/test_firmware_unpack_and_vgx_helpers.py new file mode 100644 index 00000000..c4161827 --- /dev/null +++ b/tests/offline/test_firmware_unpack_and_vgx_helpers.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Offline tests for portable toolchain and artifact resolution in +test_gpu_firmware_unpack.py, test_timer_timeout_vgx.py, and +timer-timeout-provenance-report.py. +""" +import importlib.util +import os +from pathlib import Path +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 FirmwareUnpackAndVgxPortabilityTest(unittest.TestCase): + def test_firmware_unpack_resolves_recorded_home_geodd_paths_into_repo(self): + mod = _load("test_gpu_firmware_unpack", "tools/test_gpu_firmware_unpack.py") + resolved = mod._resolve_repo_artifact( + "/home/geodd/nvidia-driver-rs/analysis/acr-580/11430c8-24.packed" + ) + self.assertTrue(resolved.is_file()) + self.assertEqual(resolved, ROOT / "analysis/acr-580/11430c8-24.packed") + + with self.assertRaises(FileNotFoundError): + mod._resolve_repo_artifact("/nonexistent/path/missing.bin") + + def test_vgx_resolves_kernel_src_and_rustc_from_env(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for rel in ("conftest.sh", "nvidia/os-interface.c", "common/inc/nv-linux.h"): + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text("", encoding="utf-8") + with mock.patch.dict(os.environ, { + "NV_RS_KERNEL_SRC": str(root), + "RUSTC": "/custom/bin/rustc", + }): + mod = _load("test_timer_timeout_vgx", "tools/test_timer_timeout_vgx.py") + self.assertEqual(mod.ARTIFACT, root) + self.assertEqual(mod._find_rustc(), "/custom/bin/rustc") + + def test_provenance_report_is_importable_and_honors_analysis_root(self): + with tempfile.TemporaryDirectory() as tmp: + with mock.patch.dict(os.environ, {"NV_RS_ANALYSIS_ROOT": tmp}): + mod = _load( + "timer_timeout_provenance_report", + "tools/timer-timeout-provenance-report.py", + ) + self.assertEqual(mod.ANALYSIS_ROOT, Path(tmp)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/timer-timeout-vgx/provider.rs b/tests/timer-timeout-vgx/provider.rs index 26b2d281..fe014377 100644 --- a/tests/timer-timeout-vgx/provider.rs +++ b/tests/timer-timeout-vgx/provider.rs @@ -1,3 +1,4 @@ +#[allow(dead_code)] #[path = "../../src/nvidia/kernel/hypervisor.rs"] mod hypervisor; diff --git a/tools/test_gpu_firmware_unpack.py b/tools/test_gpu_firmware_unpack.py index da3e4d3e..a1e3c05e 100644 --- a/tools/test_gpu_firmware_unpack.py +++ b/tools/test_gpu_firmware_unpack.py @@ -1,45 +1,154 @@ #!/usr/bin/env python3 """Independent zlib + artifact firmware corpus against the production Rust decoder.""" from pathlib import Path -import tempfile,subprocess,zlib,random,json,hashlib,os -R=Path(__file__).resolve().parents[1] -def q(p):return json.dumps(str(p)) -with tempfile.TemporaryDirectory(prefix='nv-firmware-unpack-')as d: - d=Path(d);cases=[];rng=random.Random(58017804) - patterns=[b'a',bytes(range(256))*300,b'a'*70000,bytes(rng.getrandbits(8)for _ in range(66000)),(b'gpu firmware\0'*3000)+bytes(range(256)),b'x'*32768+b'y'*32768+b'x'*32768] - for i,pattern in enumerate(patterns): - for level in [0,1,6,9]: - for strategy in [zlib.Z_DEFAULT_STRATEGY,zlib.Z_FIXED]: - c=zlib.compressobj(level,zlib.DEFLATED,-15,8,strategy);packed=c.compress(pattern)+c.flush();name=f'zlib-{i}-{level}-{strategy}' - a=d/(name+'.packed');b=d/(name+'.decoded');a.write_bytes(packed);b.write_bytes(pattern);cases.append((a,b,1)) - inventory=json.loads((R/'reports/gpu-acr-packed-inventory.json').read_text()) - for row in inventory['records']:cases.append((Path(row['packed_file']),Path(row['decoded_file']),row['flags'])) - test='''#[path = SOURCE] mod firmware_unpack; +import shutil +import tempfile, subprocess, zlib, random, json, hashlib, os + +R = Path(__file__).resolve().parents[1] + + +def q(p): + return json.dumps(str(p)) + + +def _find_cargo() -> str: + env = os.environ.get("CARGO") + if env: + return env + found = shutil.which("cargo") + if found: + return found + cargo_home = os.environ.get("CARGO_HOME") + if cargo_home: + candidate = Path(cargo_home) / "bin" / "cargo" + if candidate.is_file(): + return str(candidate) + return str(Path.home() / ".cargo/bin/cargo") + + +def _resolve_repo_artifact(raw_path: str) -> Path: + path = Path(raw_path) + if path.is_file(): + return path + marker = "/analysis/" + if marker in raw_path: + rel = Path("analysis") / raw_path.split(marker, 1)[1] + candidate = R / rel + if candidate.is_file(): + return candidate + raise FileNotFoundError(f"packed/decoded firmware artifact not found: {raw_path}") + + +def main() -> None: + with tempfile.TemporaryDirectory(prefix='nv-firmware-unpack-') as d: + d = Path(d) + cases = [] + rng = random.Random(58017804) + patterns = [ + b'a', + bytes(range(256)) * 300, + b'a' * 70000, + bytes(rng.getrandbits(8) for _ in range(66000)), + (b'gpu firmware\0' * 3000) + bytes(range(256)), + b'x' * 32768 + b'y' * 32768 + b'x' * 32768, + ] + for i, pattern in enumerate(patterns): + for level in [0, 1, 6, 9]: + for strategy in [zlib.Z_DEFAULT_STRATEGY, zlib.Z_FIXED]: + c = zlib.compressobj(level, zlib.DEFLATED, -15, 8, strategy) + packed = c.compress(pattern) + c.flush() + name = f'zlib-{i}-{level}-{strategy}' + a = d / (name + '.packed') + b = d / (name + '.decoded') + a.write_bytes(packed) + b.write_bytes(pattern) + cases.append((a, b, 1)) + inventory = json.loads((R / 'reports/gpu-acr-packed-inventory.json').read_text(encoding='utf-8')) + for row in inventory['records']: + cases.append(( + _resolve_repo_artifact(row['packed_file']), + _resolve_repo_artifact(row['decoded_file']), + row['flags'], + )) + test = '''#[path = SOURCE] mod firmware_unpack; use firmware_unpack::*; fn limits()->Limits{Limits{max_output:4*1024*1024,max_blocks:10000,max_symbols:4*1024*1024}} #[test]fn independent_valid_and_partial_failure_corpus(){ let mut workspace=Workspace::new(); -'''.replace('SOURCE',q(R/'src/nvidia/src/gpu/firmware_unpack.rs')) - for a,b,flags in cases: - test+='''{let packed=include_bytes!(PACKED);let expected=include_bytes!(DECODED);let mut output=vec![0xa5;expected.len()+256];let header=Header{decoded_size:expected.len()as u32,flags:FLAGS};let decoded=unpack(header,packed,&mut output,&mut workspace,limits()).unwrap();assert_eq!(decoded.bytes(),expected.len());assert_eq!(&output[..expected.len()],expected);assert!(output[expected.len()..].iter().all(|x|*x==0xa5));assert!(decoded.input_consumed()<=packed.len()); +'''.replace('SOURCE', q(R / 'src/nvidia/src/gpu/firmware_unpack.rs')) + for a, b, flags in cases: + test += '''{let packed=include_bytes!(PACKED);let expected=include_bytes!(DECODED);let mut output=vec![0xa5;expected.len()+256];let header=Header{decoded_size:expected.len()as u32,flags:FLAGS};let decoded=unpack(header,packed,&mut output,&mut workspace,limits()).unwrap();assert_eq!(decoded.bytes(),expected.len());assert_eq!(&output[..expected.len()],expected);assert!(output[expected.len()..].iter().all(|x|*x==0xa5));assert!(decoded.input_consumed()<=packed.len()); for missing in [1,decoded.input_consumed()/2,decoded.input_consumed()]{if missing>0{let mut partial=vec![0xa5;expected.len()];assert!(unpack(header,&packed[..decoded.input_consumed()-missing],&mut partial,&mut workspace,limits()).is_err());}} let mut partial=vec![0xa5;expected.len()];let budget=Limits{max_output:expected.len()-1,..limits()};assert_eq!(unpack(header,packed,&mut partial,&mut workspace,budget).err().unwrap().kind,Kind::OutputBounds); } -'''.replace('PACKED',q(a)).replace('DECODED',q(b)).replace('FLAGS',str(flags)) - test+='''} +'''.replace('PACKED', q(a)).replace('DECODED', q(b)).replace('FLAGS', str(flags)) + test += '''} #[test]fn malformed_budgets_and_roles(){let mut w=Workspace::new();let mut out=[0xa5;256];let h=Header{decoded_size:1,flags:1};assert_eq!(unpack(h,&[7],&mut out,&mut w,limits()).err().unwrap().kind,Kind::InvalidBlock);assert_eq!(unpack(h,&[1,1,0,0,0],&mut out,&mut w,limits()).err().unwrap().kind,Kind::InvalidBlock);assert_eq!(unpack(h,&[1,1,0,254,255,65],&mut out,&mut w,Limits{max_blocks:0,..limits()}).err().unwrap().kind,Kind::Budget);assert_eq!(Header{decoded_size:u32::MAX,flags:0}.allocation_size(Role::Primary),Err(Kind::OutputBounds));assert_eq!(h.allocation_size(Role::Metadata),Err(Kind::Alignment));assert_eq!(h.allocation_size(Role::Primary),Ok(256));let r=unpack(Header{flags:0,..h},&[42],&mut out,&mut w,limits()).unwrap();assert_eq!(r.bytes(),1);assert_eq!(out[0],42);assert_eq!(out[1],0xa5);} ''' - test+='\nmod registers {pub use nv_rs_core::gpu::registers::RegisterIo;}\n#[path = '+q(R/'src/nvidia/src/gpu/firmware_signature.rs')+'] mod firmware_signature;\n#[test] fn original_signature_instruction_vectors(){use firmware_signature::*;\n' - for row in json.loads((R/'reports/gpu-acr-signature-oracle.json').read_text())['cases']: - base=R/'analysis/acr-580/signature-oracle';n=row['id'] - test+='{{let mut image=*include_bytes!({});let production=include_bytes!({});let debug=include_bytes!({});let expected=include_bytes!({});let applied=apply(&mut image,production,debug,Policy{{debug_fuse:{},signature_version:{},maximum_version:{},signature_count:{},signature_bytes:{},patch_location:{},patch_index:{}}}).unwrap();assert_eq!(&image,expected);assert_eq!(applied.words,4);}}\n'.format(q(base/f'{n}-image.bin'),q(base/f'{n}-production.bin'),q(base/f'{n}-debug.bin'),q(base/f'{n}-expected.bin'),str(row['debug_fuse']).lower(),row['signature_version'],row['maximum_version'],row['signature_count'],row['signature_bytes'],row['patch_location'],row['patch_index']) - test+='let mut image=[0xa5;8];let p=Policy{debug_fuse:false,signature_version:0,maximum_version:0,signature_count:0,signature_bytes:4,patch_location:0,patch_index:0};assert_eq!(apply(&mut image,&[0;4],&[],p),Err(Error::ZeroCount));assert_eq!(image,[0xa5;8]);assert_eq!(apply(&mut image,&[0;3],&[],Policy{signature_count:1,..p}),Err(Error::SourceBounds));assert_eq!(image,[0xa5;8]);}\n' - test+='#[test] fn original_debug_register_read(){ struct Io(u32,bool);impl registers::RegisterIo for Io{fn read32(&mut self,offset:u32)->Result{assert_eq!(offset,0x10ac08);assert!(!self.1);self.1=true;Ok(self.0)}fn write32(&mut self,_:u32,_:u32)->Result<(),nv_rs_abi::NvStatus>{panic!("unexpected write")}}' - for word,expected in json.loads((R/'reports/gpu-acr-signature-oracle.json').read_text())['debug_read_vectors']: - test+='assert_eq!(firmware_signature::read_debug_fuse(&mut Io('+str(word)+',false)),Ok('+str(expected!=0).lower()+'));' - test+='}\n' - (d/'test.rs').write_text(test) - (d/'Cargo.toml').write_text('[package]\nname="nv-firmware-corpus"\nversion="0.1.0"\nedition="2024"\n[dependencies]\nnv-rs-abi={path='+q(R/'src/common/abi')+'}\nnv-rs-core={path='+q(R/'src/nvidia')+'}\n[[test]]\nname="corpus"\npath="test.rs"\n') - subprocess.run([os.environ.get('CARGO',str(Path.home()/'.cargo/bin/cargo')),'test','--manifest-path',str(d/'Cargo.toml')],check=True) - report={'production_source_sha256':hashlib.sha256((R/'src/nvidia/src/gpu/firmware_unpack.rs').read_bytes()).hexdigest(),'independent_zlib_cases':48,'actual_original_descriptor_cases':len(inventory['records']),'each_valid_case_checks':['exact decoded bytes','untouched allocation padding','bounded consumed bytes','three truncation cuts rejected','output budget rejected'],'physical_gpu_access':False,'signature_authentication':False,'original_decoder_execution':False,'original_signature_instruction_cases':80,'original_debug_read_instruction_cases':36,'source_sha256':{str(p.relative_to(R)):hashlib.sha256(p.read_bytes()).hexdigest()for p in [R/'src/nvidia/src/gpu/firmware_unpack.rs',R/'src/nvidia/src/gpu/firmware_signature.rs',R/'src/nvidia/kernel/firmware.rs']}} - (R/'reports/gpu-firmware-unpack-validation.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report)) + test += '\nmod registers {pub use nv_rs_core::gpu::registers::RegisterIo;}\n#[path = ' + q(R / 'src/nvidia/src/gpu/firmware_signature.rs') + '] mod firmware_signature;\n#[test] fn original_signature_instruction_vectors(){use firmware_signature::*;\n' + sig_oracle = json.loads((R / 'reports/gpu-acr-signature-oracle.json').read_text(encoding='utf-8')) + for row in sig_oracle['cases']: + base = R / 'analysis/acr-580/signature-oracle' + n = row['id'] + test += '{{let mut image=*include_bytes!({});let production=include_bytes!({});let debug=include_bytes!({});let expected=include_bytes!({});let applied=apply(&mut image,production,debug,Policy{{debug_fuse:{},signature_version:{},maximum_version:{},signature_count:{},signature_bytes:{},patch_location:{},patch_index:{}}}).unwrap();assert_eq!(&image,expected);assert_eq!(applied.words,4);}}\n'.format( + q(base / f'{n}-image.bin'), + q(base / f'{n}-production.bin'), + q(base / f'{n}-debug.bin'), + q(base / f'{n}-expected.bin'), + str(row['debug_fuse']).lower(), + row['signature_version'], + row['maximum_version'], + row['signature_count'], + row['signature_bytes'], + row['patch_location'], + row['patch_index'], + ) + test += 'let mut image=[0xa5;8];let p=Policy{debug_fuse:false,signature_version:0,maximum_version:0,signature_count:0,signature_bytes:4,patch_location:0,patch_index:0};assert_eq!(apply(&mut image,&[0;4],&[],p),Err(Error::ZeroCount));assert_eq!(image,[0xa5;8]);assert_eq!(apply(&mut image,&[0;3],&[],Policy{signature_count:1,..p}),Err(Error::SourceBounds));assert_eq!(image,[0xa5;8]);}\n' + test += '#[test] fn original_debug_register_read(){ struct Io(u32,bool);impl registers::RegisterIo for Io{fn read32(&mut self,offset:u32)->Result{assert_eq!(offset,0x10ac08);assert!(!self.1);self.1=true;Ok(self.0)}fn write32(&mut self,_:u32,_:u32)->Result<(),nv_rs_abi::NvStatus>{panic!("unexpected write")}}' + for word, expected in sig_oracle['debug_read_vectors']: + test += 'assert_eq!(firmware_signature::read_debug_fuse(&mut Io(' + str(word) + ',false)),Ok(' + str(expected != 0).lower() + '));' + test += '}\n' + (d / 'test.rs').write_text(test, encoding='utf-8') + (d / 'Cargo.toml').write_text( + '[package]\nname="nv-firmware-corpus"\nversion="0.1.0"\nedition="2024"\n[dependencies]\nnv-rs-abi={path=' + + q(R / 'src/common/abi') + + '}\nnv-rs-core={path=' + + q(R / 'src/nvidia') + + '}\n[[test]]\nname="corpus"\npath="test.rs"\n', + encoding='utf-8', + ) + subprocess.run([_find_cargo(), 'test', '--manifest-path', str(d / 'Cargo.toml')], check=True) + report = { + 'production_source_sha256': hashlib.sha256((R / 'src/nvidia/src/gpu/firmware_unpack.rs').read_bytes()).hexdigest(), + 'independent_zlib_cases': 48, + 'actual_original_descriptor_cases': len(inventory['records']), + 'each_valid_case_checks': [ + 'exact decoded bytes', + 'untouched allocation padding', + 'bounded consumed bytes', + 'three truncation cuts rejected', + 'output budget rejected', + ], + 'physical_gpu_access': False, + 'signature_authentication': False, + 'original_decoder_execution': False, + 'original_signature_instruction_cases': 80, + 'original_debug_read_instruction_cases': 36, + 'source_sha256': { + str(p.relative_to(R)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in [ + R / 'src/nvidia/src/gpu/firmware_unpack.rs', + R / 'src/nvidia/src/gpu/firmware_signature.rs', + R / 'src/nvidia/kernel/firmware.rs', + ] + }, + } + (R / 'reports/gpu-firmware-unpack-validation.json').write_text( + json.dumps(report, indent=2) + '\n', + encoding='utf-8', + ) + print(json.dumps(report)) + + +if __name__ == '__main__': + main() diff --git a/tools/test_timer_timeout_vgx.py b/tools/test_timer_timeout_vgx.py index 4f5fa85d..a0ae8135 100644 --- a/tools/test_timer_timeout_vgx.py +++ b/tools/test_timer_timeout_vgx.py @@ -8,11 +8,43 @@ import json import os from pathlib import Path import re +import shutil import subprocess import tempfile ROOT = Path(__file__).resolve().parents[1] -ARTIFACT = Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel') +REQUIRED_FILES = ('conftest.sh', 'nvidia/os-interface.c', 'common/inc/nv-linux.h') + + +def _resolve_kernel_artifact() -> Path: + candidates = [] + if env_src := os.environ.get('NV_RS_KERNEL_SRC'): + candidates.append(Path(env_src)) + if env_root := os.environ.get('NV_RS_ANALYSIS_ROOT'): + candidates.append(Path(env_root) / 'extracted/kernel') + candidates.extend([ + Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel'), + Path('/usr/src/nvidia-580.178.04'), + ]) + for candidate in candidates: + if all((candidate / rel).is_file() for rel in REQUIRED_FILES): + return candidate + return candidates[0] + + +def _find_rustc() -> str: + if env_rustc := os.environ.get('RUSTC'): + return env_rustc + if found := shutil.which('rustc'): + return found + if cargo_home := os.environ.get('CARGO_HOME'): + candidate = Path(cargo_home) / 'bin/rustc' + if candidate.is_file(): + return str(candidate) + return str(Path.home() / '.cargo/bin/rustc') + + +ARTIFACT = _resolve_kernel_artifact() NAMES = ('VGX_BUILD', 'VGX_KVM_BUILD', 'VGX_DEVICE_VM_BUILD') CASES = ('dom0_kernel_present', 'nvidia_vgpu_kvm_build', 'device_vm_build') DEFINES = ('NV_DOM0_KERNEL_PRESENT', 'NV_VGPU_KVM_BUILD', 'NV_DEVICE_VM_BUILD') @@ -40,11 +72,28 @@ def main(): cfg_cases = 0 with tempfile.TemporaryDirectory(prefix='nv-vgx-test-') as temp: out = Path(temp) - rustc = str(Path.home()/'.cargo/bin/rustc') + rustc = _find_rustc() + abi_rlib = out / 'libnv_rs_abi.rlib' + core_rlib = out / 'libnv_rs_core.rlib' + run([ + rustc, '--edition=2024', '--crate-name=nv_rs_abi', '--crate-type=rlib', + str(ROOT / 'src/common/abi/src/lib.rs'), '-o', str(abi_rlib), + ]) + run([ + rustc, '--edition=2024', '--crate-name=nv_rs_core', '--crate-type=rlib', + str(ROOT / 'src/nvidia/src/lib.rs'), '--extern', f'nv_rs_abi={abi_rlib}', + '-L', f'dependency={out}', '-o', str(core_rlib), + ]) executables = [] for mask in range(9): binary = out/f'provider-{mask}' - args = [rustc, '--edition=2024', '-Dwarnings', str(ROOT/'tests/timer-timeout-vgx/provider.rs'), '-o', str(binary)] + args = [ + rustc, '--edition=2024', '-Dwarnings', + '--extern', f'nv_rs_core={core_rlib}', + '--extern', f'nv_rs_abi={abi_rlib}', + '-L', f'dependency={out}', + str(ROOT/'tests/timer-timeout-vgx/provider.rs'), '-o', str(binary), + ] if mask != 8: args += ['--cfg=nv_rs_build_product_resolved'] args += ['--cfg='+cfg for bit,cfg in enumerate(CFG) if mask & (1<u32MAX/1000 saturate bothusfields; override marksData+0. RmDefaultTimeoutFlags key4 mapsOSTIMER8, key8 mapsOSDELAY16. Absent reads preserve values; unavailable provider cannot be fabricated as absent. Mode reinit049687 rewrites default_flags8 and honors overridden/default-scaled booleans.'}, - 'thread_database': {'setup_global': '05fd21a0', 'non_compute_ms_global': '05fd21d8:u64', 'compute_ms_global': '05fd21e0:u64', 'compute_gpu_mask_global': '05fd21e8:u32', 'timeout_flags_global': '05fd21ec:u32', 'startup': 'Linux049808 calls059486(0x87). 059486 zeros compute/noncompute intervals and mask, writes setup0x87; timeout_flags is not written by059486. Zero-initialized globals are not sufficient initialized timeout config.', 'setup_flags': '0x87=ENABLED1|TIMEOUT_ENABLED2|SLI_LOGIC4|DO_NOT_INCLUDE_SLEEP_TIME80. No ASSERT10/RESET40/PRINT80000000 default.', 'per_gpu_init': '059487 uses actual GPUc9c gpuInstance bit. Graphics clears bit and sets noncompute_ms=providedus/1000. Compute sets bit and preserves noncompute_ms. Always calls049687 again for compute_ms=(perOSus/1000)*GPU1e18 wrappingu32, zeroextendedu64; timeout_flags=providedflags.', 'initial_ordinary_gpu': 'After actual first ordinary graphics initialization: noncompute_ms4000,compute_ms4000,timeout_flags8,thatinstancebitclear. After first compute reference: compute_ms30000,bitset; prior noncompute interval persists.', 'setup_override': '059485 successfully reads RmThreadStateSetupFlags then replaces global setup flags. No read success means no override; missing registry provider is not evidence of absence.', 'current_node': 'Real _threadStateInitCommon zeroes node, captures actual threadSeq/cpu/flags, enablesfreecallbacks, calls016370 deadline initializer, marksTIMEOUT_INITED20 only on executedNV_OK, and insertsactualcurrentOSthread in map.016370 uses500ms for low4 flagbits, actualDatabase otherwise; nonzero override_ms wins, NODE_DEVICE_INIT80 applies minimum60000ms; enter time initialized once,nextyield now+2s. Missing current node must preserve actual lookupstatus, not synthesize zeroNode.'}, - 'gpu_state': {'properties': {hex(k): v for k, v in expected.items()}, 'constructor': '006647 zeroes actual6e70-byte GPU allocation before005722/005825.005825 setsIS_CONNECTED915=true unconditionally. Reset917/918/919/926 remain zero through this data initializer. This is construction-only state, not permission to freeze reset/loss fields forever.', 'connected_updates': '031166 lost-device path setsIS_LOST91d=true,IS_CONNECTED915=false.000802 crashdump temporarily saves915/91d, may set915true/91dfalse for capture, then restores both. Connection is not STATE_INITIALIZED90d/Load completion.', 'reset_updates': '039110 and039123 full-reset routes write917=true after successful reset method;039123 fallback and039121 secondary-reset route write918=true before its reset callback. These are observed methods, not a claim that every method is selected on GV100. All reset paths must update actual same-owner state; removal must force connection false and/or gate access. Global search alone cannot prove all packed/generic setter updates.', 'excluded_false_positive': '052491 writes many property-location bytes to1 enmasse in a second argument; that is not evidence that live GPU reset bits are initialized true. Do not use broad offset grep to infer object identity.'}, - 'wait_routes': {'bar2_bind_039307': {'requested_us': 0, 'flags': 0, 'with_initialized_linux_default': '0xa=OSTIMER|USE_THREAD_STATE', 'requires': 'actual current-thread database/node, real yield service, journal on expiry, liveGPUstate. LocalOSclock is still initialized but threadstate governs expiry.'}, 'tlb_040843': {'requested_us': 0, 'flags': '0x105=DEFAULT|BYPASS_THREAD_STATE|BYPASS_CPU_YIELD', 'with_initialized_linux_default': '0x10d=OSTIMER|DEFAULT|BYPASS_THREAD_STATE|BYPASS_CPU_YIELD', 'requires': 'monotonic clock+tick, ownedData/live resetstate, journal on expiry. Neither GPU timer reads nor currentthread/yield calls on this selected route. Callerflush/reset thread operations remain separate required services.'}, 'fecs_055403': {'requested_us': 'scale*500000 silicon;scale*5000000 emulation/simulation', 'flags': '0 silicon/emulation;4 simulation', 'with_initialized_linux_default': '8 silicon (nonzero duration meansUSE_THREAD_STATE is not forced)', 'requires': 'explicit059492 resetcurrentthread before wait, real yield;059505 still consults thread_timeout after localnonexpiry unlessbypass4; actualFECS submit/recoverydiagnosticservices remain mandatory.'}}, - 'owner_requirements': ['Data.gpu is nativeOBJGPU pointer identity. RustGpuId must resolve retained same-owner GPU state; BDF, BOOT identity or GPU-ID truncation is not a substitute.', 'Thread compute mask uses actual allocatedgpuInstance, not prepared registry key/devicegroup/PCIid.', 'Construct Data from actual ownedGPUsoftware/runtime+LinuxOSdefaultpolicy+real registry override, retain sameowner for whole wait. No caller-supplied ready/defaultflags.', 'Connected/reset/emulation fields must be read from actual lifecycle owner under serialization; hardware_ready=false is neither disconnected nor in reset.', 'OS_TIMER bypasses hardware PTIMER only. It does not permit unavailable thread/yield/journal providers to return success. TLB0x105 is the proven minimal localOS route; changing BAR2bind/FECS flags would change original behavior.'], - 'validation': {'evidence_assertions': len(checks), 'checks': checks, 'new_runtime_tests': 0, 'reason': 'Read-only investigation; existing original timeout/thread differential suites remain unchanged.'}, - 'evidence': records, - 'guidance': ['matching580 source gpu_timeout.c,unix/os.c:2005,unix/osinit.c:275,thread_state.c:228/519/1149,generated/g_gpu_nvoc.h properties and g_gpu_nvoc.c init_dataField', 'existing reports/gpu-pf-constructor.txt and gpu-pf-constructor-validation.json prove zeroed6e70 GPU canonical image and ordered381 constructor writes', 'matching580 kern_gmmu_gm107.c:165 corroborates TLB0x105; existing BAR2bind/TLB and FECS REA indices contain complete selectedcaller evidence'] -} -(ROOT/'reports/timer-timeout-provenance.json').write_text(json.dumps(report, indent=2)+'\n') -print(json.dumps({'evidence_assertions':len(checks),'rea_functions':len(records),'report':'reports/timer-timeout-provenance.json'})) +def main(): + checks = [] + + def has(name, *snippets): + data = evidence(name) + text = '\n'.join(data['normalized_result']['instructions']) + for snippet in snippets: + if snippet not in text: + raise SystemExit(f"missing expected instruction {snippet!r} in {name}") + checks.append({'function': name, 'instruction_contains': snippet}) + + has('_nv049808rm', 'MOV EDI, 0x87', 'CALL 0x0617b310') + has('_nv039307rm', 'XOR ECX, ECX', 'CALL 0x067547a0') + has('_nv040843rm', 'MOV ECX, 0x105', 'CALL 0x067547a0') + has('_nv055403rm', '0x7a120', '0x4c4b40', 'CALL 0x067547a0') + has('_nv059486rm', '[0x05fd21d8], 0x0', '[0x05fd21e0], 0x0', '[0x05fd21e8], 0x0', '[0x05fd21a0], EDI') + has('_nv059487rm', '[RDI + 0xc9c]', '[RDI + 0x1e30]', '[0x05fd21ec], R12D', '[RBX + 0x1e18]') + has('_nv005825rm', '[RDI + 0x915], 0x1') + has('_nv031166rm', '[RDI + 0x91d], 0x1', '[RDI + 0x915], 0x0') + has('_nv039121rm', '[RDI + 0x918], 0x1') + # Symbolic source names independently corroborate the closed-object offsets. + header_path = SOURCE / 'src/nvidia/generated/g_gpu_nvoc.h' + if not header_path.is_file(): + raise SystemExit(f"missing reference header: {header_path} (set NV_RS_ANALYSIS_ROOT)") + header = header_path.read_text(encoding='utf-8') + properties = header[header.index('// 124 PDB properties'):].split('NvBool ') + expected = {0x915: 'IS_CONNECTED', 0x917: 'IN_FULLCHIP_RESET', 0x918: 'IN_SECONDARY_BUS_RESET', 0x919: 'IN_GC6_RESET', 0x926: 'SECONDARY_BUS_RESET_PENDING'} + for offset, name in expected.items(): + if not properties[offset - 0x908 + 1].startswith('PDB_PROP_GPU_' + name + ';'): + raise SystemExit(f"unexpected property at {hex(offset)}: expected PDB_PROP_GPU_{name}") + checks.append({'property_offset': hex(offset), 'name': name}) + records = [] + for path in sorted(REA.glob('_nv*.rea.json')): + data = evidence(path.name.removesuffix('.rea.json')) + records.append({'function': data['normalized_result']['procedure']['name'], 'evidence_id': data['evidence_id'], 'file': str(path.relative_to(ROOT)), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}) + report = { + 'scope': 'Original580.178.04 selected Linux timeout defaults/provider provenance; read-only. No production edits or physical GPU calls.', + 'binary_sha256': '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b', + 'timeout_data': {'gpu_offset': '0x1e08', 'fields': {'+0': 'bDefaultOverridden:u8', '+1': 'bScaled:u8', '+4': 'defaultus:u32', '+8': 'defaultResetus:u32', '+c': 'defaultFlags:u32', '+10': 'scale:u32', '+18': 'actual retained OBJGPU pointer'}, 'initialization': '031028 clears computeModeRefCount atGPU1e30 then059507. 059507 stores OBJGPU pointer, calls Linux049687, sets defaults if not overridden, scales defaultus once, calls059487 then059492. Return statuses of these last calls are ignored after execution.', 'ordinary_silicon_non_vgx': {'compute_refcount_zero': {'default_us': 4000000, 'default_flags': 8, 'scale': 1}, 'compute_refcount_positive': {'default_us': 30000000, 'default_flags': 8, 'scale': 1}}, 'mode_updates': '030185 command10 increments; transition0to1 calls059507. command11 decrements/clampsnegative0; reaching0 calls059507. Runtime mode cannot be inferred from BOOT/PCI identity.', 'other_profiles': '049687 VGX default1800000us except extended GSP-client preinitialization4000000us; emulation90e or simulation4de2 sets scale60. These must come from actual selected runtime/OS providers.', 'registry': '059508 reads RmOverrideInternalTimeoutsMs: highbit31 forces low24-bit ms including0; else successful nonzero RmDefaultTimeout ms. Values>u32MAX/1000 saturate bothusfields; override marksData+0. RmDefaultTimeoutFlags key4 mapsOSTIMER8, key8 mapsOSDELAY16. Absent reads preserve values; unavailable provider cannot be fabricated as absent. Mode reinit049687 rewrites default_flags8 and honors overridden/default-scaled booleans.'}, + 'thread_database': {'setup_global': '05fd21a0', 'non_compute_ms_global': '05fd21d8:u64', 'compute_ms_global': '05fd21e0:u64', 'compute_gpu_mask_global': '05fd21e8:u32', 'timeout_flags_global': '05fd21ec:u32', 'startup': 'Linux049808 calls059486(0x87). 059486 zeros compute/noncompute intervals and mask, writes setup0x87; timeout_flags is not written by059486. Zero-initialized globals are not sufficient initialized timeout config.', 'setup_flags': '0x87=ENABLED1|TIMEOUT_ENABLED2|SLI_LOGIC4|DO_NOT_INCLUDE_SLEEP_TIME80. No ASSERT10/RESET40/PRINT80000000 default.', 'per_gpu_init': '059487 uses actual GPUc9c gpuInstance bit. Graphics clears bit and sets noncompute_ms=providedus/1000. Compute sets bit and preserves noncompute_ms. Always calls049687 again for compute_ms=(perOSus/1000)*GPU1e18 wrappingu32, zeroextendedu64; timeout_flags=providedflags.', 'initial_ordinary_gpu': 'After actual first ordinary graphics initialization: noncompute_ms4000,compute_ms4000,timeout_flags8,thatinstancebitclear. After first compute reference: compute_ms30000,bitset; prior noncompute interval persists.', 'setup_override': '059485 successfully reads RmThreadStateSetupFlags then replaces global setup flags. No read success means no override; missing registry provider is not evidence of absence.', 'current_node': 'Real _threadStateInitCommon zeroes node, captures actual threadSeq/cpu/flags, enablesfreecallbacks, calls016370 deadline initializer, marksTIMEOUT_INITED20 only on executedNV_OK, and insertsactualcurrentOSthread in map.016370 uses500ms for low4 flagbits, actualDatabase otherwise; nonzero override_ms wins, NODE_DEVICE_INIT80 applies minimum60000ms; enter time initialized once,nextyield now+2s. Missing current node must preserve actual lookupstatus, not synthesize zeroNode.'}, + 'gpu_state': {'properties': {hex(k): v for k, v in expected.items()}, 'constructor': '006647 zeroes actual6e70-byte GPU allocation before005722/005825.005825 setsIS_CONNECTED915=true unconditionally. Reset917/918/919/926 remain zero through this data initializer. This is construction-only state, not permission to freeze reset/loss fields forever.', 'connected_updates': '031166 lost-device path setsIS_LOST91d=true,IS_CONNECTED915=false.000802 crashdump temporarily saves915/91d, may set915true/91dfalse for capture, then restores both. Connection is not STATE_INITIALIZED90d/Load completion.', 'reset_updates': '039110 and039123 full-reset routes write917=true after successful reset method;039123 fallback and039121 secondary-reset route write918=true before its reset callback. These are observed methods, not a claim that every method is selected on GV100. All reset paths must update actual same-owner state; removal must force connection false and/or gate access. Global search alone cannot prove all packed/generic setter updates.', 'excluded_false_positive': '052491 writes many property-location bytes to1 enmasse in a second argument; that is not evidence that live GPU reset bits are initialized true. Do not use broad offset grep to infer object identity.'}, + 'wait_routes': {'bar2_bind_039307': {'requested_us': 0, 'flags': 0, 'with_initialized_linux_default': '0xa=OSTIMER|USE_THREAD_STATE', 'requires': 'actual current-thread database/node, real yield service, journal on expiry, liveGPUstate. LocalOSclock is still initialized but threadstate governs expiry.'}, 'tlb_040843': {'requested_us': 0, 'flags': '0x105=DEFAULT|BYPASS_THREAD_STATE|BYPASS_CPU_YIELD', 'with_initialized_linux_default': '0x10d=OSTIMER|DEFAULT|BYPASS_THREAD_STATE|BYPASS_CPU_YIELD', 'requires': 'monotonic clock+tick, ownedData/live resetstate, journal on expiry. Neither GPU timer reads nor currentthread/yield calls on this selected route. Callerflush/reset thread operations remain separate required services.'}, 'fecs_055403': {'requested_us': 'scale*500000 silicon;scale*5000000 emulation/simulation', 'flags': '0 silicon/emulation;4 simulation', 'with_initialized_linux_default': '8 silicon (nonzero duration meansUSE_THREAD_STATE is not forced)', 'requires': 'explicit059492 resetcurrentthread before wait, real yield;059505 still consults thread_timeout after localnonexpiry unlessbypass4; actualFECS submit/recoverydiagnosticservices remain mandatory.'}}, + 'owner_requirements': ['Data.gpu is nativeOBJGPU pointer identity. RustGpuId must resolve retained same-owner GPU state; BDF, BOOT identity or GPU-ID truncation is not a substitute.', 'Thread compute mask uses actual allocatedgpuInstance, not prepared registry key/devicegroup/PCIid.', 'Construct Data from actual ownedGPUsoftware/runtime+LinuxOSdefaultpolicy+real registry override, retain sameowner for whole wait. No caller-supplied ready/defaultflags.', 'Connected/reset/emulation fields must be read from actual lifecycle owner under serialization; hardware_ready=false is neither disconnected nor in reset.', 'OS_TIMER bypasses hardware PTIMER only. It does not permit unavailable thread/yield/journal providers to return success. TLB0x105 is the proven minimal localOS route; changing BAR2bind/FECS flags would change original behavior.'], + 'validation': {'evidence_assertions': len(checks), 'checks': checks, 'new_runtime_tests': 0, 'reason': 'Read-only investigation; existing original timeout/thread differential suites remain unchanged.'}, + 'evidence': records, + 'guidance': ['matching580 source gpu_timeout.c,unix/os.c:2005,unix/osinit.c:275,thread_state.c:228/519/1149,generated/g_gpu_nvoc.h properties and g_gpu_nvoc.c init_dataField', 'existing reports/gpu-pf-constructor.txt and gpu-pf-constructor-validation.json prove zeroed6e70 GPU canonical image and ordered381 constructor writes', 'matching580 kern_gmmu_gm107.c:165 corroborates TLB0x105; existing BAR2bind/TLB and FECS REA indices contain complete selectedcaller evidence'] + } + (ROOT / 'reports/timer-timeout-provenance.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8') + print(json.dumps({'evidence_assertions': len(checks), 'rea_functions': len(records), 'report': 'reports/timer-timeout-provenance.json'})) + + +if __name__ == '__main__': + main()