From 597cf76623d62416db7b378b4df6492d4604533b Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 07:30:48 -0500 Subject: [PATCH] TOOLS-WINE-GAME-RUN: scripts/run_game_wine.sh, one bounded game run under Wine The launcher runs gta6rt.exe --run once under Wine on Linux, headless on a private kwin_wayland --virtual --xwayland session (Xvfb has no DRI3, so RADV cannot present there) or on the current display with --visible. Sound is off (Wine's audio drivers disabled, Pulse/PipeWire/ALSA pointed at nothing, LEONIDA_AUDIO=silent for the runtime's silent output endpoint), --device pins the Vulkan device through MESA_VK_DEVICE_SELECT, and a hard time limit, a lock and full teardown bound the run. Every path comes from arguments or the environment. tools/game_run_summary.py prints counts only: run time, end, exceptions by code, D3D12 calls by outcome, presents, the top failing calls and the [rt] lines by category with numbers masked. It never prints a log line. Tests need no game, Wine or GPU: the script against stubs, the summary on synthetic run folders. docs/linux_proton.md describes the script. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/linux.md | 1 + docs/linux_proton.md | 46 ++++++ scripts/run_game_wine.sh | 293 +++++++++++++++++++++++++++++++++ tests/test_game_run_summary.py | 158 ++++++++++++++++++ tests/test_run_game_wine.py | 202 +++++++++++++++++++++++ tools/game_run_summary.py | 225 +++++++++++++++++++++++++ 7 files changed, 926 insertions(+), 1 deletion(-) create mode 100755 scripts/run_game_wine.sh create mode 100644 tests/test_game_run_summary.py create mode 100644 tests/test_run_game_wine.py create mode 100644 tools/game_run_summary.py diff --git a/docs/README.md b/docs/README.md index 6856349124..63d0860ac6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -81,7 +81,7 @@ method, scope and caveats. No game data is included. | [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. | | [xbox_d3d12_xs.md](xbox_d3d12_xs.md) | The `d3d12_xs` graphics ABI quoted from Microsoft's public GDK reference: root signatures, state objects, DXIL libraries, hit groups, shader cache sessions; which pages are missing or NDA-gated. | | [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | -| [linux_proton.md](linux_proton.md) | Building and booting under Proton/Wine on Linux, a healthy boot's timeline, and the test report of one Linux and two Windows machines | +| [linux_proton.md](linux_proton.md) | Building and booting under Proton/Wine on Linux, one bounded game run with `scripts/run_game_wine.sh`, a healthy boot's timeline, and the test report of one Linux and two Windows machines | | [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. | | [exe_fail_fast.md](exe_fail_fast.md) | Where the retail executable stops itself (`int3`) on an import's result: 78 sites over 27 imports (`tools/import_fail_fast.py`), grouped by how `main` binds each import (all 13 non-host fatal-checked imports now bind to shims; 0 unbound). | | [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. | diff --git a/docs/linux.md b/docs/linux.md index f051ca84a7..555cb3ed41 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -16,6 +16,7 @@ names; the build lists anything it can't find before it starts. | Shader translator, its tests and the GPU test tools (`vk_harness`, `vk_pipeline_check`, ...) | Native, GCC or Clang | CI (`linux-gpu-tools`: GCC, tests on llvmpipe); Clang builds them too, but no CI job uses it yet | | `rpf9dump` (asset export) | Native, .NET 8 or newer | CI builds it on Windows only (the `check` job) | | `gta6rt`, its shims and their tests | Windows program, under Wine or Proton | Cross-built with clang-cl and xwin; CI runs the Windows build under Wine on pushes to `main` | +| `scripts/run_game_wine.sh`: one retail run under Wine, headless or visible, counts only ([linux_proton.md](linux_proton.md#running-the-game-under-wine-with-one-command)) | Native (`bash`) around the Windows `gta6rt` | `tests/test_run_game_wine.py` and `tests/test_game_run_summary.py`, without the game | ## Build the port diff --git a/docs/linux_proton.md b/docs/linux_proton.md index f98aacf149..c792a550d1 100644 --- a/docs/linux_proton.md +++ b/docs/linux_proton.md @@ -60,6 +60,52 @@ Three setup mistakes each give a blank or empty picture without an error: the ex from the library (`exe/index.json`), a build without SDL3 (no pad), and a BCPack predictor file that was never generated (`tools/build_dstorage_history.py`; without it the loading art and most BC7 textures stay empty). +## Running the game under Wine with one command + +`scripts/run_game_wine.sh` makes one bounded, silent run of the retail game under Wine and prints counts only. It +complements `scripts/run_wine_session.sh` (the runtime's unit tests under Wine) and the `systemd --user` boot +wrappers described above: it needs no fixed paths, and its output is a summary that can go into an issue. + +```sh +scripts/run_game_wine.sh --build --exe --game-dir \ + --shaders --out --device 1002:744c --seconds 600 +``` + +`--help` lists every input. Each path comes from an argument or from `LEONIDA_GAME_EXE`, `LEONIDA_GAME_DIR` and +`LEONIDA_SHADERS`; `WINE` names another Wine (Proton's `files/bin/wine`), and `WINEPREFIX` (or `--prefix`) a prefix to +reuse instead of a new one in the run folder. + +What it needs: + +- **Wine** (the `wine` on `PATH`, or `WINE`), `timeout`, `flock`, `setsid` and Python 3. +- **A Vulkan driver** for the GPU (Mesa's RADV was tested). `--device VID:DID` pins it through + `MESA_VK_DEVICE_SELECT`; without it the script warns that Mesa picks the device. +- **A display.** By default the run is headless: a private `kwin_wayland --virtual --xwayland` session under + `dbus-run-session`, with its own `XDG_RUNTIME_DIR` in the run folder, so nothing appears on the desktop. Its + rootless Xwayland offers DRI3, which RADV needs to present; Xvfb has none, so without `kwin_wayland` the script + says what is missing instead of falling back. `--visible` opens the window on the current `DISPLAY` instead. +- **A runtime build**: a folder with `gta6rt.exe` and `gta6rt_tls_host.dll`, or a checkout, whose `runtime/` it + cross-builds first with clang-cl and xwin (`XWIN_DIR`, see [linux.md](linux.md#the-runtime-under-wine-or-proton)). + +What it does: + +- **Sound off:** Wine's audio drivers are disabled through `WINEDLLOVERRIDES`, PulseAudio, PipeWire and ALSA point + at nothing, and `LEONIDA_AUDIO=silent` makes the runtime serve its silent output endpoint + ([runtime_imports.md](runtime_imports.md)); the summary says whether it was served. +- **Limits:** a hard time limit (`--seconds`, then SIGTERM and SIGKILL 10 s later), a lock so one run happens at a + time (`--lock`, by default in `XDG_RUNTIME_DIR`), and teardown of Wine and the whole session on exit, time-out or + signal. +- **Traces:** `gta6rt --run` with `--trace` and `--trace-d3d12`, a fresh `--overlay` and save folder in the run + folder. Every other `LEONIDA_*` variable reaches the runtime unchanged, so `LEONIDA_INPUT_SCRIPT=a@210,a@240` + presses A as above. Arguments after `--` go to `gta6rt`. +- **Summary:** `tools/game_run_summary.py` prints the run time, how it ended, exceptions by code, D3D12 calls by + outcome, presents, the most frequent failing calls and the `[rt]` lines by category with numbers masked. It never + prints a log line. `--screenshot-every S` captures the game window into the run folder (ImageMagick's `import` and + `xprop`). + +The run folder's `stderr.log`, `boot.jsonl` and screenshots can show or quote what the title prints, so they stay on +your machine; share the summary. + ## What a healthy boot looks like (Linux machine) | Time | Stage | diff --git a/scripts/run_game_wine.sh b/scripts/run_game_wine.sh new file mode 100755 index 0000000000..ce01b0a07d --- /dev/null +++ b/scripts/run_game_wine.sh @@ -0,0 +1,293 @@ +#!/usr/bin/env bash +# Run the retail game once under Wine on Linux: `gta6rt.exe --run ` with the startup and D3D12 traces on, sound +# off, a pinned Vulkan device, a hard time limit and full teardown, then print counts only +# (tools/game_run_summary.py). Headless on a private kwin_wayland session by default, or on the current display with +# --visible. `scripts/run_game_wine.sh --help` lists the inputs; docs/linux_proton.md has the requirements. +# +# The run folder's logs can quote what the title prints: they stay on this machine. Share the printed summary. +set -u + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +SELF=$ROOT/scripts/run_game_wine.sh + +usage() { + cat <<'EOF' +Usage: scripts/run_game_wine.sh --build DIR --exe FILE --game-dir DIR --out DIR [options] [-- gta6rt arguments] + +Runs `gta6rt.exe --run ` once under Wine, headless or on this display, with sound off, a pinned Vulkan device, +a time limit and the startup and D3D12 traces on, then prints counts only. Every path comes from here or from the +environment; nothing is assumed. + +Inputs: + --build DIR a build folder holding gta6rt.exe and gta6rt_tls_host.dll, or a checkout: its runtime/ is + cross-built with clang-cl and xwin (XWIN_DIR must be set) into --build-dir first + --build-dir DIR where a checkout is built (default /runtime/build/wine-game-run) + --exe FILE the game executable (or LEONIDA_GAME_EXE) + --game-dir DIR the package folder; the working folder (or LEONIDA_GAME_DIR) + --shaders DIR the translated shader library (or LEONIDA_SHADERS; "none" leaves it unset) + --out DIR the run folder; it must not hold a run yet (logs, traces, saves, overlay, summary) + --prefix DIR the Wine prefix (or WINEPREFIX; default /prefix) + +Options: + --seconds N hard time limit of the run (default 600; SIGTERM, then SIGKILL 10 s later) + --visible open the window on the current DISPLAY instead of a private headless session + --device VID:DID the Vulkan device, as MESA_VK_DEVICE_SELECT=VID:DID! (e.g. 1002:744c); without it Mesa picks + --screenshot-every S capture the game window into /shots every S seconds (needs ImageMagick's import and + xprop); the shots are game content and stay local + --lock FILE the lock that allows one run at a time (default $XDG_RUNTIME_DIR/leonida-run-game-wine.lock, + or /run.lock without XDG_RUNTIME_DIR) + -h, --help this text + -- ARGS further gta6rt arguments, after the fixed ones + +Environment: + WINE the wine to use (default wine on PATH; for Proton, its files/bin/wine) + LEONIDA_* passed to the runtime unchanged (LEONIDA_INPUT_SCRIPT, LEONIDA_ARENA_MB, ...); the launcher + sets LEONIDA_AUDIO=silent, and LEONIDA_D3D12=vulkan, LEONIDA_RUMBLE=0 and LEONIDA_SAVE_DIR + unless they are set + +Headless needs kwin_wayland (with Xwayland) and dbus-run-session: Xvfb has no DRI3, so RADV cannot present there. +Sound: Wine's audio drivers are disabled, PulseAudio, PipeWire and ALSA point at nothing, and the runtime serves its +silent output endpoint (LEONIDA_AUDIO=silent). +EOF +} + +die() { echo "run_game_wine.sh: $*" >&2; exit 2; } + +if [ "${1:-}" = --inner ]; then + # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ---- + RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5 + shift 5 + WINE=${WINE:-wine} + WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver + [ -x "$WINESERVER" ] || WINESERVER=wineserver + unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver + { + echo "display: ${DISPLAY:-none}" + if command -v xdpyinfo >/dev/null 2>&1; then + echo "DRI3 extension: $(xdpyinfo 2>/dev/null | grep -c -w DRI3)" + fi + } >> "$RUN/session.txt" + mkdir -p "$WINEPREFIX" + "$WINESERVER" -p + # Warm-up: starts the prefix's services; no Mono/Gecko prompts in a new prefix. + WINEDLLOVERRIDES="$WINEDLLOVERRIDES;mscoree,mshtml=" "$WINE" wineboot -u /dev/null 2>&1 + SHOTS= + if [ "$SHOT_EVERY" != 0 ]; then + mkdir -p "$RUN/shots" + ( + n=0 + while sleep "$SHOT_EVERY"; do + n=$((n + 1)) + # Wine names the window's class after the executable: gta6rt.exe. + for id in $(xprop -root _NET_CLIENT_LIST 2>/dev/null | grep -o '0x[0-9a-f]*'); do + if xprop -id "$id" WM_CLASS 2>/dev/null | grep -qi 'gta6rt'; then + import -window "$id" "$RUN/shots/$(printf '%04d' "$n").png" 2>/dev/null + break + fi + done + done + ) & + SHOTS=$! + fi + cd "$GAME_DIR" || { echo 2 > "$RUN/exit_code"; exit 0; } + t0=$(date +%s) + timeout -k 10 "$LIMIT" "$WINE" "$BUILD/gta6rt.exe" --run "Z:$GAME_EXE" --game-dir "Z:$GAME_DIR" \ + --overlay "Z:$RUN/overlay" --trace "Z:$RUN/boot.jsonl" --trace-d3d12 "$@" \ + "$RUN/stdout.log" 2> "$RUN/stderr.log" + code=$? + echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds" + echo "$code" > "$RUN/exit_code" + [ -n "$SHOTS" ] && kill "$SHOTS" 2>/dev/null + "$WINESERVER" -k 2>/dev/null + exit 0 +fi + +# ---- arguments ---- +SRC= BUILD_DIR= OUT= PREFIX=${WINEPREFIX:-} LIMIT=600 VISIBLE=0 DEVICE= SHOT_EVERY=0 LOCK= +EXE=${LEONIDA_GAME_EXE:-} GAME=${LEONIDA_GAME_DIR:-} SHADERS=${LEONIDA_SHADERS:-} +need() { [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value (see --help)"; } +while [ $# -gt 0 ]; do + case $1 in + -h|--help) usage; exit 0 ;; + --build) need "$@"; SRC=$2; shift 2 ;; + --build-dir) need "$@"; BUILD_DIR=$2; shift 2 ;; + --exe) need "$@"; EXE=$2; shift 2 ;; + --game-dir) need "$@"; GAME=$2; shift 2 ;; + --shaders) need "$@"; SHADERS=$2; shift 2 ;; + --out) need "$@"; OUT=$2; shift 2 ;; + --prefix) need "$@"; PREFIX=$2; shift 2 ;; + --seconds) need "$@"; LIMIT=$2; shift 2 ;; + --visible) VISIBLE=1; shift ;; + --device) need "$@"; DEVICE=$2; shift 2 ;; + --screenshot-every) need "$@"; SHOT_EVERY=$2; shift 2 ;; + --lock) need "$@"; LOCK=$2; shift 2 ;; + --) shift; break ;; + *) die "unknown argument: $1 (see --help)" ;; + esac +done + +[ -n "$SRC" ] || die "--build is required: a build folder with gta6rt.exe, or a checkout" +[ -n "$EXE" ] || die "--exe (or LEONIDA_GAME_EXE) is required: the game executable" +[ -n "$GAME" ] || die "--game-dir (or LEONIDA_GAME_DIR) is required: the package folder" +[ -n "$OUT" ] || die "--out is required: the run folder" +[ -n "$SHADERS" ] || die "--shaders (or LEONIDA_SHADERS) is required: the translated shader library, or none" +case $LIMIT in ''|*[!0-9]*|0*) die "--seconds must be a whole number of seconds above 0, not '$LIMIT'" ;; esac +case $SHOT_EVERY in ''|*[!0-9]*) die "--screenshot-every must be a whole number of seconds, not '$SHOT_EVERY'" ;; esac +if [ -n "$DEVICE" ] && ! [[ $DEVICE =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$ ]]; then + die "--device takes VID:DID in hex, as lspci -nn prints it (e.g. 1002:744c), not '$DEVICE'" +fi +[ -f "$EXE" ] || die "no game executable at $EXE" +[ -d "$GAME" ] || die "no package folder at $GAME" +if [ "$SHADERS" != none ]; then + SHADERS=${SHADERS#Z:} + [ -d "$SHADERS" ] || die "no shader library at $SHADERS" +fi +EXE=$(readlink -f "$EXE"); GAME=$(readlink -f "$GAME"); SRC=$(readlink -f "$SRC") + +# ---- what the host needs ---- +WINE=${WINE:-wine} +missing=() +command -v "$WINE" >/dev/null 2>&1 || missing+=("$WINE (Wine)") +for t in timeout flock setsid python3; do command -v $t >/dev/null 2>&1 || missing+=("$t"); done +if [ "$VISIBLE" = 1 ]; then + [ -n "${DISPLAY:-}" ] || die "--visible needs DISPLAY: run it from the desktop session (an X11 or Xwayland display)" +else + for t in kwin_wayland dbus-run-session Xwayland; do command -v $t >/dev/null 2>&1 || missing+=("$t"); done +fi +if [ "$SHOT_EVERY" != 0 ]; then + for t in import xprop; do command -v $t >/dev/null 2>&1 || missing+=("$t (for --screenshot-every)"); done +fi +if [ ${#missing[@]} -gt 0 ]; then + echo "run_game_wine.sh: missing: ${missing[*]}" >&2 + [ "$VISIBLE" = 1 ] || echo " headless runs need kwin_wayland with Xwayland: Xvfb has no DRI3, so RADV cannot" \ + "present there. Install KWin, or run on your display with --visible." >&2 + exit 2 +fi + +# ---- the run folder ---- +mkdir -p "$OUT" || die "cannot create $OUT" +OUT=$(readlink -f "$OUT") +RUN=$OUT +if [ -e "$RUN/boot.jsonl" ] || [ -e "$RUN/stderr.log" ]; then + die "$RUN already holds a run; name a new --out" +fi + +# ---- the runtime: a build folder as is, or a checkout built here ---- +if [ -f "$SRC/gta6rt.exe" ]; then + BUILD=$SRC +elif [ -f "$SRC/runtime/CMakeLists.txt" ]; then + [ -n "${XWIN_DIR:-}" ] || die "building $SRC needs XWIN_DIR (an xwin splat, docs/linux.md); or pass a build folder" + BUILD=$(readlink -f -m "${BUILD_DIR:-$SRC/runtime/build/wine-game-run}") + mkdir -p "$BUILD" + echo "building the runtime into $BUILD" + if [ ! -f "$BUILD/CMakeCache.txt" ]; then + cmake -S "$SRC/runtime" -B "$BUILD" --toolchain "$SRC/runtime/cmake/clang-cl-xwin.cmake" \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo > "$RUN/configure.log" 2>&1 \ + || die "configure failed (see $RUN/configure.log)" + fi + cmake --build "$BUILD" --parallel --target gta6rt gta6rt_tls_host > "$RUN/build.log" 2>&1 \ + || die "build failed (see $RUN/build.log)" +else + die "$SRC is neither a build folder with gta6rt.exe nor a checkout with runtime/CMakeLists.txt" +fi +[ -f "$BUILD/gta6rt_tls_host.dll" ] || die "no gta6rt_tls_host.dll next to $BUILD/gta6rt.exe" + +# ---- one run at a time: a shared prefix has one wineserver ---- +LOCK=${LOCK:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/leonida-run-game-wine.lock}} +LOCK=${LOCK:-$RUN/run.lock} +exec 9>"$LOCK" || die "cannot open the lock $LOCK" +flock -n 9 || die "another run holds $LOCK" +mkdir -p "$RUN/overlay" "$RUN/saves" + +# ---- environment: private session, sound off, pinned device ---- +export GAME_EXE=$EXE GAME_DIR=$GAME +unset LEONIDA_GAME_EXE LEONIDA_GAME_DIR # launcher inputs; LEONIDA_GAME_DIR also switches the runtime's tests +export WINE +export XDG_RUNTIME_DIR=$RUN/xdg +rm -rf "$XDG_RUNTIME_DIR"; mkdir -p -m 700 "$XDG_RUNTIME_DIR" +export XDG_CONFIG_HOME=$RUN/session/config XDG_DATA_HOME=$RUN/session/data XDG_CACHE_HOME=$RUN/session/cache \ + XDG_STATE_HOME=$RUN/session/state +mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME" +unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS +if [ "$VISIBLE" = 1 ]; then + if command -v xdpyinfo >/dev/null 2>&1 && ! xdpyinfo >/dev/null 2>&1; then + die "--visible: cannot open display $DISPLAY (XAUTHORITY=${XAUTHORITY:-unset})" + fi +else + unset DISPLAY XAUTHORITY +fi +export QT_QPA_PLATFORM=offscreen +if [ -n "$DEVICE" ]; then + export MESA_VK_DEVICE_SELECT="$DEVICE!" + # kwin and Xwayland's glamor on the card that renders, so the present path stays on one device. + for n in /sys/class/drm/renderD*; do + [ "$(cat "$n/device/vendor" 2>/dev/null):$(cat "$n/device/device" 2>/dev/null)" = "0x${DEVICE%%:*}:0x${DEVICE#*:}" ] \ + && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} + done +else + unset MESA_VK_DEVICE_SELECT + echo "warning: no --device: Mesa picks the Vulkan device (pass --device VID:DID to pin it)" >&2 +fi +export WINEPREFIX=${PREFIX:-$RUN/prefix} WINEDEBUG=${WINEDEBUG:--all} +export WINEDLLOVERRIDES="winedbg.exe=d;winemenubuilder.exe=d;winepulse.drv=d;winealsa.drv=d;wineoss.drv=d;winecoreaudio.drv=d" +export PULSE_SERVER=unix:/nonexistent PIPEWIRE_REMOTE=/nonexistent ALSA_CONFIG_PATH=/dev/null SDL_AUDIODRIVER=dummy +export LEONIDA_AUDIO=silent +export LEONIDA_D3D12=${LEONIDA_D3D12:-vulkan} +export LEONIDA_RUMBLE=${LEONIDA_RUMBLE:-0} +export LEONIDA_SAVE_DIR=${LEONIDA_SAVE_DIR:-Z:$RUN/saves} +if [ "$SHADERS" = none ]; then + unset LEONIDA_SHADERS +else + export LEONIDA_SHADERS=Z:$SHADERS +fi +env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" + +WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver +[ -x "$WINESERVER" ] || WINESERVER=wineserver +SESSION_PID= +teardown() { + "$WINESERVER" -k 2>/dev/null + if [ -n "$SESSION_PID" ] && kill -0 "$SESSION_PID" 2>/dev/null; then + pkill -TERM -s "$SESSION_PID" 2>/dev/null; sleep 2; pkill -KILL -s "$SESSION_PID" 2>/dev/null + fi + rm -rf "$XDG_RUNTIME_DIR" +} +trap teardown EXIT +trap 'exit 130' INT TERM HUP + +# The session command with its arguments baked in (kwin takes one program path). +{ + echo '#!/bin/sh' + printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" + for a in "$@"; do printf ' %q' "$a"; done + echo +} > "$RUN/inner.sh" +chmod +x "$RUN/inner.sh" + +T0=$(date +%s) +# setsid: Wine (and kwin, Xwayland and the private D-Bus when headless) form one session that teardown ends as a +# whole, and never the user's desktop. +if [ "$VISIBLE" = 1 ]; then + setsid "$RUN/inner.sh" > "$RUN/session.log" 2>&1 9>&- & +else + setsid dbus-run-session -- kwin_wayland --virtual --xwayland --socket leonida-run-game-wine --width 1920 \ + --height 1080 --no-lockscreen --no-global-shortcuts --exit-with-session "$RUN/inner.sh" \ + > "$RUN/session.log" 2>&1 9>&- & +fi +SESSION_PID=$! +# The session ends when the inner run returns; this outer limit adds a margin for the start-up. +( sleep $((LIMIT + 180)); kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- 2>/dev/null & +WATCH=$! +wait "$SESSION_PID" +pkill -P "$WATCH" 2>/dev/null; kill "$WATCH" 2>/dev/null +teardown; SESSION_PID= +T1=$(date +%s) + +echo "== $(tr '\n' ';' < "$RUN/session.txt" 2>/dev/null | sed 's/;$//')" +if [ ! -f "$RUN/exit_code" ]; then + echo "the run did not start or the session ended early ($((T1 - T0)) s); see $RUN/session.log" >&2 + exit 3 +fi +python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" +echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." +exit 0 diff --git a/tests/test_game_run_summary.py b/tests/test_game_run_summary.py new file mode 100644 index 0000000000..080f8c72ef --- /dev/null +++ b/tests/test_game_run_summary.py @@ -0,0 +1,158 @@ +"""tools/game_run_summary.py on synthetic run folders: counts, endings, masked categories, and no log text printed. + + python -I tests/test_game_run_summary.py + +Each test writes a small run folder (stderr.log, boot.jsonl, exit_code, seconds) by hand; no game files, no Wine, +no GPU. +""" +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, os.path.join(ROOT, "tools")) + +import game_run_summary as summary + +# A line the summary must never print: it stands for text the title itself would put in a log. +SECRET = "Synthetic Title Text 42" + +STDERR = [ + "[rt] loader: mapped 7 modules", + "[rt] audio: serving the silent output endpoint (LEONIDA_AUDIO=silent): 48 kHz float 7.1, every sample discarded", + "[d3d12-trace] #1 ID3D12Device::CreateCommandQueue ok", + "[d3d12-trace] #2 ID3D12Device::CreateHeap failed", + "[d3d12-trace] #3 ID3D12Device::CreateHeap failed", + "[d3d12-trace] #4 SetMarker/BeginEvent with unknown metadata unsupported", + "[d3d12-trace] #5 XboxID3D12CommandQueue::PresentX ok", + "[d3d12-trace] #6 XboxID3D12CommandQueue::PresentX ok", + "[d3d12-trace] #7 XboxID3D12CommandQueue::Slot40 console-only", + "[rt] slot 31: 12 pages at 0x1f000", + "[rt] slot 32: 3 pages", + f"[rt] game dialog: {SECRET}", + f"[rt] {SECRET}, said the title; with a colon: here", + "[rt] present: pacing summary frames=2 samples=2 target_us=16666 mean_us=16666.0 drift_us=+0.0 p50_us=1 " + "p95_us=1 p99_us=1 latency_samples=0 latency_p50_us=0 latency_p95_us=0 latency_p99_us=0", + SECRET, +] +STARTUP = [ + {"seq": 1, "t": 0.0, "kind": "trace_open", "pid": 1}, + {"seq": 2, "kind": "debug_string", "text": SECRET}, + {"seq": 3, "kind": "exception", "code": "0xc0000005", "at": "game.exe+0x1234", "access": "read", + "address": "0x10"}, + {"seq": 4, "kind": "exception", "code": "0x406d1388", "at": SECRET}, + {"seq": 5, "kind": "file_open_failed", "path": SECRET, "error": 2, "caller": "game.exe+0x10"}, +] + + +class GameRunSummaryTest(unittest.TestCase): + def run_folder(self, stderr=STDERR, startup=STARTUP, exit_code=None, seconds=None, tail=""): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + run = tmp.name + with open(os.path.join(run, "stderr.log"), "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(stderr) + "\n") + with open(os.path.join(run, "boot.jsonl"), "w", encoding="utf-8", newline="\n") as f: + f.write("".join(json.dumps(e) + "\n" for e in startup) + tail) + for name, value in (("exit_code", exit_code), ("seconds", seconds)): + if value is not None: + with open(os.path.join(run, name), "w", encoding="utf-8", newline="\n") as f: + f.write(f"{value}\n") + return run + + def printed(self, *argv): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(summary.main(list(argv)), 0) + return out.getvalue() + + def test_counts(self): + s = summary.summarize(self.run_folder(exit_code=124, seconds=121), limit_seconds=120) + self.assertEqual(s["seconds"], 121) + self.assertEqual(s["d3d12_calls"], 7) + self.assertEqual(s["d3d12_outcomes"], {"failed": 2, "ok": 3, "unsupported": 1, "console-only": 1}) + self.assertEqual(s["presents"], 2) + self.assertEqual(s["presents_by_method"], {"XboxID3D12CommandQueue::PresentX ok": 2}) + self.assertEqual(s["paced_frames"], 2) + self.assertEqual(s["failing_calls"]["failed"], {"total": 2, "methods": 1, + "top": {"ID3D12Device::CreateHeap": 2}}) + self.assertEqual(s["failing_calls"]["unsupported"]["top"], {"SetMarker/BeginEvent with unknown metadata": 1}) + self.assertEqual(s["silent_audio_endpoint"], 1) + self.assertEqual(s["exceptions"], 2) + self.assertEqual(s["exception_codes"], {"0xc0000005": 1, "0x406d1388": 1}) + self.assertEqual(s["last_exception"], {"code": "0x406d1388", "at": None}) + self.assertEqual(s["startup_events"], {"exception": 2, "trace_open": 1, "debug_string": 1, + "file_open_failed": 1}) + + def test_categories_mask_numbers_and_hide_free_text(self): + s = summary.summarize(self.run_folder()) + self.assertEqual(s["rt_lines"], 7) + self.assertEqual(s["rt_categories"], {"slot #": 2, "loader": 1, "audio": 1, "game dialog": 1, + "(other)": 1, "present": 1}) + self.assertEqual(summary.rt_category("pool 0x1f00 stats: x"), "pool # stats") + self.assertEqual(summary.rt_category("no colon at all"), "(other)") + self.assertEqual(summary.rt_category("d3d12_xs: x"), "d3d12_xs") + + def test_endings(self): + cases = [ + (dict(exit_code=124), [], "time limit (120 s) reached, stopped (exit 124)"), + (dict(exit_code=137), [], "time limit (120 s) reached, stopped (exit 137)"), + (dict(exit_code=0), [{"kind": "exit", "code": 3}], "guest returned 3 (process exit 0)"), + (dict(exit_code=1), [{"kind": "error", "what": SECRET}], "loader error event (process exit 1)"), + (dict(exit_code=-1073741819), [], "process exit -1073741819 (0xc0000005), no exit event"), + (dict(), [], "no exit code recorded"), + ] + for files, events, want in cases: + with self.subTest(want=want): + run = self.run_folder(startup=[{"kind": "trace_open"}] + events, **files) + self.assertIn(want, summary.summarize(run, limit_seconds=120)["end"]) + + def test_a_truncated_trace_line_is_counted_not_fatal(self): + s = summary.summarize(self.run_folder(tail='{"kind": "excep')) + self.assertEqual(s["startup_bad_lines"], 1) + self.assertEqual(s["exceptions"], 2) + + def test_an_empty_folder_gives_zero_counts(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + text = self.printed(tmp.name) + self.assertIn("D3D12 calls traced: 0 (none)", text) + self.assertIn("silent audio endpoint: not seen", text) + + def test_the_printed_report_never_quotes_the_logs(self): + run = self.run_folder(exit_code=124, seconds=121) + for argv in ([run, "--limit-seconds", "120"], [run, "--json"]): + with self.subTest(argv=argv[1:]): + text = self.printed(*argv) + self.assertNotIn("Synthetic", text) + self.assertNotIn("12 pages", text) + self.assertNotIn("said the title", text) + text = self.printed(run, "--limit-seconds", "120") + self.assertIn("run time: 121 s; end: time limit (120 s) reached", text) + self.assertIn("presents: 2 (XboxID3D12CommandQueue::PresentX ok: 2); pacing summary frames 2", text) + self.assertIn("failed: 2 -> ID3D12Device::CreateHeap 2", text) + self.assertIn("silent audio endpoint: served (1 lines)", text) + self.assertIn("last: 0x406d1388 at (location not printed)", text) + self.assertEqual(json.loads(self.printed(run, "--json"))["presents"], 2) + + def test_top_limits_the_methods_listed(self): + lines = [f"[d3d12-trace] #{i} M{i % 5}::Call failed" for i in range(1, 21)] + text = self.printed(self.run_folder(stderr=lines), "--top", "2") + self.assertIn("failed: 20 -> ", text) + self.assertIn("(+3 more methods)", text) + + def test_bad_arguments_fail(self): + for argv in (["/nonexistent/run/folder"], [HERE, "--top", "0"]): + with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as raised: + summary.main(argv) + self.assertEqual(raised.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_run_game_wine.py b/tests/test_run_game_wine.py new file mode 100644 index 0000000000..a7d09c8899 --- /dev/null +++ b/tests/test_run_game_wine.py @@ -0,0 +1,202 @@ +"""scripts/run_game_wine.sh, the Linux/Wine launcher for one game run, checked without the game, Wine or a GPU. + + python -I tests/test_run_game_wine.py + +The script must parse (`bash -n`), print its inputs with --help, and stop with a clear message (exit 2) for a missing +or wrong argument, a missing host tool (headless without kwin_wayland names it and says why Xvfb is no substitute) or +a held lock. A whole --visible run is then made against stubs: `wine` and `wineserver` are shell scripts that record +their arguments and environment, `setsid` just runs its command, and the build, executable, package and shader +folders are empty files and folders made by the test. The run must reach the summary with the sound off +(Wine's audio drivers disabled, LEONIDA_AUDIO=silent), the device pinned or a warning printed, the traces on and the +extra gta6rt arguments passed. PATH holds only the stubs and the few real commands the script uses, so the machine's +own Wine and KWin are never started. POSIX only; no game files. +""" +import fcntl +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "run_game_wine.sh" +# Real commands the launcher (and its inner half) runs, besides bash builtins and the stubs. +REAL = ("bash", "dirname", "readlink", "mkdir", "rm", "cat", "env", "grep", "sort", "chmod", "date", "sed", "tr", "sleep", + "pkill", "flock", "timeout", "tee") + +WINE_STUB = """#!/bin/sh +if [ "$1" = wineboot ]; then exit 0; fi +for a in "$@"; do printf '%s\\n' "$a"; done > "$STUB_LOG/wine.args" +env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|WINEPREFIX|PULSE_SERVER|PIPEWIRE_REMOTE|DISPLAY)' | sort > "$STUB_LOG/wine.env" +pwd > "$STUB_LOG/wine.cwd" +echo "[rt] audio: serving the silent output endpoint (LEONIDA_AUDIO=silent): 48 kHz float 7.1" >&2 +echo "[d3d12-trace] #1 XboxID3D12CommandQueue::PresentX ok" >&2 +exit 0 +""" +WINESERVER_STUB = "#!/bin/sh\nexit 0\n" +SETSID_STUB = '#!/bin/sh\nexec "$@"\n' + + +@unittest.skipIf(os.name == "nt" or not shutil.which("bash"), "a POSIX bash launcher") +class RunGameWineTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = Path(tmp.name) + self.bin = self.tmp / "bin" + self.bin.mkdir() + for name in REAL: + found = shutil.which(name) + if not found: + self.skipTest(f"no {name}") + (self.bin / name).symlink_to(found) + (self.bin / "python3").symlink_to(sys.executable) + self.stub("wine", WINE_STUB) + self.stub("wineserver", WINESERVER_STUB) + self.stub("setsid", SETSID_STUB) + self.log = self.tmp / "log" + self.log.mkdir() + # The inputs: empty stand-ins, nothing of the game. + self.build = self.tmp / "build" + self.build.mkdir() + (self.build / "gta6rt.exe").write_bytes(b"") + (self.build / "gta6rt_tls_host.dll").write_bytes(b"") + self.exe = self.tmp / "title.exe" + self.exe.write_bytes(b"") + self.game = self.tmp / "package" + self.game.mkdir() + self.shaders = self.tmp / "spirv" + self.shaders.mkdir() + self.out = self.tmp / "run" + self.lock = self.tmp / "run.lock" + + def stub(self, name, text): + path = self.bin / name + path.write_text(text, encoding="utf-8", newline="\n") + path.chmod(0o755) + + def inputs(self, **drop): + args = {"--build": self.build, "--exe": self.exe, "--game-dir": self.game, "--shaders": self.shaders, + "--out": self.out, "--lock": self.lock} + flat = [] + for flag, value in args.items(): + if flag not in drop.values(): + flat += [flag, str(value)] + return flat + + def run_script(self, *args, display=":99"): + env = {"PATH": str(self.bin), "HOME": str(self.tmp), "STUB_LOG": str(self.log)} + if display: + env["DISPLAY"] = display + return subprocess.run([str(self.bin / "bash"), str(SCRIPT), *args], cwd=self.tmp, env=env, capture_output=True, text=True, + timeout=120) + + def test_the_script_parses_is_executable_and_lf(self): + p = subprocess.run(["bash", "-n", str(SCRIPT)], capture_output=True, text=True, timeout=60) + self.assertEqual(p.returncode, 0, p.stderr) + data = SCRIPT.read_bytes() + self.assertTrue(os.access(SCRIPT, os.X_OK), "scripts/run_game_wine.sh lost its executable bit") + self.assertNotIn(b"\r", data) + self.assertTrue(data.startswith(b"#!/usr/bin/env bash\n")) + + def test_help_lists_the_inputs(self): + p = self.run_script("--help") + self.assertEqual(p.returncode, 0, p.stderr) + for word in ("--build", "--exe", "--game-dir", "--shaders", "--out", "--seconds", "--visible", "--device", + "--screenshot-every", "LEONIDA_SHADERS", "LEONIDA_GAME_EXE", "LEONIDA_AUDIO=silent", + "kwin_wayland", "DRI3"): + self.assertIn(word, p.stdout) + + def test_a_missing_input_is_named(self): + for flag, word in (("--build", "--build is required"), ("--exe", "--exe (or LEONIDA_GAME_EXE)"), + ("--game-dir", "--game-dir (or LEONIDA_GAME_DIR)"), ("--out", "--out is required"), + ("--shaders", "--shaders (or LEONIDA_SHADERS)")): + with self.subTest(flag=flag): + p = self.run_script(*self.inputs(drop=flag), "--visible") + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn(word, p.stderr) + + def test_wrong_arguments_are_refused(self): + cases = ( + (["--seconds", "ten"], "--seconds must be a whole number"), + (["--seconds", "0"], "--seconds must be a whole number"), + (["--seconds", "08"], "--seconds must be a whole number"), + (["--device", "radeon"], "--device takes VID:DID"), + (["--screenshot-every", "x"], "--screenshot-every must be"), + (["--exe", str(self.tmp / "nothing.exe")], "no game executable at"), + (["--game-dir", str(self.tmp / "nothing")], "no package folder at"), + (["--shaders", str(self.tmp / "nothing")], "no shader library at"), + (["--build", str(self.game)], "neither a build folder with gta6rt.exe nor a checkout"), + (["--bogus"], "unknown argument: --bogus"), + (["--out"], "--out needs a value"), + ) + for extra, word in cases: + with self.subTest(extra=extra): + p = self.run_script(*self.inputs(), "--visible", *extra) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn(word, p.stderr) + self.assertFalse((self.log / "wine.args").exists()) + + def test_headless_without_kwin_names_what_is_missing(self): + p = self.run_script(*self.inputs()) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn("missing: kwin_wayland dbus-run-session Xwayland", p.stderr) + self.assertIn("Xvfb has no DRI3", p.stderr) + + def test_visible_needs_a_display(self): + p = self.run_script(*self.inputs(), "--visible", display=None) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn("--visible needs DISPLAY", p.stderr) + + def test_a_held_lock_stops_a_second_run(self): + with open(self.lock, "w", encoding="utf-8", newline="\n") as held: + fcntl.flock(held, fcntl.LOCK_EX) + p = self.run_script(*self.inputs(), "--visible") + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn("another run holds", p.stderr) + self.assertFalse((self.log / "wine.args").exists()) + + def test_a_visible_run_against_stubs(self): + p = self.run_script(*self.inputs(), "--visible", "--device", "1002:744C", "--seconds", "30", "--", + "--extra", "a b") + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + self.assertNotIn("Mesa picks", p.stderr) + args = (self.log / "wine.args").read_text(encoding="utf-8").splitlines() + self.assertEqual(args[0], str(self.build / "gta6rt.exe")) + self.assertEqual(args[1:5], ["--run", f"Z:{self.exe}", "--game-dir", f"Z:{self.game}"]) + self.assertIn("--trace-d3d12", args) + self.assertEqual(args[-2:], ["--extra", "a b"]) + env = dict(line.split("=", 1) for line in (self.log / "wine.env").read_text(encoding="utf-8").splitlines()) + self.assertEqual(env["LEONIDA_AUDIO"], "silent") + self.assertEqual(env["MESA_VK_DEVICE_SELECT"], "1002:744C!") + self.assertEqual(env["LEONIDA_SHADERS"], f"Z:{self.shaders}") + self.assertEqual(env["LEONIDA_D3D12"], "vulkan") + self.assertEqual(env["PULSE_SERVER"], "unix:/nonexistent") + self.assertEqual(env["WINEPREFIX"], str(self.out / "prefix")) + self.assertEqual(env["DISPLAY"], ":99") + for driver in ("winepulse.drv=d", "winealsa.drv=d", "wineoss.drv=d", "winecoreaudio.drv=d"): + self.assertIn(driver, env["WINEDLLOVERRIDES"]) + self.assertNotIn("LEONIDA_GAME_DIR", env) + self.assertEqual((self.log / "wine.cwd").read_text(encoding="utf-8").strip(), str(self.game)) + self.assertIn("end: process exit 0", p.stdout) + self.assertIn("silent audio endpoint: served (1 lines)", p.stdout) + self.assertIn("presents: 1", p.stdout) + self.assertTrue((self.out / "summary.txt").is_file()) + self.assertFalse((self.out / "xdg").exists(), "the private XDG_RUNTIME_DIR outlived the run") + # The same folder again is refused: the trace would not be overwritten. + p = self.run_script(*self.inputs(), "--visible") + self.assertEqual(p.returncode, 2) + self.assertIn("already holds a run", p.stderr) + + def test_without_a_device_it_warns(self): + p = self.run_script(*self.inputs(), "--visible", "--seconds", "30") + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + self.assertIn("warning: no --device: Mesa picks the Vulkan device", p.stderr) + env = (self.log / "wine.env").read_text(encoding="utf-8") + self.assertNotIn("MESA_VK_DEVICE_SELECT", env) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/game_run_summary.py b/tools/game_run_summary.py new file mode 100644 index 0000000000..7dbec9c91b --- /dev/null +++ b/tools/game_run_summary.py @@ -0,0 +1,225 @@ +"""Counts for one game run under Wine (`scripts/run_game_wine.sh`): numbers and the runtime's own names, never log text. + + python -I tools/game_run_summary.py [--limit-seconds N] [--top N] [--json] + +Reads, in the run folder: + +* `stderr.log`: the `[d3d12-trace] # ` lines (`--trace-d3d12`) and the `[rt] ...` lines; +* `boot.jsonl`: the startup trace (`--trace`, runtime/README.md "Startup trace"); +* `exit_code` and `seconds`: written by the launcher (the process exit code and the run time). + +Prints the run time, how the run ended, the exceptions by code, the startup trace events by kind, the D3D12 calls by +outcome, the presents, the most frequent failing calls by method name, whether the runtime served its silent audio +endpoint (`LEONIDA_AUDIO=silent`), and the `[rt]` lines counted by category: the text before the line's first colon, +with every number masked as `#` (`slot 31` counts as `slot #`; a name such as `d3d12` stays) and anything that is not a short list of plain words counted as `(other)`. + +It never prints a log line. The logs and traces in the run folder can quote what the title prints (debug strings, +file paths, the title's own messages), so they stay on the machine that made them: share this summary in issues and +pull requests, not the files it reads (AGENTS.md, "No game data"). Method names and outcomes come from fixed strings +in the runtime (runtime/shims/d3d12_trace.h), so they are safe to print. + +Standard library only; reads files, never runs them. A missing file counts as empty; a truncated last line (the shape +a crash leaves) is skipped. +""" + +from __future__ import annotations + +import argparse +import collections +import json +import os +import re +import sys + +# The method can hold spaces, so the outcome is the last field (as tools/boot_trace.py reads it). +D3D12_LINE = re.compile(r"^(?:.+ : )?\[d3d12-trace\] #(\d+) (.+) (\S+)\s*$") +D3D12_PROBLEMS = ("failed", "unsupported", "refused", "partial") +PRESENT_SUFFIXES = ("::PresentX", "::Present", "::Present1") +RT_LINE = re.compile(r"^(?:.+ : )?\[rt\] (.*)$") +# A category is a short run of plain words before the first colon: "audio", "present", "xmem pool", "slot 31". +CATEGORY = re.compile(r"^[A-Za-z][A-Za-z0-9_ ./-]{0,39}$") +SILENT_AUDIO = "audio: serving the silent output endpoint" +PACING = re.compile(r"^present: pacing summary frames=(\d+) ") +# The exception codes and module+RVA locations the startup trace writes; anything else is not printed. +EXCEPTION_CODE = re.compile(r"^(?:0x)?[0-9A-Fa-f]{1,8}$") +LOCATION = re.compile(r"^(?:host:)?[A-Za-z0-9_.-]{1,64}\+0x[0-9A-Fa-f]{1,16}$") +TIMEOUT_CODES = (124, 137) # timeout(1): SIGTERM at the limit, SIGKILL after its grace period + + +def _lines(path): + """The file's lines (UTF-8, or UTF-16 with a byte-order mark), or nothing when it is missing.""" + try: + with open(path, "rb") as raw: + head = raw.read(2) + except OSError: + return + encoding = "utf-16" if head in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig" + with open(path, encoding=encoding, errors="replace") as f: + yield from f + + +def _read_int(path): + try: + with open(path, encoding="utf-8") as f: + return int(f.read().strip()) + except (OSError, ValueError): + return None + + +def rt_category(text: str) -> str: + """The category of one `[rt]` line's text, numbers masked; `(other)` when it is not a short list of words.""" + head, colon, _ = text.partition(":") + head = head.strip() + if not colon or not CATEGORY.match(head): + return "(other)" + return re.sub(r"\b(?:0x[0-9A-Fa-f]+|\d+)\b", "#", head) + + +def summarize(run: str, limit_seconds: int | None = None, top: int = 12) -> dict: + calls = collections.Counter() + bad = {k: collections.Counter() for k in D3D12_PROBLEMS} + presents = collections.Counter() + categories = collections.Counter() + rt_total = silent_audio = 0 + paced_frames = None + for line in _lines(os.path.join(run, "stderr.log")): + m = D3D12_LINE.match(line.rstrip("\r\n")) + if m: + method, outcome = m.group(2), m.group(3) + calls[outcome] += 1 + if outcome in bad: + bad[outcome][method] += 1 + if method.endswith(PRESENT_SUFFIXES): + presents[f"{method} {outcome}"] += 1 + continue + m = RT_LINE.match(line.rstrip("\r\n")) + if m: + rt_total += 1 + text = m.group(1) + categories[rt_category(text)] += 1 + if text.startswith(SILENT_AUDIO): + silent_audio += 1 + p = PACING.match(text) + if p: + paced_frames = max(paced_frames or 0, int(p.group(1))) + + kinds = collections.Counter() + exception_codes = collections.Counter() + last_exception = None + exit_event = None + bad_lines = 0 + for line in _lines(os.path.join(run, "boot.jsonl")): + if not line.strip(): + continue + try: + event = json.loads(line) + except ValueError: + bad_lines += 1 + continue + if not isinstance(event, dict) or "kind" not in event: + bad_lines += 1 + continue + kind = str(event["kind"]) + kinds[kind if re.fullmatch(r"[a-z0-9_]{1,40}", kind) else "(other)"] += 1 + if kind == "exception": + code = str(event.get("code", "")) + code = code if EXCEPTION_CODE.match(code) else "(other)" + exception_codes[code] += 1 + at = str(event.get("at", "")) + last_exception = {"code": code, "at": at if LOCATION.match(at) else None} + elif kind in ("exit", "error"): + exit_event = kind, event.get("code") if type(event.get("code")) is int else None + + code = _read_int(os.path.join(run, "exit_code")) + if code is None: + end = "no exit code recorded: the run did not start or the session ended first" + elif code in TIMEOUT_CODES: + end = f"time limit{f' ({limit_seconds} s)' if limit_seconds else ''} reached, stopped (exit {code})" + elif exit_event and exit_event[0] == "exit": + end = f"guest returned {exit_event[1]} (process exit {code})" + elif exit_event: + end = f"loader error event (process exit {code})" + else: + end = f"process exit {code} (0x{code & 0xFFFFFFFF:08x}), no exit event in the startup trace" + + return { + "seconds": _read_int(os.path.join(run, "seconds")), + "exit_code": code, + "end": end, + "exceptions": sum(exception_codes.values()), + "exception_codes": dict(exception_codes.most_common()), + "last_exception": last_exception, + "startup_events": dict(kinds.most_common()), + "startup_bad_lines": bad_lines, + "d3d12_calls": sum(calls.values()), + "d3d12_outcomes": dict(calls.most_common()), + "presents": sum(presents.values()), + "presents_by_method": dict(presents.most_common()), + "paced_frames": paced_frames, + "failing_calls": {k: {"total": sum(v.values()), "methods": len(v), "top": dict(v.most_common(top))} + for k, v in bad.items() if v}, + "silent_audio_endpoint": silent_audio, + "rt_lines": rt_total, + "rt_categories": dict(categories.most_common()), + } + + +def _pairs(counts, sep=" "): + return ", ".join(f"{k}{sep}{n}" for k, n in counts.items()) or "none" + + +def render(s: dict, top: int = 12) -> str: + secs = "unknown" if s["seconds"] is None else f"{s['seconds']} s" + out = [f"run time: {secs}; end: {s['end']}"] + exc = f"exceptions traced: {s['exceptions']}" + if s["exception_codes"]: + exc += f" (by code: {_pairs(s['exception_codes'])})" + if s["last_exception"]: + where = s["last_exception"]["at"] or "(location not printed)" + exc += f"; last: {s['last_exception']['code']} at {where}" + out.append(exc) + events = f"startup trace events: {_pairs(s['startup_events'])}" + if s["startup_bad_lines"]: + events += f"; unreadable lines {s['startup_bad_lines']}" + out.append(events) + out.append(f"D3D12 calls traced: {s['d3d12_calls']} ({_pairs(s['d3d12_outcomes'])})") + presents = f"presents: {s['presents']}" + if s["presents_by_method"]: + presents += f" ({_pairs(s['presents_by_method'], ': ')})" + if s["paced_frames"] is not None: + presents += f"; pacing summary frames {s['paced_frames']}" + out.append(presents) + for outcome, row in s["failing_calls"].items(): + more = f" (+{row['methods'] - len(row['top'])} more methods)" if row["methods"] > len(row["top"]) else "" + out.append(f"{outcome}: {row['total']} -> {_pairs(row['top'])}{more}") + out.append("silent audio endpoint: " + (f"served ({s['silent_audio_endpoint']} lines)" + if s["silent_audio_endpoint"] else "not seen")) + cats = list(s["rt_categories"].items()) + shown = ", ".join(f"{k} {n}" for k, n in cats[:top * 2]) or "none" + more = f" (+{len(cats) - top * 2} more)" if len(cats) > top * 2 else "" + out.append(f"[rt] lines: {s['rt_lines']} by category: {shown}{more}") + return "\n".join(out) + "\n" + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + description="Counts for one scripts/run_game_wine.sh run: run time, end, exceptions, D3D12 calls by " + "outcome, presents, the top failing calls and [rt] log categories with digits masked. It never " + "prints a log line: the run folder's own logs can quote what the title prints and stay local; " + "share this summary, not them.") + parser.add_argument("run", help="the run folder (stderr.log, boot.jsonl, exit_code, seconds)") + parser.add_argument("--limit-seconds", type=int, help="the run's time limit, named when it was reached") + parser.add_argument("--top", type=int, default=12, help="failing methods listed per outcome (default 12)") + parser.add_argument("--json", action="store_true", help="print the counts as JSON") + args = parser.parse_args(argv) + if not os.path.isdir(args.run): + parser.error(f"no run folder: {args.run}") + if args.top < 1: + parser.error("--top must be 1 or more") + s = summarize(args.run, args.limit_seconds, args.top) + sys.stdout.write(json.dumps(s, indent=1) + "\n" if args.json else render(s, args.top)) + return 0 + + +if __name__ == "__main__": + sys.exit(main())