tools,gpu: fix broken timer-state-load-test.sh and hardcoded toolchain/analysis paths

- tools/timer-state-load-test.sh: resolve rustc and clippy-driver via rustup which / PATH / rustc sibling instead of hardcoding $HOME/.rustup/toolchains/1.100.0-x86_64-unknown-linux-gnu, and mark executable.
- src/nvidia/src/gpu/timer/load.rs: collapse nested if-let chain so timer-state-load-test.sh passes clippy-driver -D warnings cleanly on edition 2024.
- tools/gpu_generate_owned_clock_templates.py, tools/gpu_generate_clock_level_program.py, tools/gpu_generate_clock_cache_data.py: discover rustfmt via RUSTFMT / rustup which / PATH / RUSTUP_HOME instead of hardcoded ~/.rustup/toolchains/..., honor NV_RS_RM_OBJECT / NV_RS_ANALYSIS_ROOT, and wrap CLI entrypoints in main().
- tools/first_open_coverage.py: resolve nv-kernel.o_binary via NV_RS_RM_OBJECT / NV_RS_ANALYSIS_ROOT / /usr/src/nvidia-580.178.04 fallback, defer SPINE loading out of import scope, and handle missing reports/first-open-coverage.json cleanly under --check.
- tests/offline/test_toolchain_and_coverage_tools.py: 4 offline unit tests.
This commit is contained in:
morebrackets
2026-12-02 03:07:40 -08:00
parent db720ba4a6
commit 36f7b979d2
7 changed files with 327 additions and 76 deletions

View File

@ -129,11 +129,11 @@ pub fn state_load<B: StateLoad>(
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()?;

View File

@ -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()

View File

@ -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")

View File

@ -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())

View File

@ -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)

View File

