#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only """Reproduce selected Linux v6.12 pure helpers, without accessing a device.""" import argparse import hashlib import json from pathlib import Path import re import subprocess import tempfile import urllib.request ROOT = Path(__file__).resolve().parent SOURCES = json.loads((ROOT / "sources.json").read_text()) PREFIX = r""" #include #include #include #include #include #include #include typedef uint16_t u16; typedef uint8_t u8; #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define BITS_PER_BYTE CHAR_BIT #define BITS_PER_LONG (CHAR_BIT * sizeof(long)) #define unlikely(x) (x) #define hweight8(x) __builtin_popcount((unsigned char)(x)) #define hweight_long(x) __builtin_popcountl((unsigned long)(x)) struct mtd_info { unsigned int erasesize, writesize, ecc_step_size; }; struct nand_chip { struct mtd_info mtd; }; static struct mtd_info *nand_to_mtd(struct nand_chip *n) { return &n->mtd; } static int mtd_div_by_ws(unsigned int size, struct mtd_info *m) { return size / m->writesize; } """ MAIN = r""" int main(void) { for (int s = 0; s < 32768; s++) printf("L %d %u %u %u\n", s, sunxi_nfc_randomizer_step(s, 1), sunxi_nfc_randomizer_step(s, 8), sunxi_nfc_randomizer_step(s, 15)); for (unsigned int size = 512; size <= 1024; size *= 2) { for (int i = 0; i < 128; i++) { const u16 *tab = size == 512 ? sunxi_nfc_randomizer_ecc512_seeds : sunxi_nfc_randomizer_ecc1024_seeds; printf("T %u %d %u %u\n", size, i, tab[i], sunxi_nfc_randomizer_step(sunxi_nfc_randomizer_page_seeds[i], size * 8 + 15)); } int pages[] = {0, 1, 63, 64, 127, 128, 255}; for (unsigned int ppb = 64; ppb <= 256; ppb *= 2) { struct nand_chip n = {{ppb * 2048, 2048, size}}; for (unsigned int i = 0; i < ARRAY_SIZE(pages); i++) { u8 marker[] = {0xff, 0xff}; sunxi_nfc_randomize_bbm(&n, pages[i], marker); printf("B %u %u %d %u %u %u %u\n", size, ppb, pages[i], sunxi_nfc_randomizer_state(&n, pages[i], false), sunxi_nfc_randomizer_state(&n, pages[i], true), marker[0], marker[1]); } } } /* These are constructed buffers, not valid NAND codewords or device reads. */ for (int id = 0; id < 8; id++) { unsigned char data[24], ecc[8], extra[4]; memset(data, 0xff, sizeof data); memset(ecc, 0xff, sizeof ecc); memset(extra, 0xff, sizeof extra); int threshold = 4, elen = 8, xlen = 4; if (id == 1 || id == 2 || id == 3) { data[0] = 0xfe; ecc[0] = 0; } if (id == 2) elen = 0; if (id == 3) threshold = 9; if (id == 4) { data[0] = 0xf0; extra[0] = 0xfe; } if (id == 5) { data[0] = 0xf0; extra[0] = 0xfe; xlen = 0; } if (id == 6) { data[0] = 0xf0; data[12] = 0xf0; } if (id == 7) { data[0] = 0xf0; } int ret = nand_check_erased_ecc_chunk(data, sizeof data, ecc, elen, extra, xlen, threshold); printf("E %d %d %u %u %u\n", id, ret, data[0], ecc[0], extra[0]); } return 0; } """ def require(condition, message): if not condition: raise ValueError(message) def verified_sources(directory): texts = {} for item in SOURCES["sources"][:2]: raw = (Path(directory) / item["file"]).read_bytes() require(hashlib.sha256(raw).hexdigest() == item["sha256"], "Source hash mismatch: " + item["file"]) texts[item["id"]] = raw.decode() return texts def extract_function(text, name): pattern = r"^(?:static )?(?:u16|void|int) " + re.escape(name) + r"\([^;{]*\{.*?^\}" matches = re.findall(pattern, text, re.M | re.S) require(len(matches) == 1, "Expected exactly one function: " + name) return matches[0] + "\n" def extract_array(text, name): matches = re.findall(r"^static const u16 " + re.escape(name) + r"\[\] = \{.*?^\};", text, re.M | re.S) require(len(matches) == 1, "Expected exactly one array: " + name) return matches[0] + "\n" def arrays(text): values = {} for suffix in ("page", "ecc512", "ecc1024"): block = extract_array(text, "sunxi_nfc_randomizer_" + suffix + "_seeds") values[suffix] = [int(x, 16) for x in re.findall(r"0x[0-9a-f]+", block)] require(len(values[suffix]) == 128, "Unexpected seed-table length") return values def advance(state, count): """Independent LSB-first bit-list recurrence, not the C shift expression.""" require(type(state) is int and 0 <= state < 32768, "15-bit state required") require(type(count) is int and count >= 0, "Nonnegative count required") bits = [(state >> i) & 1 for i in range(15)] for _ in range(count): feedback = bits[0] ^ bits[1] bits = bits[1:] + [feedback] return sum(bit * (2 ** i) for i, bit in enumerate(bits)) def seed_for(tables, page, pages_per_block, step, ecc=True): require(type(page) is int and page >= 0, "Nonnegative page required") require(type(pages_per_block) is int and pages_per_block > 0, "Positive block required") require(step in (512, 1024), "Only driver-supported example step sizes") key = "ecc" + str(step) if ecc else "page" return tables[key][page % min(pages_per_block, 128)] def bbm_mask(seed): return bytes([seed & 255, advance(seed, 8) & 255]) def apply_mask(payload, mask): require(len(payload) == len(mask) == 2, "This helper covers exactly two marker bytes") return bytes(a ^ b for a, b in zip(payload, mask)) def erased_check(buffers, threshold): require(type(threshold) is int and threshold >= 0, "Nonnegative threshold required") flips = sum(8 - byte.bit_count() for buf in buffers for byte in buf) return flips if flips <= threshold else -74 # Linux EBADMSG for the pinned platform. def c_source(texts): # Retain original notices in the temporary Linux-derived translation unit. source = texts["sunxi"].split("#include", 1)[0] source += texts["nand-base"].split("#define pr_fmt", 1)[0] source += PREFIX for suffix in ("page", "ecc512", "ecc1024"): source += extract_array(texts["sunxi"], "sunxi_nfc_randomizer_" + suffix + "_seeds") for name in ("sunxi_nfc_randomizer_step", "sunxi_nfc_randomizer_state", "sunxi_nfc_randomize_bbm"): source += extract_function(texts["sunxi"], name) for name in ("nand_check_erased_buf", "nand_check_erased_ecc_chunk"): source += extract_function(texts["nand-base"], name) return source + MAIN def native(texts, optimization): with tempfile.TemporaryDirectory(prefix="hesela-nand-") as directory: root = Path(directory) cfile, binary = root / "helpers.c", root / "helpers" cfile.write_text(c_source(texts)) command = ["cc", "-std=c11", optimization, "-Wall", "-Wextra", "-Wno-sign-compare", "-Werror", "-fno-strict-aliasing", "-fsanitize=undefined", "-fno-sanitize-recover=all", str(cfile), "-o", str(binary)] subprocess.run(command, check=True, capture_output=True, text=True) result = subprocess.run([str(binary)], check=True, capture_output=True, text=True) require(not result.stderr, "Unexpected native diagnostic") return [line.split() for line in result.stdout.splitlines()] def report(directory, optimization="-O2"): texts = verified_sources(directory) tables = arrays(texts["sunxi"]) rows = native(texts, optimization) counts = {"state_checks": 0, "oob_seed_checks": 0, "address_marker_checks": 0} erased = [] seen = set() expected_erase = [ (0, 255, 255, 255), (-74, 254, 0, 255), (1, 255, 0, 255), (9, 255, 255, 255), (-74, 240, 255, 254), (4, 255, 255, 254), (-74, 240, 255, 255), (4, 255, 255, 255), ] for row in rows: label, nums = row[0], list(map(int, row[1:])) key_length = {"L": 1, "T": 2, "B": 3, "E": 1}.get(label, 0) identity = (label, *nums[:key_length]) require(identity not in seen, "Duplicate native row") seen.add(identity) if label == "L": s, *actual = nums require(actual == [advance(s, n) for n in (1, 8, 15)], "LFSR mismatch") counts["state_checks"] += 3 elif label == "T": size, i, actual, c_derived = nums expected = advance(tables["page"][i], size * 8 + 15) require(actual == c_derived == expected, "OOB table mismatch") counts["oob_seed_checks"] += 1 elif label == "B": size, ppb, page, pseed, eseed, a, b = nums require(pseed == seed_for(tables, page, ppb, size, False), "Page seed mismatch") require(eseed == seed_for(tables, page, ppb, size), "ECC seed mismatch") require(bytes([a, b]) == apply_mask(b"\xff\xff", bbm_mask(eseed)), "BBM mismatch") counts["address_marker_checks"] += 1 elif label == "E": ident, *outcome = nums require(tuple(outcome) == expected_erase[ident], "Erased buffer mismatch") erased.append({"case": ident, "return": outcome[0], "after_first_bytes": outcome[1:]}) else: raise ValueError("Unknown native row") require(counts == {"state_checks": 98304, "oob_seed_checks": 256, "address_marker_checks": 42}, "Incomplete native output") require([row["case"] for row in erased] == list(range(8)), "Missing erased cases") marker = b"\xff\xff" masks = {str(p): bbm_mask(seed_for(tables, p, 64, 512)) for p in (0, 1, 64)} encoded = apply_mask(marker, masks["0"]) witnesses = { "scope": "two-byte software BBM pre/post XOR only; not full NAND-page emulation", "pages_per_eraseblock": 64, "ecc_step_bytes": 512, "input_hex": marker.hex(), "page_masks_hex": {p:m.hex() for p,m in masks.items()}, "after_page0_transform_hex": encoded.hex(), "same_page_roundtrip_hex": apply_mask(encoded, masks["0"]).hex(), "page0_then_page1_hex": apply_mask(encoded, masks["1"]).hex(), "page0_then_page64_hex": apply_mask(encoded, masks["64"]).hex(), } return { "schema_version": 1, "kind": "source-helper execution and exact constructed inputs", "linux_commit": SOURCES["linux_commit"], "source_sha256": {s["id"]:s["sha256"] for s in SOURCES["sources"][:2]}, "coverage": counts, "marker_witness": witnesses, "erased_buffer_cases": erased, "not_measured": ["NAND media", "ECC decoding", "controller registers", "whole-page scrambling", "copyback commands", "error rates"], } def fetch_sources(directory): Path(directory).mkdir(parents=True, exist_ok=True) for item in SOURCES["sources"][:2]: path = Path(directory) / item["file"] if not path.exists(): with urllib.request.urlopen(item["url"], timeout=45) as response: raw = response.read(1024 * 1024) require(hashlib.sha256(raw).hexdigest() == item["sha256"], "Download hash mismatch") path.write_bytes(raw) verified_sources(directory) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--sources", required=True, type=Path) parser.add_argument("--fetch", action="store_true") parser.add_argument("--optimization", choices=["O0", "O2"], default="O2") parser.add_argument("--output", type=Path) parser.add_argument("--check", type=Path) args = parser.parse_args() if args.fetch: fetch_sources(args.sources) result = report(args.sources, "-" + args.optimization) if args.check: require(result == json.loads(args.check.read_text()), "Frozen result mismatch") rendered = json.dumps(result, indent=2) + "\n" if args.output: args.output.write_text(rendered) else: print(rendered, end="") if __name__ == "__main__": main()