#!/usr/bin/env python3
"""
Verify (and optionally fix) Siemens MS42 checksums.

Usage:
    python3 -I ms42_checksum.py <file.bin>            # verify
    python3 -I ms42_checksum.py <file.bin> --fix      # rewrite in place
    python3 -I ms42_checksum.py <file.bin> --json     # machine-readable report

Accepts a 512 KB full image (file offset == flash offset == ECU address) or a
32 KB calibration file (file offset 0 == flash/ECU 0x48000).

Six checksums. The first three are the ones the MS4x community documents and
nfsx (packages/flash-data/src/ms4x-checksum.ts) implements; #4-#6 were found
while building this wiki.

  1 Boot          CRC-16  result u16 @ 0x03C24, count @ 0x3C26, range @ 0x3C28,
                          seed u16 @ 0x03FE6
  2 Program       CRC-16  header @ 0x502CE: result pointer (-> 0x50306),
                          seed pointer @ 0x502D2 (-> 0x50032); count + region
                          table follow the result
  3 Calibration   CRC-16  header @ 0x502F2: result pointer (-> 0x4FEE0),
                          seed pointer @ 0x502F6 (-> 0x4800C); count + region
                          table follow the result
  4 Boot block    add-32  u32 @ 0x0BFF8 = sum of u16 LE words 0x8000-0xBFF7
  5 Boot modules  XOR-16  table @ 0x0B800, 8 bytes per entry
                          (id u16, start u16, length u16, xor u16), 0xFF00 ends;
                          xor = XOR of u16 LE words over [start, start+length)
  6 Adaptation    CRC-16  1 KB records in the EEPROM-emulation sectors
    records               0x4000-0x7FFF; record+0x3F6 = data length L,
                          record+0x3FE = CRC over [record, record+L), seed 0x000F

CRC-16: reflected polynomial 0xA001 (CRC-16/ARC table), init = seed, no final
XOR, stored little-endian, chained over all regions of a checksum, region
ends inclusive (#1-#3). All addresses are ECU addresses and equal file offsets.

--fix order: #5 (inside the #4 range) before #4; the rest are independent.
Adaptation records are only rewritten when their stored CRC is wrong and
their header looks valid (seq word and its complement at +0x3F8).

A 32 KB file holds only the calibration. #3 is fully self-described inside
it (region table at 0x4FEE0); the seed address 0x4800C is the value the
program's seed pointer holds in every known MS42 image (0110AD and 0110C6).
"""
import json
import sys
from pathlib import Path

FULL, CAL = 0x80000, 0x8000
CAL_BASE = 0x48000
CAL_RESULT, CAL_SEED = 0x4FEE0, 0x4800C  # fallbacks for 32 KB files

TABLE = []
for _i in range(256):
    _c = _i
    for _ in range(8):
        _c = (_c >> 1) ^ 0xA001 if _c & 1 else _c >> 1
    TABLE.append(_c)


def crc16(buf, start, end, crc):
    """CRC over buf[start..end] inclusive."""
    for b in buf[start:end + 1]:
        crc = (crc >> 8) ^ TABLE[(crc ^ b) & 0xFF]
    return crc & 0xFFFF


def u16(buf, o):
    return buf[o] | buf[o + 1] << 8


def u32(buf, o):
    return u16(buf, o) | u16(buf, o + 2) << 16


def put16(buf, o, v):
    buf[o:o + 2] = v.to_bytes(2, "little")


def put32(buf, o, v):
    buf[o:o + 4] = v.to_bytes(4, "little")


# -- checksums (all work on a 512 KB buffer) ------------------------------

def boot(buf):
    start, end = u32(buf, 0x3C28), u32(buf, 0x3C2C)
    seed = u16(buf, 0x3FE6)
    return dict(name="Boot", kind="crc16", at=0x3C24, size=2,
                stored=u16(buf, 0x3C24), computed=crc16(buf, start, end, seed),
                seed=seed, ranges=[(start, end)])


def table_crc(buf, name, header, fallback=None):
    """Header: u32 result address, u32 seed address. At the result: u16 CRC,
    u16 count, count x (u32 start, u32 end)."""
    at, seed_addr = u32(buf, header), u32(buf, header + 4)
    if at >= FULL or seed_addr >= FULL:
        if fallback is None:
            raise ValueError(f"{name}: header @0x{header:X} empty")
        at, seed_addr = fallback
    seed = u16(buf, seed_addr)
    count = u16(buf, at + 2)
    if not 0 < count < 16:
        raise ValueError(f"{name}: implausible region count {count} @0x{at + 2:X}")
    crc, ranges = seed, []
    for i in range(count):
        e = at + 4 + 8 * i
        s, t = u32(buf, e), u32(buf, e + 4)
        ranges.append((s, t))
        crc = crc16(buf, s, t, crc)
    return dict(name=name, kind="crc16", at=at, size=2, stored=u16(buf, at),
                computed=crc, seed=seed, seed_addr=seed_addr, ranges=ranges)


def program(buf):
    return table_crc(buf, "Program", 0x502CE)


def calibration(buf):
    return table_crc(buf, "Calibration", 0x502F2, (CAL_RESULT, CAL_SEED))


def boot_block(buf):
    acc = 0
    for p in range(0x8000, 0xBFF8, 2):
        acc = (acc + u16(buf, p)) & 0xFFFFFFFF
    return dict(name="Boot block (add)", kind="add32", at=0xBFF8, size=4,
                stored=u32(buf, 0xBFF8), computed=acc, ranges=[(0x8000, 0xBFF7)])


