mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
169 lines
7.3 KiB
Python
169 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Bind the embedded shader to the immutable original-driver execution baseline."""
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path, PurePosixPath
|
|
import struct
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
BASELINE = ROOT / 'reports/checkpoints/native-hello-baseline-2da2fe783377'
|
|
EXPECTED_CUBIN_SHA256 = '2da2fe78337788e5c8103837255d3dd79fe248ae26a3d4f51b5f3e6e05ccb7ac'
|
|
|
|
|
|
class _FallbackSection(dict):
|
|
def __init__(self, name, data_bytes, **fields):
|
|
super().__init__(**fields)
|
|
self.name = name
|
|
self._data = data_bytes
|
|
|
|
def data(self):
|
|
return self._data
|
|
|
|
|
|
class _FallbackELFFile:
|
|
"""Minimal stdlib ELF64 little-endian section reader used when pyelftools is absent."""
|
|
|
|
def __init__(self, stream):
|
|
raw = stream.read()
|
|
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
|
|
raise SystemExit('cubin 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)
|
|
if e_shoff == 0 or e_shentsize < 64 or e_shnum == 0 or e_shstrndx >= e_shnum:
|
|
raise SystemExit('cubin ELF section header table is missing or malformed')
|
|
table_end = e_shoff + e_shentsize * e_shnum
|
|
if table_end > len(raw):
|
|
raise SystemExit('cubin ELF section header table exceeds file size')
|
|
|
|
headers = []
|
|
for idx in range(e_shnum):
|
|
off = e_shoff + idx * e_shentsize
|
|
sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize = (
|
|
struct.unpack_from('<IIQQQQIIQQ', raw, off)
|
|
)
|
|
headers.append((sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize))
|
|
|
|
str_hdr = headers[e_shstrndx]
|
|
str_off, str_size = str_hdr[4], str_hdr[5]
|
|
if str_off + str_size > len(raw):
|
|
raise SystemExit('cubin ELF section string table exceeds file size')
|
|
shstrtab = raw[str_off:str_off + str_size]
|
|
|
|
self._sections = []
|
|
self._by_name = {}
|
|
for sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize in headers:
|
|
nul = shstrtab.find(b'\x00', sh_name)
|
|
name = shstrtab[sh_name:nul if nul != -1 else len(shstrtab)].decode('utf-8', errors='replace')
|
|
if sh_type != 8 and sh_offset + sh_size > len(raw):
|
|
raise SystemExit(f'cubin ELF section {name!r} exceeds file size')
|
|
payload = b'' if sh_type == 8 else raw[sh_offset:sh_offset + sh_size]
|
|
sec = _FallbackSection(
|
|
name,
|
|
payload,
|
|
sh_name=sh_name,
|
|
sh_type=sh_type,
|
|
sh_flags=sh_flags,
|
|
sh_addr=sh_addr,
|
|
sh_offset=sh_offset,
|
|
sh_size=sh_size,
|
|
sh_link=sh_link,
|
|
sh_info=sh_info,
|
|
sh_addralign=sh_addralign,
|
|
sh_entsize=sh_entsize,
|
|
)
|
|
self._sections.append(sec)
|
|
self._by_name[name] = sec
|
|
|
|
def get_section_by_name(self, name):
|
|
return self._by_name.get(name)
|
|
|
|
def iter_sections(self):
|
|
return iter(self._sections)
|
|
|
|
|
|
def _open_elf(stream):
|
|
try:
|
|
from elftools.elf.elffile import ELFFile
|
|
except ImportError:
|
|
return _FallbackELFFile(stream)
|
|
return ELFFile(stream)
|
|
|
|
|
|
def recorded_digest(record, relative_path):
|
|
# The original archive stored absolute paths on its evidence host.
|
|
expected_suffix = PurePosixPath(relative_path).parts
|
|
matches = [
|
|
digest for path, digest in record['artifacts'].items()
|
|
if PurePosixPath(path).parts[-len(expected_suffix):] == expected_suffix
|
|
]
|
|
if len(matches) != 1:
|
|
raise SystemExit(f'expected one archived artifact entry for {relative_path}')
|
|
return matches[0]
|
|
|
|
|
|
def main():
|
|
cubin = BASELINE / 'target/hardware-hello/native_hello.sm70.cubin'
|
|
expected = EXPECTED_CUBIN_SHA256
|
|
actual_cubin_sha = hashlib.sha256(cubin.read_bytes()).hexdigest()
|
|
if actual_cubin_sha != expected:
|
|
raise SystemExit(f'baseline cubin sha256 mismatch: {actual_cubin_sha} != {expected}')
|
|
record = json.loads((BASELINE / 'reports/native-hello-original-580/validation.json').read_text(encoding='utf-8'))
|
|
if record['passed'] is not True or record['pci_driver_before'] != 'nvidia':
|
|
raise SystemExit('archived original-driver validation did not pass')
|
|
if not record['runs'] or any(
|
|
run['observed']['passed'] is not True or run['observed']['verified_words'] != 64
|
|
for run in record['runs']
|
|
):
|
|
raise SystemExit('archived original-driver runs are missing or incomplete')
|
|
|
|
cubin_path = cubin.relative_to(BASELINE).as_posix()
|
|
if recorded_digest(record, cubin_path) != expected:
|
|
raise SystemExit('archived validation identifies a different cubin')
|
|
source_path = 'tests/hardware/native_hello.cu'
|
|
source = ROOT / source_path
|
|
if hashlib.sha256(source.read_bytes()).hexdigest() != recorded_digest(record, source_path):
|
|
raise SystemExit('native shader source differs from archived validation')
|
|
|
|
with cubin.open('rb') as stream:
|
|
elf = _open_elf(stream)
|
|
text = elf.get_section_by_name('.text.native_hello')
|
|
if text is None:
|
|
raise SystemExit('missing .text.native_hello section in baseline cubin')
|
|
code = text.data()
|
|
if len(code) != 256 or text['sh_addralign'] != 128:
|
|
raise SystemExit(
|
|
f'unexpected .text.native_hello size/alignment: len={len(code)} align={text["sh_addralign"]}'
|
|
)
|
|
if (text['sh_info'] >> 24) != 8:
|
|
raise SystemExit(f'unexpected .text.native_hello register count: {text["sh_info"] >> 24}')
|
|
const_sec = elf.get_section_by_name('.nv.constant0.native_hello')
|
|
if const_sec is None:
|
|
raise SystemExit('missing .nv.constant0.native_hello section in baseline cubin')
|
|
constant = const_sec.data()
|
|
if len(constant) != 368 or any(constant):
|
|
raise SystemExit(f'unexpected .nv.constant0.native_hello contents (len={len(constant)})')
|
|
if any(section.name.startswith(('.rel.text.native_hello', '.rela.text.native_hello')) for section in elf.iter_sections()):
|
|
raise SystemExit('unexpected relocation sections for .text.native_hello')
|
|
|
|
embedded = ROOT / 'src/nvidia/src/compute/native_hello_sm70.bin'
|
|
if embedded.read_bytes() != code:
|
|
raise SystemExit('embedded native_hello_sm70.bin differs from baseline cubin .text.native_hello')
|
|
|
|
result = {
|
|
'passed': True,
|
|
'baseline_cubin_sha256': expected,
|
|
'code_sha256': hashlib.sha256(code).hexdigest(),
|
|
'code_bytes': len(code),
|
|
'constant0_bytes': len(constant),
|
|
'registers': 8,
|
|
'scope': 'Exact shader bytes from recorded original-driver execution. No replacement QMD, firmware, initialization or physical GPU execution is established by this check.',
|
|
}
|
|
out = ROOT / 'reports/native-shader-baseline-check.json'
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
|
|
print(json.dumps(result))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|