@ -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<v<2**32
return f'Some(MethodId(NonZeroU32::new(0x{v:x}).unwrap()))'
code='// Generated from exact580 original ELF template relocations.\n'
code+='const HEADERS: &[(TemplateId, Header)] = &[\n'
for t in meta['templates']:
v=int(t['section_offset'],16)+1;slots=t['slots'];assert slots[0]['symbol']==t['symbol'] and not slots[0]['addend']
tid=f'TemplateId(NonZeroU32::new(0x{v:x}).unwrap())'
code+=f' ({tid}, Header {{template_0:Some({tid}),method_8:{mid(slots[1],v-1+8)},methods_10_38:['+','.join(mid(slot,v-1+16+i*8) for i,slot in enumerate(slots[2:]))+']}), // '+t['symbol']+'\n'
code+='];\n'
for name,symbol in [('CRYSTAL_TEMPLATE','_nv021326rm'),('CONDITIONAL_BASE_TEMPLATE','_nv021357rm'),('CONDITIONAL_PARENT_TEMPLATE','_nv021342rm')]:
code+=f'pub const {name}: TemplateId = TemplateId(NonZeroU32::new(0x{byname[symbol]["st_value"]+1:x}).unwrap());\n'
native={t['symbol']:int(t['section_offset'],16) for t in meta['templates']}
def target_at(template,offset):
rel=relocs[native[template]+offset];symbol=symbols[rel['r_info_sym']];assert e.get_section(symbol['st_shndx']).name=='.text';return symbol['st_value']+rel['r_addend']
fixed={'NOOP_METHOD':byname['_nv021089rm']['st_value'],'FIXED_020586':target_at('_nv021342rm',0x10),'FIXED_020592':target_at('_nv021342rm',0x18),'FIXED_021059':target_at('_nv021326rm',0x20)}
assert fixed['FIXED_020592']==0x1fd7e0 and target_at('_nv021326rm',0x18)==0x1d9ad0
for name,value in fixed.items():code+=f'const {name}: MethodId = MethodId(NonZeroU32::new(0x{value+1:x}).unwrap());\n'
report={'source_sha256':source_sha,'headers':len(meta['templates']),'token_encoding':'Immutable original rodata/text section offset+1. Object lifetime IDs use separate per-registry tags.','constructor_functions':['020711','020712'],'same_named_020592_text_offsets':[hex(v['st_value']) for v in symbols if v.name=='_nv020592rm'],'crystal_slot18':'0x1d9ad0','conditional_parent_slot18':'0x1fd7e0','fixed_bindings_from_context':{k:hex(v) for k,v in fixed.items()},'limits':'Original immutable headers only. Constructed object/owner state and all missing services remain required.'}
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
for out,text in [(r/'src/nvidia/src/gpu/clock_owned_templates.rs',code),(r/'reports/gpu-clock-owned-templates.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('Original owned clock templates:35headers,020711/020712bindings')
import argparse, hashlib, json, os, re, shutil, subprocess
def find_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 cand in candidates:
if cand.is_file():
return cand
raise SystemExit('nv-kernel.o_binary not found (set NV_RS_RM_OBJECT or NV_RS_ANALYSIS_ROOT)')
def find_rustfmt(repo_root):
if os.environ.get('RUSTFMT'):
return Path(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 Path(res.stdout.strip())
which = shutil.which('rustfmt')
if which:
return Path(which)
channel = re.search(r'channel\s*=\s*"([^"]+)"', (repo_root / 'rust-toolchain.toml').read_text())[1]
rustup_home = Path(os.environ.get('RUSTUP_HOME', str(Path.home() / '.rustup')))
return rustup_home / 'toolchains' / f'{channel}-x86_64-unknown-linux-gnu/bin/rustfmt'
def main(argv=None):
try:
from elftools.elf.elffile import ELFFile
except ImportError as error:
raise SystemExit(f'pyelftools is required: {error}')
r = Path(__file__).resolve().parent.parent
p = argparse.ArgumentParser()
p.add_argument('--check', action='store_true')
a = p.parse_args(argv)
f = find_rm_object()
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 < v < 2**32
return f'Some(MethodId(NonZeroU32::new(0x{v:x}).unwrap()))'
code = '// Generated from exact580 original ELF template relocations.\n'
code += 'const HEADERS: &[(TemplateId, Header)] = &[\n'
for t in meta['templates']:
v = int(t['section_offset'], 16) + 1
slots = t['slots']
assert slots[0]['symbol'] == t['symbol'] and not slots[0]['addend']
tid = f'TemplateId(NonZeroU32::new(0x{v:x}).unwrap())'
code += (
f' ({tid}, Header {{template_0:Some({tid}),method_8:{mid(slots[1], v - 1 + 8)},'
f'methods_10_38:[' + ','.join(mid(slot, v - 1 + 16 + i * 8) for i, slot in enumerate(slots[2:]))
+ ']}), // ' + t['symbol'] + '\n'
)
code += '];\n'
for name, symbol in [
('CRYSTAL_TEMPLATE', '_nv021326rm'),
('CONDITIONAL_BASE_TEMPLATE', '_nv021357rm'),
('CONDITIONAL_PARENT_TEMPLATE', '_nv021342rm'),
]:
code += f'pub const {name}: TemplateId = TemplateId(NonZeroU32::new(0x{byname[symbol]["st_value"] + 1:x}).unwrap());\n'
native = {t['symbol']: int(t['section_offset'], 16) for t in meta['templates']}
def target_at(template, offset):
rel = relocs[native[template] + offset]
symbol = symbols[rel['r_info_sym']]
assert e.get_section(symbol['st_shndx']).name == '.text'
return symbol['st_value'] + rel['r_addend']
fixed = {
'NOOP_METHOD': byname['_nv021089rm']['st_value'],
'FIXED_020586': target_at('_nv021342rm', 0x10),
'FIXED_020592': target_at('_nv021342rm', 0x18),
'FIXED_021059': target_at('_nv021326rm', 0x20),
}
assert fixed['FIXED_020592'] == 0x1fd7e0 and target_at('_nv021326rm', 0x18) == 0x1d9ad0
for name, value in fixed.items():
code += f'const {name}: MethodId = MethodId(NonZeroU32::new(0x{value + 1:x}).unwrap());\n'
report = {
'source_sha256': source_sha,
'headers': len(meta['templates']),
'token_encoding': 'Immutable original rodata/text section offset+1. Object lifetime IDs use separate per-registry tags.',
'constructor_functions': ['020711', '020712'],
'same_named_020592_text_offsets': [hex(v['st_value']) for v in symbols if v.name == '_nv020592rm'],
'crystal_slot18': '0x1d9ad0',
'conditional_parent_slot18': '0x1fd7e0',
'fixed_bindings_from_context': {k: hex(v) for k, v in fixed.items()},
'limits': 'Original immutable headers only. Constructed object/owner state and all missing services remain required.',
}
rustfmt = find_rustfmt(r)
code = subprocess.run([str(rustfmt), '--edition', '2024'], input=code, text=True, capture_output=True, check=True).stdout
for out, text in [
(r / 'src/nvidia/src/gpu/clock_owned_templates.rs', code),
(r / 'reports/gpu-clock-owned-templates.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('Original owned clock templates:35headers,020711/020712bindings')
return 0
if __name__ == '__main__':
raise SystemExit(main())

6
tools/timer-state-load-test.sh Normal file → Executable file
View File

@ -4,7 +4,7 @@ TASK_ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$TASK_ROOT"
TASK_OUT="$TASK_ROOT/target/timer-state-load"
mkdir -p "$TASK_OUT"
RUSTC=${RUSTC:-$(command -v rustc || echo "$HOME/.cargo/bin/rustc")}
RUSTC=${RUSTC:-$(rustup which rustc 2>/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" <<RUST
@ -18,5 +18,7 @@ mod timer {
RUST
"$RUSTC" -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"
"$TASK_OUT/test"
CLIPPY_DRIVER=${CLIPPY_DRIVER:-$HOME/.rustup/toolchains/1.100.0-x86_64-unknown-linux-gnu/bin/clippy-driver}
if [ -z "${CLIPPY_DRIVER:-}" ]; then
CLIPPY_DRIVER=$(rustup which clippy-driver 2>/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"