505 lines
18 KiB
Python
505 lines
18 KiB
Python
"""Text-level readers/patchers for the Rust pin constants that guard sealed PTX.
|
|
|
|
Every patcher either performs exactly one replacement or raises PinError; none guesses. The forms handled
|
|
are the ones that exist in crates/cuda-driver:
|
|
|
|
FIELD SPEC DECLARATION IT PATCHES
|
|
------------------------------------------- ----------------------------------------------------------------
|
|
NAME.source_sha256 / NAME.ptx_sha256 const NAME: PtxPin = PtxPin { source_sha256: [..], ptx_sha256: [..] };
|
|
NAME[i].source_sha256 / NAME[i].ptx_sha256 const NAME: [PtxPin; N] = [PtxPin {..}; N] (repeat form is expanded)
|
|
NAME.sha static NAME: AssetSpec = AssetSpec { .., sha: [..], .. };
|
|
NAME[i] const NAME: [Option<(usize, [u8; 32])>; N] = [None, ..];
|
|
NAME (type usize / Option<usize>) raw PTX length (without NUL)
|
|
NAME (type [u8; 32] / Option<[u8; 32]>) sha256 of the raw PTX
|
|
NAME (type Option<(usize, [u8; 32])>) Some((raw length + 1, sha256)) (the +1 is the terminal NUL, as
|
|
mmq.rs / mmq_original_group.rs compare against include_bytes!)
|
|
|
|
source_sha256 is the SHA-256 of the checked-in .cu bytes; ptx_sha256 / sha / digests are over the PTX body
|
|
*without* the terminal NUL.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
from typing import List, Optional, Tuple
|
|
|
|
|
|
class PinError(ValueError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PinValues:
|
|
raw_len: int # PTX body length, no NUL
|
|
ptx_sha256: bytes
|
|
source_sha256: bytes
|
|
|
|
|
|
# -------------------------------------------------------------------------------------------- scanning
|
|
|
|
|
|
def _skip_literal(text: str, i: int) -> int:
|
|
"""If text[i] starts a string/char/comment, return the index after it, else i."""
|
|
c = text[i]
|
|
if c == '"':
|
|
j = i + 1
|
|
while j < len(text):
|
|
if text[j] == "\\":
|
|
j += 2
|
|
continue
|
|
if text[j] == '"':
|
|
return j + 1
|
|
j += 1
|
|
raise PinError("unterminated string literal")
|
|
if text.startswith("//", i):
|
|
j = text.find("\n", i)
|
|
return len(text) if j < 0 else j
|
|
if text.startswith("/*", i):
|
|
j = text.find("*/", i)
|
|
if j < 0:
|
|
raise PinError("unterminated block comment")
|
|
return j + 2
|
|
return i
|
|
|
|
|
|
def _scan_depth0(text: str, start: int, stops: str) -> int:
|
|
"""Index of the first char in `stops` at bracket depth 0 (()[]{}) from `start`."""
|
|
depth = 0
|
|
i = start
|
|
while i < len(text):
|
|
j = _skip_literal(text, i)
|
|
if j != i:
|
|
i = j
|
|
continue
|
|
c = text[i]
|
|
if depth == 0 and c in stops:
|
|
return i
|
|
if c in "([{":
|
|
depth += 1
|
|
elif c in ")]}":
|
|
if depth == 0:
|
|
raise PinError("unbalanced bracket")
|
|
depth -= 1
|
|
i += 1
|
|
raise PinError(f"none of {stops!r} found at depth 0")
|
|
|
|
|
|
@dataclass
|
|
class Decl:
|
|
start: int # line start of the declaration
|
|
indent: str
|
|
ty: str # normalized (no whitespace)
|
|
val_start: int
|
|
val_end: int # index of the terminating ';'
|
|
|
|
|
|
def find_decl(text: str, name: str) -> Decl:
|
|
pat = re.compile(r"(?m)^([ \t]*)(?:pub(?:\([^)]*\))?\s+)?(?:const|static)\s+" + re.escape(name) + r"\s*:\s*")
|
|
ms = list(pat.finditer(text))
|
|
if len(ms) != 1:
|
|
raise PinError(f"expected exactly one declaration of {name}, found {len(ms)}")
|
|
m = ms[0]
|
|
eq = _scan_depth0_type(text, m.end())
|
|
ty = re.sub(r"\s+", "", text[m.end() : eq])
|
|
val_start = eq + 1
|
|
while val_start < len(text) and text[val_start] in " \t\r\n":
|
|
val_start += 1
|
|
val_end = _scan_depth0(text, val_start, ";")
|
|
return Decl(m.start(), m.group(1), ty, val_start, val_end)
|
|
|
|
|
|
def _scan_depth0_type(text: str, start: int) -> int:
|
|
depth = 0
|
|
for i in range(start, len(text)):
|
|
c = text[i]
|
|
if c in "<([":
|
|
depth += 1
|
|
elif c in ">)]":
|
|
depth -= 1
|
|
elif c == "=" and depth == 0:
|
|
return i
|
|
elif c == ";" and depth == 0:
|
|
break
|
|
raise PinError("declaration has no '='")
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------- literals
|
|
|
|
_ZERO_RE = re.compile(r"^\[\s*0\s*;\s*32\s*\]$")
|
|
|
|
|
|
def parse_digest(literal: str) -> bytes:
|
|
lit = literal.strip()
|
|
if _ZERO_RE.match(lit):
|
|
return bytes(32)
|
|
if not (lit.startswith("[") and lit.endswith("]")):
|
|
raise PinError(f"not a digest literal: {literal[:40]!r}")
|
|
nums = [x.strip() for x in lit[1:-1].split(",") if x.strip()]
|
|
try:
|
|
vals = [int(x, 0) for x in nums]
|
|
except ValueError as error:
|
|
raise PinError(f"not a digest literal: {literal[:40]!r}") from error
|
|
if len(vals) != 32 or any(not 0 <= v < 256 for v in vals):
|
|
raise PinError(f"digest literal has {len(vals)} elements, expected 32 bytes")
|
|
return bytes(vals)
|
|
|
|
|
|
def render_digest(d: bytes, indent: str = "", wrapped: bool = False, sep: str = ", ", width: int = 100) -> str:
|
|
"""`[1, 2, ..]` inline, or rustfmt-style wrapped at `indent` (the indent of the line that opens the array)."""
|
|
assert len(d) == 32
|
|
if not wrapped:
|
|
return "[" + sep.join(str(b) for b in d) + "]"
|
|
inner = indent + " "
|
|
lines, cur = [], inner
|
|
for b in d:
|
|
tok = f"{b},"
|
|
if len(cur) + (0 if cur == inner else 1) + len(tok) > width:
|
|
lines.append(cur)
|
|
cur = inner
|
|
cur += tok if cur == inner else " " + tok
|
|
lines.append(cur)
|
|
return "[\n" + "\n".join(lines) + "\n" + indent + "]"
|
|
|
|
|
|
def _split_top(text: str, sep: str) -> List[str]:
|
|
out, depth, cur, i = [], 0, [], 0
|
|
while i < len(text):
|
|
j = _skip_literal(text, i)
|
|
if j != i:
|
|
cur.append(text[i:j])
|
|
i = j
|
|
continue
|
|
c = text[i]
|
|
if c in "([{":
|
|
depth += 1
|
|
elif c in ")]}":
|
|
depth -= 1
|
|
if c == sep and depth == 0:
|
|
out.append("".join(cur))
|
|
cur = []
|
|
else:
|
|
cur.append(c)
|
|
i += 1
|
|
out.append("".join(cur))
|
|
return out
|
|
|
|
|
|
def _strip_brackets(value: str) -> str:
|
|
v = value.strip()
|
|
if not (v.startswith("[") and v.endswith("]")):
|
|
raise PinError("expected a [...] value")
|
|
return v[1:-1]
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------- PtxPin forms
|
|
|
|
_FIELDS = ("source_sha256", "ptx_sha256")
|
|
|
|
|
|
def _parse_ptxpin(elem: str) -> dict:
|
|
m = re.fullmatch(r"\s*PtxPin\s*\{(.*)\}\s*", elem, re.S)
|
|
if not m:
|
|
raise PinError(f"not a PtxPin literal: {elem.strip()[:50]!r}")
|
|
pairs = {}
|
|
for part in _split_top(m.group(1), ","):
|
|
if not part.strip():
|
|
continue
|
|
km = re.fullmatch(r"\s*(\w+)\s*:\s*(.*?)\s*", part, re.S)
|
|
if not km or km.group(1) not in _FIELDS or km.group(1) in pairs:
|
|
raise PinError(f"unexpected PtxPin field {part.strip()[:40]!r}")
|
|
pairs[km.group(1)] = parse_digest(km.group(2))
|
|
if set(pairs) != set(_FIELDS):
|
|
raise PinError("PtxPin literal lacks one of source_sha256 / ptx_sha256")
|
|
return pairs
|
|
|
|
|
|
def _render_ptxpin(pin: dict, indent: str) -> str:
|
|
inner = indent + " "
|
|
lines = [f"{indent}PtxPin {{"]
|
|
for f in _FIELDS:
|
|
lines.append(f"{inner}{f}: {_render_field_digest(pin[f], inner)},")
|
|
lines.append(f"{indent}}}")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def _render_field_digest(d: bytes, indent: str) -> str:
|
|
return "[0; 32]" if d == bytes(32) else render_digest(d, indent, wrapped=True)
|
|
|
|
|
|
def _ptxpin_elems(value: str) -> Tuple[List[dict], bool]:
|
|
"""Elements of `[PtxPin{..}; N]` / `[PtxPin{..}, ..]`; second result: repeat form."""
|
|
inner = _strip_brackets(value)
|
|
semi = _split_top(inner, ";")
|
|
if len(semi) == 2:
|
|
n = int(semi[1].strip())
|
|
return [_parse_ptxpin(semi[0]) for _ in range(n)], True
|
|
elems = [e for e in _split_top(inner, ",") if e.strip()]
|
|
return [_parse_ptxpin(e) for e in elems], False
|
|
|
|
|
|
def patch_ptxpin(text: str, name: str, idx: Optional[int], field: str, digest: bytes) -> str:
|
|
if field not in _FIELDS:
|
|
raise PinError(f"unknown PtxPin field {field}")
|
|
d = find_decl(text, name)
|
|
value = text[d.val_start : d.val_end]
|
|
if idx is None:
|
|
if not d.ty == "PtxPin":
|
|
raise PinError(f"{name} has type {d.ty}, expected PtxPin")
|
|
pin = _parse_ptxpin(value)
|
|
pin[field] = digest
|
|
new = _render_ptxpin(pin, d.indent).lstrip()
|
|
return text[: d.val_start] + new + text[d.val_end :]
|
|
m = re.fullmatch(r"\[PtxPin;(\d+)\]", d.ty)
|
|
if not m:
|
|
raise PinError(f"{name} has type {d.ty}, expected [PtxPin; N]")
|
|
elems, _ = _ptxpin_elems(value)
|
|
if len(elems) != int(m.group(1)):
|
|
raise PinError(f"{name}: {len(elems)} elements but type says {m.group(1)}")
|
|
if not 0 <= idx < len(elems):
|
|
raise PinError(f"{name}[{idx}] is out of range 0..{len(elems)}")
|
|
elems[idx][field] = digest
|
|
inner = d.indent + " "
|
|
new = "[\n" + "".join(_render_ptxpin(e, inner) + ",\n" for e in elems) + d.indent + "]"
|
|
return text[: d.val_start] + new + text[d.val_end :]
|
|
|
|
|
|
def read_ptxpin(text: str, name: str, idx: Optional[int], field: str) -> bytes:
|
|
d = find_decl(text, name)
|
|
value = text[d.val_start : d.val_end]
|
|
pin = _parse_ptxpin(value) if idx is None else _ptxpin_elems(value)[0][idx]
|
|
return pin[field]
|
|
|
|
|
|
# ------------------------------------------------------------------------------------- AssetSpec.sha
|
|
|
|
|
|
def _asset_spec_span(text: str, name: str) -> Tuple[int, int, str]:
|
|
d = find_decl(text, name)
|
|
if d.ty != "AssetSpec":
|
|
raise PinError(f"{name} has type {d.ty}, expected AssetSpec")
|
|
return d.val_start, d.val_end, text[d.val_start : d.val_end]
|
|
|
|
|
|
def patch_asset_spec_sha(text: str, name: str, digest: bytes) -> str:
|
|
s, e, value = _asset_spec_span(text, name)
|
|
pat = re.compile(r"(\bsha\s*:\s*)(\[[^\]]*\])")
|
|
ms = list(pat.finditer(value))
|
|
if len(ms) != 1:
|
|
raise PinError(f"{name}: expected one 'sha: [..]' field, found {len(ms)}")
|
|
m = ms[0]
|
|
old = m.group(2)
|
|
sep = "," if re.search(r"\d,\d", old) else ", "
|
|
new = value[: m.start(2)] + render_digest(digest, sep=sep) + value[m.end(2) :]
|
|
return text[:s] + new + text[e:]
|
|
|
|
|
|
def read_asset_spec_sha(text: str, name: str) -> bytes:
|
|
_, _, value = _asset_spec_span(text, name)
|
|
m = re.search(r"\bsha\s*:\s*(\[[^\]]*\])", value)
|
|
if not m:
|
|
raise PinError(f"{name}: no sha field")
|
|
return parse_digest(m.group(1))
|
|
|
|
|
|
# ------------------------------------------------------------------------------- Option tuple array
|
|
|
|
_OPT_TUPLE = "Option<(usize,[u8;32])>"
|
|
|
|
|
|
def _render_some_tuple(length: int, digest: bytes) -> str:
|
|
return f"Some(({length}, {render_digest(digest)}))"
|
|
|
|
|
|
def patch_pin_array(text: str, name: str, idx: int, length_with_nul: int, digest: bytes) -> str:
|
|
d = find_decl(text, name)
|
|
m = re.fullmatch(r"\[" + re.escape(_OPT_TUPLE) + r";(\d+)\]", d.ty)
|
|
if not m:
|
|
raise PinError(f"{name} has type {d.ty}, expected [Option<(usize, [u8; 32])>; N]")
|
|
n = int(m.group(1))
|
|
elems = [e.strip() for e in _split_top(_strip_brackets(text[d.val_start : d.val_end]), ",") if e.strip()]
|
|
if len(elems) != n:
|
|
raise PinError(f"{name}: {len(elems)} elements but type says {n}")
|
|
if not 0 <= idx < n:
|
|
raise PinError(f"{name}[{idx}] is out of range")
|
|
elems[idx] = _render_some_tuple(length_with_nul, digest)
|
|
if all(e == "None" for e in elems):
|
|
new = "[" + ", ".join(elems) + "]"
|
|
else:
|
|
new = "[\n" + "".join(f"{d.indent} {e},\n" for e in elems) + d.indent + "]"
|
|
return text[: d.val_start] + new + text[d.val_end :]
|
|
|
|
|
|
def read_pin_array(text: str, name: str, idx: int) -> Optional[Tuple[int, bytes]]:
|
|
d = find_decl(text, name)
|
|
elems = [e.strip() for e in _split_top(_strip_brackets(text[d.val_start : d.val_end]), ",") if e.strip()]
|
|
return _parse_opt_tuple(elems[idx])
|
|
|
|
|
|
def _parse_opt_tuple(e: str) -> Optional[Tuple[int, bytes]]:
|
|
if e == "None":
|
|
return None
|
|
m = re.fullmatch(r"Some\(\(\s*(\d+)\s*,\s*(\[.*\])\s*,?\s*\)\)", e, re.S)
|
|
if not m:
|
|
raise PinError(f"not Some((len, digest)): {e[:40]!r}")
|
|
return int(m.group(1)), parse_digest(m.group(2))
|
|
|
|
|
|
# ------------------------------------------------------------------------------------ plain consts
|
|
|
|
_PLAIN_TYPES = ("usize", "Option<usize>", "[u8;32]", "Option<[u8;32]>", _OPT_TUPLE)
|
|
|
|
|
|
def _render_plain(ty: str, indent: str, v: PinValues, wrapped_hint: bool, sep: str) -> str:
|
|
if ty == "usize":
|
|
return str(v.raw_len)
|
|
if ty == "Option<usize>":
|
|
return f"Some({v.raw_len})"
|
|
if ty == "[u8;32]":
|
|
return render_digest(v.ptx_sha256, indent, wrapped_hint, sep)
|
|
if ty == "Option<[u8;32]>":
|
|
return "Some(" + render_digest(v.ptx_sha256, indent, wrapped_hint, sep) + ")"
|
|
if ty == _OPT_TUPLE:
|
|
return f"Some(({v.raw_len + 1}, {render_digest(v.ptx_sha256, sep=sep)}))"
|
|
raise PinError(f"unsupported pin type {ty}")
|
|
|
|
|
|
def patch_plain(text: str, name: str, v: PinValues) -> str:
|
|
d = find_decl(text, name)
|
|
if d.ty not in _PLAIN_TYPES:
|
|
raise PinError(
|
|
f"{name} has type {d.ty}: only {', '.join(_PLAIN_TYPES)} can be sealed by value "
|
|
"(Option<&[u8]> assets need code wiring, not a pin)"
|
|
)
|
|
old = text[d.val_start : d.val_end]
|
|
wrapped = "\n" in old
|
|
sep = "," if re.search(r"\d,\d", old) else ", "
|
|
new = _render_plain(d.ty, d.indent, v, wrapped, sep)
|
|
return text[: d.val_start] + new + text[d.val_end :]
|
|
|
|
|
|
def read_plain(text: str, name: str):
|
|
d = find_decl(text, name)
|
|
val = text[d.val_start : d.val_end].strip()
|
|
if d.ty == "usize":
|
|
return int(val)
|
|
if d.ty == "Option<usize>":
|
|
return None if val == "None" else int(re.fullmatch(r"Some\((\d+)\)", val).group(1))
|
|
if d.ty == "[u8;32]":
|
|
return parse_digest(val)
|
|
if d.ty == "Option<[u8;32]>":
|
|
return None if val == "None" else parse_digest(re.fullmatch(r"Some\((.*)\)", val, re.S).group(1))
|
|
if d.ty == _OPT_TUPLE:
|
|
return _parse_opt_tuple(val)
|
|
raise PinError(f"unsupported type {d.ty}")
|
|
|
|
|
|
# ------------------------------------------------------------------------------------- field dispatch
|
|
|
|
_SPEC_RE = re.compile(r"^(\w+)(?:\[(\d+)\])?(?:\.(\w+))?(?:\s*:.*)?$")
|
|
|
|
|
|
def parse_spec(spec: str) -> Tuple[str, Optional[int], Optional[str]]:
|
|
m = _SPEC_RE.match(spec.strip())
|
|
if not m:
|
|
raise PinError(f"unparseable field spec {spec!r}")
|
|
return m.group(1), (int(m.group(2)) if m.group(2) is not None else None), m.group(3)
|
|
|
|
|
|
def apply_field(text: str, spec: str, v: PinValues) -> str:
|
|
"""Patch one rust_fields_to_fill entry in `text`; raise PinError unless exactly one declaration changed."""
|
|
name, idx, field = parse_spec(spec)
|
|
if field in _FIELDS:
|
|
digest = v.source_sha256 if field == "source_sha256" else v.ptx_sha256
|
|
return patch_ptxpin(text, name, idx, field, digest)
|
|
if field == "sha":
|
|
if idx is not None:
|
|
raise PinError(f"{spec}: AssetSpec.sha takes no index")
|
|
return patch_asset_spec_sha(text, name, v.ptx_sha256)
|
|
if field is not None:
|
|
raise PinError(f"{spec}: unknown field {field!r}")
|
|
if idx is not None:
|
|
return patch_pin_array(text, name, idx, v.raw_len + 1, v.ptx_sha256)
|
|
return patch_plain(text, name, v)
|
|
|
|
|
|
def read_field(text: str, spec: str, v: PinValues) -> bool:
|
|
"""True if the pin currently in `text` equals the values for `v` (round-trip check after patching)."""
|
|
name, idx, field = parse_spec(spec)
|
|
if field in _FIELDS:
|
|
want = v.source_sha256 if field == "source_sha256" else v.ptx_sha256
|
|
return read_ptxpin(text, name, idx, field) == want
|
|
if field == "sha":
|
|
return read_asset_spec_sha(text, name) == v.ptx_sha256
|
|
if idx is not None:
|
|
return read_pin_array(text, name, idx) == (v.raw_len + 1, v.ptx_sha256)
|
|
got = read_plain(text, name)
|
|
d = find_decl(text, name)
|
|
if d.ty in ("usize", "Option<usize>"):
|
|
return got == (v.raw_len if d.ty == "usize" else v.raw_len)
|
|
if d.ty in ("[u8;32]", "Option<[u8;32]>"):
|
|
return got == v.ptx_sha256
|
|
return got == (v.raw_len + 1, v.ptx_sha256)
|
|
|
|
|
|
# ------------------------------------------------------------------------- re-pin of existing digests
|
|
|
|
|
|
def decimal_pattern(digest: bytes) -> "re.Pattern[str]":
|
|
return re.compile(r"\[\s*" + r"\s*,\s*".join(str(b) for b in digest) + r"\s*,?\s*\]")
|
|
|
|
|
|
def find_decimal_pins(text: str, digest: bytes) -> List[re.Match]:
|
|
return list(decimal_pattern(digest).finditer(text))
|
|
|
|
|
|
def repin_decimal(text: str, old: bytes, new: bytes) -> Tuple[str, int]:
|
|
"""Replace every `[b0, b1, ..]` spelling of `old` by `new`, keeping inline/wrapped and separator style."""
|
|
pat = decimal_pattern(old)
|
|
count = 0
|
|
|
|
def sub(m: "re.Match[str]") -> str:
|
|
nonlocal count
|
|
count += 1
|
|
body = m.group(0)
|
|
if "\n" in body:
|
|
line_start = text.rfind("\n", 0, m.start()) + 1
|
|
indent = re.match(r"[ \t]*", text[line_start : m.start()]).group(0)
|
|
return render_digest(new, indent, wrapped=True)
|
|
sep = "," if re.search(r"\d,\d", body) else ", "
|
|
return render_digest(new, sep=sep)
|
|
|
|
out = pat.sub(sub, text)
|
|
return out, count
|
|
|
|
|
|
def replace_hex(text: str, old_hex: str, new_hex: str) -> Tuple[str, int]:
|
|
n = text.count(old_hex)
|
|
return text.replace(old_hex, new_hex), n
|
|
|
|
|
|
# --------------------------------------------------------------------------------------- follow-ups
|
|
|
|
_FOLLOWUP_PATTERNS = ("UNSEALED", "[0; 32]", "placeholder", "Unpinned", "unsealed")
|
|
|
|
|
|
def placeholder_tests(text: str) -> List[str]:
|
|
"""#[test] functions whose body mentions the placeholder state; they must be revisited after sealing."""
|
|
out = []
|
|
for m in re.finditer(r"#\[test\]\s*(?:#\[ignore[^\]]*\]\s*)*(?:async\s+)?fn\s+(\w+)\s*\([^)]*\)[^{]*\{", text):
|
|
start = m.end()
|
|
depth, i = 1, start
|
|
while i < len(text) and depth:
|
|
j = _skip_literal(text, i)
|
|
if j != i:
|
|
i = j
|
|
continue
|
|
if text[i] == "{":
|
|
depth += 1
|
|
elif text[i] == "}":
|
|
depth -= 1
|
|
i += 1
|
|
body = text[start:i]
|
|
if any(p in body for p in _FOLLOWUP_PATTERNS) or any(p in m.group(1) for p in ("placeholder", "unsealed", "unpinned")):
|
|
out.append(m.group(1))
|
|
return out
|