mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
tools: make clock metadata, register-policy oracle, engine-set, and timer evidence tools portable and -O-safe
This commit is contained in:
87
tests/offline/test_clock_register_policy_and_timer_tools.py
Normal file
87
tests/offline/test_clock_register_policy_and_timer_tools.py
Normal file
@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for gpu_generate_clock_object_metadata,
|
||||
gpu_generate_register_policy_oracle, gen_engine_set_tables,
|
||||
timer-timeout-vgx-evidence, and timer-alarm-context-os-evidence.
|
||||
"""
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
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 ClockRegisterPolicyAndTimerToolsTest(unittest.TestCase):
|
||||
def test_all_five_scripts_are_import_safe(self):
|
||||
for rel in (
|
||||
"tools/gpu_generate_clock_object_metadata.py",
|
||||
"tools/gpu_generate_register_policy_oracle.py",
|
||||
"tools/gen_engine_set_tables.py",
|
||||
"tools/timer-timeout-vgx-evidence.py",
|
||||
"tools/timer-alarm-context-os-evidence.py",
|
||||
):
|
||||
mod = _load(Path(rel).stem.replace("-", "_"), rel)
|
||||
self.assertTrue(callable(mod.main))
|
||||
|
||||
def test_gen_engine_set_tables_cli_and_rustfmt_and_number_under_O(self):
|
||||
mod = _load("gen_engine_set_tables", "tools/gen_engine_set_tables.py")
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
mod.main(["--unknown"])
|
||||
self.assertEqual(ctx.exception.code, 2)
|
||||
with self.assertRaisesRegex(SystemExit, "unexpected symbol name"):
|
||||
mod.number("bad_symbol")
|
||||
with mock.patch.dict(os.environ, {"RUSTFMT": "/custom/rustfmt"}, clear=True):
|
||||
self.assertEqual(mod.find_rustfmt(), "/custom/rustfmt")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fake = Path(tmp) / "bin/rustfmt"
|
||||
fake.parent.mkdir(parents=True)
|
||||
fake.write_text("", encoding="utf-8")
|
||||
with (
|
||||
mock.patch.dict(os.environ, {"CARGO_HOME": tmp}, clear=True),
|
||||
mock.patch.object(shutil, "which", return_value=None),
|
||||
):
|
||||
self.assertEqual(mod.find_rustfmt(), str(fake))
|
||||
|
||||
def test_rm_object_sha256_rejection_under_O(self):
|
||||
for rel in (
|
||||
"tools/gpu_generate_clock_object_metadata.py",
|
||||
"tools/gpu_generate_register_policy_oracle.py",
|
||||
):
|
||||
mod = _load(Path(rel).stem, rel)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fake = Path(tmp) / "nv-kernel.o_binary"
|
||||
fake.write_bytes(b"corrupt")
|
||||
with mock.patch.dict(os.environ, {"NV_RS_RM_OBJECT": str(fake)}, clear=True):
|
||||
self.assertEqual(mod.find_rm_object(), fake)
|
||||
with self.assertRaisesRegex(SystemExit, "sha256 mismatch"):
|
||||
mod.main(["--check"])
|
||||
|
||||
def test_timer_evidence_portable_nvidia_ko_discovery(self):
|
||||
vgx = _load("timer_timeout_vgx_evidence", "tools/timer-timeout-vgx-evidence.py")
|
||||
alarm = _load("timer_alarm_context_os_evidence", "tools/timer-alarm-context-os-evidence.py")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fake_ko = Path(tmp) / "nvidia.ko"
|
||||
fake_ko.write_bytes(b"not-elf")
|
||||
with mock.patch.dict(os.environ, {"NV_RS_NVIDIA_KO": str(fake_ko)}, clear=True):
|
||||
self.assertEqual(vgx.find_nvidia_ko(), fake_ko)
|
||||
self.assertEqual(alarm.find_nvidia_ko(), fake_ko)
|
||||
with self.assertRaisesRegex(SystemExit, "not a valid 64-bit"):
|
||||
alarm.main([])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -13,12 +13,13 @@ every constructed class with that oracle, so a stale table fails there.
|
||||
The output is passed through rustfmt. `--check` exits non-zero when the checked-in file
|
||||
differs from what would be written.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "analysis/closed-driver-580/first-open-spine.json"
|
||||
@ -38,12 +39,31 @@ CORRECTIONS = {
|
||||
|
||||
|
||||
def number(name):
|
||||
assert name.startswith("_nv") and name.endswith("rm"), name
|
||||
if not (name.startswith("_nv") and name.endswith("rm")):
|
||||
raise SystemExit(f"unexpected symbol name: {name!r}")
|
||||
return int(name[3:-2])
|
||||
|
||||
|
||||
def find_rustfmt() -> str:
|
||||
env_rustfmt = os.environ.get("RUSTFMT")
|
||||
if env_rustfmt:
|
||||
return env_rustfmt
|
||||
which = shutil.which("rustfmt")
|
||||
if which:
|
||||
return which
|
||||
candidates = []
|
||||
cargo_home = os.environ.get("CARGO_HOME")
|
||||
if cargo_home:
|
||||
candidates.append(Path(cargo_home) / "bin/rustfmt")
|
||||
candidates.append(Path.home() / ".cargo/bin/rustfmt")
|
||||
for candidate in candidates:
|
||||
if candidate.is_file():
|
||||
return str(candidate)
|
||||
raise SystemExit("rustfmt not found; set RUSTFMT or add rustfmt to PATH")
|
||||
|
||||
|
||||
def render():
|
||||
data = json.loads(SOURCE.read_text())
|
||||
data = json.loads(SOURCE.read_text(encoding="utf-8"))
|
||||
lines = [
|
||||
"//! Generated by tools/gen_engine_set_tables.py from",
|
||||
"//! analysis/closed-driver-580/first-open-spine.json. Do not edit by hand.",
|
||||
@ -99,7 +119,8 @@ def render():
|
||||
]
|
||||
lines += [f" {slot}," for slot in slots]
|
||||
lines += [" ],", " },"]
|
||||
assert used == set(CORRECTIONS), set(CORRECTIONS) - used
|
||||
if used != set(CORRECTIONS):
|
||||
raise SystemExit(f"unused CORRECTIONS entries: {sorted(set(CORRECTIONS) - used)}")
|
||||
lines += [
|
||||
"];",
|
||||
"",
|
||||
@ -120,20 +141,31 @@ def render():
|
||||
|
||||
def formatted(text):
|
||||
"""The text as rustfmt leaves it (the workspace check formats every file)."""
|
||||
rustfmt = shutil.which("rustfmt") or os.path.expanduser("~/.cargo/bin/rustfmt")
|
||||
return subprocess.run([rustfmt, "--edition", "2024"], input=text, text=True, check=True,
|
||||
capture_output=True, cwd=ROOT).stdout
|
||||
rustfmt = find_rustfmt()
|
||||
return subprocess.run(
|
||||
[rustfmt, "--edition", "2024"],
|
||||
input=text,
|
||||
text=True,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
cwd=ROOT,
|
||||
).stdout
|
||||
|
||||
|
||||
def main():
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--check", action="store_true", help="exit non-zero if checked-in file differs")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
text = render()
|
||||
if "--check" in sys.argv:
|
||||
if not TARGET.exists() or TARGET.read_text() != text:
|
||||
if args.check:
|
||||
if not TARGET.exists() or TARGET.read_text(encoding="utf-8") != text:
|
||||
print(f"{TARGET.relative_to(ROOT)} is not what the dossier gives; run this tool")
|
||||
return 1
|
||||
print(json.dumps({"checked": str(TARGET.relative_to(ROOT))}))
|
||||
return 0
|
||||
TARGET.write_text(text)
|
||||
TARGET.parent.mkdir(parents=True, exist_ok=True)
|
||||
TARGET.write_text(text, encoding="utf-8")
|
||||
print(json.dumps({"written": str(TARGET.relative_to(ROOT))}))
|
||||
return 0
|
||||
|
||||
|
||||
@ -1,38 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exact580 original method identities and relocation-backed template headers."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import argparse,hashlib,json,struct
|
||||
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')
|
||||
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};rd=e.get_section_by_name('.rodata');rdidx=e.get_section_index('.rodata');data=rd.data();rels={v['r_offset']:v for v in e.get_section_by_name('.rela.rodata').iter_relocations()}
|
||||
methods={}
|
||||
for n in ['021082','021087','021096','021084','021089','021090','021095','021080','021094','021085','021088','021079','021081','021083','021086','021091','021092','021093','020586','020592','021059']:
|
||||
s=byname['_nv'+n+'rm'];assert e.get_section(s['st_shndx']).name=='.text';methods[n]=s['st_value']
|
||||
noop=byname['_nv021089rm'];assert e.get_section(noop['st_shndx']).data()[noop['st_value']:noop['st_value']+noop['st_size']]==bytes.fromhex('f30f1efac3')
|
||||
templates=[]
|
||||
for s in symbols:
|
||||
if s['st_shndx']!=rdidx or s['st_size']!=64 or not s.name.startswith('_nv0213'):continue
|
||||
slots=[]
|
||||
for i in range(8):
|
||||
off=s['st_value']+i*8;v=rels.get(off)
|
||||
if v is None:assert struct.unpack_from('<Q',data,off)[0]==0;slots.append(None)
|
||||
else:
|
||||
target=symbols[v['r_info_sym']];slots.append({'symbol':target.name,'addend':v['r_addend']})
|
||||
assert slots[0]=={'symbol':s.name,'addend':0}
|
||||
templates.append({'symbol':s.name,'section_offset':hex(s['st_value']),'slots':slots})
|
||||
assert len(templates)>20
|
||||
deactivation={n:v for n,v in methods.items() if n not in ('020586','020592','021059')}
|
||||
replacements={n:methods[n] for n in ('020586','020592','021059')}
|
||||
unknown_template_callbacks=sorted({t['slots'][1]['symbol'] for t in templates if t['slots'][1]}-{'_nv'+n+'rm' for n in deactivation})
|
||||
assert len(deactivation)==18 and not unknown_template_callbacks
|
||||
code='// Generated from exact580 ELF .text offsets; arbitrary unknown bindings remain External.\nimpl OriginalMethod {\n pub fn from_580_text_offset(offset: u32) -> Self {\n match offset {\n'
|
||||
for n,v in methods.items():code+=f' 0x{v:x} => Self::Nv{n},\n'
|
||||
code+=' _ => Self::External,\n }\n }\n}\n'
|
||||
report={'source_sha256':hashlib.sha256(f.read_bytes()).hexdigest(),'method_text_offsets':{n:hex(v) for n,v in methods.items()},'deactivation_method_offsets':{n:hex(v) for n,v in deactivation.items()},'header_replacement_function_offsets':{n:hex(v) for n,v in replacements.items()},'unknown_template_deactivation_callbacks':unknown_template_callbacks,'original_noop_bytes':'f30f1efac3','template_count':len(templates),'templates':templates,'limits':'Original relocation-backed headers. Actual object-template and method token registry still must retain the constructed objects. No hardware execution.'}
|
||||
for out,text in [(r/'src/nvidia/src/gpu/clock_object_methods.rs',code),(r/'reports/gpu-clock-object-metadata.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(f'Original clock-object metadata:{len(deactivation)}deactivation+{len(replacements)}header identities,{len(templates)}self-linked templates')
|
||||
import struct
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
|
||||
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
||||
METHOD_IDS = [
|
||||
'021082', '021087', '021096', '021084', '021089', '021090', '021095',
|
||||
'021080', '021094', '021085', '021088', '021079', '021081', '021083',
|
||||
'021086', '021091', '021092', '021093', '020586', '020592', '021059',
|
||||
]
|
||||
|
||||
|
||||
def find_rm_object() -> Path:
|
||||
candidates = []
|
||||
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 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:
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--check', action='store_true')
|
||||
args = p.parse_args(argv)
|
||||
|
||||
rm_obj = find_rm_object()
|
||||
raw = rm_obj.read_bytes()
|
||||
sha = hashlib.sha256(raw).hexdigest()
|
||||
if sha != EXPECTED_SHA256:
|
||||
raise SystemExit(f'{rm_obj}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
|
||||
|
||||
sections, by_name = parse_elf64(raw)
|
||||
syms = load_symbols(raw, sections, by_name['.symtab'])
|
||||
byname = {s[0]: s for s in syms}
|
||||
rdidx = by_name['.rodata']
|
||||
rd_h = sections[rdidx][1]
|
||||
data = raw[rd_h[4]:rd_h[4] + rd_h[5]]
|
||||
|
||||
rel_h = sections[by_name['.rela.rodata']][1]
|
||||
rel_entsize = rel_h[9] or 24
|
||||
rels = {}
|
||||
for i in range(rel_h[5] // rel_entsize):
|
||||
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw, rel_h[4] + i * rel_entsize)
|
||||
rels[r_offset] = (r_info >> 32, r_addend)
|
||||
|
||||
methods = {}
|
||||
for n in METHOD_IDS:
|
||||
s = byname['_nv' + n + 'rm']
|
||||
if sections[s[1]][0] != '.text':
|
||||
raise SystemExit(f'symbol {s[0]} is in {sections[s[1]][0]!r}, expected .text')
|
||||
methods[n] = s[2]
|
||||
|
||||
noop = byname['_nv021089rm']
|
||||
noop_h = sections[noop[1]][1]
|
||||
noop_bytes = raw[noop_h[4] + noop[2]:noop_h[4] + noop[2] + noop[3]]
|
||||
if noop_bytes != bytes.fromhex('f30f1efac3'):
|
||||
raise SystemExit(f'unexpected _nv021089rm bytes: {noop_bytes.hex()}')
|
||||
|
||||
templates = []
|
||||
for s in syms:
|
||||
if s[1] != rdidx or s[3] != 64 or not s[0].startswith('_nv0213'):
|
||||
continue
|
||||
slots = []
|
||||
for i in range(8):
|
||||
off = s[2] + i * 8
|
||||
v = rels.get(off)
|
||||
if v is None:
|
||||
if struct.unpack_from('<Q', data, off)[0] != 0:
|
||||
raise SystemExit(f'non-zero unrelocated slot {i} in {s[0]}')
|
||||
slots.append(None)
|
||||
else:
|
||||
target = syms[v[0]]
|
||||
slots.append({'symbol': target[0], 'addend': v[1]})
|
||||
if slots[0] != {'symbol': s[0], 'addend': 0}:
|
||||
raise SystemExit(f'template {s[0]} is not self-linked at slot 0: {slots[0]}')
|
||||
templates.append({'symbol': s[0], 'section_offset': hex(s[2]), 'slots': slots})
|
||||
|
||||
if len(templates) <= 20:
|
||||
raise SystemExit(f'expected >20 clock object templates, found {len(templates)}')
|
||||
deactivation = {n: v for n, v in methods.items() if n not in ('020586', '020592', '021059')}
|
||||
replacements = {n: methods[n] for n in ('020586', '020592', '021059')}
|
||||
unknown_template_callbacks = sorted(
|
||||
{t['slots'][1]['symbol'] for t in templates if t['slots'][1]} - {'_nv' + n + 'rm' for n in deactivation}
|
||||
)
|
||||
if len(deactivation) != 18 or unknown_template_callbacks:
|
||||
raise SystemExit(f'unexpected deactivation callbacks: count={len(deactivation)} unknown={unknown_template_callbacks}')
|
||||
|
||||
code = '// Generated from exact580 ELF .text offsets; arbitrary unknown bindings remain External.\nimpl OriginalMethod {\n pub fn from_580_text_offset(offset: u32) -> Self {\n match offset {\n'
|
||||
for n, v in methods.items():
|
||||
code += f' 0x{v:x} => Self::Nv{n},\n'
|
||||
code += ' _ => Self::External,\n }\n }\n}\n'
|
||||
report = {
|
||||
'source_sha256': sha,
|
||||
'method_text_offsets': {n: hex(v) for n, v in methods.items()},
|
||||
'deactivation_method_offsets': {n: hex(v) for n, v in deactivation.items()},
|
||||
'header_replacement_function_offsets': {n: hex(v) for n, v in replacements.items()},
|
||||
'unknown_template_deactivation_callbacks': unknown_template_callbacks,
|
||||
'original_noop_bytes': 'f30f1efac3',
|
||||
'template_count': len(templates),
|
||||
'templates': templates,
|
||||
'limits': 'Original relocation-backed headers. Actual object-template and method token registry still must retain the constructed objects. No hardware execution.',
|
||||
}
|
||||
for out, text in [
|
||||
(ROOT / 'src/nvidia/src/gpu/clock_object_methods.rs', code),
|
||||
(ROOT / 'reports/gpu-clock-object-metadata.json', json.dumps(report, indent=2) + '\n'),
|
||||
]:
|
||||
if args.check:
|
||||
if not out.is_file() or out.read_text(encoding='utf-8') != text:
|
||||
raise SystemExit('Stale ' + str(out))
|
||||
else:
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(text, encoding='utf-8')
|
||||
print(f'Original clock-object metadata:{len(deactivation)}deactivation+{len(replacements)}header identities,{len(templates)}self-linked templates')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@ -1,46 +1,175 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile literal original inferred C policy selectors, with relocation-backed tables."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import argparse,hashlib,json,struct,subprocess
|
||||
from elftools.elf.elffile import ELFFile
|
||||
root=Path(__file__).resolve().parent.parent
|
||||
base=Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
||||
source=base/'extracted/kernel/nvidia/nv-kernel.o_binary'
|
||||
check=argparse.ArgumentParser();check.add_argument('--check',action='store_true');args=check.parse_args()
|
||||
with source.open('rb') as stream:
|
||||
elf=ELFFile(stream);data=elf.get_section_by_name('.data').data();symbols=elf.get_section_by_name('.symtab')
|
||||
groups=[struct.unpack_from('<6I',data,0x41120+i*24) for i in range(32)]
|
||||
sub=[struct.unpack_from('<8I',data,0x40c00+i*32) for i in range(41)]
|
||||
rows=json.loads((root/'reports/gpu-gv100-hal-audit-diff.json').read_text())['rows']
|
||||
bindings={'0x740':'_nv030423rm','0x750':'_nv030519rm','0x768':'_nv030894rm','0x6e8':'_nv031029rm'}
|
||||
for variant in ('0','1','2'):
|
||||
for slot,fn in bindings.items():assert rows[variant][slot]==fn
|
||||
rodata=elf.get_section_by_name('.rodata')
|
||||
mo=0x05dfe560-0x100000-rodata['sh_addr']
|
||||
engine_keys=[struct.unpack_from('<II',rodata.data(),mo+i*8) for i in range(18)]
|
||||
assert all(region not in [r for r,k in engine_keys] for region in (0,0x8b000))
|
||||
assert groups[1]==(7,0,18,15,0,0)
|
||||
assert sub[40]==(0xb33b1500,0,7,5,28,15,0,0)
|
||||
descriptors=[]
|
||||
relocs={r['r_offset']:r for r in elf.get_section_by_name('.rela.data').iter_relocations()}
|
||||
import struct
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
|
||||
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
||||
|
||||
|
||||
def find_rm_object() -> Path:
|
||||
candidates = []
|
||||
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 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
|
||||
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]
|
||||
syms.append((st_shndx, st_value))
|
||||
return syms
|
||||
|
||||
|
||||
def main(argv=None) -> None:
|
||||
check = argparse.ArgumentParser(description=__doc__)
|
||||
check.add_argument('--check', action='store_true')
|
||||
args = check.parse_args(argv)
|
||||
|
||||
source = find_rm_object()
|
||||
raw_elf = source.read_bytes()
|
||||
sha = hashlib.sha256(raw_elf).hexdigest()
|
||||
if sha != EXPECTED_SHA256:
|
||||
raise SystemExit(f'{source}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
|
||||
|
||||
sections, by_name = parse_elf64(raw_elf)
|
||||
data_h = sections[by_name['.data']][1]
|
||||
data = raw_elf[data_h[4]:data_h[4] + data_h[5]]
|
||||
syms = load_symbols(raw_elf, sections, by_name['.symtab'])
|
||||
|
||||
groups = [struct.unpack_from('<6I', data, 0x41120 + i * 24) for i in range(32)]
|
||||
sub = [struct.unpack_from('<8I', data, 0x40C00 + i * 32) for i in range(41)]
|
||||
rows = json.loads((ROOT / 'reports/gpu-gv100-hal-audit-diff.json').read_text(encoding='utf-8'))['rows']
|
||||
bindings = {'0x740': '_nv030423rm', '0x750': '_nv030519rm', '0x768': '_nv030894rm', '0x6e8': '_nv031029rm'}
|
||||
for variant in ('0', '1', '2'):
|
||||
for slot, fn in bindings.items():
|
||||
if rows[variant][slot] != fn:
|
||||
raise SystemExit(f'HAL binding mismatch for variant {variant} slot {slot}: {rows[variant][slot]} != {fn}')
|
||||
|
||||
ro_h = sections[by_name['.rodata']][1]
|
||||
rodata = raw_elf[ro_h[4]:ro_h[4] + ro_h[5]]
|
||||
mo = 0x05DFE560 - 0x100000 - ro_h[3]
|
||||
engine_keys = [struct.unpack_from('<II', rodata, mo + i * 8) for i in range(18)]
|
||||
if any(region in [r for r, _k in engine_keys] for region in (0, 0x8B000)):
|
||||
raise SystemExit('unexpected BIF fallback region found in region_engine_keys')
|
||||
if groups[1] != (7, 0, 18, 15, 0, 0):
|
||||
raise SystemExit(f'unexpected group7 row: {groups[1]}')
|
||||
if sub[40] != (0xB33B1500, 0, 7, 5, 28, 15, 0, 0):
|
||||
raise SystemExit(f'unexpected subtype sentinel row: {sub[40]}')
|
||||
|
||||
rel_h = sections[by_name['.rela.data']][1]
|
||||
rel_entsize = rel_h[9] or 24
|
||||
relocs = {}
|
||||
for i in range(rel_h[5] // rel_entsize):
|
||||
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw_elf, rel_h[4] + i * rel_entsize)
|
||||
relocs[r_offset] = (r_info >> 32, r_addend)
|
||||
|
||||
descriptors = []
|
||||
for i in range(21):
|
||||
o=0x46c40+i*24;region,_,_,count,_=struct.unpack_from('<IIQII',data,o)
|
||||
r=relocs[o+8];target=symbols.get_symbol(r['r_info_sym']);assert elf.get_section(target['st_shndx']).name=='.data'
|
||||
p=target['st_value']+r['r_addend'];pairs=[struct.unpack_from('<II',data,p+j*8) for j in range(count)]
|
||||
descriptors.append({'region':region,'count':count,'offset':p,'pairs':pairs})
|
||||
assert next(x['pairs'] for x in descriptors if x['region']==0)==[(0x884e8,0x44)]
|
||||
assert next(x['pairs'] for x in descriptors if x['region']==0x8b000)==[(0x8e000,0x4b)]
|
||||
# Kept source is reviewed literal inferred C, with harness helpers separate.
|
||||
c=root/'tools/gpu_register_policy_oracle.c'
|
||||
build=root/'target/register-policy-oracle';build.parent.mkdir(exist_ok=True)
|
||||
subprocess.run(['cc','-std=gnu11','-O0','-fno-strict-aliasing',str(c),'-o',str(build)],check=True)
|
||||
result=subprocess.check_output([str(build)],text=True).strip().split()
|
||||
assert len(result)==2
|
||||
output='// Generated by tools/gpu_generate_register_policy_oracle.py; literal original C oracle.\n'
|
||||
output+=f'const ORIGINAL_POLICY_CASES: usize = {result[0]};\nconst ORIGINAL_POLICY_HASH: u64 = 0x{result[1]};\n'
|
||||
report={'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'oracle_c_sha256':hashlib.sha256(c.read_bytes()).hexdigest(),'case_count':int(result[0]),'fnv1a64':result[1],'runtime_variant_bindings':bindings,'region_engine_keys':engine_keys,'bif_fallback_engine_key':'0xb33b1500','group7':groups[1],'subtype_sentinel':sub[40],'region_descriptors':descriptors,'limits':'Synthetic memory and recorded writes. Literal inferred original C, not execution of original machine code or hardware. Only physical BIF regions 0 and 0x8b000 translated.'}
|
||||
for path,text in [(root/'src/nvidia/src/gpu/gv100_register_policy_oracle.rs',output),(root/'reports/gpu-gv100-register-policy-oracle.json',json.dumps(report,indent=2)+'\n')]:
|
||||
if args.check:
|
||||
if path.read_text()!=text:raise SystemExit(f'Stale {path}')
|
||||
else:path.write_text(text)
|
||||
print(f'Original register-policy oracle: {result[0]} cases; hash {result[1]}')
|
||||
o = 0x46C40 + i * 24
|
||||
region, _, _, count, _ = struct.unpack_from('<IIQII', data, o)
|
||||
r_sym, r_addend = relocs[o + 8]
|
||||
shndx, st_value = syms[r_sym]
|
||||
if sections[shndx][0] != '.data':
|
||||
raise SystemExit(f'unexpected region descriptor target section {sections[shndx][0]!r} != .data')
|
||||
p = st_value + r_addend
|
||||
pairs = [struct.unpack_from('<II', data, p + j * 8) for j in range(count)]
|
||||
descriptors.append({'region': region, 'count': count, 'offset': p, 'pairs': pairs})
|
||||
|
||||
if next((x['pairs'] for x in descriptors if x['region'] == 0), None) != [(0x884E8, 0x44)]:
|
||||
raise SystemExit('unexpected region 0 descriptor pairs')
|
||||
if next((x['pairs'] for x in descriptors if x['region'] == 0x8B000), None) != [(0x8E000, 0x4B)]:
|
||||
raise SystemExit('unexpected region 0x8b000 descriptor pairs')
|
||||
|
||||
# Kept source is reviewed literal inferred C, with harness helpers separate.
|
||||
c = ROOT / 'tools/gpu_register_policy_oracle.c'
|
||||
build = ROOT / 'target/register-policy-oracle'
|
||||
build.parent.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run(['cc', '-std=gnu11', '-O0', '-fno-strict-aliasing', str(c), '-o', str(build)], check=True)
|
||||
result = subprocess.check_output([str(build)], text=True).strip().split()
|
||||
if len(result) != 2:
|
||||
raise SystemExit(f'unexpected oracle output: {result!r}')
|
||||
|
||||
output = '// Generated by tools/gpu_generate_register_policy_oracle.py; literal original C oracle.\n'
|
||||
output += f'const ORIGINAL_POLICY_CASES: usize = {result[0]};\nconst ORIGINAL_POLICY_HASH: u64 = 0x{result[1]};\n'
|
||||
report = {
|
||||
'source_sha256': sha,
|
||||
'oracle_c_sha256': hashlib.sha256(c.read_bytes()).hexdigest(),
|
||||
'case_count': int(result[0]),
|
||||
'fnv1a64': result[1],
|
||||
'runtime_variant_bindings': bindings,
|
||||
'region_engine_keys': [list(k) for k in engine_keys],
|
||||
'bif_fallback_engine_key': '0xb33b1500',
|
||||
'group7': list(groups[1]),
|
||||
'subtype_sentinel': list(sub[40]),
|
||||
'region_descriptors': [
|
||||
{**d, 'pairs': [list(pair) for pair in d['pairs']]} for d in descriptors
|
||||
],
|
||||
'limits': 'Synthetic memory and recorded writes. Literal inferred original C, not execution of original machine code or hardware. Only physical BIF regions 0 and 0x8b000 translated.',
|
||||
}
|
||||
for path, text in [
|
||||
(ROOT / 'src/nvidia/src/gpu/gv100_register_policy_oracle.rs', output),
|
||||
(ROOT / 'reports/gpu-gv100-register-policy-oracle.json', json.dumps(report, indent=2) + '\n'),
|
||||
]:
|
||||
if args.check:
|
||||
if not path.is_file() or path.read_text(encoding='utf-8') != text:
|
||||
raise SystemExit(f'Stale {path}')
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding='utf-8')
|
||||
print(f'Original register-policy oracle: {result[0]} cases; hash {result[1]}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@ -1,20 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only installed580 OS timer/queue relocation evidence, no execution."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from elftools.elf.elffile import ELFFile
|
||||
import json,hashlib
|
||||
R=Path(__file__).resolve().parents[1];M=Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko');wanted=['nv_create_nano_timer','nv_start_nano_timer','nv_cancel_nano_timer','nv_jiffy_timer_callback_typed_data','nv_nano_timer_callback_typed_data','nvidia_nano_timer_callback','os_queue_work_item','os_execute_work_item']
|
||||
with M.open('rb')as f:
|
||||
e=ELFFile(f);ss=list(e.get_section_by_name('.symtab').iter_symbols());defs={s.name:s for s in ss};ti=e.get_section_index('.text');text=e.get_section_by_name('.text').data();byoff={s['st_value']:s.name for s in ss if s['st_shndx']==ti and s['st_info']['type']=='STT_FUNC'};records={name:{'present':name in defs,'references':[]}for name in wanted}
|
||||
for name in wanted:
|
||||
if name in defs:
|
||||
s=defs[name];records[name].update(module_text_offset=hex(s['st_value']),bytes=s['st_size'],prefix16=text[s['st_value']:s['st_value']+16].hex())
|
||||
for r in e.get_section_by_name('.rela.text').iter_relocations():
|
||||
off=r['r_offset'];owners=[name for name in wanted if name in defs and defs[name]['st_value']<=off<defs[name]['st_value']+defs[name]['st_size']]
|
||||
if not owners:continue
|
||||
s=ss[r['r_info_sym']];target=s.name
|
||||
if s['st_shndx']==ti and s['st_info']['type']!='STT_FUNC':
|
||||
at=s['st_value']+r['r_addend']+(4 if r['r_info_type']in[2,4]else 0);target=byoff.get(at,'text+'+hex(at))
|
||||
for name in owners:records[name]['references'].append({'offset':hex(off-defs[name]['st_value']),'type':r['r_info_type'],'target':target,'addend':r['r_addend']})
|
||||
report={'read_only':True,'installed_module':str(M),'installed_module_sha256':hashlib.sha256(M.read_bytes()).hexdigest(),'functions':records,'claim':'Installed580 usesjiffytimer branch andqueuesRMwork; relocationfactsnotlivecallbackexecution.','tracing_changed':False};(R/'reports/timer-alarm-context-os-evidence.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
for name,v in records.items():print(name,v['present'],[x['target']for x in v['references']])
|
||||
import platform
|
||||
import struct
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WANTED = [
|
||||
'nv_create_nano_timer',
|
||||
'nv_start_nano_timer',
|
||||
'nv_cancel_nano_timer',
|
||||
'nv_jiffy_timer_callback_typed_data',
|
||||
'nv_nano_timer_callback_typed_data',
|
||||
'nvidia_nano_timer_callback',
|
||||
'os_queue_work_item',
|
||||
'os_execute_work_item',
|
||||
]
|
||||
|
||||
|
||||
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(raw: bytes):
|
||||
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
|
||||
raise SystemExit('input 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('--nvidia-ko', type=Path, default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
module_path = find_nvidia_ko(args.nvidia_ko)
|
||||
raw = module_path.read_bytes()
|
||||
sections, by_name = _parse_elf64(raw)
|
||||
ss = _load_symbols(raw, sections, by_name['.symtab'])
|
||||
defs = {s[0]: s for s in ss}
|
||||
ti = by_name['.text']
|
||||
text_h = sections[ti][1]
|
||||
text = raw[text_h[4]:text_h[4] + text_h[5]]
|
||||
byoff = {s[2]: s[0] for s in ss if s[1] == ti and s[4] == 2} # STT_FUNC = 2
|
||||
|
||||
records = {name: {'present': name in defs, 'references': []} for name in WANTED}
|
||||
for name in WANTED:
|
||||
if name in defs:
|
||||
s = defs[name]
|
||||
records[name].update(
|
||||
module_text_offset=hex(s[2]),
|
||||
bytes=s[3],
|
||||
prefix16=text[s[2]:s[2] + 16].hex(),
|
||||
)
|
||||
|
||||
rel_h = sections[by_name['.rela.text']][1]
|
||||
rel_entsize = rel_h[9] or 24
|
||||
for i in range(rel_h[5] // rel_entsize):
|
||||
off, r_info, r_addend = struct.unpack_from('<QQq', raw, rel_h[4] + i * rel_entsize)
|
||||
r_sym = r_info >> 32
|
||||
r_type = r_info & 0xFFFFFFFF
|
||||
owners = [
|
||||
name for name in WANTED
|
||||
if name in defs and defs[name][2] <= off < defs[name][2] + defs[name][3]
|
||||
]
|
||||
if not owners:
|
||||
continue
|
||||
s = ss[r_sym]
|
||||
target = s[0]
|
||||
if s[1] == ti and s[4] != 2:
|
||||
at = s[2] + r_addend + (4 if r_type in (2, 4) else 0)
|
||||
target = byoff.get(at, 'text+' + hex(at))
|
||||
for name in owners:
|
||||
records[name]['references'].append({
|
||||
'offset': hex(off - defs[name][2]),
|
||||
'type': r_type,
|
||||
'target': target,
|
||||
'addend': r_addend,
|
||||
})
|
||||
|
||||
report = {
|
||||
'read_only': True,
|
||||
'installed_module': str(module_path),
|
||||
'installed_module_sha256': hashlib.sha256(raw).hexdigest(),
|
||||
'functions': records,
|
||||
'claim': 'Installed580 usesjiffytimer branch andqueuesRMwork; relocationfactsnotlivecallbackexecution.',
|
||||
'tracing_changed': False,
|
||||
}
|
||||
out = ROOT / 'reports/timer-alarm-context-os-evidence.json'
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
|
||||
for name, v in records.items():
|
||||
print(name, v['present'], [x['target'] for x in v['references']])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@ -1,51 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read original ELF symbols/source only; never call or change the driver."""
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from elftools.elf.elffile import ELFFile
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import struct
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ANALYSIS = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
||||
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
||||
|
||||
|
||||
def symbol(path, name):
|
||||
with path.open('rb') as stream:
|
||||
elf = ELFFile(stream)
|
||||
table = elf.get_section_by_name('.symtab')
|
||||
item = next(s for s in table.iter_symbols() if s.name == name)
|
||||
section = elf.get_section(item['st_shndx'])
|
||||
start, size = item['st_value'], item['st_size']
|
||||
code = section.data()[start:start+size]
|
||||
relocations = []
|
||||
for relocation_section in elf.iter_sections():
|
||||
if relocation_section['sh_type'] not in ('SHT_RELA', 'SHT_REL'):
|
||||
continue
|
||||
if elf.get_section(relocation_section['sh_info']).name != section.name:
|
||||
continue
|
||||
symbols = elf.get_section(relocation_section['sh_link'])
|
||||
for relocation in relocation_section.iter_relocations():
|
||||
offset = relocation['r_offset']
|
||||
if start <= offset < start+size:
|
||||
relocations.append({'offset': offset-start,
|
||||
'target': symbols.get_symbol(relocation['r_info_sym']).name,
|
||||
'addend': relocation.entry.get('r_addend')})
|
||||
return {'path':str(path), 'file_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
'symbol':name, 'section':section.name, 'offset':hex(start),
|
||||
'size':size, 'bytes':code.hex(), 'relocations':relocations}
|
||||
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 pass --rm-object')
|
||||
|
||||
|
||||
def main():
|
||||
wrapper = symbol(ANALYSIS/'extracted/kernel/nvidia/nv-kernel.o_binary','_nv036619rm')
|
||||
installed = symbol(Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko'),'os_is_vgx_hyper')
|
||||
assert wrapper['size'] == 9 and wrapper['bytes'].startswith('f30f1efae9')
|
||||
assert any(row['target']=='os_is_vgx_hyper' for row in wrapper['relocations'])
|
||||
assert installed['bytes']=='e8000000005531c04889e55de900000000'
|
||||
assert [r['target'] for r in installed['relocations']] == ['__fentry__','__x86_return_thunk']
|
||||
output = {'scope':'Static ELF bytes and exact relocations; no loaded-driver execution',
|
||||
'fresh_REA':'reports/timer-timeout-vgx-rea/_nv036619rm.rea.json',
|
||||
'original_RM_tail_forwarder':wrapper,'installed_Linux_false_implementation':installed}
|
||||
(ROOT/'reports/timer-timeout-vgx-binary-evidence.json').write_text(json.dumps(output,indent=2)+'\n')
|
||||
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(raw: bytes):
|
||||
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
|
||||
raise SystemExit('input 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 symbol(path: Path, name: str) -> dict:
|
||||
raw = path.read_bytes()
|
||||
sections, by_name = _parse_elf64(raw)
|
||||
syms = _load_symbols(raw, sections, by_name['.symtab'])
|
||||
item = next((s for s in syms if s[0] == name), None)
|
||||
if item is None:
|
||||
raise SystemExit(f'symbol {name!r} not found in {path}')
|
||||
sec_name, sec_h = sections[item[1]]
|
||||
start, size = item[2], item[3]
|
||||
code = raw[sec_h[4] + start:sec_h[4] + start + size]
|
||||
relocations = []
|
||||
for _rname, rh in sections:
|
||||
sh_type = rh[1]
|
||||
if sh_type not in (4, 9): # SHT_RELA (4), SHT_REL (9)
|
||||
continue
|
||||
if sections[rh[7]][0] != sec_name:
|
||||
continue
|
||||
rsyms = _load_symbols(raw, sections, rh[6])
|
||||
entsize = rh[9] or (24 if sh_type == 4 else 16)
|
||||
for i in range(rh[5] // entsize):
|
||||
if sh_type == 4:
|
||||
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw, rh[4] + i * entsize)
|
||||
else:
|
||||
r_offset, r_info = struct.unpack_from('<QQ', raw, rh[4] + i * entsize)
|
||||
r_addend = None
|
||||
if start <= r_offset < start + size:
|
||||
relocations.append({
|
||||
'offset': r_offset - start,
|
||||
'target': rsyms[r_info >> 32][0],
|
||||
'addend': r_addend,
|
||||
})
|
||||
return {
|
||||
'path': str(path),
|
||||
'file_sha256': hashlib.sha256(raw).hexdigest(),
|
||||
'symbol': name,
|
||||
'section': sec_name,
|
||||
'offset': hex(start),
|
||||
'size': size,
|
||||
'bytes': code.hex(),
|
||||
'relocations': relocations,
|
||||
}
|
||||
|
||||
|
||||
def main(argv=None) -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--rm-object', type=Path, default=None)
|
||||
parser.add_argument('--nvidia-ko', type=Path, default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
wrapper = symbol(find_rm_object(args.rm_object), '_nv036619rm')
|
||||
installed = symbol(find_nvidia_ko(args.nvidia_ko), 'os_is_vgx_hyper')
|
||||
if wrapper['size'] != 9 or not wrapper['bytes'].startswith('f30f1efae9'):
|
||||
raise SystemExit(f'unexpected _nv036619rm bytes: {wrapper["bytes"]}')
|
||||
if not any(row['target'] == 'os_is_vgx_hyper' for row in wrapper['relocations']):
|
||||
raise SystemExit('_nv036619rm does not relocate to os_is_vgx_hyper')
|
||||
if installed['bytes'] != 'e8000000005531c04889e55de900000000':
|
||||
raise SystemExit(f'unexpected os_is_vgx_hyper bytes: {installed["bytes"]}')
|
||||
if [r['target'] for r in installed['relocations']] != ['__fentry__', '__x86_return_thunk']:
|
||||
raise SystemExit(f'unexpected os_is_vgx_hyper relocations: {installed["relocations"]}')
|
||||
|
||||
output = {
|
||||
'scope': 'Static ELF bytes and exact relocations; no loaded-driver execution',
|
||||
'fresh_REA': 'reports/timer-timeout-vgx-rea/_nv036619rm.rea.json',
|
||||
'original_RM_tail_forwarder': wrapper,
|
||||
'installed_Linux_false_implementation': installed,
|
||||
}
|
||||
out = ROOT / 'reports/timer-timeout-vgx-binary-evidence.json'
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(output, indent=2) + '\n', encoding='utf-8')
|
||||
print('Original nine-byte RM tail-forwarder and installed constant-false Linux implementation verified.')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user