diff --git a/src/nvidia/src/gpu/timer/load.rs b/src/nvidia/src/gpu/timer/load.rs index 4e49741f..b7e75bc6 100644 --- a/src/nvidia/src/gpu/timer/load.rs +++ b/src/nvidia/src/gpu/timer/load.rs @@ -129,11 +129,11 @@ pub fn state_load( let hardware = (|| { if alarm_present { let kind = backend.callback_kind()?; - if backend.callback_pending(kind)? as u8 != 0 { - if let Some(head) = backend.alarm_active_head()? { - let deadline = backend.alarm_deadline_ns(&head)?; - backend.rearm_alarm(deadline)?; - } + if backend.callback_pending(kind)? as u8 != 0 + && let Some(head) = backend.alarm_active_head()? + { + let deadline = backend.alarm_deadline_ns(&head)?; + backend.rearm_alarm(deadline)?; } // Rearm/pending may change kind. The original reloads248 here. let kind = backend.callback_kind()?; diff --git a/tests/offline/test_toolchain_and_coverage_tools.py b/tests/offline/test_toolchain_and_coverage_tools.py new file mode 100644 index 00000000..9e9d6a33 --- /dev/null +++ b/tests/offline/test_toolchain_and_coverage_tools.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Offline tests for portable toolchain discovery and first_open_coverage.py.""" +from __future__ import annotations + +import importlib.util +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +def load_module(name: str, rel_path: str): + path = ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class TestPortableToolchainTools(unittest.TestCase): + def test_timer_state_load_script_syntax_and_executable(self) -> None: + script = ROOT / "tools/timer-state-load-test.sh" + self.assertTrue(os.access(script, os.X_OK)) + res = subprocess.run(["sh", "-n", str(script)], capture_output=True, text=True) + self.assertEqual(res.returncode, 0, res.stderr) + + def test_owned_clock_templates_rm_object_and_rustfmt_resolution(self) -> None: + mod = load_module("gpu_gen_templates", "tools/gpu_generate_owned_clock_templates.py") + with tempfile.TemporaryDirectory() as td: + fake = Path(td) / "nv-kernel.o_binary" + fake.write_bytes(b"ELF") + old = os.environ.get("NV_RS_RM_OBJECT") + try: + os.environ["NV_RS_RM_OBJECT"] = str(fake) + self.assertEqual(mod.find_rm_object(), fake) + finally: + if old is None: + os.environ.pop("NV_RS_RM_OBJECT", None) + else: + os.environ["NV_RS_RM_OBJECT"] = old + + def test_clock_cache_data_import_safe_and_rustfmt_override(self) -> None: + mod = load_module("gpu_gen_cache", "tools/gpu_generate_clock_cache_data.py") + old = os.environ.get("RUSTFMT") + try: + os.environ["RUSTFMT"] = "/custom/rustfmt" + self.assertEqual(mod.find_rustfmt(ROOT), "/custom/rustfmt") + finally: + if old is None: + os.environ.pop("RUSTFMT", None) + else: + os.environ["RUSTFMT"] = old + + def test_first_open_coverage_import_safe_and_rm_object_override(self) -> None: + mod = load_module("first_open_coverage", "tools/first_open_coverage.py") + with tempfile.TemporaryDirectory() as td: + fake = Path(td) / "nv-kernel.o_binary" + fake.write_bytes(b"ELF") + old = os.environ.get("NV_RS_RM_OBJECT") + try: + os.environ["NV_RS_RM_OBJECT"] = str(fake) + self.assertEqual(mod.find_original_rm_object(), fake) + finally: + if old is None: + os.environ.pop("NV_RS_RM_OBJECT", None) + else: + os.environ["NV_RS_RM_OBJECT"] = old + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/first_open_coverage.py b/tools/first_open_coverage.py index df62b801..70a21f32 100644 --- a/tools/first_open_coverage.py +++ b/tools/first_open_coverage.py @@ -43,18 +43,38 @@ This is a planning aid derived from the tables in this file, not evidence about give. `--markdown` prints the tables for the integration plan. """ import json +import os import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -ORIGINAL = Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/" - "nv-kernel.o_binary") + + +def find_original_rm_object(): + candidates = [] + if os.environ.get("NV_RS_RM_OBJECT"): + candidates.append(Path(os.environ["NV_RS_RM_OBJECT"])) + if os.environ.get("NV_RS_ANALYSIS_ROOT"): + candidates.append( + Path(os.environ["NV_RS_ANALYSIS_ROOT"]) / "extracted/kernel/nvidia/nv-kernel.o_binary" + ) + candidates.extend([ + Path("/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary"), + Path("/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary"), + Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/" + "nv-kernel.o_binary"), + ]) + for candidate in candidates: + if candidate.is_file(): + return candidate + raise SystemExit("nv-kernel.o_binary not found (set NV_RS_RM_OBJECT or NV_RS_ANALYSIS_ROOT)") + + LIVE = ROOT / "target/gpu-stage/original-engine-live.txt" REPORT = ROOT / "reports/first-open-coverage.json" -SPINE = json.loads((ROOT / "analysis/closed-driver-580/first-open-spine.json").read_text()) -NAMES = {child["class_id"]: child["name"] for child in SPINE["children"]} +SPINE_PATH = ROOT / "analysis/closed-driver-580/first-open-spine.json" PASS_OF = {"PreInitUnlocked": "PreInit", "PreInitLocked": "PreInit", "InitUnlocked": "Init", "InitLocked": "Init", "PreLoad": "PreLoad", "Load": "Load", "PostLoad": "PostLoad"} SLOT_ORDER = ("PreInitUnlocked", "PreInitLocked", "InitUnlocked", "InitLocked", "PreLoad", "Load", @@ -220,13 +240,16 @@ def walk(): def sizes(): - listing = subprocess.run(["nm", "-S", "--defined-only", str(ORIGINAL)], capture_output=True, + original = find_original_rm_object() + listing = subprocess.run(["nm", "-S", "--defined-only", str(original)], capture_output=True, text=True, check=True).stdout return {fields[3]: int(fields[1], 16) for fields in map(str.split, listing.splitlines()) if len(fields) == 4} def build(): + spine = json.loads(SPINE_PATH.read_text()) + names = {child["class_id"]: child["name"] for child in spine["children"]} callbacks, classes = walk() answered = connected() size = sizes() @@ -235,7 +258,7 @@ def build(): trees = json.loads((ROOT / "reports/gv100-engine-call-trees.json").read_text())["classes"] segments = {segment["id"]: segment for segment in json.loads( (ROOT / "reports/original-trace-b3-segment-map.json").read_text())["segments"]} - by_name = {name: class_id for class_id, name in NAMES.items()} + by_name = {name: class_id for class_id, name in names.items()} def status_of(name, slot, class_id, body): if answered.get((class_id, slot)) == body: @@ -250,7 +273,7 @@ def build(): rows, order = {}, [] for position, (descriptor, slot, body) in enumerate(callbacks): class_id = descriptor >> 8 - name = NAMES[class_id] + name = names[class_id] key = (name, slot) if key not in rows: rows[key] = {"class": name, "class_id": f"{class_id:x}", "slot": slot, @@ -312,8 +335,8 @@ def build(): return found walk_verified = [position for position, (descriptor, slot, _body) in enumerate(callbacks) - if (NAMES[descriptor >> 8], slot) in verified - and NAMES[descriptor >> 8] in COMPUTE_PATH] + if (names[descriptor >> 8], slot) in verified + and names[descriptor >> 8] in COMPUTE_PATH] candidates = [] for name in COMPUTE_PATH: slots = [slot for slot in ("ConstructEngine",) + SLOT_ORDER if missing(name, slot)] @@ -441,7 +464,7 @@ def main(): report = build() text = json.dumps(report, indent=1) + "\n" if "--check" in sys.argv: - if REPORT.read_text() != text: + if not REPORT.is_file() or REPORT.read_text() != text: print("reports/first-open-coverage.json is stale", file=sys.stderr) return 1 print("reports/first-open-coverage.json is current") diff --git a/tools/gpu_generate_clock_cache_data.py b/tools/gpu_generate_clock_cache_data.py index a776ee4c..ef1c856b 100644 --- a/tools/gpu_generate_clock_cache_data.py +++ b/tools/gpu_generate_clock_cache_data.py @@ -1,20 +1,65 @@ #!/usr/bin/env python3 """Exact selected020153 base-level cache-prefix stores from original inference.""" from pathlib import Path -import re,json,argparse,hashlib,subprocess -r=Path(__file__).resolve().parent.parent;p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');a=p.parse_args() -s=next(Path('/home/geodd/nvidia-driver/analysis-580.178.04/decompiled/kernel-rm-all/functions').glob('*/*__nv020153rm.c')).read_text();s=s[:s.index(' lVar11 = *(long *)(param_1 + 0x1ec0);')] -rows=[] -for index,value in re.findall(r'(?:\*param_5|param_5\[([^]]+)\]) = (0x[0-9a-f]+);',s): - i=0 if not index else int(index,0);assert i%4==0;rows.append((i//4,int(value,16))) -flags=[int(off,16)//16 for off in re.findall(r'\*\(undefined1 \*\)\(\(long\)param_5 \+ (0x[0-9a-f]+)\) = 0;',s)] -assert [i for i,v in rows]==list(range(66))+list(range(67,75)) and flags==list(range(66)) -code='// Generated from literal original020153 base-level cache prefix.\nconst ADDRESS_STORES: &[(usize,u32)] = &[\n'+''.join(f' ({i},0x{v:x}),\n' for i,v in rows)+'];\n' -toolchain=re.search(r'channel\s*=\s*"([^"]+)"',(r/'rust-toolchain.toml').read_text()).group(1) -code=subprocess.run([str(Path.home()/'.rustup/toolchains'/f'{toolchain}-x86_64-unknown-linux-gnu/bin/rustfmt'),'--edition','2024'],input=code,text=True,capture_output=True,check=True).stdout -report={'source_sha256':'5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b','inferred_prefix_sha256':hashlib.sha256(s.encode()).hexdigest(),'address_stores':rows,'clear_byte_d_rows':flags,'untouched_address_rows':[66]+list(range(75,130)),'limits':'Only actual constructor stores; all other record fields retain caller-provided state. No empty/default records or hardware access.'} -for out,text in [(r/'src/nvidia/src/gpu/clock_cache_data.rs',code),(r/'reports/gpu-clock-cache-data.json',json.dumps(report,indent=2)+'\n')]: - if a.check: - if out.read_text()!=text:raise SystemExit('Stale '+str(out)) - else:out.write_text(text) -print('Original020153cache:74address stores,66byteD clears; record66 address untouched') +import argparse, hashlib, json, os, re, shutil, subprocess + + +def find_rustfmt(repo_root): + if os.environ.get('RUSTFMT'): + return os.environ['RUSTFMT'] + rustup = shutil.which('rustup') + if rustup: + res = subprocess.run([rustup, 'which', 'rustfmt'], capture_output=True, text=True) + if res.returncode == 0 and res.stdout.strip(): + return res.stdout.strip() + which = shutil.which('rustfmt') + if which: + return which + toolchain = re.search(r'channel\s*=\s*"([^"]+)"', (repo_root / 'rust-toolchain.toml').read_text()).group(1) + rustup_home = Path(os.environ.get('RUSTUP_HOME', str(Path.home() / '.rustup'))) + return str(rustup_home / 'toolchains' / f'{toolchain}-x86_64-unknown-linux-gnu/bin/rustfmt') + + +def main(argv=None): + r = Path(__file__).resolve().parent.parent + p = argparse.ArgumentParser() + p.add_argument('--check', action='store_true') + a = p.parse_args(argv) + analysis_root = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', '/home/geodd/nvidia-driver/analysis-580.178.04')) + matches = list((analysis_root / 'decompiled/kernel-rm-all/functions').glob('*/*__nv020153rm.c')) + if not matches: + raise SystemExit(f'missing __nv020153rm.c under {analysis_root} (set NV_RS_ANALYSIS_ROOT)') + s = matches[0].read_text() + s = s[:s.index(' lVar11 = *(long *)(param_1 + 0x1ec0);')] + rows = [] + for index, value in re.findall(r'(?:\*param_5|param_5\[([^]]+)\]) = (0x[0-9a-f]+);', s): + i = 0 if not index else int(index, 0) + assert i % 4 == 0 + rows.append((i // 4, int(value, 16))) + flags = [int(off, 16) // 16 for off in re.findall(r'\*\(undefined1 \*\)\(\(long\)param_5 \+ (0x[0-9a-f]+)\) = 0;', s)] + assert [i for i, v in rows] == list(range(66)) + list(range(67, 75)) and flags == list(range(66)) + code = '// Generated from literal original020153 base-level cache prefix.\nconst ADDRESS_STORES: &[(usize,u32)] = &[\n' + ''.join(f' ({i},0x{v:x}),\n' for i, v in rows) + '];\n' + code = subprocess.run([find_rustfmt(r), '--edition', '2024'], input=code, text=True, capture_output=True, check=True).stdout + report = { + 'source_sha256': '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b', + 'inferred_prefix_sha256': hashlib.sha256(s.encode()).hexdigest(), + 'address_stores': rows, + 'clear_byte_d_rows': flags, + 'untouched_address_rows': [66] + list(range(75, 130)), + 'limits': 'Only actual constructor stores; all other record fields retain caller-provided state. No empty/default records or hardware access.', + } + for out, text in [ + (r / 'src/nvidia/src/gpu/clock_cache_data.rs', code), + (r / 'reports/gpu-clock-cache-data.json', json.dumps(report, indent=2) + '\n'), + ]: + if a.check: + if out.read_text() != text: + raise SystemExit('Stale ' + str(out)) + else: + out.write_text(text) + print('Original020153cache:74address stores,66byteD clears; record66 address untouched') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/gpu_generate_clock_level_program.py b/tools/gpu_generate_clock_level_program.py index c7acbc2b..82a12c1b 100644 --- a/tools/gpu_generate_clock_level_program.py +++ b/tools/gpu_generate_clock_level_program.py @@ -5,8 +5,9 @@ Original machine-instruction image comparisons validate the resulting program. """ from pathlib import Path from pycparser import c_parser,c_ast -import re,json,hashlib,collections,struct -ROOT=Path('/home/geodd/nvidia-driver/analysis-580.178.04');source=next((ROOT/'decompiled/kernel-rm-all/functions').glob('*/*__nv020153rm.c')).read_text() +import re, json, hashlib, collections, os, shutil, struct +ROOT = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', '/home/geodd/nvidia-driver/analysis-580.178.04')) +source = next((ROOT / 'decompiled/kernel-rm-all/functions').glob('*/*__nv020153rm.c')).read_text() text=re.sub(r'/\*.*?\*/','',source,flags=re.S) text=text.replace('(**(code **)(lVar11 + 0x8c0))','_memory_engine_query') text='typedef unsigned char byte,undefined1; typedef unsigned short ushort,undefined2;typedef unsigned int uint,undefined4;typedef unsigned long ulong,undefined8;typedef void code();\n'+text @@ -140,8 +141,22 @@ for key in ['param_1','param_2','param_3','param_4','param_5','unaff_RBP']:code+ code+='const LOCAL_COUNT:usize='+str(len(vars))+';\n' for name in ['_nv021326rm','_nv021357rm','_nv021342rm']:code+='const TEMPLATE_'+name[3:9]+':u64='+str(globals[name])+';\n' # Format only small trailing declarations; skip tables for stable bounded source. -channel=re.search(r'channel\s*=\s*"([^"]+)"',(r/'rust-toolchain.toml').read_text())[1];rustfmt=Path.home()/'.rustup/toolchains'/f'{channel}-x86_64-unknown-linux-gnu/bin/rustfmt';code=subprocess.run([str(rustfmt),'--edition','2024'],input=code,text=True,capture_output=True,check=True).stdout +rustfmt = os.environ.get('RUSTFMT') +if not rustfmt: + rustup = shutil.which('rustup') + if rustup: + res = subprocess.run([rustup, 'which', 'rustfmt'], capture_output=True, text=True) + if res.returncode == 0 and res.stdout.strip(): + rustfmt = res.stdout.strip() +if not rustfmt: + rustfmt = shutil.which('rustfmt') +if not rustfmt: + channel = re.search(r'channel\s*=\s*"([^"]+)"', (r / 'rust-toolchain.toml').read_text())[1] + rustup_home = Path(os.environ.get('RUSTUP_HOME', str(Path.home() / '.rustup'))) + rustfmt = str(rustup_home / 'toolchains' / f'{channel}-x86_64-unknown-linux-gnu/bin/rustfmt') +code = subprocess.run([rustfmt, '--edition', '2024'], input=code, text=True, capture_output=True, check=True).stdout report={'artifact_sha256':artifact_sha,'inferred_c_sha256':hashlib.sha256(source.encode()).hexdigest(),'variables':len(vars),'expressions':len(exprs),'operations':len(ops),'calls':calls,'limits':'Generated fulloriginalinferredC control/store program. Actualboundownedmemory/services and independentoriginalinstructionparity remain required. No native/GPU execution.'} for dest,content in [(r/'src/nvidia/src/gpu/clock_level_program.rs',code),(r/'reports/gpu-clock-level-program.json',json.dumps(report,indent=2)+'\n')]: - if options.check:assert dest.read_text()==content,'Stale '+str(dest) + if options.check: + if dest.read_text()!=content:raise SystemExit('Stale '+str(dest)) else:dest.write_text(content) diff --git a/tools/gpu_generate_owned_clock_templates.py b/tools/gpu_generate_owned_clock_templates.py index 3e246a45..d941b791 100644 --- a/tools/gpu_generate_owned_clock_templates.py +++ b/tools/gpu_generate_owned_clock_templates.py @@ -1,41 +1,132 @@ #!/usr/bin/env python3 """Immutable original clock templates and exact native constructor identities.""" from pathlib import Path -import json,argparse,hashlib,subprocess,re -from elftools.elf.elffile import ELFFile -r=Path(__file__).resolve().parent.parent;p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');a=p.parse_args() -f=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary') -meta=json.loads((r/'reports/gpu-clock-object-metadata.json').read_text()) -source_sha=hashlib.sha256(f.read_bytes()).hexdigest() -assert source_sha=='5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b' -with f.open('rb') as stream: - e=ELFFile(stream);symbols=list(e.get_section_by_name('.symtab').iter_symbols());byname={s.name:s for s in symbols};relocs={v['r_offset']:v for v in e.get_section_by_name('.rela.rodata').iter_relocations()} - def mid(slot,offset): - if slot is None:return 'None' - rel=relocs[offset];s=symbols[rel['r_info_sym']];assert e.get_section(s['st_shndx']).name=='.text' - v=s['st_value']+rel['r_addend']+1;assert 0/dev/null || command -v rustc || echo "$HOME/.cargo/bin/rustc")} "$RUSTC" -D warnings --edition=2024 --crate-name nv_rs_abi --crate-type=rlib src/common/abi/src/lib.rs -o "$TASK_OUT/libnv_rs_abi.rlib" "$RUSTC" -D warnings --edition=2024 --crate-name nv_rs_core --crate-type=rlib src/nvidia/src/lib.rs --extern nv_rs_abi="$TASK_OUT/libnv_rs_abi.rlib" -o "$TASK_OUT/libnv_rs_core.rlib" cat > "$TASK_OUT/fixture.rs" </dev/null || command -v clippy-driver || printf '%s/clippy-driver' "$(dirname "$RUSTC")") +fi "$CLIPPY_DRIVER" -D warnings --edition=2024 --test --crate-name timer_state_load "$TASK_OUT/fixture.rs" --extern nv_rs_abi="$TASK_OUT/libnv_rs_abi.rlib" --extern nv_rs_core="$TASK_OUT/libnv_rs_core.rlib" -L dependency="$TASK_OUT" -o "$TASK_OUT/test-clippy"