120 KiB
Build
Relinker only
The relinker can be built without initializing submodules or configuring SDL, Vulkan, FFmpeg, FreeType or the shader recompiler. It requires CMake, a C++20 compiler and a build tool. Python 3.9 or newer enables the Python regression tests; Python 3.11 or newer also registers the patch advisor and patch catalog tests (patch_advisor_unit, patch_advisor_json, patch_advisor_json_integration, patch_advisor_integration, tools_catalog_json and validate_patch_catalog), which need tomllib.
cmake -S . -B build-relinker -G Ninja -DCMAKE_BUILD_TYPE=Release -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON
cmake --build build-relinker --parallel
ctest --test-dir build-relinker --output-on-failure
Python must be found during CMake configuration for Python tests to be registered. List registered tests with ctest --test-dir build-relinker -N and look for input_magic, a Python-backed relinker test. If automatic discovery fails, add -DPython3_EXECUTABLE="C:/path/to/python.exe" to the configure command, using the path to your Python interpreter, then list the tests again.
This mode builds the conversion tool and its tests on Linux, Windows and macOS, including Apple Silicon. macOS uses AppleClang from the Xcode command-line tools (xcode-select --install); CMake and Ninja come from Homebrew (brew install cmake ninja). Windows uses MinGW-w64 GCC with C++20 support and accepts distributions with static or shared runtimes; the full build also requires the exception support described below. The executable is build-relinker/core/relinker/relinker (relinker.exe on Windows with Ninja).
The output is x86-64: Linux ELF by default, Windows PE with --windows or Mach-O with --macos (usage). Converted games need system libraries built for the target OS and a compatible x86-64 host. This mode does not build those libraries, and releases ship them for Linux and Windows only. Tests inspect all three output formats; execution checks run only on their compatible hosts.
Use a separate build directory for the full build.
Fuzzing
ANYPS5_BUILD_FUZZERS builds relinker_conversion_fuzzer, a libFuzzer target that runs the whole conversion on its input, as the web converter does. It requires ANYPS5_RELINKER_ONLY, Clang on Linux and the compiler-rt sanitizer runtimes (libclang-rt-18-dev on Ubuntu 24.04). Every target is built with AddressSanitizer and UndefinedBehaviorSanitizer, without -fsanitize=function: that check reads a signature before the target of every indirect call and faults on the generated code the codegen tests call. The first input byte selects the target system (modulo 3: Linux, Windows, macOS), bit 2 --to-intel and the byte shifted right by 3, modulo 3, the unused-filter level; the remaining bytes are the executable. A conversion that throws a std::exception is a rejected input; a sanitizer report, an abort or a timeout is a finding.
cmake -S . -B build-fuzz -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DANYPS5_RELINKER_ONLY=ON -DANYPS5_BUILD_FUZZERS=ON -DBUILD_TESTING=ON -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
cmake --build build-fuzz --target relinker_conversion_fuzzer
python3 tools/relinker_fuzz_seeds.py build-fuzz/fuzz-corpus
build-fuzz/tests/relinker_conversion_fuzzer build-fuzz/fuzz-corpus -fork=2 -max_total_time=1200 -timeout=20
relinker_fuzz_seeds.py writes the executables built by the relinker's Python tests as seeds, one per target system. With BUILD_TESTING=ON, CTest runs 20000 inputs from an empty corpus as relinker_conversion_fuzzer. Findings are written to the working directory as crash-*, timeout-* or oom-*; reproduce one with build-fuzz/tests/relinker_conversion_fuzzer <file>.
tools/relinker_seed_manifest.py <corpus> describes each file of a flat fuzz corpus as one JSON object: its name, its size, the SHA-256 of its content and its first byte, which selects the target system.
Full build
git submodule update --init --recursive
Self-hosted Linux checkout recovery
The self-hosted Linux Build job in .github/workflows/build.yml is designed to recover from an interrupted recursive checkout. Before checkout it removes stale Git lock files. If actions/checkout fails, it removes only submodules that have a worktree but no valid HEAD (and their matching .git/modules directories), then retries the recursive checkout. If no specific broken submodule can be identified safely, it empties the workspace and retries instead.
That retry is a repair path, not a substitute for a healthy runner seed. If the same runner repeatedly spends most of its job timeout fetching recorded submodule commits, or repeatedly returns with half-cloned submodules, take it out of rotation and reseed its AnyPS5 workspace with a complete recursive checkout at the recorded commits before returning it to service. This avoids carrying one interrupted checkout into every later job while preserving the shared compiler and shader caches outside GITHUB_WORKSPACE.
Selective test builds
tools/select_tests.py selects the tests whose build inputs a change touches, so a pull request can build and run only those tests. Configure and build a full tree with -DBUILD_TESTING=ON (dump needs the header dependencies that only exist once the objects are built), then:
git diff --name-only -z --output=changed.txt origin/main...HEAD
python3 tools/select_tests.py dump build test-graph.json
python3 tools/select_tests.py select build test-graph.json changed.txt
if [ -f build/select.ninja ]; then
ninja -C build -f select.ninja selected
else
cmake --build build
fi
python3 tools/select_tests.py ctest build --output-on-failure
dump reads the header dependencies recorded by a built tree, so build before dumping. select writes select.ninja and select.tests into the build directory; ninja -f select.ninja selected builds only the selected targets (when the change selects the full run, or the graph file is missing, select removes select.ninja and writes none, so run cmake --build build instead, as CI does), and the ctest subcommand verifies the saved test names before running the selection. Rerun select and build the selected targets again if CTest reports changed registrations. A change to CMakeLists.txt, core/libs/CMakeLists.txt, 3rdparty/, cmake/, .gitmodules, the build workflow or tools/select_tests.py selects the full run. The select=true CI build uses the same selection.
tools/build_changed_guest_tests.py builds and runs the guest and host-only core/libs tests that a change touches, from the build directory and an optional changed-paths argument; --output-log writes its log to a file. tools/build_mingw_host_only_tests.py builds the core/libs test executables that do not link guest libc. It prints the executables it selects, and --list-only stops there without building them.
Requirements
- x86-64, Git, CMake 3.22.1 or newer for the default full build with bundled dependencies, 3.24 or newer on macOS (bundled glslang, SPIRV-Tools and Vulkan-Headers declare 3.22.1, bundled SDL's Apple configuration 3.24, and the test build's CMake scripts use
file(COPY_FILE), added in CMake 3.21;CMakeLists.txtdeclares 3.20), Ninja, C++20. - Linux display refresh queries require SDL's XRandR support (
libxrandr-devon Debian/Ubuntu;libXrandr-develon Fedora). Bundled SDL configuration fails without it. KeepSDL_X11_XRANDRenabled. - Linux: GCC, G++ (
gcc-c++on Fedora), binutils. SDL's X11 backend requires X11 and Xext development headers (libx11-devandlibxext-devon Debian/Ubuntu;libX11-develandlibXext-develon Fedora). SDL's Wayland backend requires the Wayland, xkbcommon and EGL development files (libwayland-dev,libxkbcommon-devandlibegl-devon Debian/Ubuntu;wayland-devel,libxkbcommon-develandmesa-libEGL-develon Fedora), andlibdecor-0-dev(libdecor-devel) for window decorations on GNOME. AnyPS5 asks SDL to try Wayland before X11. SetSDL_VIDEODRIVER=x11to select X11 explicitly (XWayland in a Wayland session). Titles that bundle their own SDL readSDL_VIDEODRIVERtoo, and some of them fail to start withx11. Without the Wayland files configuration still succeeds, and the build uses X11 only. Audio output needs SDL's PipeWire, PulseAudio or ALSA backend, built from their development files (libpipewire-0.3-dev,libpulse-devandlibasound2-devon Debian/Ubuntu;pipewire-devel,pulseaudio-libs-develandalsa-lib-develon Fedora). SDL loads them at run time. Without any of them SDL keeps only its silent dummy and disk drivers, so configuration fails. - Fedora: if CMake reports
Could NOT find Threads, installglibc-staticandlibstdc++-staticwithsudo dnf install glibc-static libstdc++-static, then rerun configuration. The project enables static executable linking, and FFmpeg's thread check needs these libraries. - Windows: x86-64 MinGW-w64 GCC with POSIX threads. The compiler must provide DWARF exceptions with
-fno-asynchronous-unwind-tables, or SEH exceptions for System V ABI functions; CMake checks these capabilities. WinLibs GCC 15.2.0 (x86_64-ucrt-posix-seh, release15.2.0posix-14.0.0-ucrt-r7) uses DWARF. MSYS2 UCRT64 GCC 16.2.0-6 uses SEH. Add the selected toolchain'sbindirectory toPATHbefore configuring. - Windows antivirus software can block or quarantine the executables that the relinker tests create and run, which fails
optional_plt,empty_tls,windows_address_space,windows_bss,windows_fixed_base,windows_icon,loadexec_arguments,exec_argumentsandexec_sys_*_arguments. CTest setsTMPDIR,TEMPandTMPof the relinker tests tocore/relinker/test-tempin the build directory, so setting them before runningctestdoes not move these files; add that directory (or the build directory ifrelinker.exeitself is quarantined) to the scanner's exclusions instead. - On Windows, older Microsoft Defender signatures quarantined
agc_shader_replay.exeand sometests/agc_*_tests.exe(35 of about 950 in a full build on Windows 11) asTrojan:Win64/ShellCode.MKA!MTB. The signature matched the instructions GCC emitted for% 65inRuntimeAbi::UintStorageImageBinding(#26777); current source computes the same stage-local slot without that division. Binaries built before this change can still be flagged, and theobjcopypost-step then fails withInvalid argumentbecause the executable is already gone. Add the build directory to the scanner's exclusions when rebuilding old binaries. - FFmpeg binaries are downloaded during configuration unless
FFMPEG_PREBUILT_DIRis set. With the WinLibs CMake, the download fails with status 60 (SSL peer certificate or SSH remote key was not OK) unlessSSL_CERT_FILEnames a CA bundle, for exampleC:\Program Files\Git\ucrt64\etc\ssl\certs\ca-bundle.crtfrom Git for Windows 2.56 and later (mingw64instead ofucrt64before 2.56), as in CI. - Smart App Control (Windows 11) blocks the executables the build and the relinker tests produce, because none of them is signed, and it is not an antivirus setting, so scanner exclusions do not apply to it. The Python relinker tests then fail with
OSError: [WinError 4551] An Application Control policy has blocked this filewhen they startrelinker.exeor a converted program, and CTest reports the native test executables asNot Run(Process not started).VerifiedAndReputablePolicyStateunderHKLM\SYSTEM\CurrentControlSet\Control\CI\Policyis 1 while it is on and 0 once it is off. Turn it off under Windows Security > App & browser control > Smart App Control settings before building; only recent Windows updates allow turning it back on afterwards without a reinstall. - Microsoft Defender can remove the program that the relinker test
windows_guest_main_stack_entryconverts (core/relinker/test-temp/anyps5-main-stack-*/output.exein the build directory) asTrojan:Win32/Wacatac.B!ml. The test then stops withOSError: [WinError 225]when it starts that program. Addcore/relinker/test-tempto the scanner's exclusions, as above. - Bitdefender Advanced Threat Defense hooks Windows calls that
sceKernelRaiseExceptionmakes while its target thread is suspended. When the target is suspended inside ntdll's exception dispatch while it holds an ntdll lock, the hook waits for that lock andguest_raise_exceptionhangs until its timeout. A scanning exception for the build directory does not prevent it; addguest_raise_exception_tests.exeto the Advanced Threat Defense exceptions. - NVIDIA Control Panel's Manage 3D settings > Texture filtering - Quality at High performance applies to Vulkan as well: linear mip filtering then samples fractional LODs at other values (LOD 0.5 as 0.875 on an RTX 5080 with driver 621.14), while High quality samples them exactly and Quality, the default, passes these tests. When the absolute linear mip blend checks of
agc_driver_image_plane_address_on_lineor the LOD bias case ofagc_driver_image_sample_lod_clampfail, the test measures the driver's explicit or gradient LODs and reports the checks as skipped, naming the setting, if the driver remaps them; otherwise the failure stands. Titles render with the remapped LODs too.
tools/package_release.py --output <dir> writes the release packages. With --docs <dir> it collects the documentation into the output folder. Otherwise --platform picks the package: headers writes the public header package for --version (and takes no --build or --revision); linux, windows and web package the build tree given by --build for --version, and web also needs --revision, which the other platforms refuse.
Web converter releases
The Release workflow builds the web converter and the Linux and Windows libraries from the same commit. It tests the converter and publishes its frontend and WASM files as web-<tag>.zip, with the tag and commit recorded in web-release.json.
Pages downloads the converter and both library archives from one release selected through GitHub's latest-release API. release.json records the same tag and commit. Missing, corrupt or mismatched assets fail the Pages job before deployment. Releases made before the web asset was added need a new release; Pages does not combine them with a converter built from main.
Changes to the converter or its frontend reach Pages through a release. Progress reports still come from main. For local development, build relinker_web with Emscripten and run python3 tools/test_web.py --build build-wasm. To stage a complete published release without compiling, run python3 tools/build_web.py --build build-web-release --release. Release staging replaces the selected build directory's web/ directory. --libraries is an alias for --release.
Run this command from a Git checkout that contains the commit recorded in the release's converter ZIP. If a shallow checkout is missing that commit, fetch the matching release tag from the upstream repository first.
tools/prepare_release_notes.py --input <notes> --body <body> --full <full> prepares GitHub release notes that fit the release-body limit (BODY_LIMIT characters in the script): the short body goes to --body and the full notes to --full. With --check it writes nothing and exits with status 1 when either output is missing or stale.
Commands
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
cmake --build build --parallel
cmake --build build --target libs --parallel
libs is a custom target: every library under core/libs/prx is built with
EXCLUDE_FROM_ALL. With the default BUILD_TESTING=OFF, the default build does not produce them,
so the explicit --target libs step is required. With BUILD_TESTING=ON, the default full build
also builds libs through the patched_libraries_tests dependency. Titles load the patched .prx
files from build/core/libs/libs; running a title after a library change without rebuilding libs
therefore tests the previous binaries and can show no effect at all.
To rebuild one patched module, build its libs_<name> target, where <name> is the output file name
without its extension: cmake --build build --target libs_libSceAgcDriver rebuilds and NID-patches
build/core/libs/libs/libSceAgcDriver.prx and the targets it depends on, without patching the other
modules. The same applies to the other files libs places beside them, such as libs_mimalloc.
Name the target, not the output path: with the Makefile generators, an existing file passed as a
target counts as up to date, so a stale patched module is not rebuilt.
Relinker usage and runtime layout.
tools/public_headers_manifest.py [--root <dir>] inventories the inputs of the public header package, with a content hash for each file, without creating an archive. --root defaults to the repository that contains the script.
Windows setup and troubleshooting
The full build also requires Python 3 for glslang and Git for Windows with Bash for libusb's version-header generation. A minimal Git installation without Bash is insufficient for the full build.
For MSYS2, install mingw-w64-ucrt-x86_64-gcc with pacman -S mingw-w64-ucrt-x86_64-gcc and use C:\msys64\ucrt64\bin in PowerShell. Adjust the prefix for a Scoop installation of MSYS2. Use a separate build directory for each toolchain, and select both gcc and g++ from the same installation.
Checking out another branch changes the timestamps of every file that differs, so the next build compiles those files again even if they were built before. With MSYS2, install mingw-w64-ucrt-x86_64-ccache and configure with -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache. On a Ryzen 5 5600 with 12 jobs, switching a build directory back to a branch it had built before took 126 s with 98.5 % of 1,638 compilations served from the cache, against 622 s without it; the first build of a tree is not faster. LLD cannot replace the default linker here: the runtime libraries link against each other's .prx files directly, which GNU ld accepts and ld.lld rejects with unknown file type.
Configuration rejects MinGW libstdc++ builds that combine atomic weak_ptr::lock() with mutex-based reference-count updates (GCC PR125312). Concurrent ownership changes can otherwise destroy live objects. Use a corrected distribution or the supported WinLibs GCC 15.2.0 release above, and configure in a new build directory.
The Windows MSYS2 workflow builds and tests the full runtime nightly at 08:23 UTC and can be started manually with workflow_dispatch. The regular Windows build uses WinLibs.
Scoop's standalone GCC 15.2.0 package cannot build the runtime: disabling SEH selects SjLj exceptions, and its SEH backend cannot compile System V ABI catch handlers. Use MSYS2 UCRT64 or a DWARF-capable WinLibs distribution. This restriction does not apply to relinker-only builds.
In PowerShell, prepend the supported WinLibs toolchain and Git for Windows to the current session's PATH. Adjust the paths for the installed locations; a Portable Git installation can be used in place of C:\Program Files\Git.
$env:PATH = "C:\tools\winlibs\mingw64\bin;C:\Program Files\Git\cmd;C:\Program Files\Git\usr\bin;$env:PATH"
If configuration reports Could NOT find Python3 or selects an unusable interpreter, pass the absolute path to a working Python 3 executable:
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DPython3_EXECUTABLE="C:/path/to/python.exe"
The documentation runs the Python tools as python3. With the python.org installer for Windows, which provides python.exe and the py launcher but no python3.exe, python3 resolves to the Microsoft Store alias in WindowsApps, which prints Python was not found and exits with code 9009 (49 in Git Bash). Installs that provide python3.exe, such as the Python Install Manager, are not affected. In that case run these commands with python or py -3, for example py -3 tools/check_conventions.py.
If windres reports preprocessing failed and Windows prints the first part of the WinLibs installation path as an unrecognized command, windres may be splitting the path to its preprocessor at a space. CMake 3.25 or newer with Ninja or Makefiles handles this for the relinker and test manifests by selecting the gcc.exe alongside windres. For older CMake versions, put the selected WinLibs bin directory first on PATH and append the following argument to the CMake configure command.
'-DCMAKE_RC_FLAGS=--preprocessor=gcc.exe --preprocessor-arg=-E --preprocessor-arg=-xc --preprocessor-arg=-DRC_INVOKED'
If the build stops with fatal error: opening dependency file ...\*.cpp.obj.d: No such file or directory for a few sources with long names, the path of an object or dependency file under build is at or near the 260-character Windows limit. A checkout whose path was 92 characters failed this way with LongPathsEnabled set to 1 in the registry; the same tree at C:\a5 built. Clone the repository to a short path such as C:\a5 and configure in a new build directory: a CMake build tree stores absolute paths, so moving an existing build directory does not help.
After cmake --build build --target libs --parallel succeeds, copy the toolchain's runtime DLLs beside the patched libraries:
$toolchainBin = "C:\tools\winlibs\mingw64\bin"
foreach ($runtimeName in @("libgcc_s_seh-1.dll", "libstdc++-6.dll", "libwinpthread-1.dll")) {
Copy-Item -LiteralPath (Join-Path $toolchainBin $runtimeName) -Destination "build/core/libs/libs"
}
When preparing a title's libs/ directory, copy these DLLs with the patched .prx files. The Windows runtime loader does not search PATH for these dependencies; missing DLLs can cause error 126 even when the .prx is present. See runtime layout.
CMake flags
Project switches accept ON or OFF:
| Flag | Default | Effect |
|---|---|---|
-DBUILD_TESTING=ON |
OFF |
Build and register tests. |
-DANYPS5_RELINKER_ONLY=ON |
OFF |
Build only the relinker and its tests, without third-party dependencies. |
-DANYPS5_BUILD_WASM=ON |
OFF |
Build only the browser relinker (relinker_web target). Requires emcmake from Emscripten and BUILD_TESTING=OFF. |
-DANYPS5_ENABLE_SPIRV_TOOLS=ON |
OFF |
Enable SPIR-V validation and optimization. |
-DANYPS5_ENABLE_ASAN=ON |
OFF |
Build with AddressSanitizer on Linux and move the guest arena out of ASan's shadow gap. |
-DANYPS5_ENABLE_TSAN=ON |
OFF |
Build with ThreadSanitizer on Linux and link executables dynamically. Cannot be combined with -DANYPS5_ENABLE_ASAN=ON or -DANYPS5_BUILD_FUZZERS=ON. |
-DANYPS5_USE_SYSTEM_DEPS=ON |
OFF |
Resolve SDL2, freetype, Vulkan-Headers, SPIRV-Headers, glslang and SPIRV-Tools from the system instead of the submodules. |
-DANYPS5_RELINKER_CLI=OFF |
ON |
Skip the native relinker command line (ANYPS5_BUILD_WASM turns it off). |
-DAPS5_ENABLE_TIMING_LOG=ON |
OFF |
Compile frame timing logging. |
-DAPS5_ENABLE_TRACY=ON |
OFF |
Build the Tracy profiler client into the agc driver. |
-DAGC_BUILD_VISUAL_TEST=ON |
OFF |
Build the standalone AGC SPIR-V visual test. |
-DAPS5_AGC_CREATE_LOG=OFF |
ON |
Stop logging the status of successful sceAgcCreateShader calls (libSceAgcVsh). |
-DANYPS5_REQUIRE_CPU_LEAD_TEST=ON |
OFF |
With BUILD_TESTING=ON, also register agc_driver_sparse_dma_buf_cpu_lead, which runs agc_driver_sparse_dma_buf_import_tests --require-cpu-lead and fails instead of skipping when the nonzero-lead dma-buf CPU publish is not exercised, such as on Windows or without an accessible /dev/udmabuf. |
-DANYPS5_LIBRESSL_ORACLE=ON |
OFF |
With BUILD_TESTING=ON, download LibreSSL 2.5.4 from ftp.openbsd.org at build time, check its SHA-256 and register guest_libressl_oracle, which compares libSceLibreSsl and libSceLibreSsl3 exports with it and prints the cases and differences per function. Without the flag nothing is downloaded. |
GCC and Clang compile libc with -ffp-contract=off whatever the target CPU. Toolchains that default to x86-64-v3, such as GCC 15 on Ubuntu 26.04, would otherwise fuse a * b + c into FMA instructions, which changes the last bit of math results that must match the console.
GCC compiles the project's own sources, but not those under 3rdparty/, with -fzero-init-padding-bits=all when it accepts the option. Since GCC 15, T value{} no longer zeroes the padding of every structure, so copying such a structure into guest memory would expose host stack bytes to the guest.
The Sanitizers workflow builds the full runtime on Ubuntu with -DANYPS5_ENABLE_ASAN=ON and UBSan (-fsanitize=undefined -fno-sanitize=vptr) nightly at 03:41 UTC, runs every test and can be started manually with workflow_dispatch. It builds only the F16ToF32Unpack, F64FmaSubnormals and RegistrationPrepareShutdown AGC execution tests, like the Windows MSYS2 workflow. A test that fails because of the sanitizers themselves, or because of a bug whose fix is still open, is listed with the reason in sanitizer-known-failures.txt, one test per line with its sanitizers and the reason. The job summary, written by tools/sanitizer_report.py, separates unexpected failures from known ones and names listed tests that passed or did not run, so their entries can be removed. To repeat a run locally, set ASAN_OPTIONS=detect_leaks=0 and UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1, so that undefined behavior fails the test.
Build configuration parameters:
| Flag | Value |
|---|---|
-DCMAKE_BUILD_TYPE=Release |
Debug, Release, RelWithDebInfo, or MinSizeRel. |
-DCMAKE_C_COMPILER=gcc |
C compiler name or absolute path. |
-DCMAKE_CXX_COMPILER=g++ |
C++ compiler name or absolute path. |
-DFFMPEG_PREBUILT_DIR=<path> |
Unpacked FFmpeg package for the target platform; empty by default. |
-DCMAKE_C_COMPILER_LAUNCHER=ccache |
Optional C compiler cache; requires ccache. |
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache |
Optional C++ compiler cache; requires ccache. |
-DANYPS5_NODE=<path> |
Node.js 26 or newer that runs the memory64 Emscripten tests guest_long_double and emscripten_module_unwind; node by default, Emscripten builds only. |
-DANYPS5_VIDEO_OUT_TEST_DRIVER=<driver> |
SDL video driver for the VideoOut flip tests; windows on Windows and offscreen elsewhere. |
-DANYPS5_AGC_EXECUTION_TESTS=<names> |
Semicolon-separated file names, without .cpp, of the core/libs/prx/libSceAgcDriver/tests/execution tests to build. Every other execution test is built from a stub that prints skipped, this build leaves the test out with ANYPS5_AGC_EXECUTION_TESTS and exits 77. A name with no source there fails the configure. Empty by default, which builds them all. |
-DAPS5_AGC_PROFILE=<mode> |
Profile-guided build of libSceAgcDriver and its shader recompiler (GCC): generate instruments them, use builds them with the recorded profile. Empty by default. See profile-guided driver build. |
SDL and FreeType settings forced by the root CMakeLists.txt cannot be overridden with -D.
With ANYPS5_USE_SYSTEM_DEPS=ON those libraries come from the system (on Debian and Ubuntu: libsdl2-dev, libfreetype-dev, libvulkan-dev, spirv-headers, glslang-dev, glslang-tools and spirv-tools). A missing package, Vulkan-Headers missing AGC declarations (available since 1.4.330, including VK_KHR_maintenance8, VK_KHR_present_mode_fifo_latest_ready, VK_KHR_shader_fma and the Mesa KosmicKrisp driver ID), or an SDL2 without the HIDAPI joystick driver (sdl2-compat over SDL3, or a build with HIDAPI disabled, which breaks the pad and disk-audio tests), fails the configure with an error and never falls back to the submodule. The forced SDL and FreeType settings from the root CMakeLists.txt do not apply with the flag ON: the system SDL2 comes with whatever its distribution enabled. The prx libraries are shared objects, so SDL2 is linked from the system as a shared library; the default build keeps its own static SDL2. ffmpeg-core, libjpeg-turbo, stb, VulkanMemoryAllocator, LibAtrac9, ogg, vorbis, opus, libusb-cmake, mbedtls, vgmstream, zstd, ZArchive and, on Windows, mimalloc always stay bundled and still need git submodule update --init.
tools/configure_seed.py writes the configure check results of a configured tree's CMakeCache.txt as an initial cache file for cmake -C. --include and --exclude take case-sensitive glob patterns on the check names. Repeat either flag to supply several patterns. An exclusion wins even if an inclusion matches. Quote the patterns to keep the shell from expanding them. --stdout prints the seed instead of writing a file. tools/check_configure_seed.py checks an unfiltered seed against its cache without writing anything. It compares the generated text byte for byte, so an edited seed or one generated with filters can be reported as stale. The exit status is 0 for a match, 1 for a missing or stale seed, and 2 for an input error.
Profile-guided driver build
The AGC driver's hot paths (the queue worker, the draw finisher and the draw committer) gain from a profile-guided build. Use a separate build directory:
- Configure with
-DAPS5_AGC_PROFILE=generateand buildlibs. OnlylibSceAgcDriverandshader_recompiler_agc_driverare instrumented: the runtime libraries export all their symbols, so instrumenting every library fails at link time. - Play the scenes to optimize for. The instrumented driver writes its
.gcdafiles next to its objects every 20 seconds and resets its counters, so a session ended by closing the emulator keeps everything up to the last dump. The driver's shutdown stops that thread and dumps once more. Check that the session reached the scenes before you build with the profile: a session that stayed in a menu still leaves.gcdafiles and theusebuild reports nothing (-Wno-missing-profile), but the driver is then laid out for the menu and can run the scenes slower than a plain build. The draw commits on the[commits]lines (APS5_PIPELINE_STATS=1) show whether the session drew the scenes. Delete the old.gcdafiles before recording again: a later session adds its counts to them. - Configure the same directory with
-DAPS5_AGC_PROFILE=useand buildlibsagain. Functions changed after the recording lose their profile (-Wno-coverage-mismatch), so record again after large changes.
-DCMAKE_CXX_FLAGS="-march=x86-64-v3" adds a further small gain on CPUs that have AVX2; such a build does not run on older CPUs. libc keeps -ffp-contract=off either way.
HTTP locale tests
The Linux HTTP URI locale regression needs an ISO-8859-1 locale. With tests enabled, CMake uses host localedef and installed locale sources (locales on Debian/Ubuntu; glibc-locale-source on Fedora) to generate a private en_US.ISO8859-1 under the HTTP build directory. This runs from the checked-out PR tree, including when CI dispatches the workflow from main, and changes no system locales. -DANYPS5_HTTP_TEST_LOCALE_DIR=<directory> overrides generation. Only guest_http_uri_locale receives the private directory through LOCPATH. If localedef or its source data is unavailable, configuration reports it and leaves the test to probe installed locales. Without an effective Latin-1 locale the test explicitly skips; the CI skip audit rejects that loss of coverage. Windows requires .1252.
ThreadSanitizer
A ThreadSanitizer build runs its tests with TSAN_OPTIONS=suppressions=$PWD/tools/tsan-suppressions.txt, which silences reports from Mesa's lavapipe, the LLVM it compiles shaders with, and PulseAudio: those system libraries are not instrumented, so ThreadSanitizer cannot see their locking. The driver polls labels and fences with acquire loads, but guest memory is still written with plain stores, such as copies and replay restores, as on the console, so ThreadSanitizer also reports those stores against the polls.
Quick syntax checks
After configuring a build directory, use tools/check_compile.py to check the given source files. The tool reads their compile commands from compile_commands.json or Ninja, preserving compilation options while dropping object and dependency output options. It handles -MF, -MT, -MQ and -MJ with separate or attached values so that unused output options do not cause false failures under -Werror.
python3 tools/check_compile.py --build build-relinker core/relinker/cli/src/CliArgs.cpp
With a built Ninja tree, add --headers to check the compile commands of translation units that include a header. For example, python3 tools/check_compile.py --build build-relinker --headers core/relinker/cli/include/Cli.hpp. The tool uses recorded Ninja dependencies and reports stale or missing entries. Rebuild the affected targets if coverage is incomplete or include relationships changed since the last build. Rebuild after include changes even if the tool reports no coverage warning.
Real compile errors still fail. Syntax checks do not replace a full build and test run.
tools/compile_database_inventory.py reads a saved compilation database and prints JSON that groups its records by source directory and file, with the number of variants of each file. Each database entry counts as one variant, including identical commands.
The JSON keeps each entry's arguments or command and its output field when present. It does not invoke a compiler or a build tool.
Pinned frame replay comparisons
python tools/frame_replay_compare.py run recipe.json --output replay-results runs two explicitly supplied Windows or Linux replay runtimes against one capture. The output directory must not exist or overlap an input. Each runtime directory must contain its replay executable, capture-filter executable and project libraries, with ordinary files rather than symlinks, junctions or hardlinks. Keep library search directories inside that runtime. Paths in the recipe resolve relative to the recipe file; tool and library paths inside a runtime use forward slashes.
{
"format": "aps5-frame-replay-recipe/1",
"capture": "capture",
"arms": {
"baseline": {
"runtime": "baseline-runtime",
"replay": "agc_frame_replay.exe",
"inspect": "agc_frame_capture_filter.exe",
"commit": "0123456789012345678901234567890123456789",
"library_dirs": [".", "libs"]
},
"candidate": {
"runtime": "candidate-runtime",
"replay": "agc_frame_replay.exe",
"inspect": "agc_frame_capture_filter.exe",
"commit": "1234567890123456789012345678901234567890",
"library_dirs": [".", "libs"],
"environment": {}
}
},
"environment": {},
"trials": 3,
"warmups": 1,
"timeout": 120,
"log_mib": 16
}
Use each runtime's full compiled AGC commit, not the current source checkout's commit. On Linux omit .exe. Shared environment records GPU/driver selection, Vulkan layers and other declared APS5_*, ANYPS5_* or VK_* settings. Per-arm environments record experimental differences; GPU selection belongs in the shared environment. The runner clears inherited settings in those namespaces and loader overrides, stages the runtime files, sets its library paths, and forces ANYPS5_REQUIRE_VULKAN=1, ANYPS5_HOST_REPORT=1 and its private ANYPS5_SHADER_CACHE_DIR. It does not change existing validation gates or infer a source build's cleanliness from a binary hash.
Before starting a comparison, run python tools/frame_replay_compare.py validate recipe.json to inventory the two runtime trees, check the tool paths and capture metadata, and confirm that calls.bin and memory.bin are nonempty. Preflight runs without launching either runtime or creating an output directory. The run command uses native tools to inspect the capture streams and check the runtime identity and GPU.
Each invocation uses --strict --no-synthesize --repeat 1. Capture inspection rejects truncated or obsolete captures before GPU replay. Each arm warms its own application cache; the resulting seed is copied into a fresh cache directory for every measured trial. Zero warmups starts every trial with an empty application cache. Trials alternate baseline/candidate and candidate/baseline order. Capture and runtime hashes are checked before and after execution. Original logs, process receipts, host reports, cache contents and every attempt remain in the bundle. Commands have a timeout and per-stream log byte bound; their owned Windows job or POSIX process group is terminated on completion, timeout or interruption.
report.md and report.json show per-arm observations, paired changes and repeatability when no known evidence problem prevents comparison. python tools/frame_replay_compare.py report replay-results verifies retained file hashes and regenerates the report from original logs; --json prints JSON. Exit 0 means the declared experiment completed without a recorded evidence problem, 2 means setup, execution or evidence was incomplete, and 130 means interrupted. None is a correctness or performance pass threshold.
To compare several saved cases, run python tools/frame_replay_sweep.py --case case-a replay-a --case case-b replay-b. The bundles must use identical staged capture files, staged baseline runtime files, baseline settings, and trials, warmups, timeout, and log_mib values. The command checks the retained evidence and prints a Markdown table of candidate revisions, changed environment keys, and trial outcomes without replaying the capture.
Replay throughput measures the captured driver workload, not title FPS. The native result rounds skipped_mib to 0.1 MiB and truncates its frame_ms.each values to whole milliseconds; zero reported skips cannot prove zero skipped bytes. Reference comparisons cover final recorded display buffers, not every frame. Capture omissions, original scheduling and mapping history can remain unknown even when all reported checks match. Fresh processes do not retain in-process draw/resource caches, and per-arm application-cache seeds do not control driver caches, GPU clocks or equal cache warmness across builds. Host reports identify the selected GPU and compiled AGC commit, but do not provide a physical-device UUID or dirty state. Staged file hashes do not independently enumerate every library the OS loaded. Live-title performance claims still need the project's same-machine, same-scene summaries and traces.
Repeated Vulkan validation
tools/vulkan_validation_gate.py builds two pinned clean source worktrees into a new output directory and alternates the same focused CTests between them. Linux and Windows hardware runs establish GPU behaviour; macOS synthetic tool tests do not establish native Linux/Windows or GPU correctness. Use native Windows Python or a POSIX host; Cygwin and MSYS Python are rejected because they cannot contain native Windows processes. Each configure, build and CTest command runs in its own process group on POSIX and in its own close-terminated job object on Windows, under a close-terminated guard job on the gate process itself so killing the gate also terminates active children and descendants. On Windows the command starts suspended until it has joined its job, waits in short slices so Ctrl+C interrupts promptly, and drains the job for up to 10 seconds on completion, timeout or interruption, failing the run with exit code 2 if any process in the job survives termination after normal command exit.
python3 tools/vulkan_validation_gate.py \
--baseline /path/to/main FULL_MAIN_COMMIT \
--candidate /path/to/change FULL_CHANGE_COMMIT \
--output /path/to/new-validation-run \
--target agc_driver_recorder_tests --target libs \
--tests '^agc_recorder_completion_labels$' --gpu 'expected device name' \
--repeat 20 --runtime core/libs/libs
Both worktrees must have the expected full commit ID and no tracked or untracked source changes. Output must be outside both worktrees and must not already exist. Each build uses Ninja, Release and BUILD_TESTING=ON; shared cache options can be supplied as --cmake-arg=-DNAME=VALUE. Test targets are explicit; the tool does not infer them. Configure and build logs, selected CTest commands, compiler/build configuration, commit IDs and hashes of selected command files and explicit build-relative --runtime files/directories are retained. Other dynamically loaded libraries and ignored source files are not inventoried. A clean commit alone does not identify an arbitrary existing binary, so existing build directories are not accepted.
Each iteration runs serially with ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1, VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, VK_LOADER_DEBUG=layer and the requested ANYPS5_GPU. The tool rejects declared test properties that override those values or the recorded VK_ICD_FILENAMES, VK_DRIVER_FILES and VK_LAYER_PATH values. The GPU name is a selection request, not an independent hardware measurement. Every iteration retains verbose output and JUnit, with CTest's passed/failed output-size limits disabled so diagnostics near either end of a long output are retained. Missing, disabled or skipped selected tests, test failures, the exact missing-layer phrase and test output without the loader's Insert instance layer "VK_LAYER_KHRONOS_validation" line fail the gate, even if CTest returns zero. The insertion line is required because the loader ignores VK_LAYER_PATH in elevated processes without reporting a missing layer.
The gate compares VUID, synchronization-hazard and bracketed UNASSIGNED- validation IDs per test across all baseline and candidate iterations. A new candidate ID fails; occurrence counts are reported without treating a count increase as a new violation. Existing baseline diagnostics remain visible and do not establish a clean validation run. Parsing covers standard Validation Error/Warning: and VUID/SYNC-HAZARD (ERROR/WARNING / ...) messages in JUnit test-body output, not arbitrary application formats or verbose CTest configuration text. Retain the logs for manual review of other formats. Source identity and selected artifact hashes are checked again after testing.
report.json records the comparison and execution order. Exit 0 means the comparison completed with no detected regression, 1 means a test/coverage/layer or new diagnostic failure, 2 means setup, attribution or incomplete evidence, and 130 means interrupted. --test-timeout supplies CTest's default timeout; explicit test timeout properties still apply. --timeout bounds each configure/build/CTest command. The active POSIX process group or Windows job object is killed on completion, timeout or interruption. Repetitions report observed outcomes; they do not prove absence of intermittent faults or statistical significance.
Write watch tests
On Linux the guest write watch needs the kernel's asynchronous userfaultfd write protection (UFFD_FEATURE_WP_ASYNC), available from Linux 6.7. On an older kernel the runtime falls back to comparing guest memory, and the tests that need the watch fail by design instead of skipping. WSL 2's default 5.15 kernel is such a host: run wsl --update before treating those failures as regressions.
The macOS write watch can be built and tested separately, without submodules or the prx libraries:
cmake -S core/libs/tests/write_watch -B build/write-watch -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=x86_64
cmake --build build/write-watch
ctest --test-dir build/write-watch --output-on-failure
With CMAKE_OSX_ARCHITECTURES=x86_64 Apple silicon runs the tests through Rosetta, which is how relinked titles run; without it they run natively. The full BUILD_TESTING build on macOS also registers them.
Tracy
-DAPS5_ENABLE_TRACY=ON builds the Tracy 0.14.1 client from 3rdparty/tracy as a shared library next to the patched .prx files (libTracyClient.dll, libTracyClient.so.0.14.1 on Linux); copy it with them. Every PerformanceTimer scope of libSceAgcDriver and libSceVideoOut is a zone, every presented flip ends a frame, and the queue workers and the presenter are named threads. Connect the Tracy 0.14.1 profiler to 127.0.0.1: the client listens only on localhost and records only while a profiler is connected. Sampling, system tracing, call stacks, code transfer and Tracy's crash handler are disabled. Without the flag nothing of Tracy is built.
On Windows MinGW frees thread_local objects before their destructors run, so the Tracy client is built without thread_local destructors and never destroys its event queue: a thread that emitted a zone and ended keeps its event blocks (2 MiB each) until the process exits.
Compute pipeline replay
Build agc_compute_pipeline_replay in the full build with -DANYPS5_ENABLE_SPIRV_TOOLS=ON; replay validates the captured module before calling Vulkan. Set APS5_DUMP_COMPUTE_PIPELINES to a dedicated empty directory before starting a title to save each uncached compute pipeline's final SPIR-V, descriptor layouts, push constant ranges, specialization values, subgroup size and creation flags before compilation. Files are named compute-<identity>/capture.aps5cp; identical records are deduplicated. The pipelines of the start-up f32 denormal flush, f16 conversion and f16 NaN probes are not captured. At 128 records or 256 MiB in total, capture turns itself off for the rest of the run after a [compute-capture] optional capture disabled line and the title keeps running; a single record over 36 MiB (at most 8,388,608 SPIR-V words, or 32 MiB of shader code) is an error. Capture files contain shader code and device metadata, but no guest buffers or textures; review them before sharing.
Set APS5_DUMP_COMPUTE_MIN_WORDS to capture only modules at or above that SPIR-V word count, for example 100000 when investigating large NVIDIA compilations. The default is 0 (all modules); values outside 0 through 8388608 fail. The filter applies only when capture is enabled.
cmake --build build --target agc_compute_pipeline_replay
build/core/libs/prx/libSceAgcDriver/agc_compute_pipeline_replay capture.aps5cp --cache-out pipeline.cache --output fresh.json
build/core/libs/prx/libSceAgcDriver/agc_compute_pipeline_replay capture.aps5cp --cache-in pipeline.cache --output imported.json
Use APS5_PIPELINE_STATS=1 agc_compute_pipeline_replay capture.aps5cp --inspect --output inspection.json to inspect the captured pipeline without dispatching it. This requires VK_KHR_pipeline_executable_properties, requests statistics for this replay, and prints the driver's executable and counter names, values and descriptions to stderr. Available counters depend on the driver. The JSON report marks mode as inspection, sets pipeline_statistics to true, records the effective replay_pipeline_flags, and sets milliseconds to null. The captured identity and original flags are retained. Inspection output is not a compilation benchmark. Replay without --inspect continues to reject enabled statistics or captures carrying the statistics flag. --inspect cannot be combined with --write-fixture.
On Windows use agc_compute_pipeline_replay.exe and prepend build/core/libs/libs/unpatched to the process PATH. ANYPS5_GPU selects a device by name as for the driver. The tool uses the driver's compute pipeline creation path, without recording commands, dispatching work or importing guest memory. Compile-only devices also enable supported partially-bound, variable-count and runtime-array descriptor features to replay captured layouts; ordinary runtime devices are unchanged. Binding flags are preserved independently of update-after-bind. Replay accepts the unconditional Vulkan 1.0 capabilities listed in the pinned Vulkan registry; other capabilities must be enabled by the device target. Non-Vulkan capabilities such as Kernel and unknown capabilities fail before pipeline creation. Unsupported features, non-highest variable bindings and counts exceeding layout support fail explicitly. Unsupported inputs and mismatched cache vendor, device or UUID fail explicitly. Output files must not already exist.
Each invocation creates one pipeline. With no --cache-in, its application pipeline cache starts empty; --cache-in imports a raw cache previously written by --cache-out (at most 64 MiB), and --cache-out exports the resulting cache. The title's wrapped vk-pipelines-*.bin format is not accepted. It does not load or save the title's usual pipeline cache. NVIDIA and other driver caches remain uncontrolled: a fresh application cache is not a cold driver cache. JSON reports the capture identity, GPU/driver identifiers, word count, cache policy and separate wall times for shader module, layouts, pipeline creation and cache work. Device initialization is outside these timings. Pipeline statistics captures and APS5_PIPELINE_STATS are refused because they change compilation cost.
--fixture compiles a tiny synthetic compute shader with specialization, sparse descriptor binding and push constant metadata; --write-fixture DIRECTORY saves it without opening Vulkan. It performs no GPU work and does not reproduce a title's compile workload. With BUILD_TESTING=ON, agc_compute_pipeline_capture checks serialization and rejected inputs. With SPIRV-Tools also enabled, agc_compute_pipeline_replay compiles the fixture with fresh and imported application caches, verifies cache rejection, and checks required subgroup support. agc_compute_pipeline_capture_run verifies the existing branch-past-endpgm compute fixture's output with capture disabled and enabled, then replays the captured pipelines and checks their identities and metadata. agc_compute_pipeline_inspection checks executable counter queries, diagnostic JSON, retained capture identity, and benchmark-mode guards; its timeout is 60 seconds. The other tests have 30-second timeouts. Runtime tests skip when Vulkan is absent; set ANYPS5_REQUIRE_VULKAN=1 to require execution. There is no performance pass threshold.
PM4 submission replay
Set APS5_DUMP_SUBMITS to a directory before starting a title to save every submission the AGC driver accepts, as it enters the driver. index.txt gets one line per submission: ordinal, queue, graphics or compute, serial, microseconds on the clock of the APS5_TRACE_GPU lines, dword count, kind, file name, the dword offsets of the waits whose value passed their compare when the submission entered the driver (held, which the driver then does not wait for), the COND_EXEC and predicated indirect buffer ranges as start:end dword offsets (- for none) and the packet forms in force when the driver captured the submission: ps4 once a PS4 title has submitted through libSceGnmDriver or mapped a compute queue there, from when the driver also accepts the PS4 forms of some packets (a 7-dword RELEASE_MEM, for example), and ps5 otherwise. submission_<ordinal>.bin, with the ordinal zero-padded to six digits (submission_000001.bin), holds the dwords the driver copied, with indirect buffers inlined. A REWIND tail is listed as rewind with the serial of its submission, a suspend point as suspend without a file. The index is truncated on the first submission. A failed write puts the driver in its failed state: the call that made the submission throws after the submission was queued, and every later driver call throws the same error. Unset, the switch costs one test per submission; set, one copy of the commands per submission before the driver lock, the ordinal, time and held waits under it without allocating, and the files written after it. A capture holds command buffers only, no guest memory. An index written before the forms column (column line ordinal queue type serial time_us dwords kind file held conditional) is still read, with every submission in the PS5 forms, and so is one written before the held and conditional columns (column line ordinal queue type serial time_us dwords kind file), with both unknown.
agc_pm4_replay <directory> [--full] decodes the capture offline with the driver's packet decoder, validator and store decode (Pm4::DecodeStores), each submission in the packet forms its index line names, and reports each WAIT_REG_MEM, WAIT_REG_MEM_64 and REWIND as released, unreleased or unknown. It does not model cross-queue timing: a wait is released only when the capture alone proves that the driver releases it, and unknown, with the reason, whenever its outcome depends on when the stores of another queue run, since a store of another queue can run before, between or after the stores of the waiting queue whatever order the submissions entered the driver in. A memory wait is released when its compare always passes; when it was held at submit; when the last store to the awaited bytes before it on its queue (in that submission or an earlier one) covers them with a value the compare accepts, is not conditional, and no other queue stores to any of those bytes anywhere in the capture (current value); or when a RELEASE_MEM or WRITE_DATA label earlier in the waiting submission, one the driver keeps in its label history (4-byte aligned, at most 64 bytes, not conditional), stores a value the compare accepts and fewer than 4 other stores to the awaited bytes can run between it and the wait (label history). The driver keeps the last 4 label stores per dword over all queues (LabelHistory.cpp) and finds one there only if it ran after the waiting submission entered the driver, which the capture proves only for a store earlier in that submission. The stores counted against the history are those between the label and the wait on the waiting queue and every store of another queue to the awaited bytes, whatever its submit order; stores later on the waiting queue run after the wait. A REWIND is released when its tail is in the capture. One that was valid at submit without a tail in the capture is unknown, because the driver reads the valid bit again when the queue reaches the REWIND. A memory wait is unreleased when it was not held at submit and no store in the capture that can run before it may write a value the compare accepts (a store of part of the awaited bytes or of a value known only at run time may): the GPU does not release it, but a CPU store could, and so could a shader store, since the capture holds neither. A REWIND without a tail that was not valid at submit is unreleased. Every other wait is unknown: unknown: depends on cross-queue timing (stores on queue X at #...) when another queue stores to the awaited bytes; otherwise when the last store before it on its queue is conditional (COND_WRITE, inside a COND_EXEC range or a predicated packet), stores a value known only at run time or only part of the awaited bytes, or overwrites an accepted store that the capture does not prove is still in the label history (one in an earlier submission, one the history does not keep, or one with 4 or more stores after it). When the index has no held column, a wait that would be unreleased is unknown, since its value may have passed the compare at submit; without the conditional column every packet after a COND_EXEC or predicated INDIRECT_BUFFER is conditional to the end of its submission. The report counts the waits per outcome and route and the unknown waits that depend on cross-queue timing, says when the index lacks the columns, lists up to 32 unreleased and then unknown waits, newest first, each with the packets around it and the stores to the awaited bytes that decide it (for another queue, the 4 nearest the waiting submission in submit order), then the last submissions of each queue. --full lists every wait and prints every packet. A packet the driver rejects means the capture is corrupt and fails the analysis. The exit code is 1 when a wait is unreleased and 2 on errors.
cmake --build build --target agc_pm4_replay
build/core/libs/prx/libSceAgcDriver/agc_pm4_replay submits
On Windows use agc_pm4_replay.exe and prepend build/core/libs/libs/unpatched to the process PATH. With BUILD_TESTING=ON, agc_driver_pm4_replay captures submissions made with the libSceAgc command builders through the driver and checks the index, the held waits, the conditional ranges, the dwords, the decode and the outcome of each wait, then checks hand-made captures: each release route; a store of another queue to the awaited bytes that entered before or after the store of the waiting queue (unknown); the label history limit, with the stores after the label on the waiting queue or on another queue; a fill the history does not keep; a store in an earlier submission overwritten later; later stores, rejected values and a missing rewind tail (unreleased); the six captures of the reviews (a two-queue deadlock, a store of 0 behind a released wait on another queue, with and without that wait held at submit, and labels pushed out of the history by stores of another queue), none of whose waits may be released except the one held at submit; five groups of waits in eight submission orders with identical outcomes; an index without the held and conditional columns; a capture whose submissions change from the PS5 to the PS4 packet forms, with a 7-dword RELEASE_MEM of a value, a wait it releases and a RELEASE_MEM of the system counter, the first of them rejected in the PS5 forms, also from an index without the forms column; corrupt captures; then a failed write. agc_driver_pm4_replay_tool runs the tool on the driver capture and checks its exit codes and report.
Frame capture and replay
On Windows and Linux, set APS5_FRAME_CAPTURE to a directory to record a few frames of a title at the AGC driver boundary, then replay them with agc_frame_replay through any build of the driver that accepts their calls format, with no title running. From the start of the process the driver keeps every shader registration and ABI resolution, video output registration and EOP flip reservation. At the frame boundary picked by APS5_FRAME_CAPTURE_AT_FLIP (default 1), or by the appearance of the file APS5_FRAME_CAPTURE_TRIGGER names (a number in it replaces the frame count), it waits up to 10 s for the driver to go idle, trying again at the next boundary (up to 600) when it does not or as soon as a queue waits on memory only the title can store, and writes every committed allocation of the guest allocation registry that the title can read or the GPU can access, the title's image included, as zstd chunks without their all-zero 64 KiB blocks. A frame ends at a CPU flip, at a submission that flips (a flip packet, or the EOP release of a reserved flip token), or at the next submission, flip or flip reservation after a released REWIND tail flipped; the reservation itself only records its token. For the next APS5_FRAME_CAPTURE_FRAMES (10) frames it records each submission (queue, command buffer address and size), flip and suspend point with the thread that made it and the accepted and completed serials, each preceded by the guest pages the write tracker saw the CPU write, or found newly mapped while it collected around a GPU write, since the previous call that handed work to the GPU (GuestMemory::CollectWrittenBlocks, per 4 KiB where the tracker kept page stamps), and the pages outside the write watch whose contents changed since the delta that last recorded them (GuestMemory::ChangedComparedPages: a page is hashed from the snapshot when its range is unwatched at the start, just before it leaves the watch during the capture, or recorded whole at the next delta when it left without that hash, and it is compared until it is watched again), read through the driver's coherent path once the submissions already accepted have completed or every queue still busy is parked on a REWIND control word or WAIT_REG_MEM value the title has not stored yet, with no queued draw, unrecorded label or pending label write left (the parked queues then stay at their waits until the delta is read; a recorded submission, flip or suspend point reaches the driver before the recorder takes its next call, so that wait covers every call recorded before the delta); an allocation the registry gained after the snapshot is recorded there as a new range, with all its 64 KiB blocks when later deltas collect it (write-watched or private guest-arena memory), otherwise with its nonzero ones. A page in the range of a driver store from the CPU that is written during that store counts only when it then differs from its bytes before the store with the store's own bytes applied (another thread wrote it meanwhile), and always when the store does not give the bytes it stores: MEM_SEMAPHORE packets, buffer copies the driver runs on the CPU and compare-exchange write-backs (WriteChangedIfHeld). A submission ends a frame only when it flips itself, not when another thread's submission flipped while it was being submitted. Shader registrations and ABI resolutions only collect the blocks of the shader header and the arrays it points to, and the pages of the title's image only when their content changed. At the end it stores each display buffer the title presented, decoded, as a reference image. Without the guest write watch (APS5_NO_WRITE_WATCH, or no write watch on the host) the capture throws when it starts, since it could not record CPU stores. A capture is calls.bin (calls format 2), memory.bin and capture.json (commit, switches, sizes, warnings), and the recorder stops with a warning when its volume has less than 4 GiB free. A 20-frame capture in the Demon's Souls Nexus is 5.3 GiB of snapshot and 11.5 GiB of deltas before compression, 3.9 GiB on disk.
agc_frame_replay <capture> [--no-pace] [--pace-timeout-ms <n>] [--no-release] [--release-after-ms <n>] [--no-synthesize] [--strict] [--repeat <n>] [--cold-pipelines] [--shaders] [--shader-code <dir>] [--submits <n>] [--trace-serials] [--dump <address>:<bytes>:<file>]... [--frames <dir>] maps the captured ranges at their addresses and registers them with their access (a range the replaying process already maps writable, such as the driver's fixed memory, is only refilled, and a non-GPU range it uses itself is skipped and counted), repeats the registrations, then replays the calls of each captured thread on a thread of its own, started in captured order. Before a call that hands work to the GPU it waits until no more submissions are in flight than when the title made it, and before a memory delta until no queue runs, each having finished or waiting on title memory (--no-pace turns this off). A call gives up waiting, and --strict fails, only once --pace-timeout-ms (10000) has passed and no queue is running, each having finished or parked on a wait, or after 10 minutes whatever the queues do: a queue still executing, such as one compiling pipelines on a cold shader cache, is progress. The drain after the last call ends the same way, after 10 s without a completion once no queue is running, and reports what the queues wait on every 10 s. A delta first flushes the driver's writes to the pages it restores, and the parked queues and the other threads' submissions wait until all of it is restored. It copies everything but the words that may gate a queue (the first word of each chunk, the word after each REWIND header and the words a queue is parked on), which it stores last (kept_words counts them). A delta also records the waits its queues were parked on when it was read; a replay that reaches it parked elsewhere, such as on a wait the delta's own stores release, applies it, waits until its queues park on those waits with the captured number of submissions in flight, and applies it again without the REWIND control words it sets, storing the clear ones atomically, so a title store that followed GPU work the delta released keeps its bytes (park_restores counts these). Titles release GPU waits from threads that never call the driver, so when the driver completes nothing for 3 ms, no queue is running and no memory delta is being paced or applied, the replay reads the waits its queues are blocked on (AgcDriverAwaitedWaits). A queue parked on a REWIND is released, once no queue runs, by applying the first later memory delta that sets its control word, with the delta's REWIND control words written last; for any other wait it writes the last earlier recorded CPU value that satisfies the compare, else a value derived from the reference (--no-synthesize turns this last step off). It releases one wait at a time and looks again only after another 3 ms with no queue running, so a queue released into work that a second waiting queue depends on runs before that queue is released. It prints one JSON line with the frame count and times, the submissions, the pacing wait, the released waits and how many were derived, the submissions that never completed and, for captures with reference images, the share of identical pixels and the largest channel difference of the replayed display buffers (--frames writes both images). Effects that depend on timing (temporal antialiasing, particles) make pixels differ, so expect a visual match rather than identical frames. The replay's device has no window, but it loads the title's Vulkan pipeline cache file (vk-pipelines-*.bin in the shader cache directory) as the windowed device does, so pipelines the title already compiled are not compiled again (--cold-pipelines starts with an empty one and clears an inherited APS5_HEADLESS_PIPELINE_CACHE; that variable is the driver switch). The title replayed its pipeline journal at boot, long before the captured frames, so after the registrations the replay waits for the driver's journal replay to finish before the first pass (journal_s in the JSON line). The first pass still compiles every shader and pipeline the frames use that neither cache holds, so --repeat <n> replays the frames n times in one process: before each later pass it resets guest memory in one driver transaction (AgcDriverGuestMemoryTransaction): the driver first waits until every accepted submission completed, then stops other threads from taking pending storage images to store and waits for the stores already taken, and holds its GPU lock until the reset ends, so no other thread stores, publishes or retires meanwhile. The transaction does not hold submissions back: its caller must stop every thread that submits first. It fails if a submission was accepted between that wait and its end, but only checks after its body, so it detects such a submission afterwards and misses one still copying its commands and unordered CPU flips, which are not counted. Overlapping transactions keep other threads from taking pending storage images until the last of them ends. Inside it the reset first lists the candidate pages of each captured range: the pages the write tracker saw written since the previous reset (CPU stores and the driver's own, per 64 KiB block; a block the write watch does not cover, or whose walk failed, is a candidate whole) and the pages of every resident owner whose results only the GPU holds (AgcDriverGpuOwnedRanges: the color, FMASK, CMASK, DCC and HTILE of multisampled color images drawn on the host, the planes of native depth owners written on the host, depth planes newer on the GPU and pending storage images). It retires the multisampled color images, native depth owners and depth surfaces over a candidate page (AgcDriverRetireGpuOwners, walking the driver's own owner lists: multisampled color images whole, native depth owners whole, depth surfaces with their stale planes discarded, and the HTILE reads and the HTILE clears waiting for their depth surface remembered over any part of those pages), so results the next pass rebuilds anyway are not stored first. Other images over those pages, sampled textures for example, are not retired: the rewrite is a guest write like any other, so they reload through the write generations at their next use. It then stores what must land in guest memory before the compare (recorded stores and pending storage images), adds the pages that store wrote to the candidates and retires the owners over them too, and compares only the candidate pages with the snapshot (zero where it holds nothing), page by page in windows of 4 MiB, on worker threads that take pieces of at most 64 MiB, so a range larger than one piece is split over several threads. A page that differs is rewritten from the same decoded window as soon as it is compared, and only those pages are rewritten, so caches over unchanged pages stay valid and an owner whose memory already matches is retired without a rewrite. The standalone replay has no other writer of guest memory during the reset: the threads that replay the captured calls and release GPU waits are joined, and every submission completed, before it starts; the reset fails if guest memory is mapped or unmapped during it. Each pass entry of the JSON line gives rewritten_bytes (of them rewritten_owned_bytes over GPU owners), compared_bytes, flushed_bytes (candidate pages the store added), range_bytes, reset_ms, verify_ms (the time --verify-reset took inside the transaction, not part of reset_ms), reset_workers (the threads that compared at least one page) and the owners retired (retired_color, retired_depth_owners, retired_depth_surfaces, discarded_depth_planes). --verify-reset makes the reset fail, before the transaction ends, when guest memory over a captured range differs from the capture, a resident owner with results only on the GPU remains over a captured range, or any resident owner remains over a candidate page; it walks the driver's resident owner lists (AgcDriverResidentOwnersOver), not the reset's owner inventory, but over the same plane footprints that retirement uses, so it catches an owner that retirement skipped or the inventory left out, not a footprint that is too small; the tests pin the footprints to plane ends they state themselves in agc_graphics_profile_draw and agc_driver_multisample_retirement. On Linux the replay needs the kernel write watch for every watched range and fails with the reason, including the errno of a failed registration, when it is missing (Linux 6.7 or newer); on Windows the arena is write-watched as a whole and a captured range outside it is compared whole at every reset. It then makes the reservations that were pending at the snapshot again (a token still reserved from the previous pass is kept), and the frame times then come from passes 2 to n, with each pass listed under passes with the bytes it rewrote (rewritten_bytes) of the captured ranges (range_bytes). Later passes replay the same frames, so driver caches keyed on values that change every frame in the title (ring addresses in user data, for example) can hit entries of an earlier pass; compare such changes on the first pass with warm disk caches instead. --shaders replays nothing and maps no guest memory: it reads the snapshot, applies the captured writes in call order and prints one JSON line per shader registration (code address, size, type, code hash and how many earlier registrations had the same code), then a summary; --shader-code <dir> also writes each distinct code as <dir>/type<n>-<hash>.bin. --submits <n> also reads captured memory without mapping guest addresses, applies writes in call order, and lists the first n submissions and flips of the captured frames with their queue and serials, the packets of each and the fields of its waits and releases. --trace-serials prints each submission, flip and suspend point with its call ordinal and command address as it is issued; with APS5_TRACE_GPU the driver prints the serial it accepts for each address and each completion, so a replay that stops completing can be followed to the call that made the submission. Replay times follow the GPU clock state: lock the clocks (nvidia-smi -lgc, -lmc) when comparing two drivers.
agc_frame_replay refuses a capture whose calls.bin is calls format 1 before it restores any memory: that format does not record whether GPU writes had landed before each memory delta was read, so record such a capture again. A delta first flushes the driver's writes to the pages it restores.
cmake --build build --target agc_frame_replay
build/core/libs/prx/libSceAgcDriver/agc_frame_replay capture
On Windows use agc_frame_replay.exe and prepend build/core/libs/libs/unpatched to the process PATH. With BUILD_TESTING=ON, agc_frame_capture checks the file format (round trip, zero-block elision, truncated and corrupt files), agc_frame_capture_reuse reads one capture from four threads at once and checks the reader's errors and the reads after them, and, on Windows only, agc_driver_frame_capture_eop reserves and submits six EOP flips with APS5_FRAME_CAPTURE_FRAMES=3 and checks that the capture starts after the first flipping submission and holds three frames of one reservation and one submission each, then that a flipping submission on another thread leaves this thread's flip count unchanged, then that a settled hold taken on an idle driver keeps another thread's submission out until it is released, and, on Windows and Linux, agc_driver_frame_replay captures two frames of CPU writes followed by DMA copies, the second from a block committed during the capture, replays them in agc_frame_replay, once and with --repeat 3 --verify-reset, and compares the copies; agc_driver_frame_replay_multisample_depth captures a frame that draws into a 4x native multisample depth target spanning two adjacent allocations and copies its sample 0 to single-sample targets with DB depth copies before and after the draw, then checks that --repeat 2 replays it in both passes and ends with the captured copies, and that each later pass rewrote exactly the pages that differ from the capture while retiring a native depth owner, including over pages that already match, that every reset leaves guest memory equal to the capture (--verify-reset), that --verify-reset fails a reset made to keep its owners, to hide them from the reset's inventory, to leave a wrong byte or to map memory (APS5_REPLAY_RESET_FAULT_FOR_TEST=owners, omit, bytes or remap), that no other thread takes the GPU lock inside a reset and that a transaction fails when a submission is accepted during it, and, on Linux, that the replay refuses a watched range without the guest write watch; agc_driver_frame_replay_single_sample_depth captures a frame that copies a single-sample depth target with DB depth copies before and after a draw into it and checks that the second pass of --repeat 2 reads the cleared depth again; agc_flush_exclusion checks that a reset's exclusion waits for a store that took pending storage images before it began, that no other thread takes them inside it, also after the first of two overlapping exclusions ended, and that after the reset's flush no GPU owner holds results over a range whose pending image a CPU write kept pending. agc_driver_frame_replay_subpage adds a 1-byte and a 16-byte registration in one 4 KiB host page and a 48-byte one in the next page to such a capture and checks that the replay restores all three. agc_driver_frame_replay_sub_page_resets (Windows and Linux) checks that a reset compares and rewrites exactly the parts of two ranges sharing one page that a pass wrote, compares nothing on no thread after a pass that wrote nothing or after its own rewrite, compares the ranges whole when its write walk fails, and fails when memory is mapped during it. agc_driver_frame_replay_partial_walk (Windows and Linux) makes every write walk of a reset collect half of its range and then fail, and checks that the reset compares the range whole, rewrites exactly the two written pages and restores them, and that the next reset rewrites exactly the page written since. agc_driver_frame_replay_large_range (Windows and Linux) writes all of one range two pieces and a block long and checks that the reset restores it on at least two threads, counted by the pieces each thread took. agc_driver_frame_replay_flushed_owner (Windows and Linux, needs Vulkan) keeps a depth surface resident over a captured page that only the reset's own store writes, and checks that the reset adds that page to the pages it compares, retires the surface and restores the page. agc_driver_frame_replay_untouched_gpu_owner (Windows and Linux, needs Vulkan) draws a 4x colour target over a captured range through Vulkan alone, so the write tracker reports none of its pages, and checks that the reset retires it, leaves the captured bytes unchanged and that
the target bound again resolves to the captured colour in every sample.
agc_driver_frame_capture_rewind makes the six EOP flips from REWIND tails and checks that they start the capture and that it holds the same three frames. agc_driver_frame_capture_rewind_held releases each REWIND only after its thread's next call returns and checks that no call waits at a busy frame boundary and that the capture starts at the first idle one.
Six tests with the driver's Vulkan device set a REWIND control word only after the next flip, so the delta before that flip is read while the REWIND waits, and check that the capture holds its frames: agc_driver_frame_replay_rewind_store overwrites the result of a copy gated by a WAIT_REG_MEM before the REWIND and checks that the replay keeps the CPU store, agc_driver_frame_replay_rewind_copy stores into the first page of a 128 MiB copy still running ahead of the REWIND and checks that the replayed delta holds the store and the copied bytes, and skips when the copy finished before the delta was read, agc_driver_frame_replay_rewind_compute parks a compute queue's WAIT_REG_MEM on a label the REWIND tail writes and checks that the replay runs the compute queue past it, agc_driver_frame_replay_rewind_release opens a queue's WAIT_REG_MEM gate from another thread 20 ms into a 256 MiB delta and checks that the delta holds the store, not the copy the queue makes after the gate, and agc_driver_frame_replay_rewind_fill submits a REWIND whose tail jumps to address 0 in the snapshot, fills the jump and sets the control word together, and checks that the replay runs the filled tail, and agc_driver_frame_replay_rewind_split fills the buffer a REWIND tail jumps to 64 MiB past the control word it sets in the same delta and checks that the replay resumes the REWIND only after both are restored. agc_driver_frame_replay_rewind parks a queue on a REWIND whose tail the CPU fills while it waits and checks that the strict replay runs the copy the tail chains to, agc_driver_frame_replay_fence_reuse releases and re-arms a fence between two recorded calls in each of two frames and checks that the strict replay runs both copies behind it, and agc_driver_frame_replay_busy_queue gates 64 MiB of graphics copies and a label on a fence a delta releases, parks a compute queue on that label, and checks that a replay with a 1 ms pacing timeout neither gives up nor releases the compute queue while the copies run. agc_driver_frame_replay_wait_label is the game-independent reproducer from #11157: a compute queue waits on a label, the CPU dirties an unrelated byte once the wait is registered, and a later graphics submission writes the label; it checks that the producer's submission does not wait for the capture and that the replay runs the compute queue past the label.
tools/frame_capture_minimize.py --capture C --replay R --filter F --output O --match-regex RE --expect-exit-code Nminimizes a frame capture while the replay failure that--match-regexidentifies stays reproducible.--max-trials,--confirm-runs,--replay-timeoutand--temp-dirbound the search.
tools/frame_capture_minimize.py shrinks a frame capture from --capture while a replay failure stays reproducible. It runs --replay on the capture first, --confirm-runs times (at least 2), to make sure the failure reproduces, then tries removing calls and chunks of the capture with the --filter program and keeps a removal only when the replay still matches --match-regex in its output and exits with --expect-exit-code. It stops after --max-trials replays (default 1000); --replay-arg passes an extra argument to the replay ({trial_dir} expands to a fresh folder per run). The result is written to --output, which must not exist yet.
Pipeline statistics
Set APS5_PIPELINE_STATS=1 to capture and print driver statistics for each newly created graphics or compute pipeline. This requires VK_KHR_pipeline_executable_properties and pipelineExecutableInfo; an unsupported device fails with an error. Statistic names and units are driver-specific. Capturing statistics can increase pipeline compilation cost. The setting is disabled by default.
GPU memory accounting
Set APS5_TRACE_MEMORY_BUDGET=1 to track Vulkan allocations by device, heap and allocation category. Dynamic storage-cache budget queries print [gpu-memory] reports at most once every 10 seconds. Reports contain byte counts for active and retained memory, the driver's heap budget and usage, and the storage budget's sampled, cached, reserved, available and cap terms. Image reuse changes the category without counting another allocation; slab free slots and pooled buffers count as retained memory. Host fallback allocations count against the heap actually used.
unattributed_usage is reported heap usage above tracked allocations; tracked_above_usage is the reverse difference. Vulkan heap usage is an estimate and includes driver allocations, so neither difference identifies a specific allocation class. complete=0 means accounting metadata could not be recorded consistently. The switch records allocation lifetimes and leaves cache limits and eviction unchanged. A forced APS5_TEXTURE_CACHE_MIB bypasses dynamic budget queries and their reports.
Device loss reports
On a device that supports VK_EXT_device_fault, the first VK_ERROR_DEVICE_LOST prints the driver's fault description, the faulting addresses and the vendor fault codes as [device-fault] lines. Set APS5_GPU_CHECKPOINTS=1 to also record a VK_NV_device_diagnostic_checkpoints marker with the program address before each compute dispatch; the report then lists the last markers the GPU reached. On a device without that extension but with VK_AMD_buffer_marker (RADV and AMD's own drivers), each compute dispatch instead writes a numbered marker into a host-visible buffer when the GPU reaches it and another when it finishes; the report then names the programs of the last dispatch reached, of the last one finished and of up to eight dispatches between them. Checkpoints are disabled by default and ignored on devices without the extension.
Worker sampler
Set APS5_SAMPLE_WORKER=<file> to sample queue worker 0 every millisecond (in practice every timer tick). Every 20 s and at exit it writes <file>, one module offset self inclusive line per sampled address, and <file stem>.collapsed.txt, the worker's whole stacks in the collapsed format that speedscope.app and flamegraph.pl read: one frame;...;frame count line per distinct stack, root first, each frame as module+0xRVA. A walk that ends before the thread's root starts with [truncated]. The # lines give the samples, the walk depth (64 frames), the truncated walks, the mean and longest time the worker was suspended, and the size and PE timestamp of each module, to check the binary a file is symbolized against. A frame with .pdata is stepped by RtlVirtualUnwind; any other frame by its DWARF record in .ehfram, the unwind data the libraries are built with. Those steps read only inside the worker's stack, and a module is indexed after the worker resumes, the first time a walk meets it. python tools/symbolize_samples.py <file stem>.collapsed.txt --libs <libs directory> names each frame from the COFF symbols of the module that ran, or from its export table when it has none, and leaves a module unsymbolized when its size or timestamp differs from its # module line or when it has none (--unverified symbolizes it anyway); --since <earlier copy> keeps only the samples taken after that copy, --out writes the named stacks and --demangle uses c++filt. Given <file>, it lists functions by self and by inclusive samples, where a function's inclusive count is the sum of its addresses' and overcounts a function that is on one stack more than once.
APS5_SAMPLE_COMMITTER=<file> samples queue 0's draw committer the same way and writes the same two files. The committer records the draws the worker hands over (APS5_PIPELINED_DRAWS), so when the worker's stacks wait in DrawPipeline::Enqueue, its stacks show what bounds the frame. It starts with the first pipelined draw; with APS5_PIPELINED_DRAWS=0 nothing is sampled.
APS5_SAMPLE_THREADS=<file> samples every thread of the process every 2 ms and writes the 40 hottest addresses of each busy thread to <file>, 12 frames deep and through .pdata only, under a thread <id> samples <n> line per thread and with the same # module lines. The samplers exist only on Windows; the addresses are symbolized offline with tools/symbolize_samples.py, which adds up all threads or, with --thread <id>, keeps one.
Compare two Windows sampler text files of the same kind with python tools/symbolize_samples.py before.txt --libs before/libs --compare after.txt --compare-libs after/libs. Use each build's own libraries and collect both captures with the same workload and sampler settings. The report shows recorded counts and percentage-point changes, with separate counts for unresolved and unlisted samples. Add --json for a machine-readable report.
Performance trace
Set APS5_TRACE_FRAMES=<start>:<count> to record <count> presents from present <start> (counted from 0), or APS5_TRACE_SECONDS=<start>:<length> to record from the first present at least <start> seconds after the first present until the first present <length> seconds later. Both values are whole numbers and the length is above 0; a malformed value, or both switches together, fails the first present. The window opens and closes at presents. In agc_frame_replay, which presents nothing, each replayed flip counts as a present when the driver reports it ready (IFlipRequest::GpuReady), and the thread that reports it does the presenter's part, formatting the trace when the window closes. A window that is still open when the replay ends writes nothing, so a frame window needs more than <start> + <count> replayed flips. A replay's trace has no Driver.Present slices, its resolution is the size of the first display buffer the capture stored (0x0 when it stored none), and its gpu_busy_ms_per_present is 0 because that time is counted as presentations retire; read GPU time from the gpu track.
Set APS5_TRACE_EVENTS=<count> to change the buffers of the queue workers, the presenter, the draw committer of pipelined draws (APS5_PIPELINED_DRAWS) and the draw finisher (APS5_DRAW_PIPELINE) for a frame or seconds window. The count is a whole number from 1 through 4,194,304; the default is 262,144. An invalid value fails when one of these threads first binds to the trace, before recording. Each buffer uses count * sizeof(TraceThread::Slice) bytes (currently 40 bytes per event, since each slice also carries its recorder batch): 10 MiB at the default, 120 MiB at 3145728, and 160 MiB at the maximum, per thread. The buffers are allocated even while waiting for the window to open, and formatting the trace uses additional memory. Shader preparation keeps its explicitly sized 32,768-event buffers, as does a title thread named title that binds one the first time it registers a shader or resolves a shader ABI. The GPU range buffer of a windowed trace uses the same count and is reserved once when the window opens: 32 bytes per range, 8 MiB at the default and 128 MiB at the maximum. Summary-only sessions allocate no event buffers and do not read this setting. A larger buffer can still fill; use a shorter window or increase the count within the bound. The thread table of tools/trace_digest.py divides the slices a thread retained by every frame of the window; for a thread whose buffer filled, its loss line also gives busy and wait per frame over the frames that ended before the trace buffer full instant.
Inside the window the queue workers, the presenter and the draw committer and finisher record every PerformanceTimer scope and stage as a complete event named after its frame timing key: Driver.WorkerWait, Driver.Packet, Driver.Packet.draw, Graphics.Draw, Driver.Present, Driver.Present.inflight_wait, Vulkan.Retire and so on. A slice shorter than 20 us is only counted: its time is in the thread's counter <thread> folded (milliseconds per present) and in the summary. A thread writes a present's counter sample at its first slice after the next present, so the last present of the window has no sample; its time is still in the summary. By default, each of these threads allocates a buffer for 262,144 events when it starts; a full buffer stops that thread's recording, sets trace_dropped and puts an instant event trace buffer full on the thread's track at the start of the first lost slice (slices are appended when their outer scope ends, so that can precede the last recorded slice by up to one outer-scope length), with the number of lost slices in args.events_lost. When the window closes, the presenter formats the trace once and a ProfileOutput writer thread writes aps5-trace-<commit>-<pid>.json.gz (Chrome trace-event JSON, opened by ui.perfetto.dev or chrome://tracing) and appends one line to aps5-summary.jsonl, both in APS5_TRACE_DIR or the working directory. A window that is still open when the title exits writes nothing.
The summary line has commit and dirty of the build, env (every APS5_* variable; a value containing / or \ is written as <path>), gpu, driver, os, cpu (the CPU brand string), cpu_threads and memory_mib (physical memory) of the host (all three absent on a host that is not x86 or reports no brand string), title_id, title and content_version from app0/sce_sys/param.json (only when the title has one; content_version is empty when the file has no contentVersion, or one that is not a string of at most 15 characters), resolution (the video output's), window, presents, frame_ms (p50, p90, p99 and max of the intervals between presents), gpu_busy_ms_per_present (the batch timestamps behind [present]), worker_busy_pct (share of the window each queue worker spends in Driver.Packet, Driver.Suspend, Driver.EndSubmission, Driver.Rewind, Driver.Completion and Driver.FinisherDrain), phase_totals_ms (total milliseconds for every recorded scope and stage, summed across threads, without Driver.WorkerWait), top_phases_ms_per_frame (the eight largest scopes and stages, without Driver.WorkerWait), phase_totals (only with APS5_TRACE_ALL_PHASES=1: every recorded scope and stage, each with count, sum_ms and ms_per_present, including the stages that the eight-entry top list folds away), graphics_track (counts summed across threads: Graphics.RenderPass for begun passes, Graphics.RenderPass.Continued for draws that continued one, Graphics.RenderPass.Close.<reason> for each closed pass, Graphics.Barrier.<class> and Graphics.BarrierMerged.<class> for recorded and elided barriers, and Graphics.Copy with Graphics.Copy.bytes; the timed Graphics.Draw, Graphics.DrawWithRecipe, Graphics.Submit and Graphics.Wait scopes stay in phase_totals_ms and top_phases_ms_per_frame), trace_dropped, trace_dropped_threads and trace. trace_dropped is true when any thread lost a slice, any thread's totals table (512 scope and stage entries) was full, or the gpu track was full. trace_dropped_threads is present only then and has one entry per such thread name (threads that share a name, such as the shader prepare threads, share one entry: events_lost is summed, events_full_after_s is the earliest, totals_full is true if any is): events_full_after_s (seconds from the first present of the window to the start of the first lost slice; absent for gpu and, in every summary line (windowed APS5_TRACE_FRAMES/APS5_TRACE_SECONDS and APS5_TRACE_SUMMARY_EVERY), whenever the first lost slice starts outside the line's span of presents, including a slice whose scope began before the window opened or one lost after the window's last present), events_lost (slices not recorded; absent when 0; in APS5_TRACE_SUMMARY_EVERY lines it counts the thread buffer's losses since it started, not only those of the line's span) and totals_full (true when the thread's totals table overflowed, which makes the summary numbers incomplete; a thread with events_lost only has complete totals). The raw phase totals are not divided by presents, including when no presents were recorded. Nested scopes and parallel threads can overlap; these are inclusive recorded durations, not exclusive CPU time or timings for uninstrumented background work. A trace holds timings, scope names, counts and thread names; no guest memory, paths or strings of the title.
The summary's scope durations are wall time aggregated across threads. Nested scopes include their children, and scopes on different threads can overlap; adding them does not give a frame's exclusive CPU or GPU cost. Only the eight largest aggregates are listed: a missing scope or stage does not establish that it did not run or cost nothing, even when trace_dropped is false. worker_busy_pct measures occupancy in the listed scopes, including waits inside them, rather than CPU utilization. Use the full trace and separately measured thread CPU time to distinguish these cases.
The shader preparation threads are traced as well, shader prepare, with a buffer for 32,768 events each. A wait for the GPU mutex on a traced thread is a GpuMutex.wait.<site> slice (dispatch, draw, present, flush and so on, as on the [lock] line).
A queue worker's WAIT_REG_MEM or WAIT_REG_MEM_64 is also a Driver.MemoryWait.<phase>.<exit> slice, from the start of the wait to its end, on every queue. A wait that a worker lands before a guest read because another queue's label satisfied it (the [landwait] line) is a Driver.LandingWait.<phase>.<exit> slice. <phase> is entry when the wait ended before the worker published that it is blocked and blocked when it ended in the poll loop. <exit> names what satisfied the wait:
recorder.queue_0x<q>: the recorder's label table held the value;<q>is the queue that recorded the label, written as in the worker's thread name (queue_0x0,queue_0x20).store.queue_0x<q>: a label store of queue<q>that the driver noted gave the value, whether or not it had reached memory.memory: guest memory held the value and no noted label store gave it. That is a title CPU store, or a GPU write that the driver does not track as a label and that reached memory.held_at_submit: memory already satisfied the wait when its submission arrived.settled(landings only): the recorded writes to the address completed.
A writer queue outside 0x0 to 0x58 is queue_other.
Every drain of queue 0's pipelined draws that has to wait for queued items is a DrawPipeline.Drain.<reason>.<site> slice on the thread that drains, from the start of the wait to its end. <reason> is the drain reason of the [draw] pipelined line: packet, flush, labels, capture, indirect or submission. <site> says which check drained:
packet, at the packet gate (theDriver.Packet.pipeline_drainstage):label_queued_matchorlabel_queued_mismatch(WAIT_REG_MEM): the newest queued item that writes the awaited address holds a label value, and that value passes or fails the wait.label_queued_unknown: a queued item writes the awaited address with no known value.label_not_queued: no queued item writes the awaited address. The drain then serves only the order of queue 0's earlier work against another queue's held submission.dispatch,flip,rendering(the rendering wait packet),predication(a predicated packet whose predicate a queued item writes) andother.
packet, inside a dispatch:msaa_clear,htile_patchandmemory_value_fill: a clear or fill the driver handles itself.not_candidate: the dispatch cannot be a pipelined item.cache_miss,cache_unchecked(the dispatch cache is off or stamp-validated) andverify_data.reads_queued: a queued item writes what the dispatch reads.writes_unboundedandno_recipe.not_plain,item_not_plain,item_reads_queuedanditem_writes_unbounded: a dispatch thatAPS5_PIPELINE_DISPATCH_MISSESwould have queued.
packet, elsewhere:group_ahead(group capture ahead of the packet),metadata_pass,depth_render_control,indirect_buffer_writtenandindirect_buffer_changed.flush:record,cappedorsubmit.labels:draw_capture.capture:variant_runs,decode_reads,fill_inputs,known_value_verify,unknown_writeandshader_code.indirect:arguments_queued,unpipelined(APS5_NO_PIPELINED_INDIRECT) andinline.submission:end,suspend,unordered_completionandexception.
A drain with no site has no .<site> part. A drain that finds the pipeline idle records nothing, so these slices count the drains of the [draw] pipelined line. The label_* lookup runs only while the trace records, and none of this changes when a drain happens.
A memory wait slice lies inside the packet's Driver.Packet.memory_wait stage. A gate drain lies inside Driver.Packet.pipeline_drain, and a dispatch's drain inside Driver.Packet.dispatch. So phase_totals_ms lists them next to their stage, and tools/trace_digest.py does not count their time twice. The digest counts a slice whose name contains wait as wait time:
- A memory wait inside
Driver.Packet.memory_waitadds nothing to the wait time. - A landing inside another stage (a dispatch's guest read, for example) is now wait time instead of busy time.
- A drain slice is busy time, like its stage.
The gpu track holds one batch slice per recorder batch, from the batch's timestamp pair. With APS5_PROFILE_GPU=1 it also holds a slice per command class range, under the class names of the [gputime] line (draw, copy, fill, present-blit, ...); program ranges are left out. The track keeps up to the APS5_TRACE_EVENTS count of ranges (262,144 by default); more set trace_dropped. The GPU clock is mapped onto the CPU clock with calibrated timestamps (VK_KHR_calibrated_timestamps or the EXT version, enabled only when a trace switch is set) against the performance counter on Windows and CLOCK_MONOTONIC elsewhere, or CLOCK_MONOTONIC_RAW on a device that calibrates against no CLOCK_MONOTONIC (MoltenVK), taken when the window opens and when it closes, so the two clocks are matched at both ends of the window. A batch is added when the driver reads its timestamps, after its fence signals, so the batches of the last frames of the window, which complete after it closes, are missing. Without calibrated timestamps the trace has no gpu track, and the [trace] line says so.
With any of the three switches set, the recorder writes a timestamp pair per batch for the whole run, as with APS5_PROFILE_DRAW. Without them, a PerformanceTimer, a GPU mutex acquisition, a memory wait, a pipeline drain that waits (one more for a WAIT_REG_MEM at the packet gate) and a read of batch timestamps each cost one more predictable branch.
Set APS5_TRACE_DRAW_PROGRAMS=1 (any value) to print one [draw-programs] line on stderr per draw, with the submission serial, the queue, and for each selected program its stage and role, the shader's code address and its entry address (vertex/main=0x100000(entry=0x100040)). It is for comparing the shaders a draw selects with shader-preparation failure logs; it reads no GPU state.
Summaries for a long session
Set APS5_TRACE_SUMMARY_EVERY=<seconds> (a whole number above 0; a malformed value fails the first present) to profile a long session in the background without a trace. The first present opens the first interval. Every <seconds> seconds, at the first present at least that long after the interval opened, the presenter appends one line to aps5-summary.jsonl in APS5_TRACE_DIR or the working directory and opens the next interval at that same present, so the intervals follow each other without a gap and their frame_ms cover every interval between presents. The line has the fields of the window summary line for that interval only, plus interval_start_s and interval_end_s (seconds since the first present). Its window is {"spec":"summary_every <seconds>","first_present":<present the interval opened at>,"ms":<span of the interval's presents>} and its trace is the empty string. No event buffer is allocated: each thread keeps only the per-scope totals it already folds (a few kilobytes), and the presenter subtracts the totals of the previous interval. An interval that is still open when the title exits writes nothing.
The switch combines with APS5_TRACE_FRAMES or APS5_TRACE_SECONDS. The intervals run for the whole session and the window records its full trace on top: the event buffers are allocated and filled only while the window is open, the window's own summary line (with trace set and no interval_* fields) holds only the time inside the window, and the interval lines continue unchanged around it. Without a window switch no buffer is allocated at all. The two switches do not share a clock origin: interval_* is relative to the first present, as the window's APS5_TRACE_SECONDS start is.
Set APS5_TRACE_BENCH=1 together with APS5_TRACE_SUMMARY_EVERY to also keep every interval's frame times for a benchmark report. At each interval the presenter hands the kept intervals to a writer thread, which formats and compresses the file and rewrites aps5-bench-<commit>-<pid>.json.gz in APS5_TRACE_DIR or the working directory: one JSON object with format (aps5-bench/1), the identity fields of the summary line (commit, dirty, env, gpu, driver, os, cpu, cpu_threads, memory_mib and, with param.json, title_id, title and content_version), intervals_dropped and intervals. Each interval has start_s, end_s, first_present, resolution, gpu_busy_ms (the interval's total) and frame_us, the whole microseconds between consecutive presents. The file keeps the last 240 intervals; intervals_dropped counts older ones it no longer holds. Any other value, or the switch without APS5_TRACE_SUMMARY_EVERY, fails the first present. The file is written to <name>.tmp and then moved over the previous one, so a crash or kill during a rewrite leaves the last complete report. Only the newest report waits for the writer: one handed over while an older one is still pending replaces it. The frame times cost 4 bytes per present in memory.
python tools/trace_digest.py aps5-summary.jsonl prints the interval lines of such a file as one row per interval (frame p50, p90, p99, max, GPU busy per present, the busiest queue worker and the largest phase) and a text sparkline of the frame p99 and of the GPU busy time; lines of window captures in the file are skipped, and changes to build, environment, host, resolution or title metadata between intervals are reported. --json prints the rows, the first interval's identity and the indices of identity changes as JSON. For an automatic search between known-good and known-bad commits, see tools/performance_bisect.py.
With APS5_TRACE_SUMMARY_EVERY set, the recorder writes a timestamp pair per batch for the whole run and every PerformanceTimer scope adds its time to the thread's totals, two clock reads per scope. A thread's totals are read while it runs, so a scope that straddles an interval boundary is counted in one interval or the other.
GPU time per command class
Set APS5_PROFILE_GPU=1 (any value) to time the recorder's GPU work with timestamp queries and print one [gputime] line on stderr. APS5_PROFILE_DRAW alone does not print it: a batch then gets only its whole-batch timestamp pair. A timed range is a pair of bottom-of-pipe stamps that both wait for all earlier work, so a range is the time its own work adds after everything recorded before it. A batch holds at most 512 ranges, its whole-batch range included. The line is written when a batch's timestamps are read after its fence, at least 10 s after the previous line, and covers every batch read since then.
The header fields: <n> ms of GPU time is the sum of the program-keyed ranges only (dispatches and buffer copies, see by program); draws and the driver's own commands are not in it. in <n> batches counts the batches read. batch <n> ms first to last command sums the whole-batch ranges, from the stamp written when the batch opens (it waits for the batches before it) to the stamp written at Submit. classes <n> ms is the plain sum of every class range, including present-blit, which runs outside the batches. all ranges <n> ms is, per batch, the union of its class and program ranges, with overlapping time counted once; present-blit is not in it. untimed <n> ms is batch minus all ranges: batch time that no range covers, including the work of dropped ranges. <n> presents counts the VulkanDevice::present calls since the previous line. <n> ranges dropped at the 512 cap counts ranges refused because their batch was full.
A class range covers a command together with its own barriers. In VulkanDevice::CopyBuffer the copy class range spans the leading barrier, the transfer and the trailing barrier, and the program-keyed range sits inside it around the transfer alone, so the transfer counts in both GPU time and classes but once in all ranges. An ordinary dispatch's leading barrier is before its program range; its program range spans the dispatch and the trailing visibility barrier, while dispatch-trail times that barrier too. This attributes a driver's deferred cache/visibility work to the program that caused it, while all ranges still counts the overlap once. An overlap-capable dispatch closes its program range after the dispatch because its trailing barrier is deferred and can cover several programs. GPU time plus classes can therefore exceed batch; compare all ranges with batch instead.
by program lists up to 12 keys, highest time first, as 0x<key> x<ranges> <ms>ms. A dispatch's key is its guest program address, or the program's variantId when the address is 0. A buffer copy's key is the program address of the copy kernel it replaces, or 0 for a PM4 DMA copy (opcode 0x50). by class lists every class with at least one range since the previous line as <name> x<ranges> <ms>ms <MiB>MiB (per present x<ranges> <ms>ms <MiB>MiB); the per-present figures are 0 when there was no present. MiB is the byte count each range passes to EndGpuTiming. The classes, with the function that opens each range:
dispatch-lead: a dispatch's leading barrier, when it is recorded rather than merged into the previous trailing barrier (VulkanDevice::recordDispatch). 0 MiB.dispatch-trail: a dispatch's trailing barrier (recordDispatch). 0 MiB.indirect-args: the barrier that makes an indirect dispatch's host-imported group counts visible to the indirect read (recordDispatch). 12 bytes per range.label-run: a run of GPU label stores (vkCmdUpdateBuffer, plus the queued occlusion dump folds of a per-batch run) with its barriers (Recorder::RecordStorefor inline runs,Recorder::closeStoreRunfor per-batch runs). Stored bytes.fill: a guest fill of host-imported memory, asvkCmdFillBufferor pattern copies, with its barriers (VulkanDevice::FillBuffer). Filled bytes.fill-clear: a fill done as avkCmdClearColorImageof a storage image, between two layout barriers (StorageTexture::FillClear). Filled bytes.copy: the buffer copy ofVulkanDevice::CopyBuffer, a whole-surface image copy (StorageTexture::CopyFrom) and the depth plane copies to and from storage images through a staging buffer (copyPlaneand the layered copy inDepthSurface.cpp). Copied bytes.staging-in: a build's copies of guest buffer regions into staging or host-copy buffers, between two barriers (GuestBufferMemory::recordGpuCopies). Copied bytes.staging-out: the copies of shader-written sub-ranges back into the import (GuestBufferMemory::RecordCopyBacks). Copied bytes.draw: for a lean draw, from its first barrier to the end of its render pass, so draws that continue the pass fall inside one range (recordDraw, ended byRecorder::endOpenRenderPass); for a recorded draw with layout transitions, from its first barrier to its download barrier (Draw). 0 MiB.storage-upload: detiles of guest bytes into a storage image, whole (StorageTexture::upload) or by changed runs (StorageTexture::uploadWindows), and pending units copied from an alias image (StorageTexture::borrowUnits). Uploaded bytes.storage-writeback: retiles of a storage image back to guest memory, by windows (StorageTexture::writeBackWindows) or by layers (StorageTexture::writeBackLayers). Stored bytes.dcc-clear: avkCmdClearColorImageof a storage image whose DCC keys read as a clear, at upload (StorageTexture::upload) or for a fill of its key bytes (StorageTexture::clearByKeysFill, withAPS5_KEYS_FILL_CLEAR=1). Surface bytes.dcc-keys: queued DCC key stores, as0xfffills and seed copies between two barriers (Recorder::recordKeyStores). Key bytes.present-blit: the presentation command buffer from its first to its last command, timed in its own two-query pool (VulkanDevice::present) and added when its slot retires (Recorder::AddGpuTiming). Width x height x 4 bytes of the swapchain extent.shadow-publish: copies of unit shadow slabs into the import, with their barriers (recordCopiesinUnitShadow.cpp, reached fromPublishShadow). Copied bytes.template-refresh: thevkCmdUpdateBufferupdates of a cached dispatch's changed data words, as one range from the first update to the last (ShaderResources::refreshData, called fromrecordDispatch). Refreshed bytes.
Guest clock scale
Set APS5_TIME_SCALE=<factor> to scale sceKernelGetProcessTime, sceKernelGetProcessTimeCounter and sceKernelReadTsc from their first observed value. A positive factor below 1 slows guest time; a factor above 1 speeds it up. An unset, zero, negative or non-numeric value uses 1.0 (normal speed). On Windows, sceKernelClockGettime monotonic clock ids are scaled too; on Linux they return the native host monotonic clock unchanged. A title's own rdtsc instruction and sceKernelGetTscFrequency are unscaled, so dividing scaled TSC deltas by the reported real frequency gives guest-time intervals. Host sleeps and waits still take real time, so this is a diagnostic aid for titles whose frame or timeout logic depends on guest time; it does not speed up the emulator or GPU work. The setting is read once when the process starts.
APS5_PAD_INPUT_FILE command durations and reload polling use sceKernelGetProcessTime, so they follow the scale. At 0.02, a 1-second injected press lasts about 50 seconds of real time, and a new command can take up to 5 seconds to be noticed.
Driver profile lines
With APS5_PROFILE_DRAW set (any value), the driver prints a profile line on stderr at most every 10 s. A line either counts the last 10 s (its counters are read and cleared when it is printed; the text says (10 s) or over 10 s) or counts from the start of the process (the text says (cumulative)). A rate is the difference of two cumulative lines divided by the time between them.
With APS5_DRAW_PIPELINE=1 as well, [draw] driver phases keeps counting every draw packet once on the queue worker: a draw handed to the draw finisher is drawn there, and its worker rows stop at the hand-off, with the enqueue in epilogue. The line then ends with ; draw finisher (N handed draws, N drawn, N captures), us per handed draw: queue wait X and the same rows for the part each handed draw ran on the finisher, timed from when the finisher started it; queue wait is the time from the hand-off to that start and is not part of the finisher total.
With APS5_PROFILE_DRAW=1, the lock wait row in [draw] driver phases can include time spent enqueueing a draw, including waiting for space in the draw pipeline. Draws that acquire the GPU mutex also charge that acquisition to the same row. Use the per-thread [lock] counters or GpuMutex.wait.<site> trace slices to measure GPU mutex contention. For draw pipeline backpressure, use the for room time on the [draw] pipelined line. Check the producer's sampled stacks for DrawPipeline::Enqueue and the draw committer's trace to see where the time goes.
With APS5_PROFILE_DRAW set, the queue worker hands no draw to the draw finisher (APS5_DRAW_PIPELINE) and finishes every draw itself, so the [finisher] line reports 0 draws handed to the draw finisher. A run with draw profiling does not measure the finisher: compare APS5_DRAW_PIPELINE with main in runs without APS5_PROFILE_DRAW, using the trace summaries (APS5_TRACE_SUMMARY_EVERY) instead.
| Line | Counts |
|---|---|
[rescache] revalidate |
last 10 s |
[texture-cache] |
last 10 s |
[pipecache] |
last 10 s |
[rescache] (hits, misses, entries) |
from the start |
[vk] |
from the start |
[indirect] (gpu-side, cpu-side) |
from the start |
[flip] |
from the start |
[fill-sync] |
from the start |
[buffers] descriptor elements bound |
from the start |
[textures] page digests |
from the start |
[gputime] is described above and needs APS5_PROFILE_GPU. Other profile lines state their window in their text or are not listed here because their counters were not checked.
Driver thread priority
Set APS5_THREAD_PRIORITY=high to raise the AGC driver's queue workers and the video output presenter above the title's threads. On Linux the threads get nice APS5_THREAD_NICE (default -10) through rtkit; on Windows they get THREAD_PRIORITY_HIGHEST. APS5_THREAD_PRIORITY=rt asks rtkit for real-time priority APS5_THREAD_RT (default 10, at most rtkit's MaxRealtimePriority) under rtkit's policy, SCHED_RR by default; on Windows it sets THREAD_PRIORITY_TIME_CRITICAL. rtkit only grants it when the process's hard RLIMIT_RTTIME is at most its RTTimeUSecMax (200000 us by default), so a hard limit above APS5_THREAD_RTTIME_US (default 200000, capped at RTTimeUSecMax) is lowered to it and the soft limit to at most half of it. The hard limit cannot be raised again and stays lowered for the whole process even if rtkit then refuses; see technical debt. There is no fallback between the modes: when rtkit or SetThreadPriority refuses, a queue worker reports the refusal as a driver failure, which the next submission, wait or shutdown rethrows, and the presenter's start throws it. Each raised thread logs its priority once as [thread-priority]. The setting is off by default; a value other than off, high or rt is reported the same way as a refusal.
Shader recompiler
The shader recompilation logic in core/shader/recompiler is isolated from the rest of the project and is a pure function of its input data, designed for integration into any other project. The current CMake target also includes cache support and links a supplied runtime target, glslang, and optionally SPIRV-Tools.
Register context tests
The x86-64 register capture and restore tests can be built separately on Linux and macOS, without submodules or the prx libraries. On macOS:
cmake -S core/libs/tests/register_context -B build/register-context -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=x86_64
cmake --build build/register-context
ctest --test-dir build/register-context --output-on-failure
On Linux x86-64, omit CMAKE_OSX_ARCHITECTURES; the full BUILD_TESTING build also registers these tests. Apple silicon runs the x86-64 tests through Rosetta. They cover the unwinder's register transfer, not the complete macOS runtime or guest exception handling.
Build inspection tools
tools/compile_database_inventory.py <database>groups the raw records of a saved compilation database without invoking a compiler or build tool. With--ninja-log <log>, use the compilation database and.ninja_logfrom the same build directory. The report adds the latest recorded duration to each matched compile output, counts records without anoutputfield, and lists log outputs absent from the database. The sum counts each matched output once and measures cumulative compile work. Compiles can overlap and a log can span multiple invocations. Relative log paths use the common directory of the compile commands. Use--ninja-build-dir <original-build-directory>when that differs from the original Ninja working directory.
Test selection tools
Changed-test selection uses the configured CMake target sources. Windows CI replaces AGC execution fixtures outside ANYPS5_AGC_EXECUTION_TESTS with stub sources, so a change to an omitted .cpp can pass the changed-test job without running that fixture. To run it locally, configure a full build with -DBUILD_TESTING=ON. Set -DANYPS5_AGC_EXECUTION_TESTS= to build every AGC execution fixture, or set it to the fixture's source file stem. Build the test target and run the matching CTest. Windows Build workflow
tools/build_changed_guest_tests.py <build_dir> [changed_paths] [--output-log FILE]builds and runs the changed guest and host-onlycore/libstests.tools/build_mingw_host_only_tests.py <build_dir> [changed_paths] [--list-only]builds thecore/libstest executables that do not link guest libc.--list-onlyprints them without building.
Checker scripts
tools/check_test_registration.py [build]fails when a test executable is built but no ctest test runs it, or when a library source that defines exports is never compiled.--listand--jsonprint the findings. Runpython3 tools/check_test_registration.py --scriptsafter changing Python test registration. It checks for test scripts omitted from CTest or workflows and test classes omitted from explicitly selected suites.tools/check_skips.py <junit> [--job linux|windows] [--require-tests]fails when a test is skipped for a reason the job's device is not expected to hit. Use--listto inspect reported skip reasons without applying the job's policy. Use--jsonfor policy decisions and the list of unexpected skips in machine-readable form.tools/compare_configure_checks.py <baseline> <candidate>compares the recognized configure checks in two CMake caches without writing anything. It prints a JSON object withadded,removedandchangedlists. Exit status 0 means the recognized checks match, 1 means they differ, and 2 means the command could not read or compare the inputs.tools/sanitizer_report.py <junit> --jsonwrites structured sanitizer triage to stdout. If you also pass--summary FILE, it appends Markdown to that file. Exit status 0 means there were no unexpected failures, 1 means at least one unexpected failure, and 2 means the input or output could not be processed.
Public-header archives
python3 tools/package_release.py --platform headers --version v1 --output dist packages the public headers, their project includes and LICENSE without a build directory. To reproduce the ZIP and TAR.GZ archives with the same Python and zlib versions, set SOURCE_DATE_EPOCH to the same ASCII decimal integer from 0 through 4294967295. Invalid values fail before staging or replacing outputs. Without the variable, archive metadata keeps its existing behavior.
With the variable set, archive members have mode 0644, TAR ownership is zero with empty owner names, and TAR and gzip timestamps use the selected epoch. ZIP timestamps use UTC, round down to two-second precision and clamp dates before 1980 to 1980-01-01. The gzip header omits the original filename. Source bytes, permissions and modification times remain unchanged. This controls header archive metadata; it does not establish reproducible native binaries or identical compressed bytes across Python or zlib versions.