#!/usr/bin/env python3 """Read the QR code back off a captured crash screen. This is the acceptance test for the crash channel, and it is deliberately end-to-end: it does not ask the encoder what it produced, it reads the pixels that were actually painted on the framebuffer. Everything in between -- payload construction in panic context, the encoder, the scaling into modules, the card and quiet zone -- is covered by whether this comes back as text. pwsh -File tools/crashshot.ps1 # crash on purpose, screendump it PYTHONPATH= python tools/crashqr.py Needs opencv-python-headless and numpy; see tools/qrcheck.py for the install. """ import sys try: import cv2 import numpy as np except ImportError: sys.exit("crashqr: needs opencv-python-headless and numpy") PPM = sys.argv[1] if len(sys.argv) > 1 else "build/crashscreen.ppm" try: data = open(PPM, "rb").read() except OSError as e: sys.exit(f"crashqr: {e} -- run tools/crashshot.ps1 first") # PPM P6 header: three whitespace-separated fields after the magic. Parsed by # scanning rather than assuming a fixed length, because QEMU's is compact but # nothing guarantees that. pos, fields = 2, [] while len(fields) < 3: while data[pos:pos + 1].isspace(): pos += 1 start = pos while not data[pos:pos + 1].isspace(): pos += 1 fields.append(int(data[start:pos])) pos += 1 w, h = fields[0], fields[1] img = np.frombuffer(data[pos:pos + w * h * 3], np.uint8).reshape(h, w, 3) grey = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # The symbol sits on the only light panel on an otherwise purple screen, so a # brightness threshold finds it without needing to know the layout. The white # report text passes the same threshold, which does not matter -- the detector # locates the symbol by its finder patterns, and handing it extra screen # costs nothing. mask = (grey > 240).astype(np.uint8) ys, xs = np.nonzero(mask) if len(xs) == 0: sys.exit("crashqr: no light region found -- was a crash screen captured?") crop = grey[ys.min():ys.max() + 1, xs.min():xs.max() + 1] # OpenCV's detector is sensitive to scale in ways unrelated to the encoding, # so try a few before concluding anything. See the note in tools/qrcheck.py. text = "" for scale in (1, 2, 3, 4): up = cv2.resize(crop, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST) up = cv2.copyMakeBorder(up, 40, 40, 40, 40, cv2.BORDER_CONSTANT, value=255) text, _, _ = cv2.QRCodeDetector().detectAndDecode(up) if text: break if not text: print("crashqr: FAILED -- the symbol on the crash screen did not decode") sys.exit(1) print("crashqr: decoded the crash screen's QR\n") for line in text.split("\n"): print(" ", line) # The payload is a contract with whatever reads these later, so check its shape # rather than only that something came back. lines = text.split("\n") ok = lines[0] == "SXPSOGM1" print() if not ok: print(f"crashqr: FAILED -- expected magic 'SXPSOGM1', got {lines[0]!r}") sys.exit(1) print(f"crashqr: passed ({len(text)} bytes, {len(lines)} fields)")