def modules(buf):
    """Per-module XOR-16 table at 0xB800 (boot block 2)."""
    out, o = [], 0xB800
    while o < 0xBFF0 and u16(buf, o) != 0xFF00 and u16(buf, o) != 0xFFFF:
        mid, start, length = u16(buf, o), u16(buf, o + 2), u16(buf, o + 4)
        x = 0
        for p in range(start, start + length, 2):
            x ^= u16(buf, p)
        out.append(dict(id=mid, at=o + 6, start=start, length=length,
                        stored=u16(buf, o + 6), computed=x))
        o += 8
    bad = [m for m in out if m["stored"] != m["computed"]]
    return dict(name="Boot modules (xor)", kind="xor16-table", at=0xB800,
                entries=len(out), bad=[f"id 0x{m['id']:04X} @0x{m['at']:05X}" for m in bad],
                ok=not bad, modules=out)


def records(buf):
    """Adaptation records in the EEPROM-emulation sectors 0x4000-0x7FFF."""
    out = []
    for r in range(0x4000, 0x8000, 0x400):
        rec = buf[r:r + 0x400]
        if rec == b"\xFF" * 0x400:
            continue
        seq, length = u16(buf, r), u16(buf, r + 0x3F6)
        valid_hdr = (u16(buf, r + 0x3F8) ^ seq) == 0xFFFF and 0 < length < 0x3F6
        computed = crc16(buf, r, r + length - 1, 0x000F) if valid_hdr else None
        out.append(dict(at=r, seq=seq, length=length, header_ok=valid_hdr,
                        stored=u16(buf, r + 0x3FE), computed=computed))
    bad = [x for x in out if x["computed"] is None or x["stored"] != x["computed"]]
    return dict(name="Adaptation records", kind="crc16-records", at=0x4000,
                entries=len(out), bad=[f"0x{x['at']:05X}" for x in bad],
                ok=not bad, records=out)


# -- driver ----------------------------------------------------------------

def sw(buf):
    """SW number from the calibration ident at 0x48008 ('0110xx')."""
    return bytes(buf[0x48008:0x4800E]).decode("ascii", "replace")


def load(path):
    raw = bytearray(Path(path).read_bytes())
    if len(raw) == FULL:
        return raw, raw, False
    if len(raw) == CAL:
        full = bytearray(b"\xFF" * FULL)
        full[CAL_BASE:CAL_BASE + CAL] = raw
        return raw, full, True
    raise SystemExit(f"{path}: unexpected size {len(raw)} (want 524288 or 32768)")


def check_all(full, cal_only):
    if cal_only:
        return [calibration(full)]
    return [boot(full), program(full), calibration(full), boot_block(full),
            modules(full), records(full)]


def is_ok(r):
    return r["ok"] if "ok" in r else r["stored"] == r["computed"]


def fix(full, cal_only):
    if not cal_only:
        for m in modules(full)["modules"]:
            put16(full, m["at"], m["computed"])
        put32(full, 0xBFF8, boot_block(full)["computed"])
        for x in records(full)["records"]:
            if x["computed"] is not None:
                put16(full, x["at"] + 0x3FE, x["computed"])
        put16(full, 0x3C24, boot(full)["computed"])
        put16(full, program(full)["at"], program(full)["computed"])
    c = calibration(full)
    put16(full, c["at"], c["computed"])


def fmt(r):
    if r["kind"] in ("xor16-table", "crc16-records"):
        ok = "OK " if r["ok"] else "BAD"
        what = "modules" if r["kind"] == "xor16-table" else "records"
        bad = f"  bad: {', '.join(r['bad'])}" if r["bad"] else ""
        return f"  {r['name']:<19} @0x{r['at']:05X} {r['entries']} {what}  {ok}{bad}"
    width = 8 if r["kind"] == "add32" else 4
    ok = "OK " if is_ok(r) else "BAD"
    rng = ", ".join(f"0x{s:05X}-0x{t:05X}" for s, t in r["ranges"])
    return (f"  {r['name']:<19} @0x{r['at']:05X} stored {r['stored']:0{width}X} "
            f"computed {r['computed']:0{width}X}  {ok}  over {rng}")


def main(argv):
    args = [a for a in argv[1:] if not a.startswith("--")]
    flags = {a for a in argv[1:] if a.startswith("--")}
    if len(args) != 1 or flags - {"--fix", "--json"}:
        raise SystemExit(__doc__)
    path = args[0]
    raw, full, cal_only = load(path)
    if "--fix" in flags:
        fix(full, cal_only)
        if cal_only:
            raw[:] = full[CAL_BASE:CAL_BASE + CAL]
        Path(path).write_bytes(raw)
    results = check_all(full, cal_only)
    good = all(is_ok(r) for r in results)
    if "--json" in flags:
        print(json.dumps(dict(file=path, size=len(raw), calibration_only=cal_only,
                              sw=sw(full), valid=good, results=results), indent=1))
    else:
        kind = ("32 KB calibration (addresses below are ECU addresses; file = ECU - 0x48000)"
                if cal_only else "512 KB full image")
        print(f"{path}: {kind}, SW {sw(full)}")
        for r in results:
            print(fmt(r))
        print("  all checksums valid" if good else "  CHECKSUM MISMATCH")
    return 0 if good else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
