Files
mandy/tools/bug_report_info.py
MoonEyes 63baede940 bug report info: the settings lines go through an allowlist too (review 2)
Variable values showed lists of the title's program hashes (LEONIDA_PAIRED_FOR and the like), program names and
URLs. A value is now shown as it is only when it is a number, true/false or a short word; a list shows its count
(<44 entries>), anything else <set>. Windows, the card, the profile, the upscaler and frame generation go word by
word through an allowlist (short words, numbers, model numbers such as A770, the (R)/(TM) marks); the resolution
must look like 1080 or 2560x1080. Tests cover the reviewer's probes and that real card names stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:04:24 +01:00

278 lines
14 KiB
Python

"""The text of the launcher's "Copy info for a bug report" button: pure functions, no game data.
import bug_report_info # after sys.path.insert(0, <this folder>), as -I needs
The block holds the Leonida version, Windows, the card the runtime's newest play log names, the play settings in
effect and the last error lines of that log, scrubbed so that nothing of the game and no user name is in it: no
shader, pipeline or program name or hash, no address, no home folder. It is at most MAX_LINES lines of at most
MAX_LINE characters. The launcher gathers the inputs (tools/leonida_launcher.py `bug_report_text`); this module
only parses and formats them, so a test feeds it synthetic text.
What the runtime logs of the card (d3d12/crates/leonida-gpu/src), through `tracing` to stderr, which
`play-nvidia.ps1 -Log` redirects to %LOCALAPPDATA%\\Leonida\\logs\\play-<stamp>.log:
* `indirect.rs` (runs_wide), at the run's first indirect execution: a field `card="<adapter description>"`;
* `host.rs` (chosen_adapter), only with LEONIDA_ADAPTER set: `adapter=<description> index=<n> memory_mb=<MB>`;
* `host.rs`, only with LEONIDA_D3D12_WARP: "host device on the software adapter (WARP)".
The driver version is not logged at all, and the video memory only in the LEONIDA_ADAPTER case.
"""
from __future__ import annotations
import os
import re
MAX_LINES = 25
MAX_LINE = 200
MAX_ERROR_LINES = 10
HOME = "%USERPROFILE%"
NOT_IN_LOG = "not in the log"
PLAY_LOG = re.compile(r"^play-.*\.log$", re.IGNORECASE)
# ---------------------------------------------------------------- scrubbing
ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
# C:\Users\<name>, \\?\C:\Users\<name>, C:/Users/<name>, /Users/<name>, /home/<name>: the name is what is removed.
HOME_FOLDER = re.compile(
r"(?:[A-Za-z]:[\\/]+Users[\\/]+|[\\/]+(?:home|Users)[\\/]+)"
r"(?:[^\\/\s\"'<>|:*?]+(?:[ ][^\\/\s\"'<>|:*?]+)*(?=[\\/])|[^\\/\s\"'<>|:*?]+)", re.IGNORECASE)
# An allowlist, not a blocklist: a log line is cut into words, and only words that cannot carry anything of the game or
# of the user are kept. The runtime logs program names (`names=["PS_...", ...]`, pipeline/host.rs), file paths
# (`path=D:\...`, capture.rs) and quoted strings; a blocklist always misses a new form of them.
_LEAD = r"[(\[]?"
_TAIL = r"[)\].,;:!?]*"
KEEP_WORD = re.compile(
_LEAD + r"(?:"
r"[A-Za-z]+(?:['-][A-Za-z]+)*" # a plain word: no digit, underscore or dot
r"|[-+]?\d+(?:[.,]\d+)?(?:%|ms|s|MB|KB|GB|fps)?" # a number, with a unit
r"|\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?" # a timestamp
r"|\d{1,2}:\d{2}:\d{2}(?:\.\d+)?"
r"|[a-z][a-z0-9]*(?:_[a-z0-9]+)*(?:::[a-z][a-z0-9_]*)+" # the module that logged (leonida_gpu::host)
r"|%USERPROFILE%"
r")" + _TAIL)
# Windows status and error codes (NTSTATUS 0xC0000409, HRESULT 0x887A0005, 0x80070057, 0x8876xxxx) say what went
# wrong and hold nothing of the game or the user: kept. Any other 0x value, an address among them, is not.
STATUS_CODE = re.compile(_LEAD + r"0x(?:C000|8000|8007|887[0-9A-F]|8876)[0-9A-F]{4}" + _TAIL, re.IGNORECASE)
# A field's value is kept only when it is a number, true/false or a status code: a word there may be a name.
KEEP_VALUE = re.compile(r"(?:[-+]?\d+(?:[.,]\d+)?(?:%|ms|s|MB|KB|GB|fps)?|true|false)" + _TAIL)
# A word made only of hex letters (deadbeef, cafebabe) is a hash or an address, not a word.
HEX_WORD = re.compile(_LEAD + r"[0-9A-Fa-f]{6,}" + _TAIL)
FIELD = re.compile(r"(?P<key>[A-Za-z]+(?:_[A-Za-z]+)*)(?P<eq>=)(?P<value>.*)")
REMOVED = "<removed>"
def _kept(word: str) -> bool:
if HEX_WORD.fullmatch(word) and not STATUS_CODE.fullmatch(word):
return False
return bool(KEEP_WORD.fullmatch(word) or STATUS_CODE.fullmatch(word))
def scrub_line(line: str) -> str:
"""One log line with nothing of the game or of the user left in it, cut at MAX_LINE characters.
A home folder (C:/Users/<name>, /home/<name>, either slash) becomes %USERPROFILE% first. Then every word is kept only
if it is a plain word (letters, no digit, underscore or dot), a number, a timestamp, the logging module, or a
Windows status or error code (0xC0000409, 0x887A0005); a `key=value` field keeps its key and its value only if
the value is a number, true/false or such a code. Anything else (names, paths, quoted strings, hashes, addresses) becomes <removed>, and
removed words in a row become one. The cut comes last, so it cannot leave half of a value that was meant to go."""
line = CONTROL.sub("", ANSI.sub("", line.rstrip("\r\n")))
line = HOME_FOLDER.sub(HOME, line)
out: list[str] = []
for word in line.split():
field = FIELD.fullmatch(word)
if _kept(word):
kept = word
elif field:
value = field.group("value")
kept = field.group("key") + "=" + (value if KEEP_VALUE.fullmatch(value) or STATUS_CODE.fullmatch(value)
else REMOVED)
else:
kept = REMOVED
if kept == REMOVED and out and out[-1].endswith(REMOVED):
continue
out.append(kept)
return " ".join(out)[:MAX_LINE]
def scrub_home(text: str) -> str:
"""`text` with a home folder replaced and control characters dropped, cut at MAX_LINE: for what the launcher itself
knows (the commit, Windows, the card, its own settings), where a short commit hash must stay."""
text = CONTROL.sub("", ANSI.sub("", str(text).strip()))
return HOME_FOLDER.sub(lambda m: HOME, text)[:MAX_LINE]
# ---------------------------------------------------------------- the log
ERROR_LINE = re.compile(
r"\berror\b|\bERROR\b|\bpanick?ed\b|\bpanic\b|device[ _-]?(?:lost|removed|hung)|\bremoved\b|\bexception\b"
r"|0xC0000[0-9A-Fa-f]{3}", re.IGNORECASE)
NO_ERROR = re.compile(r"\b(?:no|0|zero) errors?\b|\berrors?=0\b|\bwithout errors?\b", re.IGNORECASE)
def error_lines(text: str, limit: int = MAX_ERROR_LINES) -> list[str]:
"""The last `limit` distinct scrubbed lines of `text` that name an error, panic, lost or removed device, exception
or a 0xC0000... status, oldest first. A line repeated (a device-removed flood) is kept once, at its newest place."""
found: list[str] = []
seen: set[str] = set()
for raw in reversed(text.splitlines()):
plain = ANSI.sub("", raw)
if not ERROR_LINE.search(plain) or NO_ERROR.search(plain):
continue
line = scrub_line(plain).strip()
if not line or line in seen:
continue
seen.add(line)
found.append(line)
if len(found) >= limit:
break
found.reverse()
return found
CARD_FIELD = re.compile(r'\bcard="((?:[^"\\]|\\.)*)"')
ADAPTER_FIELD = re.compile(r"\badapter=(?:\"((?:[^\"\\]|\\.)*)\"|(.+?)(?=\s+index=\d))")
MEMORY_FIELD = re.compile(r"\bmemory_mb=(\d+)")
def gpu_from_log(text: str) -> dict:
"""The card the log names: {"name": ..., "memory_mb": int or None, "driver": None}. The driver is never in the
runtime's log. The first line that names a card wins; the memory is the one on a LEONIDA_ADAPTER line."""
info: dict = {"name": None, "memory_mb": None, "driver": None}
for raw in text.splitlines():
line = ANSI.sub("", raw)
if "software adapter (WARP)" in line and info["name"] is None:
info["name"] = "software adapter (WARP)"
card = ADAPTER_FIELD.search(line) if "LEONIDA_ADAPTER" in line else None
if card:
info["name"] = (card.group(1) or card.group(2) or "").strip() or info["name"]
memory = MEMORY_FIELD.search(line)
if memory:
info["memory_mb"] = int(memory.group(1))
break
card = CARD_FIELD.search(line)
if card and info["name"] in (None, "software adapter (WARP)"):
info["name"] = card.group(1).strip() or info["name"]
if info["name"]:
info["name"] = scrub_home(info["name"])
return info
def newest_play_log(folder: str) -> str | None:
"""The newest play-*.log of `folder` (by modification time), or None."""
try:
names = [n for n in os.listdir(folder) if PLAY_LOG.match(n)]
except OSError:
return None
best, best_time = None, -1.0
for name in names:
path = os.path.join(folder, name)
try:
if not os.path.isfile(path):
continue
stamp = os.path.getmtime(path)
except OSError:
continue
if stamp > best_time:
best, best_time = path, stamp
return best
def read_log_ends(path: str, head: int = 256 * 1024, tail: int = 2 * 1024 * 1024) -> tuple[str, str]:
"""The first `head` and the last `tail` bytes of a log as text (the card is named near the start, the errors
are near the end); ("", "") when it cannot be read. A short file comes back whole as both."""
try:
with open(path, "rb") as f:
first = f.read(head)
size = f.seek(0, os.SEEK_END)
f.seek(max(0, size - tail))
last = f.read()
except OSError:
return "", ""
return first.decode("utf-8", errors="replace"), last.decode("utf-8", errors="replace")
# ---------------------------------------------------------------- the settings
SAFE_TOKEN = re.compile(r"[A-Za-z]{1,12}(?:-[A-Za-z0-9]{1,6})?|\d+(?:[.,]\d+)*x?|[A-Za-z]{1,4}\d{1,5}[A-Za-z]{0,2}")
SAFE_VALUE = re.compile(r"[-+]?\d+(?:[.,]\d+)?|true|false|on|off|yes|no|[A-Za-z]{1,12}")
RESOLUTION = re.compile(r"\d{3,5}(?:x\d{3,5})?")
VERSION = re.compile(r"(?:[0-9a-f]{7,40}(?: \d{4}-\d{2}-\d{2})?|zip copy|unknown)")
def safe_text(text: str) -> str:
"""A setting or a name the launcher knows (Windows, the card, the profile), word by word through an allowlist:
short plain words, numbers, model numbers (A770, 4070, RX); anything else is <removed>, once in a row."""
out: list[str] = []
for word in scrub_home(text).split():
core = re.sub(r"\((?:R|TM|C)\)", "", word).strip("()[],;")
kept = word if core and SAFE_TOKEN.fullmatch(core) and not HEX_WORD.fullmatch(core) else REMOVED
if kept == REMOVED and out and out[-1] == REMOVED:
continue
out.append(kept)
return " ".join(out)[:MAX_LINE]
def _shown_value(value: str) -> str:
"""A setting's value as it goes in the block: a number, true/false or a short word as it is; a list (the
per-program lists such as LEONIDA_PAIRED_FOR name the title's programs) as its count; anything else <set>."""
value = str(value).strip()
if SAFE_VALUE.fullmatch(value):
return value
parts = [p for p in re.split(r"[,;\s]+", value) if p]
if len(parts) > 1:
return f"<{len(parts)} entries>"
return "<set>"
def describe_options(args: list[str]) -> dict:
"""What the switches PLAY passes say, for the block: resolution, upscaler, frame generation."""
def after(flag):
return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None
upscaler = "off" if "-NoDlss" in args else (f"DLSS {after('-Dlss')}" if "-Dlss" in args else "DLSS (auto)")
if "-NoFrameGen" in args:
frame = "off"
elif "-FsrFrameGen" in args:
frame = "FSR 3"
elif "-FrameGen" in args:
frame = f"DLSS {after('-FrameGen')}x"
else:
frame = "auto"
return {"resolution": after("-Resolution") or "default", "upscaler": upscaler, "frame_gen": frame}
# ---------------------------------------------------------------- the block
def build_report(version: str, system: str, console: str, args: list[str], variables: dict, log_head: str | None,
log_tail: str | None, driver: str | None = None) -> str:
"""The block, at most MAX_LINES lines. `version`: leonida_version(); `system`: Windows' name and build; `console`:
the profile the next PLAY runs; `args`: the switches PLAY passes; `variables`: the LEONIDA_* values in effect;
`log_head` and `log_tail`: the ends of the newest play log, None when there is none. `driver` is only for a caller
that has it from elsewhere (the runtime does not log it)."""
gpu = gpu_from_log((log_head or "") + "\n" + (log_tail or ""))
options = describe_options(args)
shown = [f"{name}={_shown_value(value)}" for name, value in sorted(variables.items())]
head = [
"Leonida bug report info",
f"Version: {version if VERSION.fullmatch(str(version).strip()) else safe_text(version)}",
f"Windows: {safe_text(system)}",
f"GPU: {safe_text(gpu['name']) if gpu['name'] else NOT_IN_LOG}",
f"Driver: {safe_text(driver) if driver else NOT_IN_LOG}",
f"Video memory: {str(gpu['memory_mb']) + ' MB' if gpu['memory_mb'] else NOT_IN_LOG}",
f"Console profile: {safe_text(console)}",
f"Resolution: {options['resolution'] if RESOLUTION.fullmatch(options['resolution']) or options['resolution'] == 'default' else '<set>'}",
f"Upscaler: {safe_text(options['upscaler'])}",
f"Frame generation: {safe_text(options['frame_gen'])}",
"Options: " + (" ".join(a if re.fullmatch(r"-[A-Za-z]{1,24}", a) else _shown_value(a) for a in args)[:MAX_LINE]
or "(defaults)"),
"Variables: " + ("; ".join(shown)[:MAX_LINE] if shown else "(none)"),
]
if log_head is None and log_tail is None:
tail = ["Last errors: no play log found (turn on Log in Settings or use Run in diagnostic mode)"]
else:
errors = error_lines(log_tail or log_head or "", min(MAX_ERROR_LINES, MAX_LINES - len(head) - 1))
tail = ["Last errors of the newest play log:" if errors else "Last errors of the newest play log: none"]
tail += errors
return "\n".join((head + tail)[:MAX_LINES]) + "\n"