Files
nvdriver/tools/reconcile_native_fifo_live_bootstrap.py
morebrackets 1ee1639002 Address CodeRabbit follow-up findings on #276
- tools/run_live_control.py (4778363104): fail closed when /sys/bus/pci/devices
  is unavailable instead of returning an empty inventory.
- tools/summarize_original_dispatch.py (4778363107): validate required string
  'stage' field when loading sites.json.
- tools/reconcile_native_fifo_live_bootstrap.py (4778363084, 4778363095):
  include index.json and _nv028064rm.rea.json in inputs_sha256 / existence
  checks and require len(groups) == 8 before reporting eight validated groups.
- tests/offline/test_live_control_and_summary_tools.py: add unit tests for
  missing PCI sysfs dir and malformed sites.json.
2026-12-02 17:05:52 -08:00

170 lines
12 KiB
Python

#!/usr/bin/env python3
"""Read-only reconciliation of original FIFO lifecycle and observed ACR bootstrap."""
from pathlib import Path
import hashlib, json, os, re, struct
R = Path(__file__).resolve().parents[1]
SHA = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
def _resolve_analysis_root() -> Path:
return Path(os.environ.get('NV_RS_ANALYSIS_ROOT', '/home/geodd/nvidia-driver/analysis-580.178.04'))
def _resolve_rm_object(analysis_root: Path) -> Path:
if env := os.environ.get('NV_RS_RM_OBJECT'):
return Path(env)
primary = analysis_root / 'extracted/kernel/nvidia/nv-kernel.o_binary'
if primary.is_file():
return primary
fallback = Path('/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary')
if fallback.is_file():
return fallback
return primary
def main():
try:
from elftools.elf.elffile import ELFFile
except ModuleNotFoundError as error:
raise SystemExit(f"pyelftools is required to run this script: {error}") from error
A = _resolve_analysis_root()
P = _resolve_rm_object(A)
if not P.is_file():
raise SystemExit(f"missing nv-kernel.o_binary: {P} (set NV_RS_RM_OBJECT or NV_RS_ANALYSIS_ROOT)")
if hashlib.sha256(P.read_bytes()).hexdigest() != SHA:
raise SystemExit(f"unexpected sha256 for {P}")
REF = A / 'reference/open-gpu-kernel-modules-580.178.04'
index_path = R / 'reports/native-fifo-live-bootstrap-rea/index.json'
early_rea_path = R / 'reports/native-fifo-live-bootstrap-rea/_nv028064rm.rea.json'
inputs = [
R / 'reports/original-live-init-bp-4/timestamped-dispatch.json',
R / 'reports/original-live-init-pt-3/live-initialization-timeline.json',
R / 'reports/original-live-init-pt-3/acr-early-fifo-all-calls.txt',
REF / 'src/nvidia/generated/g_eng_desc_nvoc.h',
REF / 'src/nvidia/src/kernel/gpu/mem_mgr/mem_mgr.c',
REF / 'src/nvidia/src/kernel/gpu/mem_mgr/ce_utils.c',
REF / 'src/common/sdk/nvidia/inc/class/cl0050.h',
index_path,
early_rea_path,
]
for path in inputs:
if not path.is_file():
raise SystemExit(f"missing required input: {path}")
with P.open('rb') as f:
elf = ELFFile(f)
symbols = list(elf.get_section_by_name('.symtab').iter_symbols())
byname = {s.name: s for s in symbols}
ro = elf.get_section_by_name('.rodata')
rels = {r['r_offset']: r for r in elf.get_section_by_name('.rela.rodata').iter_relocations()}
def pointer_target(offset):
r = rels[offset]
s = symbols[r['r_info_sym']]
return s['st_shndx'], s['st_value'] + r['r_addend']
def assert_target(offset, name):
s = byname[name]
if pointer_target(offset) != (s['st_shndx'], s['st_value']):
raise SystemExit(f"unexpected pointer target at {hex(offset)} for {name}")
classes = []
for base, definition, wrapper, name, classid in [(0x4da5d80, '_nv003103rm', '_nv004197rm', 'OBJFIFO', 0xb02365), (0x4dc6fc0, '_nv003098rm', '_nv004147rm', 'OBJDPAUX', 0xfd2ab9)]:
assert_target(base, definition)
assert_target(base + 0x80, wrapper)
d = byname[definition]
actual = struct.unpack_from('<I', ro.data(), d['st_value'] + 4)[0]
if actual != classid:
raise SystemExit(f"class id mismatch for {name}: got {hex(actual)}, expected {hex(classid)}")
header = inputs[3].read_text(encoding='utf-8')
if not re.search(r'#define __nvoc_class_id_' + name + r'\s+0x' + format(classid, 'x') + r'\b', header):
raise SystemExit(f"header missing class id for {name}")
classes.append(dict(name=name, class_id=hex(classid), definition=definition, metadata_offset=hex(base), load_slot_offset='metadata+0x80 / EngState-vtable+0x68', wrapper=wrapper))
assert_target(0x4da5d80 + 0x118, '_nv028309rm')
index = json.loads((R / 'reports/native-fifo-live-bootstrap-rea/index.json').read_text(encoding='utf-8'))
evidence = {x['name']: x['evidence_id'] for x in index}
for n in ['_nv016731rm', '_nv016753rm']:
p = R / 'reports/gpu-wpr-policy-rea' / f'{n}.rea.json'
x = json.loads(p.read_text(encoding='utf-8'))
d = x.get('structuredContent') or json.loads(next(v['text'] for v in x['content'] if v.get('type') == 'text'))
evidence[n] = d['evidence_id']
inputs.append(p)
p = R / 'reports/native-fifo-live-bootstrap-rea/_nv028064rm.rea.json'
x = json.loads(p.read_text(encoding='utf-8'))
d = x.get('structuredContent') or json.loads(next(v['text'] for v in x['content'] if v.get('type') == 'text'))
instructions = [line for line in d['normalized_result']['instructions'] if 0x669c598 <= int(line.split(':')[0], 16) <= 0x669c5cf]
if not (
any('XOR EDX, EDX' in line for line in instructions)
and any('[RAX + 0x118]' in line for line in instructions)
and any(line.startswith('0x669c5c5: CALL') for line in instructions)
):
raise SystemExit("missing expected instructions in _nv028064rm")
window = inputs[2].read_text(encoding='utf-8').splitlines()
need = [('_nv016753rm+0x1ed', '_nv019032rm+0x0'), ('_nv019032rm+0x46', '_nv043991rm+0x0'), ('_nv043991rm+0x161', '_nv006444rm+0x0'), ('_nv006444rm+0xd9', '_nv019130rm+0x0'), ('_nv019130rm+0x9b', '_nv030544rm+0x0'), ('_nv019130rm+0xb5', '_nv028064rm+0x0'), ('_nv028064rm+0x4c5', '__x86_indirect_thunk_rax+0x0'), ('_nv028309rm+0x38', '_nv028308rm+0x0'), ('_nv016753rm+0x216', '_nv044027rm+0x0')]
observed = []
for source, dest in need:
matches = [(i + 1, line) for i, line in enumerate(window) if source + ' ' in line and '=> ' in line and dest + ' ' in line]
if not matches:
raise SystemExit(f"missing expected PT call {source} -> {dest}")
i, line = matches[0]
observed.append(dict(source=source, destination=dest, line=i, text=line))
if [x['line'] for x in observed[:7]] != sorted(x['line'] for x in observed[:7]):
raise SystemExit("observed PT call order mismatch")
dispatch = json.loads(inputs[0].read_text(encoding='utf-8'))
groups = dispatch['gpu_groups']
if len(groups) != 8:
raise SystemExit(f"expected 8 live GPU owner groups in {inputs[0]}, found {len(groups)}")
live = []
for group in groups:
rows = [e for e in dispatch['events'] if e['gpu_owner'] == group['gpu_owner'] and e['stage'] == 'Load' and e['engine_ordinal'] in (69, 70)]
if len(rows) != 2 or [(e['engine_ordinal'], e['callback']['name']) for e in rows] != [(69, '_nv004197rm'), (70, '_nv004147rm')]:
raise SystemExit(f"unexpected Load dispatch rows for group {group['gpu_owner']}")
live.extend(rows)
report = {
'scope': 'Read-only interpretation correction/reconciliation. Production source unchanged; two separate live captures are not merged into one object/timestamp trace.',
'artifact_sha256': SHA,
'conclusion': '028309→028308 is genuine OBJFIFO StateLoad. Original ACR WPR preparation invokes it early while constructing a FIFO-lite CeUtils channel; later top-level engine69 invokes FIFO StateLoad again. Engine70 wrapper004147 is DPAUX, not FIFO.',
'class_relocation_proof': classes,
'fifo_metadata_body': 'OBJFIFO staticmetadata4da5d80+118 resolves028309;004197 adjustsEngState-8 then calls originalobjectvtable118. 028309 initializes timeout, calls028308, then selected780 callback on success.',
'early_callsite_instructions': instructions,
'live_dispatch': {'capture': str(inputs[0].relative_to(R)), 'separate_capture_from_PT': True, 'observed_gpu_owner_groups': len(groups), 'observations': live, 'limitation': 'Attempted immediate dispatches; no return statuses/PCI BDF mapping or downstream HAL completion established.'},
'early_PT': {'capture': str(inputs[2].relative_to(R)), 'bounded_lines': len(window), 'observed_source_calls': observed, 'limitation': 'Bounded decoded window; root reports no decode errors but cutoff. Static targets and observed local source-call order support this bootstrap path, not a complete lossless initialization chain or runtime pointer dereference.'},
'static_semantic_chain': [
'016753 WPR gather ->019032 CE check/init ->043991(memmanager CeUtils init,bFifoLite=true) ->006444 CeUtils create ->019130 CeUtils constructor FIFO_LITE bit2 branch ->030544 actualOBJFIFO getter ->028064 internal FIFO-lite channel construction ->objectvtable118 flags0 ->028309 ->028308',
'028064 allocates paired channel/resource owner records, links FIFO848/850 and marker7c5, prepares channel bookkeeping, invokesFIFOload before VM/pushbuffer/USERD/RAMFC construction; does not represent Falcon StateLoad',
'Later lifecycle dispatch engine69 calls004197 to the same FIFO virtual method, independently of the earlier on-demand internal copy channel path',
],
'guidance580': {
'memmgrInitCeUtils': 'src/nvidia/src/kernel/gpu/mem_mgr/mem_mgr.c4107: bFifoLite sets NV0050_CEUTILS_FLAGS_FIFO_LITE, then constructs CeUtils',
'flag': 'src/common/sdk/nvidia/inc/class/cl0050.h57: FIFO_LITE isbit2',
'public_private_difference': 'src/nvidia/src/kernel/gpu/mem_mgr/ce_utils.c182 returnsNV_ERR_NOT_SUPPORTED for FIFO_LITE in the public kernel-only code. Closed580 original implements it, so public source alone cannot replace this bootstrap recipe.',
'classids': 'g_eng_desc_nvoc.h confirms b02365 OBJFIFO and fd2ab9 OBJDPAUX',
},
'UseCe_policy': {
'observed_CeUtils_init_is_conditional': True,
'original_gate': '016753 calls019039/019032 only inside shadow-present ACR386, GPU4de4==0 and ACR385!=0 branch. It is not proactive/unconditional on this observed parent path.',
'runtime_field_inference': 'Given unchanged matching code and this observed callsite, the branch was taken; infer the tested runtime conditions, not the origin of ACR385.',
'registry_not_proven': '016731 only overwrites385=(lowbyteDWORD)&1 when RMAcrUseCeForShadowCopy read returnsNV_OK. These captures do not expose the read status/value or constructor defaults; an explicit registryDWORD1 is NOT established.',
'transfer_evidence': 'PT also observes016753+216 calling044027. This proves a transfer routine was invoked; it does not capture source/destination/length/status/content or establish completed/authenticated shadow copy.',
'Rust_CPU_path': 'Explicit owned385=0 follows original CPU mapping/copy branch and skips this CEutils bootstrap for WPRshadow copy. Existing Rust CPU policy still requires its actual selected registry/configuration ownership; this does not eliminate normal FIFO/CE/GR admission later or establish default-configuration parity.',
},
'REA_evidence': evidence,
'inputs_sha256': {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in inputs},
'validation': 'Exact original SHA, both classIDs, both Load-wrapper relocations, FIFO body relocation, zero flags/118 indirect callsite, eight independent live owner groups and local PT callchain assertions passed.',
'changed_production_files': [],
}
out = R / 'reports/native-fifo-live-bootstrap-reconciliation.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
text = [report['conclusion'], '', 'Observed first bootstrap chain (bounded PT window):']
text += [f" line{x['line']}: {x['source']} -> {x['destination']}" for x in observed]
text += ['', 'Class proof:004197 =OBJFIFO b02365;004147 =OBJDPAUX fd2ab9. Actual JSON ordinals69/70 respectively.', '', report['UseCe_policy']['original_gate'], report['UseCe_policy']['registry_not_proven'], report['UseCe_policy']['transfer_evidence'], report['UseCe_policy']['Rust_CPU_path'], '', 'Public580 CeUtils FIFO_LITE branch returnsNOT_SUPPORTED; proprietary580 has the observed bootstrap implementation.', '', report['validation'], '', 'REA evidence:']
text += [n + ' ' + eid for n, eid in evidence.items()]
(R / 'reports/native-fifo-live-bootstrap-reconciliation.txt').write_text('\n'.join(text) + '\n', encoding='utf-8')
print(report['validation'])
if __name__ == '__main__':
main()