tools: fix temp-file leak in build-product, empty-list crash in timer checker, and ELF portability

This commit is contained in:
morebrackets
2026-12-02 05:10:24 -08:00
parent db720ba4a6
commit a944c69215
5 changed files with 668 additions and 119 deletions

View File

@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Offline tests for timer-timeout-build-product, check_original_live_timer_init,
gpu_label_live_engines, and gpu_engine_dispatch_sites.
"""
import contextlib
import hashlib
import importlib.util
import io
import json
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 BuildProductAndLiveTimerToolsTest(unittest.TestCase):
def test_all_four_tools_are_import_safe(self):
for rel in (
"tools/timer-timeout-build-product.py",
"tools/check_original_live_timer_init.py",
"tools/gpu_label_live_engines.py",
"tools/gpu_engine_dispatch_sites.py",
):
mod = _load(Path(rel).stem.replace("-", "_"), rel)
self.assertTrue(callable(mod.main))
def test_build_product_cleans_up_tempfile_on_replace_failure(self):
mod = _load("timer_timeout_build_product", "tools/timer-timeout-build-product.py")
with tempfile.TemporaryDirectory() as tmp:
receipt = Path(tmp) / "receipt.json"
with (
mock.patch.object(Path, "replace", side_effect=OSError("simulated failure")),
self.assertRaises(OSError),
):
mod.main(["--receipt", str(receipt)])
self.assertEqual(list(Path(tmp).iterdir()), [])
def test_live_timer_init_handles_empty_timeout_us_without_index_error(self):
mod = _load("check_original_live_timer_init", "tools/check_original_live_timer_init.py")
with tempfile.TemporaryDirectory() as tmp:
d = Path(tmp)
perf_data = b"perf"
(d / "perf.data").write_bytes(perf_data)
sha = hashlib.sha256(perf_data).hexdigest()
(d / "before.json").write_text(json.dumps({
"sha256": "abc", "bindings": {}, "symbols": {"_nv059665rm": "0x1000"},
}), encoding="utf-8")
(d / "after.json").write_text(json.dumps({
"sha256": "abc", "bindings": {}, "symbols": {"_nv059665rm": "0x1000"}, "perf_sha256": sha,
}), encoding="utf-8")
(d / "rea-capture.json").write_text(json.dumps({
"structuredContent": {
"evidence_id": "test",
"limitations": [],
"normalized_result": {"exit": {"code": 0}, "frames": []},
}
}), encoding="utf-8")
# One load sample with zero config samples -> timeout_us is [].
(d / "perf-script.txt").write_text(
"app 1/1 1.000000001: mem:0x1000:x: 1000 _nv059665rm ABI:2 DI:0x10000 SI:0x20000 DX:0x0\n",
encoding="utf-8",
)
(d / "perf-dump.txt").write_text("", encoding="utf-8")
with contextlib.redirect_stdout(io.StringIO()):
rc = mod.main([str(d)])
self.assertEqual(rc, 1)
val = json.loads((d / "validation.json").read_text(encoding="utf-8"))
self.assertFalse(val["checks"]["all_initial_configs_4s_os_timer_and_load_flags_zero"])
def test_label_live_engines_rejects_bad_sha256_under_O(self):
mod = _load("gpu_label_live_engines", "tools/gpu_label_live_engines.py")
with tempfile.TemporaryDirectory() as tmp:
fake = Path(tmp) / "nv-kernel.o_binary"
fake.write_bytes(b"bad")
with mock.patch.dict(os.environ, {"NV_RS_RM_OBJECT": str(fake)}, clear=True):
with self.assertRaisesRegex(SystemExit, "sha256 mismatch"):
mod.main([])
if __name__ == "__main__":
unittest.main()

View File

@ -12,24 +12,31 @@ from pathlib import Path
import re
def main():
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("report_directory", type=Path)
args = parser.parse_args()
args = parser.parse_args(argv)
root = args.report_directory
before = json.loads((root / "before.json").read_text())
after = json.loads((root / "after.json").read_text())
raw = json.loads((root / "rea-capture.json").read_text())
required = ("before.json", "after.json", "rea-capture.json", "perf-script.txt", "perf-dump.txt", "perf.data")
for rel in required:
if not (root / rel).is_file():
raise SystemExit(f"missing required capture file: {root / rel}")
before = json.loads((root / "before.json").read_text(encoding="utf-8"))
after = json.loads((root / "after.json").read_text(encoding="utf-8"))
raw = json.loads((root / "rea-capture.json").read_text(encoding="utf-8"))
evidence = raw.get("structuredContent")
if evidence is None:
evidence = json.loads(next(c["text"] for c in raw["content"] if c["type"] == "text"))
text_chunk = next((c["text"] for c in raw.get("content", ()) if c.get("type") == "text"), None)
if text_chunk is None:
raise SystemExit(f"no text content entry in {root / 'rea-capture.json'}")
evidence = json.loads(text_chunk)
capture = evidence["normalized_result"]
pattern = re.compile(
r"^\s*(\S+)\s+(\d+)/(\d+)\s+(\d+)\.(\d{9}):\s+"
r"mem:(0x[0-9a-f]+):x:\s+([0-9a-f]+)\s+(_nv\d+rm)\s+ABI:2(.*)$"
)
events, rejected = [], []
for line in (root / "perf-script.txt").read_text().splitlines():
for line in (root / "perf-script.txt").read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
match = pattern.fullmatch(line)
@ -48,18 +55,27 @@ def main():
loads = [e for e in events if e["symbol"] == "_nv059665rm"]
groups = []
for load in loads:
gpu = load["registers"]["DI"]
ds = [e for e in defaults if e["registers"]["SI"] == gpu]
cs = [e for e in configs if e["registers"]["DI"] == gpu]
regs = load["registers"]
gpu = regs.get("DI")
timer = regs.get("SI")
dx = regs.get("DX")
if gpu is None or timer is None or dx is None:
rejected.append(f"incomplete registers on load sample at {load['perf_time_ns']}")
continue
ds = [e for e in defaults if e["registers"].get("SI") == gpu and "DI" in e["registers"]]
cs = [
e for e in configs
if e["registers"].get("DI") == gpu and "SI" in e["registers"] and "DX" in e["registers"]
]
groups.append({
"gpu_owner": gpu, "timer_owner": load["registers"]["SI"],
"load_flags": int(load["registers"]["DX"], 16),
"gpu_owner": gpu, "timer_owner": timer,
"load_flags": int(dx, 16),
"default_data_offsets": [int(e["registers"]["DI"], 16) - int(gpu, 16) for e in ds],
"timeout_us": [int(e["registers"]["SI"], 16) for e in cs],
"timeout_flags": [int(e["registers"]["DX"], 16) for e in cs],
"initial_order": bool(ds and cs and ds[0]["perf_time_ns"] < cs[0]["perf_time_ns"] < load["perf_time_ns"]),
})
dump = (root / "perf-dump.txt").read_text()
dump = (root / "perf-dump.txt").read_text(encoding="utf-8")
losses = {name: dump.count(name) for name in (
"PERF_RECORD_LOST", "PERF_RECORD_THROTTLE", "PERF_RECORD_UNTHROTTLE")}
output = "".join(frame["data"] for frame in capture["frames"])
@ -67,13 +83,18 @@ def main():
"original_cuda_passed_64_words_and_destroyed_context": capture["exit"]["code"] == 0
and all(s in output for s in ('"passed":true', '"verified_words":64', '"context_destroyed":true')),
"all_28_samples_parsed": len(events) == 28 and not rejected,
"function_addresses_match_snapshot": all(e["address"] == e["ip"] == before["symbols"][e["symbol"]] for e in events),
"function_addresses_match_snapshot": all(
e["address"] == e["ip"] == before["symbols"].get(e["symbol"]) for e in events
),
"ordered_perf_timestamps": all(a["perf_time_ns"] <= b["perf_time_ns"] for a, b in zip(events, events[1:])),
"no_reported_loss_or_throttle": not any(losses.values()),
"eight_distinct_gpu_and_timer_owners": len(groups) == len({g["gpu_owner"] for g in groups}) == len({g["timer_owner"] for g in groups}) == 8,
"per_owner_default_then_thread_config_then_timer_load": bool(groups) and all(g["initial_order"] for g in groups),
"all_observed_data_to_gpu_argument_offsets_match_1e08": bool(groups) and all(g["default_data_offsets"] and all(v == 0x1e08 for v in g["default_data_offsets"]) for g in groups),
"all_initial_configs_4s_os_timer_and_load_flags_zero": bool(groups) and all(g["timeout_us"][0] == 4_000_000 and all(f == 8 for f in g["timeout_flags"]) and g["load_flags"] == 0 for g in groups),
"all_initial_configs_4s_os_timer_and_load_flags_zero": bool(groups) and all(
bool(g["timeout_us"]) and g["timeout_us"][0] == 4_000_000 and all(f == 8 for f in g["timeout_flags"]) and g["load_flags"] == 0
for g in groups
),
"one_owner_4s_30s_4s_seven_owners_4s": Counter(tuple(g["timeout_us"]) for g in groups) == Counter({(4_000_000,): 7, (4_000_000, 30_000_000, 4_000_000): 1}),
"retained_input_hashes_match": before["sha256"] == after["sha256"],
"eight_original_gpu_bindings_unchanged": len(before["bindings"]) == 8 and before["bindings"] == after["bindings"] and set(after["bindings"].values()) == {"nvidia"},
@ -92,7 +113,7 @@ def main():
"related_static_proof": "reports/timer-timeout-provenance.json",
"rea_process_sampling_limits": evidence["limitations"],
}
(root / "validation.json").write_text(json.dumps(report, indent=2) + "\n")
(root / "validation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps({"passed": report["passed"], "checks": checks, "counts": report["counts"]}, indent=2))
return 0 if report["passed"] else 1

View File

@ -1,18 +1,192 @@
#!/usr/bin/env python3
"""Read-only verification of exact original engine dispatcher HW-breakpoint sites."""
import argparse
import json
import os
from pathlib import Path
from elftools.elf.elffile import ELFFile
import json,struct,subprocess,hashlib
R=Path(__file__).resolve().parents[1];C=Path('/root/.debug/[kernel.kcore]/a3aac8f0306fd819566d868c7c422dbdcf1e7d42/2026111719514581');M=Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko');K=R/'reports/original-live-init-pt-3/kallsyms.txt';lookup={}
for line in K.read_text().splitlines():
fields=line.split()
if len(fields)>=3:lookup[fields[2]]=int(fields[0],16)
sites=[('InitUnlocked','_nv026844rm',0x3e,0x58,True),('InitLocked','_nv026844rm',0x80,0x50,False),('PreLoad','_nv031217rm',0x184,0x60,False),('Load','_nv031217rm',0x31f,0x68,False)]
with M.open('rb')as f:
e=ELFFile(f);s=e.get_section_by_name('.symtab');symbols={s.name:s for s in s.iter_symbols()};text=e.get_section_by_name('.text').data();disk={name:text[symbols[name]['st_value']:symbols[name]['st_value']+symbols[name]['st_size']]for name in ['_nv026844rm','_nv031217rm','_nv031215rm']};assembly={name:subprocess.check_output(['objdump','-d','--disassemble='+name,str(M)],text=True)for name in disk}
with(C/'kcore').open('rb')as f:
e=ELFFile(f);segments=[p for p in e.iter_segments()if p['p_type']=='PT_LOAD'];rows=[]
for stage,name,off,slot,optional in sites:
ip=lookup[name]+off;ph=next(p for p in segments if p['p_vaddr']<=ip-16 and ip+16<=p['p_vaddr']+p['p_filesz']);f.seek(ph['p_offset']+ip-16-ph['p_vaddr']);live=f.read(32);instruction=live[16:21];target=ip+5+struct.unpack('<i',instruction[1:5])[0]if instruction[0]in[0xe8,0xe9]else None
rows.append({'stage':stage,'symbol':name,'symbol_offset':hex(off),'runtime_ip':hex(ip),'original_rm_text_offset':hex(symbols[name]['st_value']-0x200d0+off),'installed_module_text_offset':hex(symbols[name]['st_value']+off),'installed_instruction5_hex':disk[name][off:off+5].hex(),'cached_runtime_instruction5_hex':instruction.hex(),'cached_runtime_context32_hex':live.hex(),'branch_target':hex(target)if target else None,'target_is_actual_kernel_rax_thunk':target==lookup['__x86_indirect_thunk_rax'],'vtable_slot':hex(slot),'intr_registers':{'AX':'actual immediate method address (RAX)','DI':'GPU owner pointer (RDI)','SI':'actual EngState subobject pointer (RSI)','DX':'load flags for PreLoad/Load; unspecified for Init sites'},'optional_callback_route':optional,'claim':'A sample at this exact before-dispatch instruction proves attempted immediate method dispatch, not callback completion/status or final HAL body.'})
report={'read_only':True,'source_module':str(M),'cached_runtime_code':str(C/'kcore'),'kallsyms_snapshot':str(K),'sites':rows,'ranges':[{'symbol':n,'runtime_start':hex(lookup[n]),'bytes':symbols[n]['st_size']}for n in ['_nv026844rm','_nv031217rm','_nv031215rm']],'functions_assembly':assembly,'needed_debug_slots':4,'three_site_minimum':['InitLocked','PreLoad','Load'],'three_site_omission':'InitUnlocked is conditionally executed before InitLocked andmustnotbeclaimedcoveredbythree-sitecapture.','interpretation':['Capture actualAX/DI/SI/DX with exactinstruction-address identities, timestamp,TID,CPU andsampleloss counters.','Resolve AX againstmatchingloadedmodule symbols; it maynameanEngState wrapper, notfinalselectedengineHALbody.','GPU/engine identities areactualpointervaluesforassociation, notcopy/dereferencecapabilities.','Successfulsamplingorder isdispatchattemptorder only. Returnstatus/bodycompletionisnotrecorded.','Function-only PT ranges maymisscallee reachedthrough outsidefilter kernelretpolinethunk.'],'tracing_changed':False};(R/'reports/gpu-engine-dispatch-sites.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(rows,indent=2))
import platform
import struct
import subprocess
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_KCORE_DIR = Path('/root/.debug/[kernel.kcore]/a3aac8f0306fd819566d868c7c422dbdcf1e7d42/2026111719514581')
PT_LOAD = 1
SITES = [
('InitUnlocked', '_nv026844rm', 0x3E, 0x58, True),
('InitLocked', '_nv026844rm', 0x80, 0x50, False),
('PreLoad', '_nv031217rm', 0x184, 0x60, False),
('Load', '_nv031217rm', 0x31F, 0x68, False),
]
def find_nvidia_ko(explicit: Path | None = None) -> Path:
candidates = []
if explicit is not None:
candidates.append(explicit)
if os.environ.get('NV_RS_NVIDIA_KO'):
candidates.append(Path(os.environ['NV_RS_NVIDIA_KO']))
release = platform.release()
candidates.extend([
Path(f'/lib/modules/{release}/updates/dkms/nvidia.ko'),
Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko'),
])
for candidate in candidates:
if candidate.is_file():
return candidate
raise SystemExit('Cannot find installed nvidia.ko; set NV_RS_NVIDIA_KO or pass --nvidia-ko')
def _parse_elf64_sections(raw: bytes):
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
raise SystemExit('module file is not a valid 64-bit little-endian ELF file')
e_shoff, = struct.unpack_from('<Q', raw, 40)
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5]
if e_shstrndx == 0xFFFF:
e_shstrndx = sh0[6]
hdrs = [struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + i * e_shentsize) for i in range(e_shnum)]
str_off, str_size = hdrs[e_shstrndx][4], hdrs[e_shstrndx][5]
shstr = raw[str_off:str_off + str_size]
sections = []
by_name = {}
for idx, h in enumerate(hdrs):
nul = shstr.find(b'\x00', h[0])
name = shstr[h[0]:nul if nul != -1 else len(shstr)].decode('utf-8', errors='replace')
sections.append((name, h))
by_name[name] = idx
return sections, by_name
def _load_symbols(raw: bytes, sections, sym_idx: int):
_, h = sections[sym_idx]
entsize = h[9] or 24
str_h = sections[h[6]][1]
strtab = raw[str_h[4]:str_h[4] + str_h[5]]
ext = None
for _, sh in sections:
if sh[1] == 18 and sh[6] == sym_idx:
ext = struct.unpack_from(f'<{sh[5] // 4}I', raw, sh[4])
break
syms = {}
for i in range(h[5] // entsize):
st_name, st_info, _st_other, st_shndx, st_value, st_size = struct.unpack_from('<IBBHQQ', raw, h[4] + i * entsize)
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
st_shndx = ext[i]
nul = strtab.find(b'\x00', st_name)
name = strtab[st_name:nul if nul != -1 else len(strtab)].decode('utf-8', errors='replace')
syms[name] = (st_shndx, st_value, st_size, st_info & 0xF)
return syms
def _load_pt_load_segments(stream) -> list[tuple[int, int, int]]:
ehdr = stream.read(64)
if len(ehdr) < 64 or ehdr[:4] != b'\x7fELF' or ehdr[4] != 2 or ehdr[5] != 1:
raise SystemExit('kcore is not a valid 64-bit little-endian ELF file')
e_phoff, = struct.unpack_from('<Q', ehdr, 32)
e_phentsize, e_phnum = struct.unpack_from('<HH', ehdr, 54)
if e_phoff == 0 or e_phentsize < 56 or e_phnum == 0:
raise SystemExit('kcore has no program headers')
segments = []
stream.seek(e_phoff)
for _ in range(e_phnum):
ph = stream.read(e_phentsize)
if len(ph) < 56:
break
p_type, _p_flags, p_offset, p_vaddr, _p_paddr, p_filesz, _p_memsz, _p_align = struct.unpack_from('<IIQQQQQQ', ph, 0)
if p_type == PT_LOAD:
segments.append((p_vaddr, p_offset, p_filesz))
return segments
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--nvidia-ko', type=Path, default=None)
parser.add_argument('--kcore-dir', type=Path, default=DEFAULT_KCORE_DIR)
args = parser.parse_args(argv)
module_path = find_nvidia_ko(args.nvidia_ko)
kcore_path = args.kcore_dir / 'kcore'
if not kcore_path.is_file():
raise SystemExit(f'cached kcore not found: {kcore_path}')
kallsyms = ROOT / 'reports/original-live-init-pt-3/kallsyms.txt'
lookup = {}
for line in kallsyms.read_text(encoding='utf-8').splitlines():
fields = line.split()
if len(fields) >= 3:
lookup[fields[2]] = int(fields[0], 16)
raw_mod = module_path.read_bytes()
sections, by_name = _parse_elf64_sections(raw_mod)
symbols = _load_symbols(raw_mod, sections, by_name['.symtab'])
text_idx = by_name['.text']
text_h = sections[text_idx][1]
text = raw_mod[text_h[4]:text_h[4] + text_h[5]]
target_fns = ('_nv026844rm', '_nv031217rm', '_nv031215rm')
disk = {}
for name in target_fns:
if name not in symbols or symbols[name][0] != text_idx:
raise SystemExit(f'symbol {name!r} not found in .text of {module_path}')
_, st_value, st_size, _ = symbols[name]
disk[name] = text[st_value:st_value + st_size]
assembly = {name: subprocess.check_output(['objdump', '-d', '--disassemble=' + name, str(module_path)], text=True) for name in disk}
with kcore_path.open('rb') as f:
segments = _load_pt_load_segments(f)
rows = []
for stage, name, off, slot, optional in SITES:
ip = lookup[name] + off
ph = next((seg for seg in segments if seg[0] <= ip - 16 and ip + 16 <= seg[0] + seg[2]), None)
if ph is None:
raise SystemExit(f'no PT_LOAD segment covering {stage} ip {hex(ip)}')
p_vaddr, p_offset, _p_filesz = ph
f.seek(p_offset + ip - 16 - p_vaddr)
live = f.read(32)
instruction = live[16:21]
target = ip + 5 + struct.unpack('<i', instruction[1:5])[0] if instruction[0] in (0xE8, 0xE9) else None
rows.append({
'stage': stage, 'symbol': name, 'symbol_offset': hex(off), 'runtime_ip': hex(ip),
'original_rm_text_offset': hex(symbols[name][1] - 0x200D0 + off),
'installed_module_text_offset': hex(symbols[name][1] + off),
'installed_instruction5_hex': disk[name][off:off + 5].hex(),
'cached_runtime_instruction5_hex': instruction.hex(),
'cached_runtime_context32_hex': live.hex(),
'branch_target': hex(target) if target else None,
'target_is_actual_kernel_rax_thunk': target == lookup.get('__x86_indirect_thunk_rax'),
'vtable_slot': hex(slot),
'intr_registers': {
'AX': 'actual immediate method address (RAX)',
'DI': 'GPU owner pointer (RDI)',
'SI': 'actual EngState subobject pointer (RSI)',
'DX': 'load flags for PreLoad/Load; unspecified for Init sites',
},
'optional_callback_route': optional,
'claim': 'A sample at this exact before-dispatch instruction proves attempted immediate method dispatch, not callback completion/status or final HAL body.',
})
report = {
'read_only': True, 'source_module': str(module_path), 'cached_runtime_code': str(kcore_path),
'kallsyms_snapshot': str(kallsyms), 'sites': rows,
'ranges': [{'symbol': n, 'runtime_start': hex(lookup[n]), 'bytes': symbols[n][2]} for n in target_fns],
'functions_assembly': assembly, 'needed_debug_slots': 4,
'three_site_minimum': ['InitLocked', 'PreLoad', 'Load'],
'three_site_omission': 'InitUnlocked is conditionally executed before InitLocked andmustnotbeclaimedcoveredbythree-sitecapture.',
'interpretation': [
'Capture actualAX/DI/SI/DX with exactinstruction-address identities, timestamp,TID,CPU andsampleloss counters.',
'Resolve AX againstmatchingloadedmodule symbols; it maynameanEngState wrapper, notfinalselectedengineHALbody.',
'GPU/engine identities areactualpointervaluesforassociation, notcopy/dereferencecapabilities.',
'Successfulsamplingorder isdispatchattemptorder only. Returnstatus/bodycompletionisnotrecorded.',
'Function-only PT ranges maymisscallee reachedthrough outsidefilter kernelretpolinethunk.',
],
'tracing_changed': False,
}
out = ROOT / 'reports/gpu-engine-dispatch-sites.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps(rows, indent=2))
if __name__ == '__main__':
main()

View File

@ -2,81 +2,332 @@
"""Label observed immediate EngState callbacks through original NVOC metadata.
Read-only inputs; generates evidence, never samples or edits driver production.
"""
import argparse
from collections import Counter, defaultdict
import hashlib
import json
import os
from pathlib import Path
from collections import defaultdict,Counter
from elftools.elf.elffile import ELFFile
import json,re,struct,hashlib
R=Path(__file__).resolve().parents[1];E=Path('/home/geodd/nvidia-driver/analysis-580.178.04');P=E/'extracted/kernel/nvidia/nv-kernel.o_binary';G=E/'reference/open-gpu-kernel-modules-580.178.04/src/nvidia/generated';I=R/'reports/original-live-init-bp-4/timestamped-dispatch.json';SLOTS={'InitLocked':0x50,'InitUnlocked':0x58,'PreLoad':0x60,'Load':0x68};NOOPS={'_nv026842rm','_nv026845rm','_nv026851rm'}
cap=json.loads(I.read_text());events=[x for x in cap['events']if x['gpu_ordinal']==0];assert len(events)==257
labels=defaultdict(list)
for p in sorted(G.glob('*_nvoc.h')):
for line,s in enumerate(p.read_text().splitlines(),1):
m=re.match(r'#define __nvoc_class_id_(\w+) (0x[0-9a-fA-F]+)',s)
if m:labels[int(m[2],16)].append({'class_name':m[1],'source_file':str(p),'line':line})
def choose_label(cid):
choices=labels[cid];canonical=[x for x in choices if Path(x['source_file']).name=='g_eng_desc_nvoc.h'];return canonical or choices[:1]
methods={};class_catalog={}
with P.open('rb')as f:
elf=ELFFile(f);ss=list(elf.get_section_by_name('.symtab').iter_symbols());byname={s.name:(i,s)for i,s in enumerate(ss)};ro=elf.get_section_by_name('.rodata').data();roidx=elf.get_section_index('.rodata');rels={r['r_offset']:r for r in elf.get_section_by_name('.rela.rodata').iter_relocations()};refs=defaultdict(list)
for off,r in rels.items():refs[r['r_info_sym']].append(off)
def target(off):
rel=rels.get(off);return ss[rel['r_info_sym']]if rel else None
def ro_target(off):
rel=rels.get(off)
if rel is None:return None
s=ss[rel['r_info_sym']]
return s['st_value']+rel['r_addend']if s['st_shndx']==roidx else None
owners=defaultdict(list)
for owner in ss:
if owner['st_shndx']!=roidx or owner['st_info']['type']!='STT_OBJECT' or owner['st_size']!=40:continue
cast=ro_target(owner['st_value']+0x18)
if cast is None or cast+8>len(ro):continue
count=struct.unpack_from('<I',ro,cast)[0]
if not 0<count<32:continue
relatives=[ro_target(cast+8+i*8)for i in range(count)]
if any(x is None for x in relatives):continue
roots=[x for x in relatives if target(x) is not None and target(x).name==owner.name and struct.unpack_from('<I',ro,x+16)[0]==0]
if len(roots)!=1:continue
for base in relatives:
ancestor=target(base)
if ancestor is not None and ancestor.name=='_nv003100rm':owners[base].append((owner,roots[0],cast,relatives))
def candidates(name,slot):
answer=[]
for off in refs[byname[name][0]]:
base=off-slot
for owner,root,cast,relatives in owners[base]:
cid=struct.unpack_from('<I',ro,owner['st_value']+4)[0];key=hex(cid)
ancestor_ids=[]
for relative in relatives:
ancestor=target(relative)
if ancestor is not None and ancestor['st_info']['type']=='STT_OBJECT':ancestor_ids.append(hex(struct.unpack_from('<I',ro,ancestor['st_value']+4)[0]))
class_catalog[key]={'class_id':key,'binary_class_definition':owner.name,'class_definition_rodata_offset':hex(owner['st_value']),'class_id_field_offset':4,'source_labels':choose_label(cid),'ancestor_class_ids':ancestor_ids}
answer.append({'class_id':key,'metadata_engstate_rodata_offset':hex(base),'callback_relocation_rodata_offset':hex(off),'root_rtti_rodata_offset':hex(root),'castinfo_rodata_offset':hex(cast),'castinfo_num_relatives':len(relatives),'engstate_subobject_offset':struct.unpack_from('<I',ro,base+16)[0]})
return answer
for ev in events:
name=ev['callback']['name'];stage=ev['stage'];key=name+':'+stage
if key in methods:continue
assert ev['callback']['offset']=='0x0'
methods[key]={'symbol':name,'stage':stage,'vtable_slot':hex(SLOTS[stage]),'shared_default_noop':name in NOOPS,'candidates':candidates(name,SLOTS[stage])}
engines=[]
for ordinal in range(78):
selected=[ev for ev in events if ev['engine_ordinal']==ordinal];owners={x['engine_owner']for x in selected};assert len(owners)==1
matching=None
for ev in selected:
keys={x['class_id']for x in methods[ev['callback']['name']+':'+ev['stage']]['candidates']}
matching=keys if matching is None else matching&keys
matching=sorted(matching or []);declarations=[d for cid in matching for d in class_catalog[cid]['source_labels']]
name=declarations[0]['class_name']if len(matching)==1 and len({d['class_name']for d in declarations})==1 else None
engines.append({'engine_ordinal0':ordinal,'gpu_owner':selected[0]['gpu_owner'],'engine_owner':next(iter(owners)),'class_label':name,'phase_positions0':{phase:order.index(ordinal)for phase,order in cap['gpu_groups'][0]['engine_orders'].items()if ordinal in order},'class_candidate_ids':matching,'class_label_evidence':'intersection of actual callback-slot original metadata classes whose ClassDef CastInfo owns SAME EngStateRTTI; capturedSI matches across phases; no live classID read','callbacks':{ev['stage']:{'symbol':ev['callback']['name'],'callback_address':ev['callback_address'],'sample':ev['sample'],'source_line':ev['source_line'],'method_evidence':ev['callback']['name']+':'+ev['stage'],'shared_default_noop':ev['callback']['name']in NOOPS}for ev in selected}})
# Compare capture1 actual AX sequences/owner grouping without comparing heap addresses.
raw=R/'reports/original-live-init-bp-4/standalone-dispatch-registers.txt';raw_rows=[]
for line in raw.read_text().splitlines():
m=re.search(r'mem:(0x[0-9a-f]+):x:.*AX:(0x[0-9a-f]+).*DX:(0x[0-9a-f]+).*SI:(0x[0-9a-f]+).*DI:(0x[0-9a-f]+)',line)
if m:raw_rows.append(m.groups())
first_gpu=raw_rows[0][-1];first=[x for x in raw_rows if x[-1]==first_gpu];assert len(first)==257
repeat=[(x[0],x[1])for x in first]==[(ev['site'],ev['callback_address'])for ev in events]
used_sources={d['source_file']for c in class_catalog.values()for d in c['source_labels']};source_hashes={p:hashlib.sha256(Path(p).read_bytes()).hexdigest()for p in sorted(used_sources)}
report={'schema':1,'scope':'Observed immediate callback attempts for first GPU group. Exact580 generated-source names label original binary classIDs only; no final HAL body/completion claim.','inputs':{str(I.relative_to(R)):hashlib.sha256(I.read_bytes()).hexdigest(),str(raw.relative_to(R)):hashlib.sha256(raw.read_bytes()).hexdigest(),'original_rm_sha256':hashlib.sha256(P.read_bytes()).hexdigest()},'ordinal_convention':'engine_ordinal0 isZEROBASED and matches timestamped-dispatch.json engine_ordinal; not1-based position','sample_clock':cap['sample_clock'],'input_revision':json.loads((R/'reports/gpu-live-engine-labels-revision.json').read_text()),'first_gpu_owner':events[0]['gpu_owner'],'first_gpu_samples':257,'stage_counts':dict(Counter(x['stage']for x in events)),'capture1_callback_order_repeats_capture2':repeat,'engine_count':78,'source_named_engines':sum(x['class_label']is not None for x in engines),'ambiguous_or_undeclared_engines':[x['engine_ordinal0']for x in engines if x['class_label']is None],'engines':engines,'phase_orders':cap['gpu_groups'][0]['engine_orders'],'ordered_attempts':[{'sample':x['sample'],'perf_time_ns':x['perf_time_ns'],'stage':x['stage'],'engine_ordinal0':x['engine_ordinal'],'callback':x['callback']['name']}for x in events],'method_catalog':methods,'class_catalog':class_catalog,'label_source_hashes':source_hashes,'limitations':['No live classID/object memory dereference. Shared callback/noop mappings remain ambiguous unless other captured methods for SAME SI narrow the class.','Unknown binary classIDs without exact generated-source declaration remain numeric, unnamed. In particular ordinal38 class5dfed5 has Pmu ancestor but must not be labeled the base Pmu class.','Labels are classes consistent with the observed original metadata; no class name inferred from ordinal, method number or neighboring class.','CapturedRAX is the immediate wrapper/default method, not proof of final HAL target, completion, result status, authentication or hardware readiness.','Capture1 has no printed timestamps; primaryorder uses capture2 timestamped events and compares capture1 actual site+AX sequence.'],'read_only':True,'tracing_changed':False,'production_changed':False}
(R/'reports/gpu-live-engine-labels.json').write_text(json.dumps(report,indent=2)+'\n');print('Named',report['source_named_engines'],'of78; unresolved',report['ambiguous_or_undeclared_engines'],'repeat',repeat)
for x in engines:
if x['class_label']in['Graphics','GraphicsManager','KernelGraphics','OBJLSFM','OBJACR','OBJFIFO','KernelFifo','OBJGMMU','KernelGmmu','OBJBUS','KernelBus']:print(x['engine_ordinal0'],x['class_label'],{k:v['symbol']for k,v in x['callbacks'].items()})
import re
import struct
ROOT = Path(__file__).resolve().parents[1]
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
SLOTS = {'InitLocked': 0x50, 'InitUnlocked': 0x58, 'PreLoad': 0x60, 'Load': 0x68}
NOOPS = {'_nv026842rm', '_nv026845rm', '_nv026851rm'}
def find_rm_object(explicit: Path | None = None) -> Path:
candidates = []
if explicit is not None:
candidates.append(explicit)
if os.environ.get('NV_RS_RM_OBJECT'):
candidates.append(Path(os.environ['NV_RS_RM_OBJECT']))
if os.environ.get('NV_RS_KERNEL_SRC'):
base = Path(os.environ['NV_RS_KERNEL_SRC'])
candidates.extend([base / 'nvidia/nv-kernel.o_binary', base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / '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'),
])
for candidate in candidates:
if candidate.is_file():
return candidate
raise SystemExit('Cannot find 580.178.04 nv-kernel.o_binary; set NV_RS_RM_OBJECT or NV_RS_KERNEL_SRC')
def find_generated_dir(explicit: Path | None = None) -> Path | None:
candidates = []
if explicit is not None:
candidates.append(explicit)
for env_name in ('NV_RS_OPEN_GPU_SRC', 'OPEN_GPU_ROOT'):
val = os.environ.get(env_name)
if val:
base = Path(val)
candidates.extend([base / 'src/nvidia/generated', base / 'nvidia/generated', base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / 'reference/open-gpu-kernel-modules-580.178.04/src/nvidia/generated')
for candidate in candidates:
if candidate.is_dir():
return candidate
return None
def _parse_elf64(raw: bytes):
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
raise SystemExit('nv-kernel.o_binary is not a valid 64-bit little-endian ELF file')
e_shoff, = struct.unpack_from('<Q', raw, 40)
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5]
if e_shstrndx == 0xFFFF:
e_shstrndx = sh0[6]
hdrs = [struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + i * e_shentsize) for i in range(e_shnum)]
str_off, str_size = hdrs[e_shstrndx][4], hdrs[e_shstrndx][5]
shstr = raw[str_off:str_off + str_size]
sections = []
by_name = {}
for idx, h in enumerate(hdrs):
nul = shstr.find(b'\x00', h[0])
name = shstr[h[0]:nul if nul != -1 else len(shstr)].decode('utf-8', errors='replace')
sections.append((name, h))
by_name[name] = idx
return sections, by_name
def _load_symbols(raw: bytes, sections, sym_idx: int):
_, h = sections[sym_idx]
entsize = h[9] or 24
str_h = sections[h[6]][1]
strtab = raw[str_h[4]:str_h[4] + str_h[5]]
ext = None
for _, sh in sections:
if sh[1] == 18 and sh[6] == sym_idx:
ext = struct.unpack_from(f'<{sh[5] // 4}I', raw, sh[4])
break
syms = []
for i in range(h[5] // entsize):
st_name, st_info, _st_other, st_shndx, st_value, st_size = struct.unpack_from('<IBBHQQ', raw, h[4] + i * entsize)
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
st_shndx = ext[i]
nul = strtab.find(b'\x00', st_name)
name = strtab[st_name:nul if nul != -1 else len(strtab)].decode('utf-8', errors='replace')
syms.append((name, st_shndx, st_value, st_size, st_info & 0xF))
return syms
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--rm-object', type=Path, default=None)
parser.add_argument('--generated-dir', type=Path, default=None)
args = parser.parse_args(argv)
rm_obj = find_rm_object(args.rm_object)
raw_elf = rm_obj.read_bytes()
sha = hashlib.sha256(raw_elf).hexdigest()
if sha != EXPECTED_SHA256:
raise SystemExit(f'{rm_obj}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
dispatch_path = ROOT / 'reports/original-live-init-bp-4/timestamped-dispatch.json'
cap = json.loads(dispatch_path.read_text(encoding='utf-8'))
events = [x for x in cap['events'] if x['gpu_ordinal'] == 0]
if len(events) != 257:
raise SystemExit(f'expected 257 gpu_ordinal==0 events, found {len(events)}')
labels = defaultdict(list)
gen_dir = find_generated_dir(args.generated_dir)
if gen_dir is not None:
for p in sorted(gen_dir.glob('*_nvoc.h')):
for line, s in enumerate(p.read_text(encoding='utf-8', errors='replace').splitlines(), 1):
m = re.match(r'#define __nvoc_class_id_(\w+) (0x[0-9a-fA-F]+)', s)
if m:
labels[int(m[2], 16)].append({'class_name': m[1], 'source_file': str(p), 'line': line})
def choose_label(cid):
choices = labels[cid]
canonical = [x for x in choices if Path(x['source_file']).name == 'g_eng_desc_nvoc.h']
return canonical or choices[:1]
sections, by_name = _parse_elf64(raw_elf)
ss = _load_symbols(raw_elf, sections, by_name['.symtab'])
byname = {s[0]: (i, s) for i, s in enumerate(ss)}
roidx = by_name['.rodata']
ro_h = sections[roidx][1]
ro = raw_elf[ro_h[4]:ro_h[4] + ro_h[5]]
rel_h = sections[by_name['.rela.rodata']][1]
rel_entsize = rel_h[9] or 24
rels = {}
refs = defaultdict(list)
for i in range(rel_h[5] // rel_entsize):
off, r_info, r_addend = struct.unpack_from('<QQq', raw_elf, rel_h[4] + i * rel_entsize)
r_sym = r_info >> 32
rels[off] = (r_sym, r_addend)
refs[r_sym].append(off)
def target(off):
rel = rels.get(off)
return ss[rel[0]] if rel is not None else None
def ro_target(off):
rel = rels.get(off)
if rel is None:
return None
s = ss[rel[0]]
return s[2] + rel[1] if s[1] == roidx else None
owners = defaultdict(list)
for owner in ss:
if owner[1] != roidx or owner[4] != 1 or owner[3] != 40: # STT_OBJECT == 1
continue
cast = ro_target(owner[2] + 0x18)
if cast is None or cast + 8 > len(ro):
continue
count = struct.unpack_from('<I', ro, cast)[0]
if not (0 < count < 32):
continue
relatives = [ro_target(cast + 8 + i * 8) for i in range(count)]
if any(x is None for x in relatives):
continue
roots = [
x for x in relatives
if (t := target(x)) is not None and t[0] == owner[0] and struct.unpack_from('<I', ro, x + 16)[0] == 0
]
if len(roots) != 1:
continue
for base in relatives:
ancestor = target(base)
if ancestor is not None and ancestor[0] == '_nv003100rm':
owners[base].append((owner, roots[0], cast, relatives))
methods = {}
class_catalog = {}
def candidates(name, slot):
answer = []
for off in refs[byname[name][0]]:
base = off - slot
for owner, root, cast, relatives in owners[base]:
cid = struct.unpack_from('<I', ro, owner[2] + 4)[0]
key = hex(cid)
ancestor_ids = []
for relative in relatives:
ancestor = target(relative)
if ancestor is not None and ancestor[4] == 1:
ancestor_ids.append(hex(struct.unpack_from('<I', ro, ancestor[2] + 4)[0]))
class_catalog[key] = {
'class_id': key,
'binary_class_definition': owner[0],
'class_definition_rodata_offset': hex(owner[2]),
'class_id_field_offset': 4,
'source_labels': choose_label(cid),
'ancestor_class_ids': ancestor_ids,
}
answer.append({
'class_id': key,
'metadata_engstate_rodata_offset': hex(base),
'callback_relocation_rodata_offset': hex(off),
'root_rtti_rodata_offset': hex(root),
'castinfo_rodata_offset': hex(cast),
'castinfo_num_relatives': len(relatives),
'engstate_subobject_offset': struct.unpack_from('<I', ro, base + 16)[0],
})
return answer
for ev in events:
name = ev['callback']['name']
stage = ev['stage']
key = name + ':' + stage
if key in methods:
continue
if ev['callback']['offset'] != '0x0':
raise SystemExit(f'unexpected non-zero callback offset {ev["callback"]["offset"]!r} for {key}')
methods[key] = {
'symbol': name,
'stage': stage,
'vtable_slot': hex(SLOTS[stage]),
'shared_default_noop': name in NOOPS,
'candidates': candidates(name, SLOTS[stage]),
}
engines = []
for ordinal in range(78):
selected = [ev for ev in events if ev['engine_ordinal'] == ordinal]
engine_owners = {x['engine_owner'] for x in selected}
if len(engine_owners) != 1:
raise SystemExit(f'engine ordinal {ordinal} has {len(engine_owners)} distinct owners')
matching = None
for ev in selected:
keys = {x['class_id'] for x in methods[ev['callback']['name'] + ':' + ev['stage']]['candidates']}
matching = keys if matching is None else matching & keys
matching = sorted(matching or [])
declarations = [d for cid in matching for d in class_catalog[cid]['source_labels']]
name = declarations[0]['class_name'] if len(matching) == 1 and len({d['class_name'] for d in declarations}) == 1 else None
engines.append({
'engine_ordinal0': ordinal,
'gpu_owner': selected[0]['gpu_owner'],
'engine_owner': next(iter(engine_owners)),
'class_label': name,
'phase_positions0': {phase: order.index(ordinal) for phase, order in cap['gpu_groups'][0]['engine_orders'].items() if ordinal in order},
'class_candidate_ids': matching,
'class_label_evidence': 'intersection of actual callback-slot original metadata classes whose ClassDef CastInfo owns SAME EngStateRTTI; capturedSI matches across phases; no live classID read',
'callbacks': {
ev['stage']: {
'symbol': ev['callback']['name'],
'callback_address': ev['callback_address'],
'sample': ev['sample'],
'source_line': ev['source_line'],
'method_evidence': ev['callback']['name'] + ':' + ev['stage'],
'shared_default_noop': ev['callback']['name'] in NOOPS,
}
for ev in selected
},
})
# Compare capture1 actual AX sequences/owner grouping without comparing heap addresses.
raw_path = ROOT / 'reports/original-live-init-bp-4/standalone-dispatch-registers.txt'
raw_rows = []
for line in raw_path.read_text(encoding='utf-8').splitlines():
m = re.search(r'mem:(0x[0-9a-f]+):x:.*AX:(0x[0-9a-f]+).*DX:(0x[0-9a-f]+).*SI:(0x[0-9a-f]+).*DI:(0x[0-9a-f]+)', line)
if m:
raw_rows.append(m.groups())
if not raw_rows:
raise SystemExit(f'no register rows parsed from {raw_path}')
first_gpu = raw_rows[0][-1]
first = [x for x in raw_rows if x[-1] == first_gpu]
if len(first) != 257:
raise SystemExit(f'expected 257 capture1 rows for first GPU, found {len(first)}')
repeat = [(x[0], x[1]) for x in first] == [(ev['site'], ev['callback_address']) for ev in events]
used_sources = {d['source_file'] for c in class_catalog.values() for d in c['source_labels']}
source_hashes = {p: hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in sorted(used_sources)}
report = {
'schema': 1,
'scope': 'Observed immediate callback attempts for first GPU group. Exact580 generated-source names label original binary classIDs only; no final HAL body/completion claim.',
'inputs': {
str(dispatch_path.relative_to(ROOT)): hashlib.sha256(dispatch_path.read_bytes()).hexdigest(),
str(raw_path.relative_to(ROOT)): hashlib.sha256(raw_path.read_bytes()).hexdigest(),
'original_rm_sha256': sha,
},
'ordinal_convention': 'engine_ordinal0 isZEROBASED and matches timestamped-dispatch.json engine_ordinal; not1-based position',
'sample_clock': cap['sample_clock'],
'input_revision': json.loads((ROOT / 'reports/gpu-live-engine-labels-revision.json').read_text(encoding='utf-8')),
'first_gpu_owner': events[0]['gpu_owner'],
'first_gpu_samples': 257,
'stage_counts': dict(Counter(x['stage'] for x in events)),
'capture1_callback_order_repeats_capture2': repeat,
'engine_count': 78,
'source_named_engines': sum(x['class_label'] is not None for x in engines),
'ambiguous_or_undeclared_engines': [x['engine_ordinal0'] for x in engines if x['class_label'] is None],
'engines': engines,
'phase_orders': cap['gpu_groups'][0]['engine_orders'],
'ordered_attempts': [
{'sample': x['sample'], 'perf_time_ns': x['perf_time_ns'], 'stage': x['stage'], 'engine_ordinal0': x['engine_ordinal'], 'callback': x['callback']['name']}
for x in events
],
'method_catalog': methods,
'class_catalog': class_catalog,
'label_source_hashes': source_hashes,
'limitations': [
'No live classID/object memory dereference. Shared callback/noop mappings remain ambiguous unless other captured methods for SAME SI narrow the class.',
'Unknown binary classIDs without exact generated-source declaration remain numeric, unnamed. In particular ordinal38 class5dfed5 has Pmu ancestor but must not be labeled the base Pmu class.',
'Labels are classes consistent with the observed original metadata; no class name inferred from ordinal, method number or neighboring class.',
'CapturedRAX is the immediate wrapper/default method, not proof of final HAL target, completion, result status, authentication or hardware readiness.',
'Capture1 has no printed timestamps; primaryorder uses capture2 timestamped events and compares capture1 actual site+AX sequence.',
],
'read_only': True,
'tracing_changed': False,
'production_changed': False,
}
out = ROOT / 'reports/gpu-live-engine-labels.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print('Named', report['source_named_engines'], 'of78; unresolved', report['ambiguous_or_undeclared_engines'], 'repeat', repeat)
if __name__ == '__main__':
main()

View File

@ -4,6 +4,7 @@ import argparse
import json
import os
from pathlib import Path
import tempfile
ROLES = (
("VGX_BUILD", "NV_DOM0_KERNEL_PRESENT", "nv_rs_vgx_dom0"),
@ -17,26 +18,36 @@ def resolve(environment):
return {define: bool(environment.get(name, "")) for name, define, _ in ROLES}
def main():
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--receipt", type=Path)
parser.add_argument("--json", action="store_true")
args = parser.parse_args()
args = parser.parse_args(argv)
roles = resolve(os.environ)
receipt = {"schema": 1, "source": "matching580 nonempty build-product environment",
"roles": roles, "is_vgx_hyper": any(roles.values())}
receipt = {
"schema": 1,
"source": "matching580 nonempty build-product environment",
"roles": roles,
"is_vgx_hyper": any(roles.values()),
}
content = json.dumps(receipt, indent=2, sort_keys=True) + "\n"
if args.receipt:
args.receipt.parent.mkdir(parents=True, exist_ok=True)
if not args.receipt.exists() or args.receipt.read_text() != content:
if not args.receipt.exists() or args.receipt.read_text(encoding="utf-8") != content:
# A same-filesystem atomic replacement; parallel equal-config Make
# invocations cannot leave a partially written dependency receipt.
import tempfile
with tempfile.NamedTemporaryFile(mode="w", dir=args.receipt.parent,
delete=False) as temporary:
temporary.write(content)
temporary_path = Path(temporary.name)
temporary_path.replace(args.receipt)
temporary_path = None
try:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=args.receipt.parent, delete=False
) as temporary:
temporary_path = Path(temporary.name)
temporary.write(content)
temporary_path.replace(args.receipt)
temporary_path = None
finally:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
if args.json:
print(content, end="")
else: