diff --git a/tests/offline/test_oracle_portability_and_capture.py b/tests/offline/test_oracle_portability_and_capture.py new file mode 100644 index 00000000..b2c61d61 --- /dev/null +++ b/tests/offline/test_oracle_portability_and_capture.py @@ -0,0 +1,110 @@ +"""Offline unit tests for oracle portability and capture/comparison tools.""" +from __future__ import annotations + +import ctypes +import importlib.util +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] + + +def _load(rel_path: str, module_name: str): + path = ROOT / rel_path + spec = importlib.util.spec_from_file_location(module_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 TestOraclePortabilityAndCapture(unittest.TestCase): + def test_uvm_ioctl_layout_resolves_env_and_rejects_bad_flag(self): + mod = _load("tools/check_uvm_ioctl_layout.py", "check_uvm_ioctl_layout") + with tempfile.TemporaryDirectory() as td: + tree = Path(td) + (tree / "nvidia-uvm").mkdir(parents=True) + (tree / "common/inc").mkdir(parents=True) + (tree / "nvidia-uvm/uvm.c").write_text("// stub\n") + with mock.patch.dict(os.environ, {"NV_RS_KERNEL_SRC": str(tree)}, clear=False): + trees = mod.resolve_source_trees() + self.assertEqual(trees[0][0], "env") + self.assertEqual(trees[0][1], tree) + with self.assertRaises(SystemExit) as ctx: + mod.main(["--unknown-flag"]) + self.assertEqual(ctx.exception.code, 2) + + def test_tlb_and_system_time_oracles_honor_env_override(self): + tlb = _load("tools/check_gv100_tlb_oracle.py", "check_gv100_tlb_oracle") + systime = _load("tools/check_system_time_source.py", "check_system_time_source") + with tempfile.TemporaryDirectory() as td: + tree = Path(td) + (tree / "nvidia-uvm").mkdir(parents=True) + (tree / "nvidia").mkdir(parents=True) + (tree / "nvidia-uvm/uvm_pascal_host.c").write_text("") + (tree / "nvidia/os-interface.c").write_text("") + with mock.patch.dict(os.environ, {"NV_RS_KERNEL_SRC": str(tree)}, clear=False): + self.assertEqual(tlb.resolve_uvm_source_dir(), tree / "nvidia-uvm") + self.assertEqual( + systime.resolve_original_os_interface(), + tree / "nvidia/os-interface.c", + ) + + def test_compare_software_controls_label_normalization_is_single_pass(self): + mod = _load("tools/compare_software_controls.py", "compare_software_controls") + mapping = {0xC1: 0xC2, 0xC2: 0xC3} + # Single-pass boundary-aware replacement must not chain 0xc1->0xc2->0xc3 + # and must not corrupt longer hex tokens like 0xc10. + self.assertEqual( + mod.normalize_label("alloc 0xc1 next 0xc2 keep 0xc10", mapping), + "alloc 0xc2 next 0xc3 keep 0xc10", + ) + # Unknown ioctl kind reports an issue instead of crashing with KeyError. + rec = { + "request": "0xc01046ff", + "input_top": "00" * 16, + "response": "00" * 16, + "linux_errno": 0, + "status": 0, + "label": "unknown", + } + cases = mod.compare_records({"records": [rec]}, {"records": [rec]}) + self.assertEqual(len(cases), 1) + self.assertFalse(cases[0]["passed"]) + self.assertTrue(any("unsupported ioctl kind" in issue for issue in cases[0]["issues"])) + + def test_cuda_basic_binds_64bit_argtypes(self): + mod = _load("tools/ioctl_capture/cuda_basic.py", "ioctl_capture_cuda_basic") + + class FakeFn: + argtypes = None + restype = None + + class FakeCuda: + def __init__(self): + for name in ( + "cuInit", + "cuDeviceGet", + "cuCtxCreate_v2", + "cuMemAlloc_v2", + "cuMemcpyHtoD_v2", + "cuMemcpyDtoH_v2", + "cuCtxSynchronize", + "cuMemFree_v2", + "cuCtxDestroy_v2", + ): + setattr(self, name, FakeFn()) + + fake = mod._bind_cuda(FakeCuda()) + self.assertEqual(fake.cuMemAlloc_v2.argtypes[1], ctypes.c_size_t) + self.assertEqual(fake.cuMemcpyHtoD_v2.argtypes, [ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t]) + self.assertEqual(fake.cuMemcpyDtoH_v2.argtypes, [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_size_t]) + self.assertEqual(fake.cuMemFree_v2.argtypes, [ctypes.c_uint64]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/check_gv100_tlb_oracle.py b/tools/check_gv100_tlb_oracle.py index 852e488c..ccf4ba0f 100755 --- a/tools/check_gv100_tlb_oracle.py +++ b/tools/check_gv100_tlb_oracle.py @@ -1,18 +1,46 @@ #!/usr/bin/env python3 """Differential vectors from exact580 shipped Pascal host functions (GV100 HAL inheritance).""" -import hashlib,json,subprocess,tempfile +import hashlib +import json +import os +import subprocess +import tempfile from pathlib import Path -R=Path(__file__).resolve().parents[1] -S=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia-uvm') -def function(text,name): - start=text.rfind('\nvoid ',0,text.index(name+'('))+1 - pos=text.index('{',start);level=1;end=pos+1 - while level: - level+=(text[end]=='{')-(text[end]=='}');end+=1 - return text[start:end] -source=(S/'uvm_pascal_host.c').read_text() -body='\n'.join(function(source,n) for n in ['uvm_hal_pascal_host_membar_sys','uvm_hal_pascal_host_membar_gpu','uvm_hal_pascal_host_tlb_invalidate_all']) -prefix=r''' + +R = Path(__file__).resolve().parents[1] + + +def resolve_uvm_source_dir(): + candidates = [] + if os.environ.get("NV_RS_KERNEL_SRC"): + candidates.append(Path(os.environ["NV_RS_KERNEL_SRC"]) / "nvidia-uvm") + if os.environ.get("NV_RS_ANALYSIS_ROOT"): + candidates.append(Path(os.environ["NV_RS_ANALYSIS_ROOT"]) / "extracted/kernel/nvidia-uvm") + candidates.extend([ + Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia-uvm"), + Path("/usr/src/nvidia-580.178.04/nvidia-uvm"), + Path("/usr/src/nvidia-srv-580.178.04/nvidia-uvm"), + ]) + for candidate in candidates: + if (candidate / "uvm_pascal_host.c").is_file(): + return candidate + raise SystemExit( + "Unable to locate uvm_pascal_host.c; set NV_RS_KERNEL_SRC or NV_RS_ANALYSIS_ROOT." + ) + + +def function(text, name): + start = text.rfind("\nvoid ", 0, text.index(name + "(")) + 1 + 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 #include #include @@ -36,21 +64,73 @@ typedef struct {uint32_t words[64];unsigned n,hshub;} uvm_push_t; #define NV_PUSH_4U(p,a,x,b,y,c,z,d,w) do{push->words[push->n++]=HWCONST(B06F,DMA,SEC_OP,INC_METHOD)|HWVALUE(B06F,DMA,INCR_ADDRESS,NV##p##_##a>>2)|HWVALUE(B06F,DMA,INCR_SUBCHANNEL,0)|HWVALUE(B06F,DMA,INCR_COUNT,4);push->words[push->n++]=(x);push->words[push->n++]=(y);push->words[push->n++]=(z);push->words[push->n++]=(w);}while(0) static void uvm_hal_tlb_invalidate_membar(uvm_push_t*,uvm_membar_t); ''' + # The original helper dispatches hshub GPU barriers then the requested barrier. # Callback plumbing is replaced; the called encoding functions remain original C. -tail=r''' +TAIL = r''' static void uvm_hal_tlb_invalidate_membar(uvm_push_t*p,uvm_membar_t m){if(m==0)return;for(unsigned i=0;ihshub;i++)uvm_hal_pascal_host_membar_gpu(p);if(m==1)uvm_hal_pascal_host_membar_gpu(p);else uvm_hal_pascal_host_membar_sys(p);} int main(void){uint64_t addresses[]={0,4096,0x12345000ULL,0x12345678000ULL,0x7fffffffffff000ULL};for(unsigned a=0;a<5;a++)for(unsigned ap=0;ap<2;ap++)for(unsigned d=0;d<5;d++)for(unsigned m=0;m<3;m++)for(unsigned h=0;h<3;h++){uvm_push_t p={.hshub=h};uvm_gpu_phys_address_t pdb={addresses[a],ap};uvm_hal_pascal_host_tlb_invalidate_all(&p,pdb,d,m);printf("%llu %u %u %u %u",(unsigned long long)addresses[a],ap,d,m,h);for(unsigned n=0;n + + +PROLOGUE = '''#include #include #include typedef uint32_t u32; @@ -24,7 +55,8 @@ struct timespec64 { int64_t tv_sec; long tv_nsec; }; static struct timespec64 clock_value; static void ktime_get_real_ts64(struct timespec64 *out) { *out=clock_value; } ''' -epilogue=''' + +EPILOGUE = ''' int main(void) { int64_t seconds[]={0,1,-1,INT32_MAX,UINT32_MAX,INT64_C(4294967296),INT64_MAX}; long nanoseconds[]={0,1,999,1000,999999999}; @@ -42,10 +74,42 @@ int main(void) { printf("%u\\n",count); } ''' -out=R/'target/system-time-source';out.mkdir(parents=True,exist_ok=True) -c=out/'original-and-replacement.c';exe=out/'comparison' -c.write_text(prologue+body(original.read_text(),'NV_STATUS NV_API_CALL os_get_system_time(')+'\n'+body(replacement.read_text(),'void nv_rs_clock_system_time(')+epilogue) -subprocess.run(['cc','-std=c11','-Wall','-Wextra','-Werror',str(c),'-o',str(exe)],check=True) -cases=int(subprocess.check_output([str(exe)],text=True));assert cases==35 -report={'passed':True,'cases':cases,'source_sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [original,replacement]},'scope':'Unchanged original and adapter conversion bodies compiled with the same scripted ktime_get_real_ts64. Includes negative/wrapping seconds and microsecond truncation. Does not compare simultaneous live wall-clock samples.'} -(R/'reports/system-time-source.json').write_text(json.dumps(report,indent=2)+'\n');print(cases,'original/adapter system-time conversion cases') + + +def main(): + original = resolve_original_os_interface() + out = R / "target/system-time-source" + out.mkdir(parents=True, exist_ok=True) + c = out / "original-and-replacement.c" + exe = out / "comparison" + c.write_text( + PROLOGUE + + body(original.read_text(), "NV_STATUS NV_API_CALL os_get_system_time(") + + "\n" + + body(REPLACEMENT.read_text(), "void nv_rs_clock_system_time(") + + EPILOGUE + ) + subprocess.run(["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", str(c), "-o", str(exe)], check=True) + cases = int(subprocess.check_output([str(exe)], text=True)) + if cases != 35: + raise SystemExit(f"expected 35 system-time comparison cases, got {cases}") + report = { + "passed": True, + "cases": cases, + "source_sha256": { + str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in [original, REPLACEMENT] + }, + "scope": ( + "Unchanged original and adapter conversion bodies compiled with the same scripted " + "ktime_get_real_ts64. Includes negative/wrapping seconds and microsecond truncation. " + "Does not compare simultaneous live wall-clock samples." + ), + } + report_path = R / "reports/system-time-source.json" + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text(json.dumps(report, indent=2) + "\n") + print(cases, "original/adapter system-time conversion cases") + + +if __name__ == "__main__": + main() diff --git a/tools/check_uvm_ioctl_layout.py b/tools/check_uvm_ioctl_layout.py index 090903bb..94b1966f 100644 --- a/tools/check_uvm_ioctl_layout.py +++ b/tools/check_uvm_ioctl_layout.py @@ -10,8 +10,10 @@ Writes target/uvm/ioctl-layout.txt, which `uvm::ioctl` is tested against. Two source trees are compiled and must agree: the reference tree of the analysis and, when present, the tree the loaded module was built from (/usr/src/nvidia-srv-580.178.04). """ +import argparse import hashlib import json +import os from pathlib import Path import re import subprocess @@ -22,6 +24,38 @@ ROOT = Path(__file__).resolve().parents[1] REFERENCE = Path("/home/geodd/nvidia-driver/analysis-580.178.04/reference/" "open-gpu-kernel-modules-580.178.04/kernel-open") INSTALLED = Path("/usr/src/nvidia-srv-580.178.04") +INSTALLED_FALLBACK = Path("/usr/src/nvidia-580.178.04") + + +def resolve_source_trees(): + """Return available `(label, kernel_open_root)` source trees in priority order.""" + candidates = [] + env_kernel = os.environ.get("NV_RS_KERNEL_SRC") + if env_kernel: + candidates.append(("env", Path(env_kernel))) + env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT") + if env_analysis: + candidates.append(( + "analysis", + Path(env_analysis) / "reference/open-gpu-kernel-modules-580.178.04/kernel-open", + )) + candidates.append(("analysis_extracted", Path(env_analysis) / "extracted/kernel")) + candidates.extend([ + ("reference", REFERENCE), + ("installed", INSTALLED), + ("installed", INSTALLED_FALLBACK), + ]) + found = [] + seen = set() + for label, tree in candidates: + if not (tree / "nvidia-uvm/uvm.c").is_file() or not (tree / "common/inc").is_dir(): + continue + key = tree.resolve() + if key in seen: + continue + seen.add(key) + found.append((label, tree)) + return found FIELDS = { "UVM_INITIALIZE": ("flags", "rmStatus"), "UVM_MM_INITIALIZE": ("uvmFd", "rmStatus"), @@ -59,7 +93,8 @@ def routes(uvm_c): def layout(uvm, include): table = routes((uvm / "uvm.c").read_text()) - assert len(table) == 45, len(table) + if len(table) != 45: + raise RuntimeError(f"expected 45 UVM ioctl routes in {uvm / 'uvm.c'}, found {len(table)}") program = ['#include ', '#include ', '#include "uvm_linux_ioctl.h"', 'int main(void) {'] for name, check, heap in table: @@ -89,19 +124,35 @@ def layout(uvm, include): return subprocess.run([str(binary)], check=True, capture_output=True, text=True).stdout -def main(): - text = layout(REFERENCE / "nvidia-uvm", REFERENCE / "common/inc") - trees = ["reference"] - if INSTALLED.exists(): - assert layout(INSTALLED / "nvidia-uvm", INSTALLED / "common/inc") == text, \ - "the installed and the reference source disagree" - trees.append("installed") +def main(argv=None): + parser = argparse.ArgumentParser(description="Compute /dev/nvidia-uvm ioctl struct layouts.") + parser.add_argument("--check", action="store_true", + help="Verify target/uvm/ioctl-layout.txt matches the computed layout.") + args = parser.parse_args(argv) + + source_trees = resolve_source_trees() + if not source_trees: + raise SystemExit( + "Unable to locate NVIDIA 580.178.04 nvidia-uvm sources; " + "set NV_RS_KERNEL_SRC or NV_RS_ANALYSIS_ROOT." + ) + + first_label, first_tree = source_trees[0] + text = layout(first_tree / "nvidia-uvm", first_tree / "common/inc") + trees = [first_label] + for label, tree in source_trees[1:]: + other = layout(tree / "nvidia-uvm", tree / "common/inc") + if other != text: + raise SystemExit(f"the {label} ({tree}) and {first_label} ({first_tree}) sources disagree") + trees.append(label) + text = ("# /dev/nvidia-uvm ioctl layouts from the public source; see " "tools/check_uvm_ioctl_layout.py\n" + text) target = ROOT / "target/uvm/ioctl-layout.txt" target.parent.mkdir(parents=True, exist_ok=True) - if "--check" in sys.argv: - assert target.read_text() == text, "layout record differs from the checked copy" + if args.check: + if not target.is_file() or target.read_text() != text: + raise SystemExit("layout record differs from the checked copy") else: target.write_text(text) print(json.dumps(dict(record=str(target.relative_to(ROOT)), trees=trees, diff --git a/tools/compare_software_controls.py b/tools/compare_software_controls.py index 2a72b9a6..1dbe8a2b 100644 --- a/tools/compare_software_controls.py +++ b/tools/compare_software_controls.py @@ -1,54 +1,180 @@ #!/usr/bin/env python3 """Actual original-vs-loaded Rust parity; normalize only opaque handles/pointers.""" +import argparse +import hashlib +import json from pathlib import Path -import argparse,json,hashlib -R=Path(__file__).resolve().parent.parent -p=argparse.ArgumentParser();p.add_argument('--original',type=Path,default=R/'reports/software-controls-replay-original.json');p.add_argument('--rust',type=Path,default=R/'reports/software-controls-rust-live.json');p.add_argument('--out',type=Path,default=R/'reports/software-controls-live-comparison.json');a=p.parse_args() -original=json.loads(a.original.read_text());rust=json.loads(a.rust.read_text());mapping={};cases=[] -def word(b,offset):return int.from_bytes(b[offset:offset+4],'little') -def mapped(b,offset): - key=word(b,offset) - if key in mapping:b[offset:offset+4]=mapping[key].to_bytes(4,'little') -def normalize_top(data,kind): - data=bytearray.fromhex(data) - for offset in ({0x2b:[0,4,8],0x2a:[0,4],0x29:[0,4,8]}[kind]):mapped(data,offset) - return data -def normalize_payload(data,kind): - data=bytearray.fromhex(data or '') - if kind==0x2a and len(data)>=4:mapped(data,0) - return data -if len(original['records'])!=len(rust['records']):raise SystemExit('Request sequence lengths differ') -if not original['records']: - raise SystemExit('No records to compare') -for i,(old,new) in enumerate(zip(original['records'],rust['records'])): - issues=[];req=int(old['request'],16);kind=req&255 - if req!=int(new['request'],16):issues.append('request ioctl differs') - inp=normalize_top(old['input_top'],kind);actual_input=bytearray.fromhex(new['input_top']);ptr_offset=16 if kind in [0x2a,0x2b] else None - # Only known Python-backed non-null parameter pointers are normalized. NULL and - # sentinel/non-backed addresses would remain exact and expose validation gaps. - pointer_pair=None - if ptr_offset is not None and old.get('input_payload') is not None and new.get('input_payload') is not None: - oldptr=int.from_bytes(inp[ptr_offset:ptr_offset+8],'little');newptr=int.from_bytes(actual_input[ptr_offset:ptr_offset+8],'little') - if oldptr and newptr:pointer_pair=(oldptr,newptr);inp[ptr_offset:ptr_offset+8]=newptr.to_bytes(8,'little') - if inp!=actual_input:issues.append('normalized request wrapper differs') - if normalize_payload(old.get('input_payload'),kind)!=bytearray.fromhex(new.get('input_payload') or ''):issues.append('normalized input payload differs') - if old['linux_errno']!=new['linux_errno']:issues.append('Linux errno differs') - if old['status']!=new['status']:issues.append('NV status differs') - if kind==0x2b: - expected_obj=word(bytes.fromhex(old['response']),8);actual_obj=word(bytes.fromhex(new['response']),8) - if word(bytes.fromhex(old['input_top']),0)==0 and expected_obj and (old['status']==0 or expected_obj!=word(bytes.fromhex(old['input_top']),8)): - if expected_obj in mapping and mapping[expected_obj]!=actual_obj:issues.append('client handle mapping changed') - if actual_obj==0:issues.append('generated client became NULL') - if any(k!=expected_obj and v==actual_obj for k,v in mapping.items()):issues.append('opaque client mapping collapsed distinct handles') - mapping[expected_obj]=actual_obj - out=normalize_top(old['response'],kind);actual_out=bytearray.fromhex(new['response']) - if pointer_pair is not None: - oldptr,newptr=pointer_pair - if int.from_bytes(out[ptr_offset:ptr_offset+8],'little')==oldptr:out[ptr_offset:ptr_offset+8]=newptr.to_bytes(8,'little') - if out!=actual_out:issues.append('normalized response wrapper differs') - if normalize_payload(old.get('payload'),kind)!=bytearray.fromhex(new.get('payload') or ''):issues.append('normalized output payload differs') - label=old['label'] - for before,after in mapping.items():label=label.replace(hex(before),hex(after)) - if label!=new['label']:issues.append('case identity/order differs after handle normalization') - cases.append({'original_label':old['label'],'rust_label':new['label'],'passed':not issues,'issues':issues}) -report={'passed':all(c['passed'] for c in cases),'scope':'Actual loaded Rust software-only controls vs original responses. Not CUDA or physical GPU parity.','cases':cases,'case_count':len(cases),'source_sha256':{str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in [a.original,a.rust]},'rust_module_identity':rust.get('module_identity'),'normalization':['Generated client handles mapped consistently/injectively at root allocation responses.','Only known non-null Python-backed nested parameter pointer fields are normalized.','No NV status, Linux errno, padding, method values or output payload data are excluded.'],'limits':['Runs occur at different times; identical deterministic control inputs and normalized opaque identifiers are compared.','This finite software-client suite does not establish GPU/backend/security/concurrency parity.']};a.out.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({'passed':report['passed'],'cases':len(cases),'failures':[c for c in cases if not c['passed']]},indent=2));raise SystemExit(0 if report['passed'] else 1) +import re + +R = Path(__file__).resolve().parent.parent +HANDLE_OFFSETS = {0x2b: (0, 4, 8), 0x2a: (0, 4), 0x29: (0, 4, 8)} + + +def word(b, offset): + return int.from_bytes(b[offset:offset + 4], "little") + + +def _mapped(b, offset, mapping): + if offset + 4 > len(b): + return + key = word(b, offset) + if key in mapping: + b[offset:offset + 4] = mapping[key].to_bytes(4, "little") + + +def normalize_top(data, kind, mapping): + buf = bytearray.fromhex(data) + for offset in HANDLE_OFFSETS.get(kind, ()): + _mapped(buf, offset, mapping) + return buf + + +def normalize_payload(data, kind, mapping): + buf = bytearray.fromhex(data or "") + if kind == 0x2a and len(buf) >= 4: + _mapped(buf, 0, mapping) + return buf + + +def normalize_label(label, mapping): + if not mapping: + return label + replacements = {hex(before): hex(after) for before, after in mapping.items()} + pattern = re.compile( + r"(?